Skip to content

Instantly share code, notes, and snippets.

@directionless
Created September 17, 2019 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save directionless/593293a8455abb622c7bf4082a68dffa to your computer and use it in GitHub Desktop.
Save directionless/593293a8455abb622c7bf4082a68dffa to your computer and use it in GitHub Desktop.
Playing with go subcommand styles
// Some snippets of how I'm current doing subcommands.
package main
type subCommand struct {
Name string
Command func(context.Context, []string) error
Description string
}
func usage(subcommands []subCommand) {
fmt.Println(`NAME:
example - do a thing
USAGE:
example [command] [options]
COMMANDS:`)
w := tabwriter.NewWriter(os.Stdout, 0, 2, 2, ' ', 0)
for _, sc := range subcommands {
fmt.Fprintf(w, "\t%s\t\t\t%s\n", sc.Name, sc.Description)
}
w.Flush()
}
//subUSage is a subcommand usage formatter.
func subUsage(name string, description string, flagset *flag.FlagSet) func() {
return func() {
w := tabwriter.NewWriter(os.Stdout, 0, 2, 2, ' ', 0)
fmt.Fprintf(w, "NAME:\n\texample %s - %s\n\n", name, description)
fmt.Fprintln(w, "OPTIONS:")
flagset.VisitAll(func(f *flag.Flag) {
fmt.Fprintf(w, " --%s\t%s (default: %q)\n", f.Name, f.Usage, f.DefValue)
})
w.Flush()
}
}
func main() {
subcommands := []subCommand{
{
Name: "upload",
Command: runUpload,
Description: "upload a binary to the distribution server and the notary server",
},
{
Name: "promote",
Command: runPromote,
Description: "promote a version to a distribution channel",
},
}
if len(os.Args) < 2 {
usage(subcommands)
os.Exit(1)
}
var run func(context.Context, []string) error
for _, sc := range subcommands {
if strings.ToLower(os.Args[1]) == sc.Name {
run = sc.Command
break
}
}
if run == nil {
fmt.Printf("Unknown sub-command: %s\n\n", os.Args[1])
usage(subcommands)
os.Exit(1)
}
if err := run(ctx, os.Args[2:]); err != nil {
checkError(err)
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment