flag.go 35 KB

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