basic command structuer liberally borrowed from goose, from go

This commit is contained in:
Dan Ballard 2014-12-08 19:16:07 -08:00
parent acea92088b
commit c3e3805f66
4 changed files with 104 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.*.swp
warren

27
cmd.go Normal file
View File

@ -0,0 +1,27 @@
package main
import (
"flag"
)
// shamelessly snagged from the go tool
// each command gets its own set of args,
// defines its own entry point, and provides its own help
type Command struct {
Run func(cmd *Command, args ...string)
Flag flag.FlagSet
Name string
Usage string
Summary string
Help string
}
func (c *Command) Exec(args []string) {
c.Flag.Usage = func() {
// helpFunc(c, c.Name)
}
c.Flag.Parse(args)
c.Run(c, c.Flag.Args()...)
}

15
cmd_build.go Normal file
View File

@ -0,0 +1,15 @@
package main
import ()
var buildCmd = &Command{
Name: "build",
Usage: "",
Summary: "build the go server in the current directory",
Help: `build extended help here...`,
Run: buildRun,
}
func buildRun(cmd *Command, args ...string) {
}

60
warren.go Normal file
View File

@ -0,0 +1,60 @@
package main
import (
"flag"
"fmt"
"os"
"strings"
"text/template"
)
var usagePrefix = `
warren is a tool for building, deploying and running multiple versions of a Go server
Usage:
warren command [args]
`
var usageTmpl = template.Must(template.New("usage").Parse(`
Commands:{{range .}}
{{.Name | printf "%-10s"}} {{.Summary}}{{end}}
`))
var commands = []*Command{
buildCmd,
}
func usage() {
fmt.Print(usagePrefix)
usageTmpl.Execute(os.Stdout, commands)
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) == 0 || args[0] == "-h" {
flag.Usage()
return
}
var cmd *Command
name := args[0]
for _, c := range commands {
if strings.HasPrefix(c.Name, name) {
cmd = c
break
}
}
if cmd == nil {
fmt.Printf("error: unknown command %q\n", name)
flag.Usage()
os.Exit(1)
}
cmd.Exec(args[1:])
}