# README
subcommands
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.
Usage
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)))
}
# Functions
Alias returns a Command alias which implements a "commands" subcommand.
CommandsCommand returns Command which implements a "commands" subcommand.
Execute should be called once the default flags have been initialized by flag.Parse.
FlagsCommand returns a Command which implements "flags" for the DefaultCommander.
HelpCommand returns a Command which implements "help" for the DefaultCommander.
ImportantFlag marks a top-level flag as important, which means it will be printed out as part of the output of an ordinary "help" subcommand.
NewCommander returns a new commander with the specified top-level flags and command name.
Register adds a subcommand to the supported subcommands in the specified group.
# Variables
DefaultCommander is the default commander using flag.CommandLine for flags and os.Args[0] for the command name.
# Structs
A Commander represents a set of commands.
A CommandGroup represents a set of commands about a common topic.
# Interfaces
A Command represents a single command.
# Type aliases
An ExitStatus represents a Posix exit status that a subcommand expects to be returned to the shell.