commit | 46f0354f63152e8801bb460d26f5b6c4c878efbb | [log] [tgz] |
---|---|---|
author | nguyen-phillip <30534889+nguyen-phillip@users.noreply.github.com> | Fri Oct 12 18:53:30 2018 -0400 |
committer | Andrew Jackura <ajackura@google.com> | Fri Oct 12 15:53:30 2018 -0700 |
tree | d7d84deb61fd978036a6b432413573833c537cb9 | |
parent | 9dd77848a6fe0ab571d4a7a32bb036dab70aff51 [diff] |
minor typo fix (#17)
Subcommands is a Go package that implements a simple way for a single command to have many subcommands, each of which takes arguments and so forth.
This is not an official Google product.
Set up a ‘print’ subcommand:
import (
"context"
"flag"
"fmt"
"os"
"strings"
"github.com/google/subcommands"
)
type printCmd struct {
capitalize bool
}
func (*printCmd) Name() string { return "print" }
func (*printCmd) Synopsis() string { return "Print args to stdout." }
func (*printCmd) Usage() string {
return `print [-capitalize] <some text>:
Print args to stdout.
`
}
func (p *printCmd) SetFlags(f *flag.FlagSet) {
f.BoolVar(&p.capitalize, "capitalize", false, "capitalize output")
}
func (p *printCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
for _, arg := range f.Args() {
if p.capitalize {
arg = strings.ToUpper(arg)
}
fmt.Printf("%s ", arg)
}
fmt.Println()
return subcommands.ExitSuccess
}
Register using the default Commander, also use some built in subcommands, finally run Execute using ExitStatus as the exit code:
func main() {
subcommands.Register(subcommands.HelpCommand(), "")
subcommands.Register(subcommands.FlagsCommand(), "")
subcommands.Register(subcommands.CommandsCommand(), "")
subcommands.Register(&printCmd{}, "")
flag.Parse()
ctx := context.Background()
os.Exit(int(subcommands.Execute(ctx)))
}