Playing with go subcommand styles
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
// 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