Skip to content
100644 257 lines (202 sloc) 11.8 KB
462a160 Added license
Jesse van den Kieboom authored
1 // Copyright 2012 Jesse van den Kieboom. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
b8cec17 @jessevdk Improved documentation
5 /*
6 Package flags provides an extensive command line option parser.
7 The flags package is similar in functionality to the go built-in flag package
8 but provides more options and uses reflection to provide a convenient and
9 succinct way of specifying command line options.
12 Supported features
14 The following features are supported in go-flags:
16 Options with short names (-v)
17 Options with long names (--verbose)
18 Options with and without arguments (bool v.s. other type)
19 Options with optional arguments and default values
485648f @melor Optional default values from environment variables
melor authored
20 Option default values from ENVIRONMENT_VARIABLES, including slice and map values
b8cec17 @jessevdk Improved documentation
21 Multiple option groups each containing a set of options
22 Generate and print well-formatted help message
23 Passing remaining command line arguments after -- (optional)
24 Ignoring unknown command line options (optional)
25 Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
26 Supports multiple short options -aux
27 Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
28 Supports same option multiple times (can store in slice or last option counts)
29 Supports maps
30 Supports function callbacks
31 Supports namespaces for (nested) option groups
33 Additional features specific to Windows:
34 Options with short names (/v)
35 Options with long names (/verbose)
36 Windows-style options with arguments use a colon as the delimiter
37 Modify generated help message with Windows-style / options
40 Basic usage
42 The flags package uses structs, reflection and struct field tags
43 to allow users to specify command line options. This results in very simple
44 and concise specification of your application options. For example:
46 type Options struct {
47 Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
48 }
50 This specifies one option with a short name -v and a long name --verbose.
51 When either -v or --verbose is found on the command line, a 'true' value
52 will be appended to the Verbose field. e.g. when specifying -vvv, the
53 resulting value of Verbose will be {[true, true, true]}.
55 Slice options work exactly the same as primitive type options, except that
56 whenever the option is encountered, a value is appended to the slice.
58 Map options from string to primitive type are also supported. On the command
59 line, you specify the value for such an option as key:value. For example
61 type Options struct {
62 AuthorInfo string[string] `short:"a"`
63 }
65 Then, the AuthorInfo map can be filled with something like
66 -a name:Jesse -a "surname:van den Kieboom".
68 Finally, for full control over the conversion between command line argument
69 values and options, user defined types can choose to implement the Marshaler
70 and Unmarshaler interfaces.
73 Available field tags
75 The following is a list of tags for struct fields supported by go-flags:
77 short: the short name of the option (single character)
78 long: the long name of the option
79 required: whether an option is required to appear on the command
80 line. If a required option is not present, the parser will
81 return ErrRequired (optional)
82 description: the description of the option (optional)
83 long-description: the long description of the option. Currently only
84 displayed in generated man pages (optional)
85 no-flag: if non-empty this field is ignored as an option (optional)
5631e09 @jessevdk Improve documentation of 'optional'
87 optional: whether an argument of the option is optional. When an
88 argument is optional it can only be specified using
89 --option=argument (optional)
b8cec17 @jessevdk Improved documentation
90 optional-value: the value of an optional option when the option occurs
91 without an argument. This tag can be specified multiple
92 times in the case of maps or slices (optional)
93 default: the default value of an option. This tag can be specified
94 multiple times in the case of slices or maps (optional)
95 default-mask: when specified, this value will be displayed in the help
96 instead of the actual default value. This is useful
97 mostly for hiding otherwise sensitive information from
98 showing up in the help. If default-mask takes the special
99 value "-", then no default value will be shown at all
100 (optional)
485648f @melor Optional default values from environment variables
melor authored
101 env: the default value of the option is overridden from the
102 specified environment variable, if one has been defined.
103 (optional)
104 env-delim: the 'env' default value from environment is split into
105 multiple values with the given delimiter string, use with
106 slices and maps (optional)
eee67de Fix docs typo
Gabriel Gilder authored
107 value-name: the name of the argument value (to be shown in the help)
b8cec17 @jessevdk Improved documentation
108 (optional)
1d02749 @jessevdk Implement support for limiting argument values to a certain set
109 choice: limits the values for an option to a set of values.
110 This tag can be specified mltiple times (optional)
59aa546 @jessevdk Merge remote-tracking branch 'mvo5/master'
111 hidden: the option is not visible in the help or man page.
b8cec17 @jessevdk Improved documentation
113 base: a base (radix) used to convert strings to integer values, the
114 default base is 10 (i.e. decimal) (optional)
116 ini-name: the explicit ini option name (optional)
117 no-ini: if non-empty this field is ignored as an ini option
118 (optional)
120 group: when specified on a struct field, makes the struct
121 field a separate group with the given name (optional)
122 namespace: when specified on a group struct field, the namespace
123 gets prepended to every option's long name and
124 subgroup's namespace of this group, separated by
125 the parser's namespace delimiter (optional)
126 command: when specified on a struct field, makes the struct
127 field a (sub)command with the given name (optional)
128 subcommands-optional: when specified on a command struct field, makes
129 any subcommands of that command optional (optional)
130 alias: when specified on a command struct field, adds the
131 specified name as an alias for the command. Can be
132 be specified multiple times to add more than one
133 alias (optional)
134 positional-args: when specified on a field with a struct type,
135 uses the fields of that struct to parse remaining
136 positional command line arguments into (in order
137 of the fields). If a field has a slice type,
138 then all remaining arguments will be added to it.
139 Positional arguments are optional by default,
140 unless the "required" tag is specified together
4047bd7 @jessevdk Add doc for required rest positional arguments
141 with the "positional-args" tag. The "required" tag
142 can also be set on the individual rest argument
143 fields, to require only the first N positional
144 arguments. If the "required" tag is set on the
145 rest arguments slice, then its value determines
146 the minimum amount of rest arguments that needs to
147 be provided (e.g. `required:"2"`) (optional)
1c0255a Use positional-arg-name tag
Gabriel Gilder authored
148 positional-arg-name: used on a field in a positional argument struct; name
149 of the positional argument placeholder to be shown in
150 the help (optional)
b8cec17 @jessevdk Improved documentation
152 Either the `short:` tag or the `long:` must be specified to make the field eligible as an
153 option.
156 Option groups
158 Option groups are a simple way to semantically separate your options. All
159 options in a particular group are shown together in the help under the name
160 of the group. Namespaces can be used to specify option long names more
161 precisely and emphasize the options affiliation to their group.
163 There are currently three ways to specify option groups.
165 1. Use NewNamedParser specifying the various option groups.
166 2. Use AddGroup to add a group to an existing parser.
167 3. Add a struct field to the top-level options annotated with the
168 group:"group-name" tag.
172 Commands
174 The flags package also has basic support for commands. Commands are often
175 used in monolithic applications that support various commands or actions.
176 Take git for example, all of the add, commit, checkout, etc. are called
177 commands. Using commands you can easily separate multiple functions of your
178 application.
180 There are currently two ways to specify a command.
182 1. Use AddCommand on an existing parser.
183 2. Add a struct field to your options struct annotated with the
184 command:"command-name" tag.
186 The most common, idiomatic way to implement commands is to define a global
187 parser instance and implement each command in a separate file. These
188 command files should define a go init function which calls AddCommand on
189 the global parser.
191 When parsing ends and there is an active command and that command implements
192 the Commander interface, then its Execute method will be run with the
193 remaining command line arguments.
195 Command structs can have options which become valid to parse after the
1b89bf7 @jessevdk Allow specifying parent options after subcommands
196 command has been specified on the command line, in addition to the options
197 of all the parent commands. I.e. considering a -v flag on the parser and an
198 add command, the following are equivalent:
b8cec17 @jessevdk Improved documentation
1b89bf7 @jessevdk Allow specifying parent options after subcommands
200 ./app -v add
201 ./app add -v
203 However, if the -v flag is defined on the add command, then the first of
204 the two examples above would fail since the -v flag is not defined before
205 the add command.
b8cec17 @jessevdk Improved documentation
208 Completion
210 go-flags has builtin support to provide bash completion of flags, commands
211 and argument values. To use completion, the binary which uses go-flags
212 can be invoked in a special environment to list completion of the current
213 command line argument. It should be noted that this `executes` your application,
214 and it is up to the user to make sure there are no negative side effects (for
215 example from init functions).
6c35a71 @zimmski remove "__complete" command invocation
zimmski authored
217 Setting the environment variable `GO_FLAGS_COMPLETION=1` enables completion
218 by replacing the argument parsing routine with the completion routine which
219 outputs completions for the passed arguments. The basic invocation to
220 complete a set of arguments is therefore:
b8cec17 @jessevdk Improved documentation
6c35a71 @zimmski remove "__complete" command invocation
zimmski authored
222 GO_FLAGS_COMPLETION=1 ./completion-example arg1 arg2 arg3
b8cec17 @jessevdk Improved documentation
224 where `completion-example` is the binary, `arg1` and `arg2` are
225 the current arguments, and `arg3` (the last argument) is the argument
1f8fc78 @jessevdk Implement verbose completion
226 to be completed. If the GO_FLAGS_COMPLETION is set to "verbose", then
227 descriptions of possible completion items will also be shown, if there
228 are more than 1 completion items.
b8cec17 @jessevdk Improved documentation
230 To use this with bash completion, a simple file can be written which
231 calls the binary which supports go-flags completion:
233 _completion_example() {
234 # All arguments except the first one
235 args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
ec11066 @jessevdk Only split completions on newlines
237 # Only split on newlines
238 local IFS=$'\n'
b8cec17 @jessevdk Improved documentation
240 # Call completion (note that the first element of COMP_WORDS is
241 # the executable itself)
6c35a71 @zimmski remove "__complete" command invocation
zimmski authored
242 COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
b8cec17 @jessevdk Improved documentation
243 return 0
244 }
246 complete -F _completion_example completion-example
f287404 @zimmski PassDoubleDash is required for completion
zimmski authored
248 Completion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.
b8cec17 @jessevdk Improved documentation
250 Customized completion for argument values is supported by implementing
251 the flags.Completer interface for the argument value type. An example
252 of a type which does so is the flags.Filename type, an alias of string
cddcf3a @sqs Support completion of positional "rest" (slice/array) args
sqs authored
253 allowing simple filename completion. A slice or array argument value
254 whose element type implements flags.Completer will also be completed.
b8cec17 @jessevdk Improved documentation
255 */
c3d1968 Initial import
Jesse van den Kieboom authored
256 package flags
Something went wrong with that request. Please try again.