Documentation ¶
Overview ¶
Package flags provides an extensive command line option parser. The flags package is similar in functionality to the go built-in flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.
Supported features ¶
The following features are supported in go-flags:
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 Option default values from ENVIRONMENT_VARIABLES, including slice and map 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 Supports namespaces for (nested) option groups
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
Basic usage ¶
The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and concise 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 ¶
The following is a list of tags for struct fields supported by go-flags:
short: the short name of the option (single character) long: the long name of the option required: whether an option is required to appear on the command line. If a required option is not present, the parser will return ErrRequired (optional) description: the description of the option (optional) long-description: the long description of the option. Currently only displayed in generated man pages (optional) no-flag: if non-empty this field is ignored as an 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) env: the default value of the option is overridden from the specified environment variable, if one has been defined. (optional) env-delim: the 'env' default value from environment is split into multiple values with the given delimiter string, use with slices and maps (optional) value-name: the name of the argument value (to be shown in the help, (optional) base: a base (radix) used to convert strings to integer values, the default base is 10 (i.e. decimal) (optional) ini-name: the explicit ini option name (optional) no-ini: if non-empty this field is ignored as an ini option (optional) group: when specified on a struct field, makes the struct field a separate group with the given name (optional) namespace: when specified on a group struct field, the namespace gets prepended to every option's long name and subgroup's namespace of this group, separated by the parser's namespace delimiter (optional) command: when specified on a struct field, makes the struct field a (sub)command with the given name (optional) subcommands-optional: when specified on a command struct field, makes any subcommands of that command optional (optional) alias: when specified on a command struct field, adds the specified name as an alias for the command. Can be be specified multiple times to add more than one alias (optional) positional-args: when specified on a field with a struct type, uses the fields of that struct to parse remaining positional command line arguments into (in order of the fields). If a field has a slice type, then all remaining arguments will be added to it. Positional arguments are optional by default, unless the "required" tag is specified together with the "positional-args" tag (optional)
Either the `short:` tag or the `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. All options in a particular group are shown together in the help under the name of the group. Namespaces can be used to specify option long names more precisely and emphasize the options affiliation to their 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 top-level 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 specify 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 top-level option "-v" and a command "add":
Valid: ./app -v add Invalid: ./app add -v
Completion ¶
go-flags has builtin support to provide bash completion of flags, commands and argument values. To use completion, the binary which uses go-flags can be invoked in a special environment to list completion of the current command line argument. It should be noted that this `executes` your application, and it is up to the user to make sure there are no negative side effects (for example from init functions).
Setting the environment variable `GO_FLAGS_COMPLETION=1` enables completion by replacing the argument parsing routine with the completion routine which outputs completions for the passed arguments. The basic invocation to complete a set of arguments is therefore:
GO_FLAGS_COMPLETION=1 ./completion-example arg1 arg2 arg3
where `completion-example` is the binary, `arg1` and `arg2` are the current arguments, and `arg3` (the last argument) is the argument to be completed. If the GO_FLAGS_COMPLETION is set to "verbose", then descriptions of possible completion items will also be shown, if there are more than 1 completion items.
To use this with bash completion, a simple file can be written which calls the binary which supports go-flags completion:
_completion_example() { # All arguments except the first one args=("${COMP_WORDS[@]:1:$COMP_CWORD}") # Only split on newlines local IFS=$'\n' # Call completion (note that the first element of COMP_WORDS is # the executable itself) COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}")) return 0 } complete -F _completion_example completion-example
Completion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.
Customized completion for argument values is supported by implementing the flags.Completer interface for the argument value type. An example of a type which does so is the flags.Filename type, an alias of string allowing simple filename completion. A slice or array argument value whose element type implements flags.Completer will also be completed.
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"` // Example of a filename (useful for completion) Filename Filename `long:"filename" description:"A filename"` // Example of positional arguments Args struct { Id string Num int Rest []string } `positional-args:"yes" required:"yes"` } // 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", "--filename", "hello.go", "id", "10", "remaining1", "remaining2", } // 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 _, err := ParseArgs(&opts, args) if err != nil { panic(err) } 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("Filename: %v\n", opts.Filename) fmt.Printf("Args.Id: %s\n", opts.Args.Id) fmt.Printf("Args.Num: %d\n", opts.Args.Num) fmt.Printf("Args.Rest: %v\n", opts.Args.Rest)
Output: Verbosity: [true true] Offset: 5 Name: Me Ptr: 3 StringSlice: [hello world] PtrSlice: [hello world] IntMap: [a:1 b:5] Filename: hello.go Args.Id: id Args.Num: 10 Args.Rest: [remaining1 remaining2]
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 Arg
- 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) Args() []*Arg
- func (c *Command) Commands() []*Command
- func (c *Command) Find(name string) *Command
- type Commander
- type Completer
- type Completion
- type Error
- type ErrorType
- type Filename
- type Group
- type IniError
- type IniOptions
- type IniParser
- type Marshaler
- type Option
- type Options
- type Parser
- type SplitArgument
- type Unmarshaler
- type Usage
Examples ¶
Constants ¶
const ( // IniNone indicates no options. IniNone IniOptions = 0 // IniIncludeDefaults indicates that default values should be written. IniIncludeDefaults = 1 << iota // IniCommentDefaults indicates that if IniIncludeDefaults is used // options with default values are written but commented out. IniCommentDefaults // IniIncludeComments indicates that comments containing the description // of an option should be written. 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 formatted 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 Arg ¶
type Arg struct { // The name of the positional argument (used in the help) Name string // A description of the positional argument (used in the help) Description string // contains filtered or unexported fields }
Arg represents a positional argument on the command line.
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 // Whether subcommands are optional SubcommandsOptional bool // Aliases for the command Aliases []string // Whether positional arguments are required ArgsRequired bool // 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 Completer ¶
type Completer interface { // Complete receives a prefix representing a (partial) value // for its type and should provide a list of possible valid // completions. Complete(match string) []Completion }
Completer is an interface which can be implemented by types to provide custom command line argument completion.
type Completion ¶
type Completion struct { // The completed item Item string // A description of the completed item (optional) Description string }
Completion is a type containing information of a completion.
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 built-in 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 // ErrCommandRequired indicates that a command was required but not // specified ErrCommandRequired // ErrUnknownCommand indicates that an unknown command was specified. ErrUnknownCommand )
type Filename ¶
type Filename string
Filename is a string alias which provides filename completion.
func (*Filename) Complete ¶
func (f *Filename) Complete(match string) []Completion
Complete returns a list of existing files with the given prefix.
type Group ¶
type Group struct { // A short description of the group. The // short description is primarily used in the built-in 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 built-in generated help and man pages. LongDescription string // The namespace of the group Namespace 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 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 formatted strings.
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 format. 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 built-in 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 // The optional environment default value key name. EnvDefaultKey string // The optional delimiter string for EnvDefaultKey values. EnvDefaultDelim 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.
func (*Option) LongNameWithNamespace ¶
LongNameWithNamespace returns the option's long name with the group namespaces prepended by walking up the option's group tree. Namespaces and the long name itself are separated by the parser's namespace delimiter. If the long name is empty an empty string is returned.
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 // NamespaceDelimiter separates group namespaces and option long names NamespaceDelimiter string // UnknownOptionsHandler is a function which gets called when the parser // encounters an unknown option. The function receives the unknown option // name, a SplitArgument which specifies its value if set with an argument // separator, and the remaining command line arguments. // It should return a new list of remaining arguments to continue parsing, // or an error to indicate a parse failure. UnknownOptionHandler func(option string, arg SplitArgument, args []string) ([]string, error) // 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 built-in 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 SplitArgument ¶
type SplitArgument interface { // String returns the option's value as a string, and a boolean indicating // if the option was present. Value() (string, bool) }
SplitArgument represents the argument value of an option that was passed using an argument separator.
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.