flag.go 33 KB

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