Skip to content

Instantly share code, notes, and snippets.

@fluffysquirrels
Last active August 29, 2015 14:15
Show Gist options
  • Save fluffysquirrels/e2f251a7e775fe8c1df5 to your computer and use it in GitHub Desktop.
Save fluffysquirrels/e2f251a7e775fe8c1df5 to your computer and use it in GitHub Desktop.
Kingpin independent commands pattern
package main
import (
"fmt"
"github.com/alecthomas/kingpin"
)
type cmd struct {
*kingpin.CmdClause
ActionFunc func()
Name string
}
func addCommand(name string, help string) *cmd {
cmdClause := kingpinApp.Command(name, help)
return &cmd {
CmdClause: cmdClause,
Name: name,
}
}
func (c *cmd) Action(action func()) {
cmdActions[c.Name] = action
c.ActionFunc = action
}
var cmdActions = make(map[string]func())
func runAction(name string) {
actionFn, foundAction := cmdActions[name]
if !foundAction {
panic(fmt.Sprintf("Action not found: %s", name))
}
actionFn()
}
package main
import (
"flag"
"fmt"
"os"
"github.com/alecthomas/kingpin"
"github.com/golang/glog"
"ah.name/bookminer/util"
)
var kingpinApp = kingpin.New("cfb-cmd", "Computer finds books command runner")
func main() {
flag.Parse()
util.SetGlogConfig()
glog.CopyStandardLogTo("WARNING")
cmd, err := kingpinApp.Parse(flag.Args())
if err != nil || cmd == "" {
fmt.Fprintln(os.Stderr, err)
kingpinApp.Usage(os.Stderr)
flag.PrintDefaults()
os.Exit(1)
}
runAction(cmd)
}
func init() {
cmd := addCommand("refresh-watch", "Refresh a single watch")
argWatchId := cmd.Arg("watch-id", "Id of watch to refresh").Required().Int64()
cmd.Action(func() {
watch.RefreshWatchById(*argWatchId)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment