commit | c230ecf7bb5d565c77c0c862d40d20d082c509f9 | [log] [tgz] |
---|---|---|
author | Shun Takebayashi <shun@takebayashi.asia> | Fri Feb 03 22:12:21 2017 +0900 |
committer | Shun Takebayashi <shun@takebayashi.asia> | Fri Feb 03 22:12:21 2017 +0900 |
tree | 021c1276285bd2b5d4af7fa9c744291aa8c02eca | |
parent | a71b91e238406bd68766ee52db63bebedce0e9f6 [diff] |
Update Usage in README
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)))
}