commit | ce3d4cfc062faac7115d44e5befec8b5a08c3faa | [log] [tgz] |
---|---|---|
author | Andrew Jackura <ajackura@google.com> | Fri Feb 24 09:58:46 2017 -0800 |
committer | GitHub <noreply@github.com> | Fri Feb 24 09:58:46 2017 -0800 |
tree | 883f315beff856a2ef51fe7cb8c88c28be46aa29 | |
parent | 43f65adde14103c0e32a37df5a4abfe7b19c7251 [diff] | |
parent | 727391c61f2139c84188e5bdbd887b86812170bc [diff] |
Merge pull request #9 from kazuminn/add-godocl-link add godoc link
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)))
}