You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. [![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag)
  2. [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag)
  3. [![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag)
  4. ## Description
  5. pflag is a drop-in replacement for Go's flag package, implementing
  6. POSIX/GNU-style --flags.
  7. pflag is compatible with the [GNU extensions to the POSIX recommendations
  8. for command-line options][1]. For a more precise description, see the
  9. "Command-line flag syntax" section below.
  10. [1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
  11. pflag is available under the same style of BSD license as the Go language,
  12. which can be found in the LICENSE file.
  13. ## Installation
  14. pflag is available using the standard `go get` command.
  15. Install by running:
  16. go get github.com/spf13/pflag
  17. Run tests by running:
  18. go test github.com/spf13/pflag
  19. ## Usage
  20. pflag is a drop-in replacement of Go's native flag package. If you import
  21. pflag under the name "flag" then all code should continue to function
  22. with no changes.
  23. ``` go
  24. import flag "github.com/spf13/pflag"
  25. ```
  26. There is one exception to this: if you directly instantiate the Flag struct
  27. there is one more field "Shorthand" that you will need to set.
  28. Most code never instantiates this struct directly, and instead uses
  29. functions such as String(), BoolVar(), and Var(), and is therefore
  30. unaffected.
  31. Define flags using flag.String(), Bool(), Int(), etc.
  32. This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
  33. ``` go
  34. var ip *int = flag.Int("flagname", 1234, "help message for flagname")
  35. ```
  36. If you like, you can bind the flag to a variable using the Var() functions.
  37. ``` go
  38. var flagvar int
  39. func init() {
  40. flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
  41. }
  42. ```
  43. Or you can create custom flags that satisfy the Value interface (with
  44. pointer receivers) and couple them to flag parsing by
  45. ``` go
  46. flag.Var(&flagVal, "name", "help message for flagname")
  47. ```
  48. For such flags, the default value is just the initial value of the variable.
  49. After all flags are defined, call
  50. ``` go
  51. flag.Parse()
  52. ```
  53. to parse the command line into the defined flags.
  54. Flags may then be used directly. If you're using the flags themselves,
  55. they are all pointers; if you bind to variables, they're values.
  56. ``` go
  57. fmt.Println("ip has value ", *ip)
  58. fmt.Println("flagvar has value ", flagvar)
  59. ```
  60. There are helper functions available to get the value stored in a Flag if you have a FlagSet but find
  61. it difficult to keep up with all of the pointers in your code.
  62. If you have a pflag.FlagSet with a flag called 'flagname' of type int you
  63. can use GetInt() to get the int value. But notice that 'flagname' must exist
  64. and it must be an int. GetString("flagname") will fail.
  65. ``` go
  66. i, err := flagset.GetInt("flagname")
  67. ```
  68. After parsing, the arguments after the flag are available as the
  69. slice flag.Args() or individually as flag.Arg(i).
  70. The arguments are indexed from 0 through flag.NArg()-1.
  71. The pflag package also defines some new functions that are not in flag,
  72. that give one-letter shorthands for flags. You can use these by appending
  73. 'P' to the name of any function that defines a flag.
  74. ``` go
  75. var ip = flag.IntP("flagname", "f", 1234, "help message")
  76. var flagvar bool
  77. func init() {
  78. flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
  79. }
  80. flag.VarP(&flagVal, "varname", "v", "help message")
  81. ```
  82. Shorthand letters can be used with single dashes on the command line.
  83. Boolean shorthand flags can be combined with other shorthand flags.
  84. The default set of command-line flags is controlled by
  85. top-level functions. The FlagSet type allows one to define
  86. independent sets of flags, such as to implement subcommands
  87. in a command-line interface. The methods of FlagSet are
  88. analogous to the top-level functions for the command-line
  89. flag set.
  90. ## Setting no option default values for flags
  91. After you create a flag it is possible to set the pflag.NoOptDefVal for
  92. the given flag. Doing this changes the meaning of the flag slightly. If
  93. a flag has a NoOptDefVal and the flag is set on the command line without
  94. an option the flag will be set to the NoOptDefVal. For example given:
  95. ``` go
  96. var ip = flag.IntP("flagname", "f", 1234, "help message")
  97. flag.Lookup("flagname").NoOptDefVal = "4321"
  98. ```
  99. Would result in something like
  100. | Parsed Arguments | Resulting Value |
  101. | ------------- | ------------- |
  102. | --flagname=1357 | ip=1357 |
  103. | --flagname | ip=4321 |
  104. | [nothing] | ip=1234 |
  105. ## Command line flag syntax
  106. ```
  107. --flag // boolean flags, or flags with no option default values
  108. --flag x // only on flags without a default value
  109. --flag=x
  110. ```
  111. Unlike the flag package, a single dash before an option means something
  112. different than a double dash. Single dashes signify a series of shorthand
  113. letters for flags. All but the last shorthand letter must be boolean flags
  114. or a flag with a default value
  115. ```
  116. // boolean or flags where the 'no option default value' is set
  117. -f
  118. -f=true
  119. -abc
  120. but
  121. -b true is INVALID
  122. // non-boolean and flags without a 'no option default value'
  123. -n 1234
  124. -n=1234
  125. -n1234
  126. // mixed
  127. -abcs "hello"
  128. -absd="hello"
  129. -abcs1234
  130. ```
  131. Flag parsing stops after the terminator "--". Unlike the flag package,
  132. flags can be interspersed with arguments anywhere on the command line
  133. before this terminator.
  134. Integer flags accept 1234, 0664, 0x1234 and may be negative.
  135. Boolean flags (in their long form) accept 1, 0, t, f, true, false,
  136. TRUE, FALSE, True, False.
  137. Duration flags accept any input valid for time.ParseDuration.
  138. ## Mutating or "Normalizing" Flag names
  139. It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
  140. **Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
  141. ``` go
  142. func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
  143. from := []string{"-", "_"}
  144. to := "."
  145. for _, sep := range from {
  146. name = strings.Replace(name, sep, to, -1)
  147. }
  148. return pflag.NormalizedName(name)
  149. }
  150. myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
  151. ```
  152. **Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
  153. ``` go
  154. func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
  155. switch name {
  156. case "old-flag-name":
  157. name = "new-flag-name"
  158. break
  159. }
  160. return pflag.NormalizedName(name)
  161. }
  162. myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
  163. ```
  164. ## Deprecating a flag or its shorthand
  165. It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.
  166. **Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.
  167. ```go
  168. // deprecate a flag by specifying its name and a usage message
  169. flags.MarkDeprecated("badflag", "please use --good-flag instead")
  170. ```
  171. This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used.
  172. **Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".
  173. ```go
  174. // deprecate a flag shorthand by specifying its flag name and a usage message
  175. flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")
  176. ```
  177. This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used.
  178. Note that usage message is essential here, and it should not be empty.
  179. ## Hidden flags
  180. It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.
  181. **Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.
  182. ```go
  183. // hide a flag by specifying its name
  184. flags.MarkHidden("secretFlag")
  185. ```
  186. ## Disable sorting of flags
  187. `pflag` allows you to disable sorting of flags for help and usage message.
  188. **Example**:
  189. ```go
  190. flags.BoolP("verbose", "v", false, "verbose output")
  191. flags.String("coolflag", "yeaah", "it's really cool flag")
  192. flags.Int("usefulflag", 777, "sometimes it's very useful")
  193. flags.SortFlags = false
  194. flags.PrintDefaults()
  195. ```
  196. **Output**:
  197. ```
  198. -v, --verbose verbose output
  199. --coolflag string it's really cool flag (default "yeaah")
  200. --usefulflag int sometimes it's very useful (default 777)
  201. ```
  202. ## Supporting Go flags when using pflag
  203. In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary
  204. to support flags defined by third-party dependencies (e.g. `golang/glog`).
  205. **Example**: You want to add the Go flags to the `CommandLine` flagset
  206. ```go
  207. import (
  208. goflag "flag"
  209. flag "github.com/spf13/pflag"
  210. )
  211. var ip *int = flag.Int("flagname", 1234, "help message for flagname")
  212. func main() {
  213. flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
  214. flag.Parse()
  215. }
  216. ```
  217. ## More info
  218. You can see the full reference documentation of the pflag package
  219. [at godoc.org][3], or through go's standard documentation system by
  220. running `godoc -http=:6060` and browsing to
  221. [http://localhost:6060/pkg/github.com/spf13/pflag][2] after
  222. installation.
  223. [2]: http://localhost:6060/pkg/github.com/spf13/pflag
  224. [3]: http://godoc.org/github.com/spf13/pflag