M cmd/hackurist/main.go +22 -8
@@ 2,18 2,33 @@ package main
import (
"bitbucket.org/telesto/hackurist"
+ "flag"
"fmt"
"log"
"os"
)
+func usage() {
+ fmt.Fprintf(os.Stderr, "usage: hackurist [-h] [-a address] [-d] cmd [arg...]\n")
+ flag.PrintDefaults()
+}
+
func main() {
- //cmd := "region-pops"
- //args := []string{"list"}
- cmd := "help"
- args := []string{}
- // err := run("127.0.0.1:5000", "help", []string{}, false)
- err := run("127.0.0.1:5000", cmd, args, true)
+ address := flag.String("a", "127.0.0.1:5000", "dfhack rpc server address")
+ debug := flag.Bool("d", false, "print debug messages")
+ help := flag.Bool("h", false, "help")
+
+ flag.Parse()
+ if *help {
+ usage()
+ os.Exit(0)
+ }
+ if flag.NArg() == 0 {
+ usage()
+ os.Exit(2)
+ }
+ cmd := flag.Arg(0)
+ err := run(*address, cmd, flag.Args()[1:], *debug)
if err != nil {
log.Println(err)
os.Exit(1)
@@ 32,10 47,9 @@ func run(address, cmd string, args []str
return err
}
result, err := conn.RunCommand(cmd, args)
- fmt.Printf("result:'%s'", string(result))
+ fmt.Print(string(result))
if err != nil {
return err
}
-
return nil
}
M hackurist.go +13 -0
@@ 34,11 34,15 @@ var serverErrors = map[dfproto.CoreError
dfproto.CoreErrorNotification_CR_NOT_FOUND: errors.New("target object not found"),
}
+// Conn represents a connection to a dfhack rpc server.
type Conn struct {
conn io.ReadWriteCloser
debug bool
}
+// Dial connects to the address.
+//
+// Set debug to true for getting debug output.
func Dial(address string, debug bool) (*Conn, error) {
conn, err := net.Dial("tcp", address)
if err != nil {
@@ 47,6 51,7 @@ func Dial(address string, debug bool) (*
return &Conn{conn, debug}, nil
}
+// Close closes the connection.
func (c Conn) Close() error {
if c.debug {
log.Print("Close: sending quit request")
@@ 64,6 69,11 @@ var (
handshakeResponse = "DFHack!\n\x01\x00\x00\x00"
)
+// ShakeHands sends a shake hand request to the server and
+// validates the server response.
+//
+// ShakeHands mast be called after opening a connection with Dial and
+// before sending any commands to the server.
func (c Conn) ShakeHands() error {
if c.debug {
log.Printf("ShakeHands: sending handshake request: %q", handshakeRequest)
@@ 132,6 142,9 @@ func (c Conn) readHeader() (*header, err
return header, nil
}
+// RunCommand sends a rpc command to the server.
+// It reads the response, processes it and returns the output
+// ready for a text client.
func (c Conn) RunCommand(cmd string, args []string) ([]byte, error) {
protoCmd, err := proto.Marshal(&dfproto.CoreRunCommandRequest{Command: &cmd, Arguments: args})
if err != nil {