本站源代码
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

259 lines
12KB

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