flag.go 32 KB

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