flag.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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 Output() 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. // Output returns the destination for usage and error messages. os.Stderr is returned if
  223. // output was not set or was set to nil.
  224. func (f *FlagSet) Output() io.Writer {
  225. if f.output == nil {
  226. return os.Stderr
  227. }
  228. return f.output
  229. }
  230. // Name returns the name of the flag set.
  231. func (f *FlagSet) Name() string {
  232. return f.name
  233. }
  234. // SetOutput sets the destination for usage and error messages.
  235. // If output is nil, os.Stderr is used.
  236. func (f *FlagSet) SetOutput(output io.Writer) {
  237. f.output = output
  238. }
  239. // VisitAll visits the flags in lexicographical order or
  240. // in primordial order if f.SortFlags is false, calling fn for each.
  241. // It visits all flags, even those not set.
  242. func (f *FlagSet) VisitAll(fn func(*Flag)) {
  243. if len(f.formal) == 0 {
  244. return
  245. }
  246. var flags []*Flag
  247. if f.SortFlags {
  248. if len(f.formal) != len(f.sortedFormal) {
  249. f.sortedFormal = sortFlags(f.formal)
  250. }
  251. flags = f.sortedFormal
  252. } else {
  253. flags = f.orderedFormal
  254. }
  255. for _, flag := range flags {
  256. fn(flag)
  257. }
  258. }
  259. // HasFlags returns a bool to indicate if the FlagSet has any flags defined.
  260. func (f *FlagSet) HasFlags() bool {
  261. return len(f.formal) > 0
  262. }
  263. // HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
  264. // that are not hidden.
  265. func (f *FlagSet) HasAvailableFlags() bool {
  266. for _, flag := range f.formal {
  267. if !flag.Hidden {
  268. return true
  269. }
  270. }
  271. return false
  272. }
  273. // VisitAll visits the command-line flags in lexicographical order or
  274. // in primordial order if f.SortFlags is false, calling fn for each.
  275. // It visits all flags, even those not set.
  276. func VisitAll(fn func(*Flag)) {
  277. CommandLine.VisitAll(fn)
  278. }
  279. // Visit visits the flags in lexicographical order or
  280. // in primordial order if f.SortFlags is false, calling fn for each.
  281. // It visits only those flags that have been set.
  282. func (f *FlagSet) Visit(fn func(*Flag)) {
  283. if len(f.actual) == 0 {
  284. return
  285. }
  286. var flags []*Flag
  287. if f.SortFlags {
  288. if len(f.actual) != len(f.sortedActual) {
  289. f.sortedActual = sortFlags(f.actual)
  290. }
  291. flags = f.sortedActual
  292. } else {
  293. flags = f.orderedActual
  294. }
  295. for _, flag := range flags {
  296. fn(flag)
  297. }
  298. }
  299. // Visit visits the command-line flags in lexicographical order or
  300. // in primordial order if f.SortFlags is false, calling fn for each.
  301. // It visits only those flags that have been set.
  302. func Visit(fn func(*Flag)) {
  303. CommandLine.Visit(fn)
  304. }
  305. // Lookup returns the Flag structure of the named flag, returning nil if none exists.
  306. func (f *FlagSet) Lookup(name string) *Flag {
  307. return f.lookup(f.normalizeFlagName(name))
  308. }
  309. // ShorthandLookup returns the Flag structure of the short handed flag,
  310. // returning nil if none exists.
  311. // It panics, if len(name) > 1.
  312. func (f *FlagSet) ShorthandLookup(name string) *Flag {
  313. if name == "" {
  314. return nil
  315. }
  316. if len(name) > 1 {
  317. msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
  318. fmt.Fprintf(f.Output(), msg)
  319. panic(msg)
  320. }
  321. c := name[0]
  322. return f.shorthands[c]
  323. }
  324. // lookup returns the Flag structure of the named flag, returning nil if none exists.
  325. func (f *FlagSet) lookup(name NormalizedName) *Flag {
  326. return f.formal[name]
  327. }
  328. // func to return a given type for a given flag name
  329. func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
  330. flag := f.Lookup(name)
  331. if flag == nil {
  332. err := fmt.Errorf("flag accessed but not defined: %s", name)
  333. return nil, err
  334. }
  335. if flag.Value.Type() != ftype {
  336. err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
  337. return nil, err
  338. }
  339. sval := flag.Value.String()
  340. result, err := convFunc(sval)
  341. if err != nil {
  342. return nil, err
  343. }
  344. return result, nil
  345. }
  346. // ArgsLenAtDash will return the length of f.Args at the moment when a -- was
  347. // found during arg parsing. This allows your program to know which args were
  348. // before the -- and which came after.
  349. func (f *FlagSet) ArgsLenAtDash() int {
  350. return f.argsLenAtDash
  351. }
  352. // MarkDeprecated indicated that a flag is deprecated in your program. It will
  353. // continue to function but will not show up in help or usage messages. Using
  354. // this flag will also print the given usageMessage.
  355. func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
  356. flag := f.Lookup(name)
  357. if flag == nil {
  358. return fmt.Errorf("flag %q does not exist", name)
  359. }
  360. if usageMessage == "" {
  361. return fmt.Errorf("deprecated message for flag %q must be set", name)
  362. }
  363. flag.Deprecated = usageMessage
  364. flag.Hidden = true
  365. return nil
  366. }
  367. // MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
  368. // program. It will continue to function but will not show up in help or usage
  369. // messages. Using this flag will also print the given usageMessage.
  370. func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
  371. flag := f.Lookup(name)
  372. if flag == nil {
  373. return fmt.Errorf("flag %q does not exist", name)
  374. }
  375. if usageMessage == "" {
  376. return fmt.Errorf("deprecated message for flag %q must be set", name)
  377. }
  378. flag.ShorthandDeprecated = usageMessage
  379. return nil
  380. }
  381. // MarkHidden sets a flag to 'hidden' in your program. It will continue to
  382. // function but will not show up in help or usage messages.
  383. func (f *FlagSet) MarkHidden(name string) error {
  384. flag := f.Lookup(name)
  385. if flag == nil {
  386. return fmt.Errorf("flag %q does not exist", name)
  387. }
  388. flag.Hidden = true
  389. return nil
  390. }
  391. // Lookup returns the Flag structure of the named command-line flag,
  392. // returning nil if none exists.
  393. func Lookup(name string) *Flag {
  394. return CommandLine.Lookup(name)
  395. }
  396. // ShorthandLookup returns the Flag structure of the short handed flag,
  397. // returning nil if none exists.
  398. func ShorthandLookup(name string) *Flag {
  399. return CommandLine.ShorthandLookup(name)
  400. }
  401. // Set sets the value of the named flag.
  402. func (f *FlagSet) Set(name, value string) error {
  403. normalName := f.normalizeFlagName(name)
  404. flag, ok := f.formal[normalName]
  405. if !ok {
  406. return fmt.Errorf("no such flag -%v", name)
  407. }
  408. err := flag.Value.Set(value)
  409. if err != nil {
  410. var flagName string
  411. if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
  412. flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name)
  413. } else {
  414. flagName = fmt.Sprintf("--%s", flag.Name)
  415. }
  416. return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
  417. }
  418. if !flag.Changed {
  419. if f.actual == nil {
  420. f.actual = make(map[NormalizedName]*Flag)
  421. }
  422. f.actual[normalName] = flag
  423. f.orderedActual = append(f.orderedActual, flag)
  424. flag.Changed = true
  425. }
  426. if flag.Deprecated != "" {
  427. fmt.Fprintf(f.Output(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
  428. }
  429. return nil
  430. }
  431. // SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
  432. // This is sometimes used by spf13/cobra programs which want to generate additional
  433. // bash completion information.
  434. func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
  435. normalName := f.normalizeFlagName(name)
  436. flag, ok := f.formal[normalName]
  437. if !ok {
  438. return fmt.Errorf("no such flag -%v", name)
  439. }
  440. if flag.Annotations == nil {
  441. flag.Annotations = map[string][]string{}
  442. }
  443. flag.Annotations[key] = values
  444. return nil
  445. }
  446. // Changed returns true if the flag was explicitly set during Parse() and false
  447. // otherwise
  448. func (f *FlagSet) Changed(name string) bool {
  449. flag := f.Lookup(name)
  450. // If a flag doesn't exist, it wasn't changed....
  451. if flag == nil {
  452. return false
  453. }
  454. return flag.Changed
  455. }
  456. // Set sets the value of the named command-line flag.
  457. func Set(name, value string) error {
  458. return CommandLine.Set(name, value)
  459. }
  460. // PrintDefaults prints, to standard error unless configured
  461. // otherwise, the default values of all defined flags in the set.
  462. func (f *FlagSet) PrintDefaults() {
  463. usages := f.FlagUsages()
  464. fmt.Fprint(f.Output(), usages)
  465. }
  466. // defaultIsZeroValue returns true if the default value for this flag represents
  467. // a zero value.
  468. func (f *Flag) defaultIsZeroValue() bool {
  469. switch f.Value.(type) {
  470. case boolFlag:
  471. return f.DefValue == "false"
  472. case *durationValue:
  473. // Beginning in Go 1.7, duration zero values are "0s"
  474. return f.DefValue == "0" || f.DefValue == "0s"
  475. case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
  476. return f.DefValue == "0"
  477. case *stringValue:
  478. return f.DefValue == ""
  479. case *ipValue, *ipMaskValue, *ipNetValue:
  480. return f.DefValue == "<nil>"
  481. case *intSliceValue, *stringSliceValue, *stringArrayValue:
  482. return f.DefValue == "[]"
  483. default:
  484. switch f.Value.String() {
  485. case "false":
  486. return true
  487. case "<nil>":
  488. return true
  489. case "":
  490. return true
  491. case "0":
  492. return true
  493. }
  494. return false
  495. }
  496. }
  497. // UnquoteUsage extracts a back-quoted name from the usage
  498. // string for a flag and returns it and the un-quoted usage.
  499. // Given "a `name` to show" it returns ("name", "a name to show").
  500. // If there are no back quotes, the name is an educated guess of the
  501. // type of the flag's value, or the empty string if the flag is boolean.
  502. func UnquoteUsage(flag *Flag) (name string, usage string) {
  503. // Look for a back-quoted name, but avoid the strings package.
  504. usage = flag.Usage
  505. for i := 0; i < len(usage); i++ {
  506. if usage[i] == '`' {
  507. for j := i + 1; j < len(usage); j++ {
  508. if usage[j] == '`' {
  509. name = usage[i+1 : j]
  510. usage = usage[:i] + name + usage[j+1:]
  511. return name, usage
  512. }
  513. }
  514. break // Only one back quote; use type name.
  515. }
  516. }
  517. name = flag.Value.Type()
  518. switch name {
  519. case "bool":
  520. name = ""
  521. case "float64":
  522. name = "float"
  523. case "int64":
  524. name = "int"
  525. case "uint64":
  526. name = "uint"
  527. case "stringSlice":
  528. name = "strings"
  529. case "intSlice":
  530. name = "ints"
  531. case "uintSlice":
  532. name = "uints"
  533. case "boolSlice":
  534. name = "bools"
  535. }
  536. return
  537. }
  538. // Splits the string `s` on whitespace into an initial substring up to
  539. // `i` runes in length and the remainder. Will go `slop` over `i` if
  540. // that encompasses the entire string (which allows the caller to
  541. // avoid short orphan words on the final line).
  542. func wrapN(i, slop int, s string) (string, string) {
  543. if i+slop > len(s) {
  544. return s, ""
  545. }
  546. w := strings.LastIndexAny(s[:i], " \t\n")
  547. if w <= 0 {
  548. return s, ""
  549. }
  550. nlPos := strings.LastIndex(s[:i], "\n")
  551. if nlPos > 0 && nlPos < w {
  552. return s[:nlPos], s[nlPos+1:]
  553. }
  554. return s[:w], s[w+1:]
  555. }
  556. // Wraps the string `s` to a maximum width `w` with leading indent
  557. // `i`. The first line is not indented (this is assumed to be done by
  558. // caller). Pass `w` == 0 to do no wrapping
  559. func wrap(i, w int, s string) string {
  560. if w == 0 {
  561. return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
  562. }
  563. // space between indent i and end of line width w into which
  564. // we should wrap the text.
  565. wrap := w - i
  566. var r, l string
  567. // Not enough space for sensible wrapping. Wrap as a block on
  568. // the next line instead.
  569. if wrap < 24 {
  570. i = 16
  571. wrap = w - i
  572. r += "\n" + strings.Repeat(" ", i)
  573. }
  574. // If still not enough space then don't even try to wrap.
  575. if wrap < 24 {
  576. return strings.Replace(s, "\n", r, -1)
  577. }
  578. // Try to avoid short orphan words on the final line, by
  579. // allowing wrapN to go a bit over if that would fit in the
  580. // remainder of the line.
  581. slop := 5
  582. wrap = wrap - slop
  583. // Handle first line, which is indented by the caller (or the
  584. // special case above)
  585. l, s = wrapN(wrap, slop, s)
  586. r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
  587. // Now wrap the rest
  588. for s != "" {
  589. var t string
  590. t, s = wrapN(wrap, slop, s)
  591. r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
  592. }
  593. return r
  594. }
  595. // FlagUsagesWrapped returns a string containing the usage information
  596. // for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
  597. // wrapping)
  598. func (f *FlagSet) FlagUsagesWrapped(cols int) string {
  599. buf := new(bytes.Buffer)
  600. lines := make([]string, 0, len(f.formal))
  601. maxlen := 0
  602. f.VisitAll(func(flag *Flag) {
  603. if flag.Hidden {
  604. return
  605. }
  606. line := ""
  607. if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
  608. line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
  609. } else {
  610. line = fmt.Sprintf(" --%s", flag.Name)
  611. }
  612. varname, usage := UnquoteUsage(flag)
  613. if varname != "" {
  614. line += " " + varname
  615. }
  616. if flag.NoOptDefVal != "" {
  617. switch flag.Value.Type() {
  618. case "string":
  619. line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
  620. case "bool":
  621. if flag.NoOptDefVal != "true" {
  622. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  623. }
  624. case "count":
  625. if flag.NoOptDefVal != "+1" {
  626. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  627. }
  628. default:
  629. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  630. }
  631. }
  632. // This special character will be replaced with spacing once the
  633. // correct alignment is calculated
  634. line += "\x00"
  635. if len(line) > maxlen {
  636. maxlen = len(line)
  637. }
  638. line += usage
  639. if !flag.defaultIsZeroValue() {
  640. if flag.Value.Type() == "string" {
  641. line += fmt.Sprintf(" (default %q)", flag.DefValue)
  642. } else {
  643. line += fmt.Sprintf(" (default %s)", flag.DefValue)
  644. }
  645. }
  646. if len(flag.Deprecated) != 0 {
  647. line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
  648. }
  649. lines = append(lines, line)
  650. })
  651. for _, line := range lines {
  652. sidx := strings.Index(line, "\x00")
  653. spacing := strings.Repeat(" ", maxlen-sidx)
  654. // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
  655. fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
  656. }
  657. return buf.String()
  658. }
  659. // FlagUsages returns a string containing the usage information for all flags in
  660. // the FlagSet
  661. func (f *FlagSet) FlagUsages() string {
  662. return f.FlagUsagesWrapped(0)
  663. }
  664. // PrintDefaults prints to standard error the default values of all defined command-line flags.
  665. func PrintDefaults() {
  666. CommandLine.PrintDefaults()
  667. }
  668. // defaultUsage is the default function to print a usage message.
  669. func defaultUsage(f *FlagSet) {
  670. fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name)
  671. f.PrintDefaults()
  672. }
  673. // NOTE: Usage is not just defaultUsage(CommandLine)
  674. // because it serves (via godoc flag Usage) as the example
  675. // for how to write your own usage function.
  676. // Usage prints to standard error a usage message documenting all defined command-line flags.
  677. // The function is a variable that may be changed to point to a custom function.
  678. // By default it prints a simple header and calls PrintDefaults; for details about the
  679. // format of the output and how to control it, see the documentation for PrintDefaults.
  680. var Usage = func() {
  681. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  682. PrintDefaults()
  683. }
  684. // NFlag returns the number of flags that have been set.
  685. func (f *FlagSet) NFlag() int { return len(f.actual) }
  686. // NFlag returns the number of command-line flags that have been set.
  687. func NFlag() int { return len(CommandLine.actual) }
  688. // Arg returns the i'th argument. Arg(0) is the first remaining argument
  689. // after flags have been processed.
  690. func (f *FlagSet) Arg(i int) string {
  691. if i < 0 || i >= len(f.args) {
  692. return ""
  693. }
  694. return f.args[i]
  695. }
  696. // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
  697. // after flags have been processed.
  698. func Arg(i int) string {
  699. return CommandLine.Arg(i)
  700. }
  701. // NArg is the number of arguments remaining after flags have been processed.
  702. func (f *FlagSet) NArg() int { return len(f.args) }
  703. // NArg is the number of arguments remaining after flags have been processed.
  704. func NArg() int { return len(CommandLine.args) }
  705. // Args returns the non-flag arguments.
  706. func (f *FlagSet) Args() []string { return f.args }
  707. // Args returns the non-flag command-line arguments.
  708. func Args() []string { return CommandLine.args }
  709. // Var defines a flag with the specified name and usage string. The type and
  710. // value of the flag are represented by the first argument, of type Value, which
  711. // typically holds a user-defined implementation of Value. For instance, the
  712. // caller could create a flag that turns a comma-separated string into a slice
  713. // of strings by giving the slice the methods of Value; in particular, Set would
  714. // decompose the comma-separated string into the slice.
  715. func (f *FlagSet) Var(value Value, name string, usage string) {
  716. f.VarP(value, name, "", usage)
  717. }
  718. // VarPF is like VarP, but returns the flag created
  719. func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
  720. // Remember the default value as a string; it won't change.
  721. flag := &Flag{
  722. Name: name,
  723. Shorthand: shorthand,
  724. Usage: usage,
  725. Value: value,
  726. DefValue: value.String(),
  727. }
  728. f.AddFlag(flag)
  729. return flag
  730. }
  731. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  732. func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
  733. f.VarPF(value, name, shorthand, usage)
  734. }
  735. // AddFlag will add the flag to the FlagSet
  736. func (f *FlagSet) AddFlag(flag *Flag) {
  737. normalizedFlagName := f.normalizeFlagName(flag.Name)
  738. _, alreadyThere := f.formal[normalizedFlagName]
  739. if alreadyThere {
  740. msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
  741. fmt.Fprintln(f.Output(), msg)
  742. panic(msg) // Happens only if flags are declared with identical names
  743. }
  744. if f.formal == nil {
  745. f.formal = make(map[NormalizedName]*Flag)
  746. }
  747. flag.Name = string(normalizedFlagName)
  748. f.formal[normalizedFlagName] = flag
  749. f.orderedFormal = append(f.orderedFormal, flag)
  750. if flag.Shorthand == "" {
  751. return
  752. }
  753. if len(flag.Shorthand) > 1 {
  754. msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)
  755. fmt.Fprintf(f.Output(), msg)
  756. panic(msg)
  757. }
  758. if f.shorthands == nil {
  759. f.shorthands = make(map[byte]*Flag)
  760. }
  761. c := flag.Shorthand[0]
  762. used, alreadyThere := f.shorthands[c]
  763. if alreadyThere {
  764. msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)
  765. fmt.Fprintf(f.Output(), msg)
  766. panic(msg)
  767. }
  768. f.shorthands[c] = flag
  769. }
  770. // AddFlagSet adds one FlagSet to another. If a flag is already present in f
  771. // the flag from newSet will be ignored.
  772. func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
  773. if newSet == nil {
  774. return
  775. }
  776. newSet.VisitAll(func(flag *Flag) {
  777. if f.Lookup(flag.Name) == nil {
  778. f.AddFlag(flag)
  779. }
  780. })
  781. }
  782. // Var defines a flag with the specified name and usage string. The type and
  783. // value of the flag are represented by the first argument, of type Value, which
  784. // typically holds a user-defined implementation of Value. For instance, the
  785. // caller could create a flag that turns a comma-separated string into a slice
  786. // of strings by giving the slice the methods of Value; in particular, Set would
  787. // decompose the comma-separated string into the slice.
  788. func Var(value Value, name string, usage string) {
  789. CommandLine.VarP(value, name, "", usage)
  790. }
  791. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  792. func VarP(value Value, name, shorthand, usage string) {
  793. CommandLine.VarP(value, name, shorthand, usage)
  794. }
  795. // failf prints to standard error a formatted error and usage message and
  796. // returns the error.
  797. func (f *FlagSet) failf(format string, a ...interface{}) error {
  798. err := fmt.Errorf(format, a...)
  799. if f.errorHandling != ContinueOnError {
  800. fmt.Fprintln(f.Output(), err)
  801. f.usage()
  802. }
  803. return err
  804. }
  805. // usage calls the Usage method for the flag set, or the usage function if
  806. // the flag set is CommandLine.
  807. func (f *FlagSet) usage() {
  808. if f == CommandLine {
  809. Usage()
  810. } else if f.Usage == nil {
  811. defaultUsage(f)
  812. } else {
  813. f.Usage()
  814. }
  815. }
  816. //--unknown (args will be empty)
  817. //--unknown --next-flag ... (args will be --next-flag ...)
  818. //--unknown arg ... (args will be arg ...)
  819. func stripUnknownFlagValue(args []string) []string {
  820. if len(args) == 0 {
  821. //--unknown
  822. return args
  823. }
  824. first := args[0]
  825. if len(first) > 0 && first[0] == '-' {
  826. //--unknown --next-flag ...
  827. return args
  828. }
  829. //--unknown arg ... (args will be arg ...)
  830. if len(args) > 1 {
  831. return args[1:]
  832. }
  833. return nil
  834. }
  835. func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
  836. a = args
  837. name := s[2:]
  838. if len(name) == 0 || name[0] == '-' || name[0] == '=' {
  839. err = f.failf("bad flag syntax: %s", s)
  840. return
  841. }
  842. split := strings.SplitN(name, "=", 2)
  843. name = split[0]
  844. flag, exists := f.formal[f.normalizeFlagName(name)]
  845. if !exists {
  846. switch {
  847. case name == "help":
  848. f.usage()
  849. return a, ErrHelp
  850. case f.ParseErrorsWhitelist.UnknownFlags:
  851. // --unknown=unknownval arg ...
  852. // we do not want to lose arg in this case
  853. if len(split) >= 2 {
  854. return a, nil
  855. }
  856. return stripUnknownFlagValue(a), nil
  857. default:
  858. err = f.failf("unknown flag: --%s", name)
  859. return
  860. }
  861. }
  862. var value string
  863. if len(split) == 2 {
  864. // '--flag=arg'
  865. value = split[1]
  866. } else if flag.NoOptDefVal != "" {
  867. // '--flag' (arg was optional)
  868. value = flag.NoOptDefVal
  869. } else if len(a) > 0 {
  870. // '--flag arg'
  871. value = a[0]
  872. a = a[1:]
  873. } else {
  874. // '--flag' (arg was required)
  875. err = f.failf("flag needs an argument: %s", s)
  876. return
  877. }
  878. err = fn(flag, value)
  879. if err != nil {
  880. f.failf(err.Error())
  881. }
  882. return
  883. }
  884. func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
  885. outArgs = args
  886. if strings.HasPrefix(shorthands, "test.") {
  887. return
  888. }
  889. outShorts = shorthands[1:]
  890. c := shorthands[0]
  891. flag, exists := f.shorthands[c]
  892. if !exists {
  893. switch {
  894. case c == 'h':
  895. f.usage()
  896. err = ErrHelp
  897. return
  898. case f.ParseErrorsWhitelist.UnknownFlags:
  899. // '-f=arg arg ...'
  900. // we do not want to lose arg in this case
  901. if len(shorthands) > 2 && shorthands[1] == '=' {
  902. outShorts = ""
  903. return
  904. }
  905. outArgs = stripUnknownFlagValue(outArgs)
  906. return
  907. default:
  908. err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
  909. return
  910. }
  911. }
  912. var value string
  913. if len(shorthands) > 2 && shorthands[1] == '=' {
  914. // '-f=arg'
  915. value = shorthands[2:]
  916. outShorts = ""
  917. } else if flag.NoOptDefVal != "" {
  918. // '-f' (arg was optional)
  919. value = flag.NoOptDefVal
  920. } else if len(shorthands) > 1 {
  921. // '-farg'
  922. value = shorthands[1:]
  923. outShorts = ""
  924. } else if len(args) > 0 {
  925. // '-f arg'
  926. value = args[0]
  927. outArgs = args[1:]
  928. } else {
  929. // '-f' (arg was required)
  930. err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
  931. return
  932. }
  933. if flag.ShorthandDeprecated != "" {
  934. fmt.Fprintf(f.Output(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
  935. }
  936. err = fn(flag, value)
  937. if err != nil {
  938. f.failf(err.Error())
  939. }
  940. return
  941. }
  942. func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
  943. a = args
  944. shorthands := s[1:]
  945. // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").
  946. for len(shorthands) > 0 {
  947. shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
  948. if err != nil {
  949. return
  950. }
  951. }
  952. return
  953. }
  954. func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
  955. for len(args) > 0 {
  956. s := args[0]
  957. args = args[1:]
  958. if len(s) == 0 || s[0] != '-' || len(s) == 1 {
  959. if !f.interspersed {
  960. f.args = append(f.args, s)
  961. f.args = append(f.args, args...)
  962. return nil
  963. }
  964. f.args = append(f.args, s)
  965. continue
  966. }
  967. if s[1] == '-' {
  968. if len(s) == 2 { // "--" terminates the flags
  969. f.argsLenAtDash = len(f.args)
  970. f.args = append(f.args, args...)
  971. break
  972. }
  973. args, err = f.parseLongArg(s, args, fn)
  974. } else {
  975. args, err = f.parseShortArg(s, args, fn)
  976. }
  977. if err != nil {
  978. return
  979. }
  980. }
  981. return
  982. }
  983. // Parse parses flag definitions from the argument list, which should not
  984. // include the command name. Must be called after all flags in the FlagSet
  985. // are defined and before flags are accessed by the program.
  986. // The return value will be ErrHelp if -help was set but not defined.
  987. func (f *FlagSet) Parse(arguments []string) error {
  988. if f.addedGoFlagSets != nil {
  989. for _, goFlagSet := range f.addedGoFlagSets {
  990. goFlagSet.Parse(nil)
  991. }
  992. }
  993. f.parsed = true
  994. if len(arguments) < 0 {
  995. return nil
  996. }
  997. f.args = make([]string, 0, len(arguments))
  998. set := func(flag *Flag, value string) error {
  999. return f.Set(flag.Name, value)
  1000. }
  1001. err := f.parseArgs(arguments, set)
  1002. if err != nil {
  1003. switch f.errorHandling {
  1004. case ContinueOnError:
  1005. return err
  1006. case ExitOnError:
  1007. fmt.Println(err)
  1008. os.Exit(2)
  1009. case PanicOnError:
  1010. panic(err)
  1011. }
  1012. }
  1013. return nil
  1014. }
  1015. type parseFunc func(flag *Flag, value string) error
  1016. // ParseAll parses flag definitions from the argument list, which should not
  1017. // include the command name. The arguments for fn are flag and value. Must be
  1018. // called after all flags in the FlagSet are defined and before flags are
  1019. // accessed by the program. The return value will be ErrHelp if -help was set
  1020. // but not defined.
  1021. func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
  1022. f.parsed = true
  1023. f.args = make([]string, 0, len(arguments))
  1024. err := f.parseArgs(arguments, fn)
  1025. if err != nil {
  1026. switch f.errorHandling {
  1027. case ContinueOnError:
  1028. return err
  1029. case ExitOnError:
  1030. os.Exit(2)
  1031. case PanicOnError:
  1032. panic(err)
  1033. }
  1034. }
  1035. return nil
  1036. }
  1037. // Parsed reports whether f.Parse has been called.
  1038. func (f *FlagSet) Parsed() bool {
  1039. return f.parsed
  1040. }
  1041. // Parse parses the command-line flags from os.Args[1:]. Must be called
  1042. // after all flags are defined and before flags are accessed by the program.
  1043. func Parse() {
  1044. // Ignore errors; CommandLine is set for ExitOnError.
  1045. CommandLine.Parse(os.Args[1:])
  1046. }
  1047. // ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
  1048. // The arguments for fn are flag and value. Must be called after all flags are
  1049. // defined and before flags are accessed by the program.
  1050. func ParseAll(fn func(flag *Flag, value string) error) {
  1051. // Ignore errors; CommandLine is set for ExitOnError.
  1052. CommandLine.ParseAll(os.Args[1:], fn)
  1053. }
  1054. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  1055. func SetInterspersed(interspersed bool) {
  1056. CommandLine.SetInterspersed(interspersed)
  1057. }
  1058. // Parsed returns true if the command-line flags have been parsed.
  1059. func Parsed() bool {
  1060. return CommandLine.Parsed()
  1061. }
  1062. // CommandLine is the default set of command-line flags, parsed from os.Args.
  1063. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
  1064. // NewFlagSet returns a new, empty flag set with the specified name,
  1065. // error handling property and SortFlags set to true.
  1066. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
  1067. f := &FlagSet{
  1068. name: name,
  1069. errorHandling: errorHandling,
  1070. argsLenAtDash: -1,
  1071. interspersed: true,
  1072. SortFlags: true,
  1073. }
  1074. return f
  1075. }
  1076. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  1077. func (f *FlagSet) SetInterspersed(interspersed bool) {
  1078. f.interspersed = interspersed
  1079. }
  1080. // Init sets the name and error handling property for a flag set.
  1081. // By default, the zero FlagSet uses an empty name and the
  1082. // ContinueOnError error handling policy.
  1083. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
  1084. f.name = name
  1085. f.errorHandling = errorHandling
  1086. f.argsLenAtDash = -1
  1087. }