commit | 636abe8753b82e6eefa1beca9f46e49b470aa3d7 | [log] [tgz] |
---|---|---|
author | Ian Lewis <[email protected]> | Thu May 09 01:05:03 2019 +0900 |
committer | Andrew Jackura <[email protected]> | Wed May 08 09:05:03 2019 -0700 |
tree | ea0df52969a988d1dc83687340a7698ce55d51ce | |
parent | d47216cd17848d55a33e6f651cbe408243ed55b8 [diff] |
Allow users to override default help behavior. (#23) - CommandGroup is now public. - Commander and CommandGroup name is accessible by Name() - Commander, CommandGroup, and Command explations are now printed by overridable functions set on the Commander. - Subcommands are visitable by the VisitCommands() method. - Command groups are visitable by the VisitGroups() method. - Important flags are visitable by the VisitAllImportant() method. - Top level flags are visitable by the VisitAll() method.
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)))
}