60 lines
1.1 KiB
Go
60 lines
1.1 KiB
Go
package warren
|
|
|
|
import (
|
|
"flag"
|
|
"os"
|
|
"text/template"
|
|
)
|
|
|
|
type ICommand interface {
|
|
GetName() string
|
|
GetSummary() string
|
|
}
|
|
|
|
var commands map[string]ICommand = make(map[string]ICommand)
|
|
|
|
// 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 // multiline doc about using cmd
|
|
Summary string // one line info about cmd
|
|
}
|
|
|
|
func (c *Command) GetName() string {
|
|
return c.Name
|
|
}
|
|
|
|
func (c *Command) GetSummary() string {
|
|
return c.Summary
|
|
}
|
|
|
|
func (c *Command) Exec(args []string) {
|
|
c.Flag.Usage = func() {
|
|
// helpFunc(c, c.Name)
|
|
}
|
|
c.Flag.Parse(args)
|
|
c.Run(c, c.Flag.Args()...)
|
|
}
|
|
|
|
func RegisterCommand(c ICommand) {
|
|
commands[c.GetName()] = c
|
|
}
|
|
|
|
func GetCommand(name string) ICommand {
|
|
return commands[name]
|
|
}
|
|
|
|
var usageTmpl = template.Must(template.New("usage").Parse(`
|
|
Commands:{{range $k, $v := .}}
|
|
{{$v.GetName| printf "%-10s"}} {{$v.GetSummary}}{{end}}
|
|
`))
|
|
|
|
func PrintCommandUsage() {
|
|
usageTmpl.Execute(os.Stdout, commands)
|
|
}
|