README.md
1# subcommands #
2
3[![GoDoc](https://godoc.org/github.com/google/subcommands?status.svg)](https://godoc.org/github.com/google/subcommands)
4Subcommands is a Go package that implements a simple way for a single command to
5have many subcommands, each of which takes arguments and so forth.
6
7This is not an official Google product.
8
9## Usage ##
10
11Set up a 'print' subcommand:
12
13```go
14import (
15 "context"
16 "flag"
17 "fmt"
18 "os"
19 "strings"
20
21 "github.com/google/subcommands"
22)
23
24type printCmd struct {
25 capitalize bool
26}
27
28func (*printCmd) Name() string { return "print" }
29func (*printCmd) Synopsis() string { return "Print args to stdout." }
30func (*printCmd) Usage() string {
31 return `print [-capitalize] <some text>:
32 Print args to stdout.
33`
34}
35
36func (p *printCmd) SetFlags(f *flag.FlagSet) {
37 f.BoolVar(&p.capitalize, "capitalize", false, "capitalize output")
38}
39
40func (p *printCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
41 for _, arg := range f.Args() {
42 if p.capitalize {
43 arg = strings.ToUpper(arg)
44 }
45 fmt.Printf("%s ", arg)
46 }
47 fmt.Println()
48 return subcommands.ExitSuccess
49}
50```
51
52Register using the default Commander, also use some built in subcommands,
53finally run Execute using ExitStatus as the exit code:
54
55```go
56func main() {
57 subcommands.Register(subcommands.HelpCommand(), "")
58 subcommands.Register(subcommands.FlagsCommand(), "")
59 subcommands.Register(subcommands.CommandsCommand(), "")
60 subcommands.Register(&printCmd{}, "")
61
62 flag.Parse()
63 ctx := context.Background()
64 os.Exit(int(subcommands.Execute(ctx)))
65}
66```
67
68