Last active
August 29, 2015 14:15
-
-
Save fluffysquirrels/e2f251a7e775fe8c1df5 to your computer and use it in GitHub Desktop.
Kingpin independent commands pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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