# HG changeset patch # User telesto # Date 1418652187 -3600 # Mon Dec 15 15:03:07 2014 +0100 # Node ID 50f9f42a36fefb862279e2b87c496ea516b63ad8 # Parent 981ae5f6599d141964c902122ebaad28cef904d2 added doc; improved cmd line tool diff --git a/cmd/hackurist/main.go b/cmd/hackurist/main.go --- a/cmd/hackurist/main.go +++ b/cmd/hackurist/main.go @@ -2,18 +2,33 @@ 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 @@ 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 } diff --git a/hackurist.go b/hackurist.go --- a/hackurist.go +++ b/hackurist.go @@ -34,11 +34,15 @@ 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 @@ 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 @@ 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 @@ 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 {