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.

flag.go 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. // Copyright 2009 The Go Authors. 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 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. See
  9. http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
  10. Usage:
  11. pflag is a drop-in replacement of Go's native flag package. If you import
  12. pflag under the name "flag" then all code should continue to function
  13. with no changes.
  14. import flag "github.com/spf13/pflag"
  15. There is one exception to this: if you directly instantiate the Flag struct
  16. there is one more field "Shorthand" that you will need to set.
  17. Most code never instantiates this struct directly, and instead uses
  18. functions such as String(), BoolVar(), and Var(), and is therefore
  19. unaffected.
  20. Define flags using flag.String(), Bool(), Int(), etc.
  21. This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
  22. var ip = flag.Int("flagname", 1234, "help message for flagname")
  23. If you like, you can bind the flag to a variable using the Var() functions.
  24. var flagvar int
  25. func init() {
  26. flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
  27. }
  28. Or you can create custom flags that satisfy the Value interface (with
  29. pointer receivers) and couple them to flag parsing by
  30. flag.Var(&flagVal, "name", "help message for flagname")
  31. For such flags, the default value is just the initial value of the variable.
  32. After all flags are defined, call
  33. flag.Parse()
  34. to parse the command line into the defined flags.
  35. Flags may then be used directly. If you're using the flags themselves,
  36. they are all pointers; if you bind to variables, they're values.
  37. fmt.Println("ip has value ", *ip)
  38. fmt.Println("flagvar has value ", flagvar)
  39. After parsing, the arguments after the flag are available as the
  40. slice flag.Args() or individually as flag.Arg(i).
  41. The arguments are indexed from 0 through flag.NArg()-1.
  42. The pflag package also defines some new functions that are not in flag,
  43. that give one-letter shorthands for flags. You can use these by appending
  44. 'P' to the name of any function that defines a flag.
  45. var ip = flag.IntP("flagname", "f", 1234, "help message")
  46. var flagvar bool
  47. func init() {
  48. flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
  49. }
  50. flag.VarP(&flagval, "varname", "v", "help message")
  51. Shorthand letters can be used with single dashes on the command line.
  52. Boolean shorthand flags can be combined with other shorthand flags.
  53. Command line flag syntax:
  54. --flag // boolean flags only
  55. --flag=x
  56. Unlike the flag package, a single dash before an option means something
  57. different than a double dash. Single dashes signify a series of shorthand
  58. letters for flags. All but the last shorthand letter must be boolean flags.
  59. // boolean flags
  60. -f
  61. -abc
  62. // non-boolean flags
  63. -n 1234
  64. -Ifile
  65. // mixed
  66. -abcs "hello"
  67. -abcn1234
  68. Flag parsing stops after the terminator "--". Unlike the flag package,
  69. flags can be interspersed with arguments anywhere on the command line
  70. before this terminator.
  71. Integer flags accept 1234, 0664, 0x1234 and may be negative.
  72. Boolean flags (in their long form) accept 1, 0, t, f, true, false,
  73. TRUE, FALSE, True, False.
  74. Duration flags accept any input valid for time.ParseDuration.
  75. The default set of command-line flags is controlled by
  76. top-level functions. The FlagSet type allows one to define
  77. independent sets of flags, such as to implement subcommands
  78. in a command-line interface. The methods of FlagSet are
  79. analogous to the top-level functions for the command-line
  80. flag set.
  81. */
  82. package pflag
  83. import (
  84. "bytes"
  85. "errors"
  86. goflag "flag"
  87. "fmt"
  88. "io"
  89. "os"
  90. "sort"
  91. "strings"
  92. )
  93. // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
  94. var ErrHelp = errors.New("pflag: help requested")
  95. // ErrorHandling defines how to handle flag parsing errors.
  96. type ErrorHandling int
  97. const (
  98. // ContinueOnError will return an err from Parse() if an error is found
  99. ContinueOnError ErrorHandling = iota
  100. // ExitOnError will call os.Exit(2) if an error is found when parsing
  101. ExitOnError
  102. // PanicOnError will panic() if an error is found when parsing flags
  103. PanicOnError
  104. )
  105. // ParseErrorsWhitelist defines the parsing errors that can be ignored
  106. type ParseErrorsWhitelist struct {
  107. // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags
  108. UnknownFlags bool
  109. }
  110. // NormalizedName is a flag name that has been normalized according to rules
  111. // for the FlagSet (e.g. making '-' and '_' equivalent).
  112. type NormalizedName string
  113. // A FlagSet represents a set of defined flags.
  114. type FlagSet struct {
  115. // Usage is the function called when an error occurs while parsing flags.
  116. // The field is a function (not a method) that may be changed to point to
  117. // a custom error handler.
  118. Usage func()
  119. // SortFlags is used to indicate, if user wants to have sorted flags in
  120. // help/usage messages.
  121. SortFlags bool
  122. // ParseErrorsWhitelist is used to configure a whitelist of errors
  123. ParseErrorsWhitelist ParseErrorsWhitelist
  124. name string
  125. parsed bool
  126. actual map[NormalizedName]*Flag
  127. orderedActual []*Flag
  128. sortedActual []*Flag
  129. formal map[NormalizedName]*Flag
  130. orderedFormal []*Flag
  131. sortedFormal []*Flag
  132. shorthands map[byte]*Flag
  133. args []string // arguments after flags
  134. argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --
  135. errorHandling ErrorHandling
  136. output io.Writer // nil means stderr; use out() accessor
  137. interspersed bool // allow interspersed option/non-option args
  138. normalizeNameFunc func(f *FlagSet, name string) NormalizedName
  139. addedGoFlagSets []*goflag.FlagSet
  140. }
  141. // A Flag represents the state of a flag.
  142. type Flag struct {
  143. Name string // name as it appears on command line
  144. Shorthand string // one-letter abbreviated flag
  145. Usage string // help message
  146. Value Value // value as set
  147. DefValue string // default value (as text); for usage message
  148. Changed bool // If the user set the value (or if left to default)
  149. NoOptDefVal string // default value (as text); if the flag is on the command line without any options
  150. Deprecated string // If this flag is deprecated, this string is the new or now thing to use
  151. Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
  152. ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
  153. Annotations map[string][]string // used by cobra.Command bash autocomple code
  154. }
  155. // Value is the interface to the dynamic value stored in a flag.
  156. // (The default value is represented as a string.)
  157. type Value interface {
  158. String() string
  159. Set(string) error
  160. Type() string
  161. }
  162. // SliceValue is a secondary interface to all flags which hold a list
  163. // of values. This allows full control over the value of list flags,
  164. // and avoids complicated marshalling and unmarshalling to csv.
  165. type SliceValue interface {
  166. // Append adds the specified value to the end of the flag value list.
  167. Append(string) error
  168. // Replace will fully overwrite any data currently in the flag value list.
  169. Replace([]string) error
  170. // GetSlice returns the flag value list as an array of strings.
  171. GetSlice() []string
  172. }
  173. // sortFlags returns the flags as a slice in lexicographical sorted order.
  174. func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
  175. list := make(sort.StringSlice, len(flags))
  176. i := 0
  177. for k := range flags {
  178. list[i] = string(k)
  179. i++
  180. }
  181. list.Sort()
  182. result := make([]*Flag, len(list))
  183. for i, name := range list {
  184. result[i] = flags[NormalizedName(name)]
  185. }
  186. return result
  187. }
  188. // SetNormalizeFunc allows you to add a function which can translate flag names.
  189. // Flags added to the FlagSet will be translated and then when anything tries to
  190. // look up the flag that will also be translated. So it would be possible to create
  191. // a flag named "getURL" and have it translated to "geturl". A user could then pass
  192. // "--getUrl" which may also be translated to "geturl" and everything will work.
  193. func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
  194. f.normalizeNameFunc = n
  195. f.sortedFormal = f.sortedFormal[:0]
  196. for fname, flag := range f.formal {
  197. nname := f.normalizeFlagName(flag.Name)
  198. if fname == nname {
  199. continue
  200. }
  201. flag.Name = string(nname)
  202. delete(f.formal, fname)
  203. f.formal[nname] = flag
  204. if _, set := f.actual[fname]; set {
  205. delete(f.actual, fname)
  206. f.actual[nname] = flag
  207. }
  208. }
  209. }
  210. // GetNormalizeFunc returns the previously set NormalizeFunc of a function which
  211. // does no translation, if not set previously.
  212. func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
  213. if f.normalizeNameFunc != nil {
  214. return f.normalizeNameFunc
  215. }
  216. return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
  217. }
  218. func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
  219. n := f.GetNormalizeFunc()
  220. return n(f, name)
  221. }
  222. func (f *FlagSet) out() io.Writer {
  223. if f.output == nil {
  224. return os.Stderr
  225. }
  226. return f.output
  227. }
  228. // SetOutput sets the destination for usage and error messages.
  229. // If output is nil, os.Stderr is used.
  230. func (f *FlagSet) SetOutput(output io.Writer) {
  231. f.output = output
  232. }
  233. // VisitAll visits the flags in lexicographical order or
  234. // in primordial order if f.SortFlags is false, calling fn for each.
  235. // It visits all flags, even those not set.
  236. func (f *FlagSet) VisitAll(fn func(*Flag)) {
  237. if len(f.formal) == 0 {
  238. return
  239. }
  240. var flags []*Flag
  241. if f.SortFlags {
  242. if len(f.formal) != len(f.sortedFormal) {
  243. f.sortedFormal = sortFlags(f.formal)
  244. }
  245. flags = f.sortedFormal
  246. } else {
  247. flags = f.orderedFormal
  248. }
  249. for _, flag := range flags {
  250. fn(flag)
  251. }
  252. }
  253. // HasFlags returns a bool to indicate if the FlagSet has any flags defined.
  254. func (f *FlagSet) HasFlags() bool {
  255. return len(f.formal) > 0
  256. }
  257. // HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
  258. // that are not hidden.
  259. func (f *FlagSet) HasAvailableFlags() bool {
  260. for _, flag := range f.formal {
  261. if !flag.Hidden {
  262. return true
  263. }
  264. }
  265. return false
  266. }
  267. // VisitAll visits the command-line flags in lexicographical order or
  268. // in primordial order if f.SortFlags is false, calling fn for each.
  269. // It visits all flags, even those not set.
  270. func VisitAll(fn func(*Flag)) {
  271. CommandLine.VisitAll(fn)
  272. }
  273. // Visit visits the flags in lexicographical order or
  274. // in primordial order if f.SortFlags is false, calling fn for each.
  275. // It visits only those flags that have been set.
  276. func (f *FlagSet) Visit(fn func(*Flag)) {
  277. if len(f.actual) == 0 {
  278. return
  279. }
  280. var flags []*Flag
  281. if f.SortFlags {
  282. if len(f.actual) != len(f.sortedActual) {
  283. f.sortedActual = sortFlags(f.actual)
  284. }
  285. flags = f.sortedActual
  286. } else {
  287. flags = f.orderedActual
  288. }
  289. for _, flag := range flags {
  290. fn(flag)
  291. }
  292. }
  293. // Visit visits the command-line flags in lexicographical order or
  294. // in primordial order if f.SortFlags is false, calling fn for each.
  295. // It visits only those flags that have been set.
  296. func Visit(fn func(*Flag)) {
  297. CommandLine.Visit(fn)
  298. }
  299. // Lookup returns the Flag structure of the named flag, returning nil if none exists.
  300. func (f *FlagSet) Lookup(name string) *Flag {
  301. return f.lookup(f.normalizeFlagName(name))
  302. }
  303. // ShorthandLookup returns the Flag structure of the short handed flag,
  304. // returning nil if none exists.
  305. // It panics, if len(name) > 1.
  306. func (f *FlagSet) ShorthandLookup(name string) *Flag {
  307. if name == "" {
  308. return nil
  309. }
  310. if len(name) > 1 {
  311. msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
  312. fmt.Fprintf(f.out(), msg)
  313. panic(msg)
  314. }
  315. c := name[0]
  316. return f.shorthands[c]
  317. }
  318. // lookup returns the Flag structure of the named flag, returning nil if none exists.
  319. func (f *FlagSet) lookup(name NormalizedName) *Flag {
  320. return f.formal[name]
  321. }
  322. // func to return a given type for a given flag name
  323. func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
  324. flag := f.Lookup(name)
  325. if flag == nil {
  326. err := fmt.Errorf("flag accessed but not defined: %s", name)
  327. return nil, err
  328. }
  329. if flag.Value.Type() != ftype {
  330. err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
  331. return nil, err
  332. }
  333. sval := flag.Value.String()
  334. result, err := convFunc(sval)
  335. if err != nil {
  336. return nil, err
  337. }
  338. return result, nil
  339. }
  340. // ArgsLenAtDash will return the length of f.Args at the moment when a -- was
  341. // found during arg parsing. This allows your program to know which args were
  342. // before the -- and which came after.
  343. func (f *FlagSet) ArgsLenAtDash() int {
  344. return f.argsLenAtDash
  345. }
  346. // MarkDeprecated indicated that a flag is deprecated in your program. It will
  347. // continue to function but will not show up in help or usage messages. Using
  348. // this flag will also print the given usageMessage.
  349. func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
  350. flag := f.Lookup(name)
  351. if flag == nil {
  352. return fmt.Errorf("flag %q does not exist", name)
  353. }
  354. if usageMessage == "" {
  355. return fmt.Errorf("deprecated message for flag %q must be set", name)
  356. }
  357. flag.Deprecated = usageMessage
  358. flag.Hidden = true
  359. return nil
  360. }
  361. // MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
  362. // program. It will continue to function but will not show up in help or usage
  363. // messages. Using this flag will also print the given usageMessage.
  364. func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
  365. flag := f.Lookup(name)
  366. if flag == nil {
  367. return fmt.Errorf("flag %q does not exist", name)
  368. }
  369. if usageMessage == "" {
  370. return fmt.Errorf("deprecated message for flag %q must be set", name)
  371. }
  372. flag.ShorthandDeprecated = usageMessage
  373. return nil
  374. }
  375. // MarkHidden sets a flag to 'hidden' in your program. It will continue to
  376. // function but will not show up in help or usage messages.
  377. func (f *FlagSet) MarkHidden(name string) error {
  378. flag := f.Lookup(name)
  379. if flag == nil {
  380. return fmt.Errorf("flag %q does not exist", name)
  381. }
  382. flag.Hidden = true
  383. return nil
  384. }
  385. // Lookup returns the Flag structure of the named command-line flag,
  386. // returning nil if none exists.
  387. func Lookup(name string) *Flag {
  388. return CommandLine.Lookup(name)
  389. }
  390. // ShorthandLookup returns the Flag structure of the short handed flag,
  391. // returning nil if none exists.
  392. func ShorthandLookup(name string) *Flag {
  393. return CommandLine.ShorthandLookup(name)
  394. }
  395. // Set sets the value of the named flag.
  396. func (f *FlagSet) Set(name, value string) error {
  397. normalName := f.normalizeFlagName(name)
  398. flag, ok := f.formal[normalName]
  399. if !ok {
  400. return fmt.Errorf("no such flag -%v", name)
  401. }
  402. err := flag.Value.Set(value)
  403. if err != nil {
  404. var flagName string
  405. if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
  406. flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name)
  407. } else {
  408. flagName = fmt.Sprintf("--%s", flag.Name)
  409. }
  410. return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
  411. }
  412. if !flag.Changed {
  413. if f.actual == nil {
  414. f.actual = make(map[NormalizedName]*Flag)
  415. }
  416. f.actual[normalName] = flag
  417. f.orderedActual = append(f.orderedActual, flag)
  418. flag.Changed = true
  419. }
  420. if flag.Deprecated != "" {
  421. fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
  422. }
  423. return nil
  424. }
  425. // SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
  426. // This is sometimes used by spf13/cobra programs which want to generate additional
  427. // bash completion information.
  428. func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
  429. normalName := f.normalizeFlagName(name)
  430. flag, ok := f.formal[normalName]
  431. if !ok {
  432. return fmt.Errorf("no such flag -%v", name)
  433. }
  434. if flag.Annotations == nil {
  435. flag.Annotations = map[string][]string{}
  436. }
  437. flag.Annotations[key] = values
  438. return nil
  439. }
  440. // Changed returns true if the flag was explicitly set during Parse() and false
  441. // otherwise
  442. func (f *FlagSet) Changed(name string) bool {
  443. flag := f.Lookup(name)
  444. // If a flag doesn't exist, it wasn't changed....
  445. if flag == nil {
  446. return false
  447. }
  448. return flag.Changed
  449. }
  450. // Set sets the value of the named command-line flag.
  451. func Set(name, value string) error {
  452. return CommandLine.Set(name, value)
  453. }
  454. // PrintDefaults prints, to standard error unless configured
  455. // otherwise, the default values of all defined flags in the set.
  456. func (f *FlagSet) PrintDefaults() {
  457. usages := f.FlagUsages()
  458. fmt.Fprint(f.out(), usages)
  459. }
  460. // defaultIsZeroValue returns true if the default value for this flag represents
  461. // a zero value.
  462. func (f *Flag) defaultIsZeroValue() bool {
  463. switch f.Value.(type) {
  464. case boolFlag:
  465. return f.DefValue == "false"
  466. case *durationValue:
  467. // Beginning in Go 1.7, duration zero values are "0s"
  468. return f.DefValue == "0" || f.DefValue == "0s"
  469. case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
  470. return f.DefValue == "0"
  471. case *stringValue:
  472. return f.DefValue == ""
  473. case *ipValue, *ipMaskValue, *ipNetValue:
  474. return f.DefValue == "<nil>"
  475. case *intSliceValue, *stringSliceValue, *stringArrayValue:
  476. return f.DefValue == "[]"
  477. default:
  478. switch f.Value.String() {
  479. case "false":
  480. return true
  481. case "<nil>":
  482. return true
  483. case "":
  484. return true
  485. case "0":
  486. return true
  487. }
  488. return false
  489. }
  490. }
  491. // UnquoteUsage extracts a back-quoted name from the usage
  492. // string for a flag and returns it and the un-quoted usage.
  493. // Given "a `name` to show" it returns ("name", "a name to show").
  494. // If there are no back quotes, the name is an educated guess of the
  495. // type of the flag's value, or the empty string if the flag is boolean.
  496. func UnquoteUsage(flag *Flag) (name string, usage string) {
  497. // Look for a back-quoted name, but avoid the strings package.
  498. usage = flag.Usage
  499. for i := 0; i < len(usage); i++ {
  500. if usage[i] == '`' {
  501. for j := i + 1; j < len(usage); j++ {
  502. if usage[j] == '`' {
  503. name = usage[i+1 : j]
  504. usage = usage[:i] + name + usage[j+1:]
  505. return name, usage
  506. }
  507. }
  508. break // Only one back quote; use type name.
  509. }
  510. }
  511. name = flag.Value.Type()
  512. switch name {
  513. case "bool":
  514. name = ""
  515. case "float64":
  516. name = "float"
  517. case "int64":
  518. name = "int"
  519. case "uint64":
  520. name = "uint"
  521. case "stringSlice":
  522. name = "strings"
  523. case "intSlice":
  524. name = "ints"
  525. case "uintSlice":
  526. name = "uints"
  527. case "boolSlice":
  528. name = "bools"
  529. }
  530. return
  531. }
  532. // Splits the string `s` on whitespace into an initial substring up to
  533. // `i` runes in length and the remainder. Will go `slop` over `i` if
  534. // that encompasses the entire string (which allows the caller to
  535. // avoid short orphan words on the final line).
  536. func wrapN(i, slop int, s string) (string, string) {
  537. if i+slop > len(s) {
  538. return s, ""
  539. }
  540. w := strings.LastIndexAny(s[:i], " \t\n")
  541. if w <= 0 {
  542. return s, ""
  543. }
  544. nlPos := strings.LastIndex(s[:i], "\n")
  545. if nlPos > 0 && nlPos < w {
  546. return s[:nlPos], s[nlPos+1:]
  547. }
  548. return s[:w], s[w+1:]
  549. }
  550. // Wraps the string `s` to a maximum width `w` with leading indent
  551. // `i`. The first line is not indented (this is assumed to be done by
  552. // caller). Pass `w` == 0 to do no wrapping
  553. func wrap(i, w int, s string) string {
  554. if w == 0 {
  555. return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
  556. }
  557. // space between indent i and end of line width w into which
  558. // we should wrap the text.
  559. wrap := w - i
  560. var r, l string
  561. // Not enough space for sensible wrapping. Wrap as a block on
  562. // the next line instead.
  563. if wrap < 24 {
  564. i = 16
  565. wrap = w - i
  566. r += "\n" + strings.Repeat(" ", i)
  567. }
  568. // If still not enough space then don't even try to wrap.
  569. if wrap < 24 {
  570. return strings.Replace(s, "\n", r, -1)
  571. }
  572. // Try to avoid short orphan words on the final line, by
  573. // allowing wrapN to go a bit over if that would fit in the
  574. // remainder of the line.
  575. slop := 5
  576. wrap = wrap - slop
  577. // Handle first line, which is indented by the caller (or the
  578. // special case above)
  579. l, s = wrapN(wrap, slop, s)
  580. r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
  581. // Now wrap the rest
  582. for s != "" {
  583. var t string
  584. t, s = wrapN(wrap, slop, s)
  585. r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
  586. }
  587. return r
  588. }
  589. // FlagUsagesWrapped returns a string containing the usage information
  590. // for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
  591. // wrapping)
  592. func (f *FlagSet) FlagUsagesWrapped(cols int) string {
  593. buf := new(bytes.Buffer)
  594. lines := make([]string, 0, len(f.formal))
  595. maxlen := 0
  596. f.VisitAll(func(flag *Flag) {
  597. if flag.Hidden {
  598. return
  599. }
  600. line := ""
  601. if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
  602. line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
  603. } else {
  604. line = fmt.Sprintf(" --%s", flag.Name)
  605. }
  606. varname, usage := UnquoteUsage(flag)
  607. if varname != "" {
  608. line += " " + varname
  609. }
  610. if flag.NoOptDefVal != "" {
  611. switch flag.Value.Type() {
  612. case "string":
  613. line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
  614. case "bool":
  615. if flag.NoOptDefVal != "true" {
  616. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  617. }
  618. case "count":
  619. if flag.NoOptDefVal != "+1" {
  620. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  621. }
  622. default:
  623. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  624. }
  625. }
  626. // This special character will be replaced with spacing once the
  627. // correct alignment is calculated
  628. line += "\x00"
  629. if len(line) > maxlen {
  630. maxlen = len(line)
  631. }
  632. line += usage
  633. if !flag.defaultIsZeroValue() {
  634. if flag.Value.Type() == "string" {
  635. line += fmt.Sprintf(" (default %q)", flag.DefValue)
  636. } else {
  637. line += fmt.Sprintf(" (default %s)", flag.DefValue)
  638. }
  639. }
  640. if len(flag.Deprecated) != 0 {
  641. line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
  642. }
  643. lines = append(lines, line)
  644. })
  645. for _, line := range lines {
  646. sidx := strings.Index(line, "\x00")
  647. spacing := strings.Repeat(" ", maxlen-sidx)
  648. // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
  649. fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
  650. }
  651. return buf.String()
  652. }
  653. // FlagUsages returns a string containing the usage information for all flags in
  654. // the FlagSet
  655. func (f *FlagSet) FlagUsages() string {
  656. return f.FlagUsagesWrapped(0)
  657. }
  658. // PrintDefaults prints to standard error the default values of all defined command-line flags.
  659. func PrintDefaults() {
  660. CommandLine.PrintDefaults()
  661. }
  662. // defaultUsage is the default function to print a usage message.
  663. func defaultUsage(f *FlagSet) {
  664. fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
  665. f.PrintDefaults()
  666. }
  667. // NOTE: Usage is not just defaultUsage(CommandLine)
  668. // because it serves (via godoc flag Usage) as the example
  669. // for how to write your own usage function.
  670. // Usage prints to standard error a usage message documenting all defined command-line flags.
  671. // The function is a variable that may be changed to point to a custom function.
  672. // By default it prints a simple header and calls PrintDefaults; for details about the
  673. // format of the output and how to control it, see the documentation for PrintDefaults.
  674. var Usage = func() {
  675. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  676. PrintDefaults()
  677. }
  678. // NFlag returns the number of flags that have been set.
  679. func (f *FlagSet) NFlag() int { return len(f.actual) }
  680. // NFlag returns the number of command-line flags that have been set.
  681. func NFlag() int { return len(CommandLine.actual) }
  682. // Arg returns the i'th argument. Arg(0) is the first remaining argument
  683. // after flags have been processed.
  684. func (f *FlagSet) Arg(i int) string {
  685. if i < 0 || i >= len(f.args) {
  686. return ""
  687. }
  688. return f.args[i]
  689. }
  690. // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
  691. // after flags have been processed.
  692. func Arg(i int) string {
  693. return CommandLine.Arg(i)
  694. }
  695. // NArg is the number of arguments remaining after flags have been processed.
  696. func (f *FlagSet) NArg() int { return len(f.args) }
  697. // NArg is the number of arguments remaining after flags have been processed.
  698. func NArg() int { return len(CommandLine.args) }
  699. // Args returns the non-flag arguments.
  700. func (f *FlagSet) Args() []string { return f.args }
  701. // Args returns the non-flag command-line arguments.
  702. func Args() []string { return CommandLine.args }
  703. // Var defines a flag with the specified name and usage string. The type and
  704. // value of the flag are represented by the first argument, of type Value, which
  705. // typically holds a user-defined implementation of Value. For instance, the
  706. // caller could create a flag that turns a comma-separated string into a slice
  707. // of strings by giving the slice the methods of Value; in particular, Set would
  708. // decompose the comma-separated string into the slice.
  709. func (f *FlagSet) Var(value Value, name string, usage string) {
  710. f.VarP(value, name, "", usage)
  711. }
  712. // VarPF is like VarP, but returns the flag created
  713. func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
  714. // Remember the default value as a string; it won't change.
  715. flag := &Flag{
  716. Name: name,
  717. Shorthand: shorthand,
  718. Usage: usage,
  719. Value: value,
  720. DefValue: value.String(),
  721. }
  722. f.AddFlag(flag)
  723. return flag
  724. }
  725. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  726. func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
  727. f.VarPF(value, name, shorthand, usage)
  728. }
  729. // AddFlag will add the flag to the FlagSet
  730. func (f *FlagSet) AddFlag(flag *Flag) {
  731. normalizedFlagName := f.normalizeFlagName(flag.Name)
  732. _, alreadyThere := f.formal[normalizedFlagName]
  733. if alreadyThere {
  734. msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
  735. fmt.Fprintln(f.out(), msg)
  736. panic(msg) // Happens only if flags are declared with identical names
  737. }
  738. if f.formal == nil {
  739. f.formal = make(map[NormalizedName]*Flag)
  740. }
  741. flag.Name = string(normalizedFlagName)
  742. f.formal[normalizedFlagName] = flag
  743. f.orderedFormal = append(f.orderedFormal, flag)
  744. if flag.Shorthand == "" {
  745. return
  746. }
  747. if len(flag.Shorthand) > 1 {
  748. msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)
  749. fmt.Fprintf(f.out(), msg)
  750. panic(msg)
  751. }
  752. if f.shorthands == nil {
  753. f.shorthands = make(map[byte]*Flag)
  754. }
  755. c := flag.Shorthand[0]
  756. used, alreadyThere := f.shorthands[c]
  757. if alreadyThere {
  758. msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)
  759. fmt.Fprintf(f.out(), msg)
  760. panic(msg)
  761. }
  762. f.shorthands[c] = flag
  763. }
  764. // AddFlagSet adds one FlagSet to another. If a flag is already present in f
  765. // the flag from newSet will be ignored.
  766. func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
  767. if newSet == nil {
  768. return
  769. }
  770. newSet.VisitAll(func(flag *Flag) {
  771. if f.Lookup(flag.Name) == nil {
  772. f.AddFlag(flag)
  773. }
  774. })
  775. }
  776. // Var defines a flag with the specified name and usage string. The type and
  777. // value of the flag are represented by the first argument, of type Value, which
  778. // typically holds a user-defined implementation of Value. For instance, the
  779. // caller could create a flag that turns a comma-separated string into a slice
  780. // of strings by giving the slice the methods of Value; in particular, Set would
  781. // decompose the comma-separated string into the slice.
  782. func Var(value Value, name string, usage string) {
  783. CommandLine.VarP(value, name, "", usage)
  784. }
  785. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  786. func VarP(value Value, name, shorthand, usage string) {
  787. CommandLine.VarP(value, name, shorthand, usage)
  788. }
  789. // failf prints to standard error a formatted error and usage message and
  790. // returns the error.
  791. func (f *FlagSet) failf(format string, a ...interface{}) error {
  792. err := fmt.Errorf(format, a...)
  793. if f.errorHandling != ContinueOnError {
  794. fmt.Fprintln(f.out(), err)
  795. f.usage()
  796. }
  797. return err
  798. }
  799. // usage calls the Usage method for the flag set, or the usage function if
  800. // the flag set is CommandLine.
  801. func (f *FlagSet) usage() {
  802. if f == CommandLine {
  803. Usage()
  804. } else if f.Usage == nil {
  805. defaultUsage(f)
  806. } else {
  807. f.Usage()
  808. }
  809. }
  810. //--unknown (args will be empty)
  811. //--unknown --next-flag ... (args will be --next-flag ...)
  812. //--unknown arg ... (args will be arg ...)
  813. func stripUnknownFlagValue(args []string) []string {
  814. if len(args) == 0 {
  815. //--unknown
  816. return args
  817. }
  818. first := args[0]
  819. if len(first) > 0 && first[0] == '-' {
  820. //--unknown --next-flag ...
  821. return args
  822. }
  823. //--unknown arg ... (args will be arg ...)
  824. if len(args) > 1 {
  825. return args[1:]
  826. }
  827. return nil
  828. }
  829. func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
  830. a = args
  831. name := s[2:]
  832. if len(name) == 0 || name[0] == '-' || name[0] == '=' {
  833. err = f.failf("bad flag syntax: %s", s)
  834. return
  835. }
  836. split := strings.SplitN(name, "=", 2)
  837. name = split[0]
  838. flag, exists := f.formal[f.normalizeFlagName(name)]
  839. if !exists {
  840. switch {
  841. case name == "help":
  842. f.usage()
  843. return a, ErrHelp
  844. case f.ParseErrorsWhitelist.UnknownFlags:
  845. // --unknown=unknownval arg ...
  846. // we do not want to lose arg in this case
  847. if len(split) >= 2 {
  848. return a, nil
  849. }
  850. return stripUnknownFlagValue(a), nil
  851. default:
  852. err = f.failf("unknown flag: --%s", name)
  853. return
  854. }
  855. }
  856. var value string
  857. if len(split) == 2 {
  858. // '--flag=arg'
  859. value = split[1]
  860. } else if flag.NoOptDefVal != "" {
  861. // '--flag' (arg was optional)
  862. value = flag.NoOptDefVal
  863. } else if len(a) > 0 {
  864. // '--flag arg'
  865. value = a[0]
  866. a = a[1:]
  867. } else {
  868. // '--flag' (arg was required)
  869. err = f.failf("flag needs an argument: %s", s)
  870. return
  871. }
  872. err = fn(flag, value)
  873. if err != nil {
  874. f.failf(err.Error())
  875. }
  876. return
  877. }
  878. func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
  879. outArgs = args
  880. if strings.HasPrefix(shorthands, "test.") {
  881. return
  882. }
  883. outShorts = shorthands[1:]
  884. c := shorthands[0]
  885. flag, exists := f.shorthands[c]
  886. if !exists {
  887. switch {
  888. case c == 'h':
  889. f.usage()
  890. err = ErrHelp
  891. return
  892. case f.ParseErrorsWhitelist.UnknownFlags:
  893. // '-f=arg arg ...'
  894. // we do not want to lose arg in this case
  895. if len(shorthands) > 2 && shorthands[1] == '=' {
  896. outShorts = ""
  897. return
  898. }
  899. outArgs = stripUnknownFlagValue(outArgs)
  900. return
  901. default:
  902. err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
  903. return
  904. }
  905. }
  906. var value string
  907. if len(shorthands) > 2 && shorthands[1] == '=' {
  908. // '-f=arg'
  909. value = shorthands[2:]
  910. outShorts = ""
  911. } else if flag.NoOptDefVal != "" {
  912. // '-f' (arg was optional)
  913. value = flag.NoOptDefVal
  914. } else if len(shorthands) > 1 {
  915. // '-farg'
  916. value = shorthands[1:]
  917. outShorts = ""
  918. } else if len(args) > 0 {
  919. // '-f arg'
  920. value = args[0]
  921. outArgs = args[1:]
  922. } else {
  923. // '-f' (arg was required)
  924. err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
  925. return
  926. }
  927. if flag.ShorthandDeprecated != "" {
  928. fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
  929. }
  930. err = fn(flag, value)
  931. if err != nil {
  932. f.failf(err.Error())
  933. }
  934. return
  935. }
  936. func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
  937. a = args
  938. shorthands := s[1:]
  939. // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").
  940. for len(shorthands) > 0 {
  941. shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
  942. if err != nil {
  943. return
  944. }
  945. }
  946. return
  947. }
  948. func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
  949. for len(args) > 0 {
  950. s := args[0]
  951. args = args[1:]
  952. if len(s) == 0 || s[0] != '-' || len(s) == 1 {
  953. if !f.interspersed {
  954. f.args = append(f.args, s)
  955. f.args = append(f.args, args...)
  956. return nil
  957. }
  958. f.args = append(f.args, s)
  959. continue
  960. }
  961. if s[1] == '-' {
  962. if len(s) == 2 { // "--" terminates the flags
  963. f.argsLenAtDash = len(f.args)
  964. f.args = append(f.args, args...)
  965. break
  966. }
  967. args, err = f.parseLongArg(s, args, fn)
  968. } else {
  969. args, err = f.parseShortArg(s, args, fn)
  970. }
  971. if err != nil {
  972. return
  973. }
  974. }
  975. return
  976. }
  977. // Parse parses flag definitions from the argument list, which should not
  978. // include the command name. Must be called after all flags in the FlagSet
  979. // are defined and before flags are accessed by the program.
  980. // The return value will be ErrHelp if -help was set but not defined.
  981. func (f *FlagSet) Parse(arguments []string) error {
  982. if f.addedGoFlagSets != nil {
  983. for _, goFlagSet := range f.addedGoFlagSets {
  984. goFlagSet.Parse(nil)
  985. }
  986. }
  987. f.parsed = true
  988. if len(arguments) < 0 {
  989. return nil
  990. }
  991. f.args = make([]string, 0, len(arguments))
  992. set := func(flag *Flag, value string) error {
  993. return f.Set(flag.Name, value)
  994. }
  995. err := f.parseArgs(arguments, set)
  996. if err != nil {
  997. switch f.errorHandling {
  998. case ContinueOnError:
  999. return err
  1000. case ExitOnError:
  1001. fmt.Println(err)
  1002. os.Exit(2)
  1003. case PanicOnError:
  1004. panic(err)
  1005. }
  1006. }
  1007. return nil
  1008. }
  1009. type parseFunc func(flag *Flag, value string) error
  1010. // ParseAll parses flag definitions from the argument list, which should not
  1011. // include the command name. The arguments for fn are flag and value. Must be
  1012. // called after all flags in the FlagSet are defined and before flags are
  1013. // accessed by the program. The return value will be ErrHelp if -help was set
  1014. // but not defined.
  1015. func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
  1016. f.parsed = true
  1017. f.args = make([]string, 0, len(arguments))
  1018. err := f.parseArgs(arguments, fn)
  1019. if err != nil {
  1020. switch f.errorHandling {
  1021. case ContinueOnError:
  1022. return err
  1023. case ExitOnError:
  1024. os.Exit(2)
  1025. case PanicOnError:
  1026. panic(err)
  1027. }
  1028. }
  1029. return nil
  1030. }
  1031. // Parsed reports whether f.Parse has been called.
  1032. func (f *FlagSet) Parsed() bool {
  1033. return f.parsed
  1034. }
  1035. // Parse parses the command-line flags from os.Args[1:]. Must be called
  1036. // after all flags are defined and before flags are accessed by the program.
  1037. func Parse() {
  1038. // Ignore errors; CommandLine is set for ExitOnError.
  1039. CommandLine.Parse(os.Args[1:])
  1040. }
  1041. // ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
  1042. // The arguments for fn are flag and value. Must be called after all flags are
  1043. // defined and before flags are accessed by the program.
  1044. func ParseAll(fn func(flag *Flag, value string) error) {
  1045. // Ignore errors; CommandLine is set for ExitOnError.
  1046. CommandLine.ParseAll(os.Args[1:], fn)
  1047. }
  1048. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  1049. func SetInterspersed(interspersed bool) {
  1050. CommandLine.SetInterspersed(interspersed)
  1051. }
  1052. // Parsed returns true if the command-line flags have been parsed.
  1053. func Parsed() bool {
  1054. return CommandLine.Parsed()
  1055. }
  1056. // CommandLine is the default set of command-line flags, parsed from os.Args.
  1057. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
  1058. // NewFlagSet returns a new, empty flag set with the specified name,
  1059. // error handling property and SortFlags set to true.
  1060. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
  1061. f := &FlagSet{
  1062. name: name,
  1063. errorHandling: errorHandling,
  1064. argsLenAtDash: -1,
  1065. interspersed: true,
  1066. SortFlags: true,
  1067. }
  1068. return f
  1069. }
  1070. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  1071. func (f *FlagSet) SetInterspersed(interspersed bool) {
  1072. f.interspersed = interspersed
  1073. }
  1074. // Init sets the name and error handling property for a flag set.
  1075. // By default, the zero FlagSet uses an empty name and the
  1076. // ContinueOnError error handling policy.
  1077. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
  1078. f.name = name
  1079. f.errorHandling = errorHandling
  1080. f.argsLenAtDash = -1
  1081. }