2
0

flag.go 36 KB

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