Documentation ¶
Overview ¶
Package flags provides an extensive command line option parser. The flags package is similar in functionality to the go builtin flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.
Supported features:
Options with short names (-v) Options with long names (--verbose) Options with and without arguments (bool v.s. other type) Options with optional arguments and default values Multiple option groups each containing a set of options Generate and print well-formatted help message Passing remaining command line arguments after -- (optional) Ignoring unknown command line options (optional) Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification Supports multiple short options -aux Supports all primitive go types (string, int{8..64}, uint{8..64}, float) Supports same option multiple times (can store in slice or last option counts) Supports maps Supports function callbacks
Additional features specific to Windows:
Options with short names (/v) Options with long names (/verbose) Windows-style options with arguments use a colon as the delimiter Modify generated help message with Windows-style / options
The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and consise specification of your application options. For example:
type Options struct { Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` }
This specifies one option with a short name -v and a long name --verbose. When either -v or --verbose is found on the command line, a 'true' value will be appended to the Verbose field. e.g. when specifying -vvv, the resulting value of Verbose will be {[true, true, true]}.
Slice options work exactly the same as primitive type options, except that whenever the option is encountered, a value is appended to the slice.
Map options from string to primitive type are also supported. On the command line, you specify the value for such an option as key:value. For example
type Options struct { AuthorInfo string[string] `short:"a"` }
Then, the AuthorInfo map can be filled with something like -a name:Jesse -a "surname:van den Kieboom".
Finally, for full control over the conversion between command line argument values and options, user defined types can choose to implement the Marshaler and Unmarshaler interfaces.
Available field tags:
short: the short name of the option (single character) long: the long name of the option description: the description of the option (optional) optional: whether an argument of the option is optional (optional) optional-value: the value of an optional option when the option occurs without an argument. This tag can be specified multiple times in the case of maps or slices (optional) default: the default value of an option. This tag can be specified multiple times in the case of slices or maps (optional). default-mask: when specified, this value will be displayed in the help instead of the actual default value. This is useful mostly for hiding otherwise sensitive information from showing up in the help. If default-mask takes the special value "-", then no default value will be shown at all (optional) required: whether an option is required to appear on the command line. If a required option is not present, the parser will return ErrRequired. base: a base (radix) used to convert strings to integer values, the default base is 10 (i.e. decimal) (optional) value-name: the name of the argument value (to be shown in the help, (optional) group: when specified on a struct field, makes the struct field a separate group with the given name (optional). command: when specified on a struct field, makes the struct field a (sub)command with the given name (optional).
Either short: or long: must be specified to make the field eligible as an option.
Option groups:
Option groups are a simple way to semantically separate your options. The only real difference is in how your options will appear in the builtin generated help. All options in a particular group are shown together in the help under the name of the group.
There are currently three ways to specify option groups.
- Use NewNamedParser specifying the various option groups.
- Use AddGroup to add a group to an existing parser.
- Add a struct field to the toplevel options annotated with the group:"group-name" tag.
Commands:
The flags package also has basic support for commands. Commands are often used in monolithic applications that support various commands or actions. Take git for example, all of the add, commit, checkout, etc. are called commands. Using commands you can easily separate multiple functions of your application.
There are currently two ways to specifiy a command.
- Use AddCommand on an existing parser.
- Add a struct field to your options struct annotated with the command:"command-name" tag.
The most common, idiomatic way to implement commands is to define a global parser instance and implement each command in a separate file. These command files should define a go init function which calls AddCommand on the global parser.
When parsing ends and there is an active command and that command implements the Commander interface, then its Execute method will be run with the remaining command line arguments.
Command structs can have options which become valid to parse after the command has been specified on the command line. It is currently not valid to specify options from the parent level of the command after the command name has occurred. Thus, given a toplevel option "-v" and a command "add":
Valid: ./app -v add Invalid: ./app add -v
Example ¶
var opts struct { // Slice of bool will append 'true' each time the option // is encountered (can be set multiple times, like -vvv) Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` // Example of automatic marshalling to desired type (uint) Offset uint `long:"offset" description:"Offset"` // Example of a callback, called each time the option is found. Call func(string) `short:"c" description:"Call phone number"` // Example of a required flag Name string `short:"n" long:"name" description:"A name" required:"true"` // Example of a value name File string `short:"f" long:"file" description:"A file" value-name:"FILE"` // Example of a pointer Ptr *int `short:"p" description:"A pointer to an integer"` // Example of a slice of strings StringSlice []string `short:"s" description:"A slice of strings"` // Example of a slice of pointers PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` // Example of a map IntMap map[string]int `long:"intmap" description:"A map from string to int"` } // Callback which will invoke callto:<argument> to call a number. // Note that this works just on OS X (and probably only with // Skype) but it shows the idea. opts.Call = func(num string) { cmd := exec.Command("open", "callto:"+num) cmd.Start() cmd.Process.Release() } // Make some fake arguments to parse. args := []string{ "-vv", "--offset=5", "-n", "Me", "-p", "3", "-s", "hello", "-s", "world", "--ptrslice", "hello", "--ptrslice", "world", "--intmap", "a:1", "--intmap", "b:5", "arg1", "arg2", "arg3", } // Parse flags from `args'. Note that here we use flags.ParseArgs for // the sake of making a working example. Normally, you would simply use // flags.Parse(&opts) which uses os.Args args, err := ParseArgs(&opts, args) if err != nil { panic(err) os.Exit(1) } fmt.Printf("Verbosity: %v\n", opts.Verbose) fmt.Printf("Offset: %d\n", opts.Offset) fmt.Printf("Name: %s\n", opts.Name) fmt.Printf("Ptr: %d\n", *opts.Ptr) fmt.Printf("StringSlice: %v\n", opts.StringSlice) fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1]) fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"]) fmt.Printf("Remaining args: %s\n", strings.Join(args, " "))
Output: Verbosity: [true true] Offset: 5 Name: Me Ptr: 3 StringSlice: [hello world] PtrSlice: [hello world] IntMap: [a:1 b:5] Remaining args: arg1 arg2 arg3
Index ¶
- Constants
- Variables
- func IniParse(filename string, data interface{}) error
- func Parse(data interface{}) ([]string, error)
- func ParseArgs(data interface{}, args []string) ([]string, error)
- type Command
- func (c *Command) AddCommand(command string, shortDescription string, longDescription string, ...) (*Command, error)
- func (c *Command) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error)
- func (c *Command) Commands() []*Command
- func (c *Command) Find(name string) *Command
- type Commander
- type Error
- type ErrorType
- type Group
- type IniError
- type IniOptions
- type IniParser
- type Marshaler
- type Option
- type Options
- type Parser
- type Unmarshaler
- type Usage
Examples ¶
Constants ¶
const ( // IniNone indicates no options. IniNone IniOptions = 0 // IniIncludeDefaults indicates that default values should be written // when writing options to an ini file. IniIncludeDefaults = 1 << iota // IniIncludeComments indicates that comments containing the description // of an option should be written when writing options to an ini file. IniIncludeComments // IniDefault provides a default set of options. IniDefault = IniIncludeComments )
const ( // None indicates no options. None Options = 0 // HelpFlag adds a default Help Options group to the parser containing // -h and --help options. When either -h or --help is specified on the // command line, the parser will return the special error of type // ErrHelp. When PrintErrors is also specified, then the help message // will also be automatically printed to os.Stderr. HelpFlag = 1 << iota // PassDoubleDash passes all arguments after a double dash, --, as // remaining command line arguments (i.e. they will not be parsed for // flags). PassDoubleDash // IgnoreUnknown ignores any unknown options and passes them as // remaining command line arguments instead of generating an error. IgnoreUnknown // PrintErrors prints any errors which occurred during parsing to // os.Stderr. PrintErrors // PassAfterNonOption passes all arguments after the first non option // as remaining command line arguments. This is equivalent to strict // POSIX processing. PassAfterNonOption // Default is a convenient default set of options which should cover // most of the uses of the flags package. Default = HelpFlag | PrintErrors | PassDoubleDash )
Variables ¶
var ErrNotPointerToStruct = errors.New("provided data is not a pointer to struct")
ErrNotPointerToStruct indicates that a provided data container is not a pointer to a struct. Only pointers to structs are valid data containers for options.
Functions ¶
func IniParse ¶
IniParse is a convenience function to parse command line options with default settings from an ini file. The provided data is a pointer to a struct representing the default option group (named "Application Options"). For more control, use flags.NewParser.
func Parse ¶
Parse is a convenience function to parse command line options with default settings. The provided data is a pointer to a struct representing the default option group (named "Application Options"). For more control, use flags.NewParser.
func ParseArgs ¶
ParseArgs is a convenience function to parse command line options with default settings. The provided data is a pointer to a struct representing the default option group (named "Application Options"). The args argument is the list of command line arguments to parse. If you just want to parse the default program command line arguments (i.e. os.Args), then use flags.Parse instead. For more control, use flags.NewParser.
Types ¶
type Command ¶
type Command struct { // Embedded, see Group for more information *Group // The name by which the command can be invoked Name string // The active sub command (set by parsing) or nil Active *Command // contains filtered or unexported fields }
Command represents an application command. Commands can be added to the parser (which itself is a command) and are selected/executed when its name is specified on the command line. The Command type embeds a Group and therefore also carries a set of command specific options.
func (*Command) AddCommand ¶
func (c *Command) AddCommand(command string, shortDescription string, longDescription string, data interface{}) (*Command, error)
AddCommand adds a new command to the parser with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the command. The provided data can implement the Command and Usage interfaces.
func (*Command) AddGroup ¶
func (c *Command) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error)
AddGroup adds a new group to the command with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the group.
type Commander ¶
type Commander interface { // Execute will be called for the last active (sub)command. The // args argument contains the remaining command line arguments. The // error that Execute returns will be eventually passed out of the // Parse method of the Parser. Execute(args []string) error }
Commander is an interface which can be implemented by any command added in the options. When implemented, the Execute method will be called for the last specified (sub)command providing the remaining command line arguments.
type Error ¶
Error represents a parser error. The error returned from Parse is of this type. The error contains both a Type and Message.
type ErrorType ¶
type ErrorType uint
ErrorType represents the type of error.
const ( // ErrUnknown indicates a generic error. ErrUnknown ErrorType = iota // ErrExpectedArgument indicates that an argument was expected. ErrExpectedArgument // ErrUnknownFlag indicates an unknown flag. ErrUnknownFlag // ErrUnknownGroup indicates an unknown group. ErrUnknownGroup // ErrMarshal indicates a marshalling error while converting values. ErrMarshal // ErrHelp indicates that the builtin help was shown (the error // contains the help message). ErrHelp // ErrNoArgumentForBool indicates that an argument was given for a // boolean flag (which don't not take any arguments). ErrNoArgumentForBool // ErrRequired indicates that a required flag was not provided. ErrRequired // ErrShortNameTooLong indicates that a short flag name was specified, // longer than one character. ErrShortNameTooLong // ErrDuplicatedFlag indicates that a short or long flag has been // defined more than once ErrDuplicatedFlag // ErrTag indicates an error while parsing flag tags. ErrTag )
type Group ¶
type Group struct { // A short description of the group. The // short description is primarily used in the builtin generated help // message ShortDescription string // A long description of the group. The long // description is primarily used to present information on commands // (Command embeds Group) in the builtin generated help and man pages. LongDescription string // contains filtered or unexported fields }
Group represents an option group. Option groups can be used to logically group options together under a description. Groups are only used to provide more structure to options both for the user (as displayed in the help message) and for you, since groups can be nested.
func (*Group) AddGroup ¶
func (g *Group) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error)
AddGroup adds a new group to the command with the given name and data. The data needs to be a pointer to a struct from which the fields indicate which options are in the group.
func (*Group) Find ¶
Find locates the subgroup with the given short description and returns it. If no such group can be found Find will return nil. Note that the description is matched case insensitively.
type IniError ¶
type IniError struct { // The error message. Message string // The filename of the file in which the error occurred. File string // The line number at which the error occurred. LineNumber uint }
IniError contains location information on where in the ini file an error occured.
type IniParser ¶
type IniParser struct {
// contains filtered or unexported fields
}
IniParser is a utility to read and write flags options from and to ini files.
func NewIniParser ¶
NewIniParser creates a new ini parser for a given Parser.
func (*IniParser) Parse ¶
Parse parses flags from an ini format. You can use ParseFile as a convenience function to parse from a filename instead of a general io.Reader.
The format of the ini file is as follows:
[Option group name] option = value
Each section in the ini file represents an option group or command in the flags parser. The default flags parser option group (i.e. when using flags.Parse) is named 'Application Options'. The ini option name is matched in the following order:
- Compared to the ini-name tag on the option struct field (if present)
- Compared to the struct field name
- Compared to the option long name (if present)
- Compared to the option short name (if present)
Sections for nested groups and commands can be addressed using a dot `.' namespacing notation (i.e [subcommand.Options]). Group section names are matched case insensitive.
The returned errors can be of the type flags.Error or flags.IniError.
func (*IniParser) ParseFile ¶
ParseFile parses flags from an ini formatted file. See Parse for more information on the ini file foramt. The returned errors can be of the type flags.Error or flags.IniError.
func (*IniParser) Write ¶
func (i *IniParser) Write(writer io.Writer, options IniOptions)
Write writes the current values of all the flags to an ini format. See Parse for more information on the ini file format. You typically call this only after settings have been parsed since the default values of each option are stored just before parsing the flags (this is only relevant when IniIncludeDefaults is _not_ set in options).
type Marshaler ¶
type Marshaler interface { // MarshalFlag marshals a flag value to its string representation. MarshalFlag() (string, error) }
Marshaler is the interface implemented by types that can marshal themselves to a string representation of the flag.
type Option ¶
type Option struct { // The description of the option flag. This description is shown // automatically in the builtin help. Description string // The short name of the option (a single character). If not 0, the // option flag can be 'activated' using -<ShortName>. Either ShortName // or LongName needs to be non-empty. ShortName rune // The long name of the option. If not "", the option flag can be // activated using --<LongName>. Either ShortName or LongName needs // to be non-empty. LongName string // The default value of the option. Default []string // If true, specifies that the argument to an option flag is optional. // When no argument to the flag is specified on the command line, the // value of Default will be set in the field this option represents. // This is only valid for non-boolean options. OptionalArgument bool // The optional value of the option. The optional value is used when // the option flag is marked as having an OptionalArgument. This means // that when the flag is specified, but no option argument is given, // the value of the field this option represents will be set to // OptionalValue. This is only valid for non-boolean options. OptionalValue []string // If true, the option _must_ be specified on the command line. If the // option is not specified, the parser will generate an ErrRequired type // error. Required bool // A name for the value of an option shown in the Help as --flag [ValueName] ValueName string // A mask value to show in the help instead of the default value. This // is useful for hiding sensitive information in the help, such as // passwords. DefaultMask string // contains filtered or unexported fields }
Option flag information. Contains a description of the option, short and long name as well as a default value and whether an argument for this flag is optional.
type Options ¶
type Options uint
Options provides parser options that change the behavior of the option parser.
type Parser ¶
type Parser struct { // Embedded, see Command for more information *Command // A usage string to be displayed in the help message. Usage string // Option flags changing the behavior of the parser. Options Options // contains filtered or unexported fields }
A Parser provides command line option parsing. It can contain several option groups each with their own set of options.
func NewNamedParser ¶
NewNamedParser creates a new parser. The appname is used to display the executable name in the builtin help message. Option groups and commands can be added to this parser by using AddGroup and AddCommand.
func NewParser ¶
NewParser creates a new parser. It uses os.Args[0] as the application name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for more details). The provided data is a pointer to a struct representing the default option group (named "Application Options"), or nil if the default group should not be added. The options parameter specifies a set of options for the parser.
func (*Parser) Parse ¶
Parse parses the command line arguments from os.Args using Parser.ParseArgs. For more detailed information see ParseArgs.
func (*Parser) ParseArgs ¶
ParseArgs parses the command line arguments according to the option groups that were added to the parser. On successful parsing of the arguments, the remaining, non-option, arguments (if any) are returned. The returned error indicates a parsing error and can be used with PrintError to display contextual information on where the error occurred exactly.
When the common help group has been added (AddHelp) and either -h or --help was specified in the command line arguments, a help message will be automatically printed. Furthermore, the special error type ErrHelp is returned. It is up to the caller to exit the program if so desired.
func (*Parser) WriteHelp ¶
WriteHelp writes a help message containing all the possible options and their descriptions to the provided writer. Note that the HelpFlag parser option provides a convenient way to add a -h/--help option group to the command line parser which will automatically show the help messages using this method.
func (*Parser) WriteManPage ¶
WriteManPage writes a basic man page in groff format to the specified writer.
type Unmarshaler ¶
type Unmarshaler interface { // UnmarshalFlag unmarshals a string value representation to the flag // value (which therefore needs to be a pointer receiver). UnmarshalFlag(value string) error }
Unmarshaler is the interface implemented by types that can unmarshal a flag argument to themselves. The provided value is directly passed from the command line.