Documentation ¶
Overview ¶
Package sub provides a subcommand parsing wrapper for the flag package.
This package is designed to be very minimal and simple to use. Just create a Commander, register some commands, and run it.
For example:
var c sub.Commander c.Register(c.HelpCmd()) c.Help = `This is just a simple example for documentation purposes.` c.Register(&someExampleCmd{}) c.Register(&anotherOne{}) os.Args[0] = filepath.Base(os.Args[0]) err := c.Run(os.Args) if err != nil { if err == flag.ErrHelp { os.Exit(2) } fmt.Fprintf(os.Stderr, "Error: %v", err) os.Exit(1) }
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Command ¶
type Command interface { // Name is the name of the command. This is what the user is // expected to enter in order to call this specific command. Name() string // Desc is a short description of the command. Desc() string // Help is a longer help message. It should ideally start with a // usage line. It does not need any particular whitespace around it. Help() string // Flags fills the given FlagSet. If the command has any flags, they // should be filled here. In most cases, the client will probably // want to use the Var variants of the flag declaration functions // with fields in the command's underlying type so that their values // can be accessed when the command is run. Flags(fset *flag.FlagSet) // Run actually runs the command. It is passed any leftover // arguments after the flags have been parsed. Run(args []string) error }
Command is a subcommand.
type Commander ¶
type Commander struct { // Output is the location to which output is written. Defaults to // os.Stderr. Output io.Writer // Help is text displayed when the help command is run without any // arguments. Help string // Flags is a function that is called to populate the global // FlagSet. If it is non-nil, then it is assumed that there are // global flags, which changes some text formatting. Flags func(*flag.FlagSet) // contains filtered or unexported fields }
A Commander controls a set of subcommands.
func (*Commander) HelpCmd ¶
HelpCmd returns a "help" Command that provides help for c. If clients want an explicit "help" command to be available, this must be manually registered.
func (*Commander) Register ¶
Register registers a command with the Commander. If a command with the same name as cmd already exists, it is replaced with cmd.
func (*Commander) Run ¶
Run runs the commander against the given arguments. The first argument should be the name of the executable. In many cases, this should be filepath.Base(os.Args[0]).
If there is a problem with args, such as an attempt to call a non-existent command, flag.ErrHelp is returned. Otherwise, any errors returned from subcommand's Run method are returned directly.