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.
4
5/*
6Package flags provides an extensive command line option parser.
7The flags package is similar in functionality to the go built-in flag package
8but provides more options and uses reflection to provide a convenient and
9succinct way of specifying command line options.
10
11
12Supported features
13
14The following features are supported in go-flags:
15
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
20    Option default values from ENVIRONMENT_VARIABLES, including slice and map values
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
32
33Additional 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
38    Windows style options can be disabled at build time using the "forceposix"
39    build tag
40
41
42Basic usage
43
44The flags package uses structs, reflection and struct field tags
45to allow users to specify command line options. This results in very simple
46and concise specification of your application options. For example:
47
48    type Options struct {
49        Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
50    }
51
52This specifies one option with a short name -v and a long name --verbose.
53When either -v or --verbose is found on the command line, a 'true' value
54will be appended to the Verbose field. e.g. when specifying -vvv, the
55resulting value of Verbose will be {[true, true, true]}.
56
57Slice options work exactly the same as primitive type options, except that
58whenever the option is encountered, a value is appended to the slice.
59
60Map options from string to primitive type are also supported. On the command
61line, you specify the value for such an option as key:value. For example
62
63    type Options struct {
64        AuthorInfo string[string] `short:"a"`
65    }
66
67Then, the AuthorInfo map can be filled with something like
68-a name:Jesse -a "surname:van den Kieboom".
69
70Finally, for full control over the conversion between command line argument
71values and options, user defined types can choose to implement the Marshaler
72and Unmarshaler interfaces.
73
74
75Available field tags
76
77The following is a list of tags for struct fields supported by go-flags:
78
79    short:            the short name of the option (single character)
80    long:             the long name of the option
81    required:         if non empty, makes the option required to appear on the command
82                      line. If a required option is not present, the parser will
83                      return ErrRequired (optional)
84    description:      the description of the option (optional)
85    long-description: the long description of the option. Currently only
86                      displayed in generated man pages (optional)
87    no-flag:          if non-empty, this field is ignored as an option (optional)
88
89    optional:       if non-empty, makes the argument of the option optional. When an
90                    argument is optional it can only be specified using
91                    --option=argument (optional)
92    optional-value: the value of an optional option when the option occurs
93                    without an argument. This tag can be specified multiple
94                    times in the case of maps or slices (optional)
95    default:        the default value of an option. This tag can be specified
96                    multiple times in the case of slices or maps (optional)
97    default-mask:   when specified, this value will be displayed in the help
98                    instead of the actual default value. This is useful
99                    mostly for hiding otherwise sensitive information from
100                    showing up in the help. If default-mask takes the special
101                    value "-", then no default value will be shown at all
102                    (optional)
103    env:            the default value of the option is overridden from the
104                    specified environment variable, if one has been defined.
105                    (optional)
106    env-delim:      the 'env' default value from environment is split into
107                    multiple values with the given delimiter string, use with
108                    slices and maps (optional)
109    value-name:     the name of the argument value (to be shown in the help)
110                    (optional)
111    choice:         limits the values for an option to a set of values.
112                    Repeat this tag once for each allowable value.
113                    e.g. `long:"animal" choice:"cat" choice:"dog"`
114    hidden:         if non-empty, the option is not visible in the help or man page.
115
116    base: a base (radix) used to convert strings to integer values, the
117          default base is 10 (i.e. decimal) (optional)
118
119    ini-name:       the explicit ini option name (optional)
120    no-ini:         if non-empty this field is ignored as an ini option
121                    (optional)
122
123    group:                when specified on a struct field, makes the struct
124                          field a separate group with the given name (optional)
125    namespace:            when specified on a group struct field, the namespace
126                          gets prepended to every option's long name and
127                          subgroup's namespace of this group, separated by
128                          the parser's namespace delimiter (optional)
129    env-namespace:        when specified on a group struct field, the env-namespace
130                          gets prepended to every option's env key and
131                          subgroup's env-namespace of this group, separated by
132                          the parser's env-namespace delimiter (optional)
133    command:              when specified on a struct field, makes the struct
134                          field a (sub)command with the given name (optional)
135    subcommands-optional: when specified on a command struct field, makes
136                          any subcommands of that command optional (optional)
137    alias:                when specified on a command struct field, adds the
138                          specified name as an alias for the command. Can be
139                          be specified multiple times to add more than one
140                          alias (optional)
141    positional-args:      when specified on a field with a struct type,
142                          uses the fields of that struct to parse remaining
143                          positional command line arguments into (in order
144                          of the fields). If a field has a slice type,
145                          then all remaining arguments will be added to it.
146                          Positional arguments are optional by default,
147                          unless the "required" tag is specified together
148                          with the "positional-args" tag. The "required" tag
149                          can also be set on the individual rest argument
150                          fields, to require only the first N positional
151                          arguments. If the "required" tag is set on the
152                          rest arguments slice, then its value determines
153                          the minimum amount of rest arguments that needs to
154                          be provided (e.g. `required:"2"`) (optional)
155    positional-arg-name:  used on a field in a positional argument struct; name
156                          of the positional argument placeholder to be shown in
157                          the help (optional)
158
159Either the `short:` tag or the `long:` must be specified to make the field eligible as an
160option.
161
162
163Option groups
164
165Option groups are a simple way to semantically separate your options. All
166options in a particular group are shown together in the help under the name
167of the group. Namespaces can be used to specify option long names more
168precisely and emphasize the options affiliation to their group.
169
170There are currently three ways to specify option groups.
171
172    1. Use NewNamedParser specifying the various option groups.
173    2. Use AddGroup to add a group to an existing parser.
174    3. Add a struct field to the top-level options annotated with the
175       group:"group-name" tag.
176
177
178
179Commands
180
181The flags package also has basic support for commands. Commands are often
182used in monolithic applications that support various commands or actions.
183Take git for example, all of the add, commit, checkout, etc. are called
184commands. Using commands you can easily separate multiple functions of your
185application.
186
187There are currently two ways to specify a command.
188
189    1. Use AddCommand on an existing parser.
190    2. Add a struct field to your options struct annotated with the
191       command:"command-name" tag.
192
193The most common, idiomatic way to implement commands is to define a global
194parser instance and implement each command in a separate file. These
195command files should define a go init function which calls AddCommand on
196the global parser.
197
198When parsing ends and there is an active command and that command implements
199the Commander interface, then its Execute method will be run with the
200remaining command line arguments.
201
202Command structs can have options which become valid to parse after the
203command has been specified on the command line, in addition to the options
204of all the parent commands. I.e. considering a -v flag on the parser and an
205add command, the following are equivalent:
206
207    ./app -v add
208    ./app add -v
209
210However, if the -v flag is defined on the add command, then the first of
211the two examples above would fail since the -v flag is not defined before
212the add command.
213
214
215Completion
216
217go-flags has builtin support to provide bash completion of flags, commands
218and argument values. To use completion, the binary which uses go-flags
219can be invoked in a special environment to list completion of the current
220command line argument. It should be noted that this `executes` your application,
221and it is up to the user to make sure there are no negative side effects (for
222example from init functions).
223
224Setting the environment variable `GO_FLAGS_COMPLETION=1` enables completion
225by replacing the argument parsing routine with the completion routine which
226outputs completions for the passed arguments. The basic invocation to
227complete a set of arguments is therefore:
228
229    GO_FLAGS_COMPLETION=1 ./completion-example arg1 arg2 arg3
230
231where `completion-example` is the binary, `arg1` and `arg2` are
232the current arguments, and `arg3` (the last argument) is the argument
233to be completed. If the GO_FLAGS_COMPLETION is set to "verbose", then
234descriptions of possible completion items will also be shown, if there
235are more than 1 completion items.
236
237To use this with bash completion, a simple file can be written which
238calls the binary which supports go-flags completion:
239
240    _completion_example() {
241        # All arguments except the first one
242        args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
243
244        # Only split on newlines
245        local IFS=$'\n'
246
247        # Call completion (note that the first element of COMP_WORDS is
248        # the executable itself)
249        COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
250        return 0
251    }
252
253    complete -F _completion_example completion-example
254
255Completion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.
256
257Customized completion for argument values is supported by implementing
258the flags.Completer interface for the argument value type. An example
259of a type which does so is the flags.Filename type, an alias of string
260allowing simple filename completion. A slice or array argument value
261whose element type implements flags.Completer will also be completed.
262*/
263package flags
264