flag.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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.Fprintf(f.out(), "%s", 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. return true
  387. }
  388. }
  389. // UnquoteUsage extracts a back-quoted name from the usage
  390. // string for a flag and returns it and the un-quoted usage.
  391. // Given "a `name` to show" it returns ("name", "a name to show").
  392. // If there are no back quotes, the name is an educated guess of the
  393. // type of the flag's value, or the empty string if the flag is boolean.
  394. func UnquoteUsage(flag *Flag) (name string, usage string) {
  395. // Look for a back-quoted name, but avoid the strings package.
  396. usage = flag.Usage
  397. for i := 0; i < len(usage); i++ {
  398. if usage[i] == '`' {
  399. for j := i + 1; j < len(usage); j++ {
  400. if usage[j] == '`' {
  401. name = usage[i+1 : j]
  402. usage = usage[:i] + name + usage[j+1:]
  403. return name, usage
  404. }
  405. }
  406. break // Only one back quote; use type name.
  407. }
  408. }
  409. name = flag.Value.Type()
  410. switch name {
  411. case "bool":
  412. name = ""
  413. case "float64":
  414. name = "float"
  415. case "int64":
  416. name = "int"
  417. case "uint64":
  418. name = "uint"
  419. }
  420. return
  421. }
  422. // FlagUsages Returns a string containing the usage information for all flags in
  423. // the FlagSet
  424. func (f *FlagSet) FlagUsages() string {
  425. x := new(bytes.Buffer)
  426. lines := make([]string, 0, len(f.formal))
  427. maxlen := 0
  428. f.VisitAll(func(flag *Flag) {
  429. if len(flag.Deprecated) > 0 || flag.Hidden {
  430. return
  431. }
  432. line := ""
  433. if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
  434. line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
  435. } else {
  436. line = fmt.Sprintf(" --%s", flag.Name)
  437. }
  438. varname, usage := UnquoteUsage(flag)
  439. if len(varname) > 0 {
  440. line += " " + varname
  441. }
  442. if len(flag.NoOptDefVal) > 0 {
  443. switch flag.Value.Type() {
  444. case "string":
  445. line += fmt.Sprintf("[=%q]", flag.NoOptDefVal)
  446. case "bool":
  447. if flag.NoOptDefVal != "true" {
  448. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  449. }
  450. default:
  451. line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
  452. }
  453. }
  454. // This special character will be replaced with spacing once the
  455. // correct alignment is calculated
  456. line += "\x00"
  457. if len(line) > maxlen {
  458. maxlen = len(line)
  459. }
  460. line += usage
  461. if !flag.defaultIsZeroValue() {
  462. if flag.Value.Type() == "string" {
  463. line += fmt.Sprintf(" (default %q)", flag.DefValue)
  464. } else {
  465. line += fmt.Sprintf(" (default %s)", flag.DefValue)
  466. }
  467. }
  468. lines = append(lines, line)
  469. })
  470. for _, line := range lines {
  471. sidx := strings.Index(line, "\x00")
  472. spacing := strings.Repeat(" ", maxlen-sidx)
  473. fmt.Fprintln(x, line[:sidx], spacing, line[sidx+1:])
  474. }
  475. return x.String()
  476. }
  477. // PrintDefaults prints to standard error the default values of all defined command-line flags.
  478. func PrintDefaults() {
  479. CommandLine.PrintDefaults()
  480. }
  481. // defaultUsage is the default function to print a usage message.
  482. func defaultUsage(f *FlagSet) {
  483. fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
  484. f.PrintDefaults()
  485. }
  486. // NOTE: Usage is not just defaultUsage(CommandLine)
  487. // because it serves (via godoc flag Usage) as the example
  488. // for how to write your own usage function.
  489. // Usage prints to standard error a usage message documenting all defined command-line flags.
  490. // The function is a variable that may be changed to point to a custom function.
  491. // By default it prints a simple header and calls PrintDefaults; for details about the
  492. // format of the output and how to control it, see the documentation for PrintDefaults.
  493. var Usage = func() {
  494. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  495. PrintDefaults()
  496. }
  497. // NFlag returns the number of flags that have been set.
  498. func (f *FlagSet) NFlag() int { return len(f.actual) }
  499. // NFlag returns the number of command-line flags that have been set.
  500. func NFlag() int { return len(CommandLine.actual) }
  501. // Arg returns the i'th argument. Arg(0) is the first remaining argument
  502. // after flags have been processed.
  503. func (f *FlagSet) Arg(i int) string {
  504. if i < 0 || i >= len(f.args) {
  505. return ""
  506. }
  507. return f.args[i]
  508. }
  509. // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
  510. // after flags have been processed.
  511. func Arg(i int) string {
  512. return CommandLine.Arg(i)
  513. }
  514. // NArg is the number of arguments remaining after flags have been processed.
  515. func (f *FlagSet) NArg() int { return len(f.args) }
  516. // NArg is the number of arguments remaining after flags have been processed.
  517. func NArg() int { return len(CommandLine.args) }
  518. // Args returns the non-flag arguments.
  519. func (f *FlagSet) Args() []string { return f.args }
  520. // Args returns the non-flag command-line arguments.
  521. func Args() []string { return CommandLine.args }
  522. // Var defines a flag with the specified name and usage string. The type and
  523. // value of the flag are represented by the first argument, of type Value, which
  524. // typically holds a user-defined implementation of Value. For instance, the
  525. // caller could create a flag that turns a comma-separated string into a slice
  526. // of strings by giving the slice the methods of Value; in particular, Set would
  527. // decompose the comma-separated string into the slice.
  528. func (f *FlagSet) Var(value Value, name string, usage string) {
  529. f.VarP(value, name, "", usage)
  530. }
  531. // VarPF is like VarP, but returns the flag created
  532. func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
  533. // Remember the default value as a string; it won't change.
  534. flag := &Flag{
  535. Name: name,
  536. Shorthand: shorthand,
  537. Usage: usage,
  538. Value: value,
  539. DefValue: value.String(),
  540. }
  541. f.AddFlag(flag)
  542. return flag
  543. }
  544. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  545. func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
  546. _ = f.VarPF(value, name, shorthand, usage)
  547. }
  548. // AddFlag will add the flag to the FlagSet
  549. func (f *FlagSet) AddFlag(flag *Flag) {
  550. // Call normalizeFlagName function only once
  551. normalizedFlagName := f.normalizeFlagName(flag.Name)
  552. _, alreadythere := f.formal[normalizedFlagName]
  553. if alreadythere {
  554. msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
  555. fmt.Fprintln(f.out(), msg)
  556. panic(msg) // Happens only if flags are declared with identical names
  557. }
  558. if f.formal == nil {
  559. f.formal = make(map[NormalizedName]*Flag)
  560. }
  561. flag.Name = string(normalizedFlagName)
  562. f.formal[normalizedFlagName] = flag
  563. if len(flag.Shorthand) == 0 {
  564. return
  565. }
  566. if len(flag.Shorthand) > 1 {
  567. fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
  568. panic("shorthand is more than one character")
  569. }
  570. if f.shorthands == nil {
  571. f.shorthands = make(map[byte]*Flag)
  572. }
  573. c := flag.Shorthand[0]
  574. old, alreadythere := f.shorthands[c]
  575. if alreadythere {
  576. fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
  577. panic("shorthand redefinition")
  578. }
  579. f.shorthands[c] = flag
  580. }
  581. // AddFlagSet adds one FlagSet to another. If a flag is already present in f
  582. // the flag from newSet will be ignored
  583. func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
  584. if newSet == nil {
  585. return
  586. }
  587. newSet.VisitAll(func(flag *Flag) {
  588. if f.Lookup(flag.Name) == nil {
  589. f.AddFlag(flag)
  590. }
  591. })
  592. }
  593. // Var defines a flag with the specified name and usage string. The type and
  594. // value of the flag are represented by the first argument, of type Value, which
  595. // typically holds a user-defined implementation of Value. For instance, the
  596. // caller could create a flag that turns a comma-separated string into a slice
  597. // of strings by giving the slice the methods of Value; in particular, Set would
  598. // decompose the comma-separated string into the slice.
  599. func Var(value Value, name string, usage string) {
  600. CommandLine.VarP(value, name, "", usage)
  601. }
  602. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  603. func VarP(value Value, name, shorthand, usage string) {
  604. CommandLine.VarP(value, name, shorthand, usage)
  605. }
  606. // failf prints to standard error a formatted error and usage message and
  607. // returns the error.
  608. func (f *FlagSet) failf(format string, a ...interface{}) error {
  609. err := fmt.Errorf(format, a...)
  610. fmt.Fprintln(f.out(), err)
  611. f.usage()
  612. return err
  613. }
  614. // usage calls the Usage method for the flag set, or the usage function if
  615. // the flag set is CommandLine.
  616. func (f *FlagSet) usage() {
  617. if f == CommandLine {
  618. Usage()
  619. } else if f.Usage == nil {
  620. defaultUsage(f)
  621. } else {
  622. f.Usage()
  623. }
  624. }
  625. func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
  626. if err := flag.Value.Set(value); err != nil {
  627. return f.failf("invalid argument %q for %s: %v", value, origArg, err)
  628. }
  629. // mark as visited for Visit()
  630. if f.actual == nil {
  631. f.actual = make(map[NormalizedName]*Flag)
  632. }
  633. f.actual[f.normalizeFlagName(flag.Name)] = flag
  634. flag.Changed = true
  635. if len(flag.Deprecated) > 0 {
  636. fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
  637. }
  638. if len(flag.ShorthandDeprecated) > 0 && containsShorthand(origArg, flag.Shorthand) {
  639. fmt.Fprintf(os.Stderr, "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
  640. }
  641. return nil
  642. }
  643. func containsShorthand(arg, shorthand string) bool {
  644. // filter out flags --<flag_name>
  645. if strings.HasPrefix(arg, "-") {
  646. return false
  647. }
  648. arg = strings.SplitN(arg, "=", 2)[0]
  649. return strings.Contains(arg, shorthand)
  650. }
  651. func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
  652. a = args
  653. name := s[2:]
  654. if len(name) == 0 || name[0] == '-' || name[0] == '=' {
  655. err = f.failf("bad flag syntax: %s", s)
  656. return
  657. }
  658. split := strings.SplitN(name, "=", 2)
  659. name = split[0]
  660. flag, alreadythere := f.formal[f.normalizeFlagName(name)]
  661. if !alreadythere {
  662. if name == "help" { // special case for nice help message.
  663. f.usage()
  664. return a, ErrHelp
  665. }
  666. err = f.failf("unknown flag: --%s", name)
  667. return
  668. }
  669. var value string
  670. if len(split) == 2 {
  671. // '--flag=arg'
  672. value = split[1]
  673. } else if len(flag.NoOptDefVal) > 0 {
  674. // '--flag' (arg was optional)
  675. value = flag.NoOptDefVal
  676. } else if len(a) > 0 {
  677. // '--flag arg'
  678. value = a[0]
  679. a = a[1:]
  680. } else {
  681. // '--flag' (arg was required)
  682. err = f.failf("flag needs an argument: %s", s)
  683. return
  684. }
  685. err = f.setFlag(flag, value, s)
  686. return
  687. }
  688. func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
  689. if strings.HasPrefix(shorthands, "test.") {
  690. return
  691. }
  692. outArgs = args
  693. outShorts = shorthands[1:]
  694. c := shorthands[0]
  695. flag, alreadythere := f.shorthands[c]
  696. if !alreadythere {
  697. if c == 'h' { // special case for nice help message.
  698. f.usage()
  699. err = ErrHelp
  700. return
  701. }
  702. //TODO continue on error
  703. err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
  704. return
  705. }
  706. var value string
  707. if len(shorthands) > 2 && shorthands[1] == '=' {
  708. value = shorthands[2:]
  709. outShorts = ""
  710. } else if len(flag.NoOptDefVal) > 0 {
  711. value = flag.NoOptDefVal
  712. } else if len(shorthands) > 1 {
  713. value = shorthands[1:]
  714. outShorts = ""
  715. } else if len(args) > 0 {
  716. value = args[0]
  717. outArgs = args[1:]
  718. } else {
  719. err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
  720. return
  721. }
  722. err = f.setFlag(flag, value, shorthands)
  723. return
  724. }
  725. func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
  726. a = args
  727. shorthands := s[1:]
  728. for len(shorthands) > 0 {
  729. shorthands, a, err = f.parseSingleShortArg(shorthands, args)
  730. if err != nil {
  731. return
  732. }
  733. }
  734. return
  735. }
  736. func (f *FlagSet) parseArgs(args []string) (err error) {
  737. for len(args) > 0 {
  738. s := args[0]
  739. args = args[1:]
  740. if len(s) == 0 || s[0] != '-' || len(s) == 1 {
  741. if !f.interspersed {
  742. f.args = append(f.args, s)
  743. f.args = append(f.args, args...)
  744. return nil
  745. }
  746. f.args = append(f.args, s)
  747. continue
  748. }
  749. if s[1] == '-' {
  750. if len(s) == 2 { // "--" terminates the flags
  751. f.argsLenAtDash = len(f.args)
  752. f.args = append(f.args, args...)
  753. break
  754. }
  755. args, err = f.parseLongArg(s, args)
  756. } else {
  757. args, err = f.parseShortArg(s, args)
  758. }
  759. if err != nil {
  760. return
  761. }
  762. }
  763. return
  764. }
  765. // Parse parses flag definitions from the argument list, which should not
  766. // include the command name. Must be called after all flags in the FlagSet
  767. // are defined and before flags are accessed by the program.
  768. // The return value will be ErrHelp if -help was set but not defined.
  769. func (f *FlagSet) Parse(arguments []string) error {
  770. f.parsed = true
  771. f.args = make([]string, 0, len(arguments))
  772. err := f.parseArgs(arguments)
  773. if err != nil {
  774. switch f.errorHandling {
  775. case ContinueOnError:
  776. return err
  777. case ExitOnError:
  778. os.Exit(2)
  779. case PanicOnError:
  780. panic(err)
  781. }
  782. }
  783. return nil
  784. }
  785. // Parsed reports whether f.Parse has been called.
  786. func (f *FlagSet) Parsed() bool {
  787. return f.parsed
  788. }
  789. // Parse parses the command-line flags from os.Args[1:]. Must be called
  790. // after all flags are defined and before flags are accessed by the program.
  791. func Parse() {
  792. // Ignore errors; CommandLine is set for ExitOnError.
  793. CommandLine.Parse(os.Args[1:])
  794. }
  795. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  796. func SetInterspersed(interspersed bool) {
  797. CommandLine.SetInterspersed(interspersed)
  798. }
  799. // Parsed returns true if the command-line flags have been parsed.
  800. func Parsed() bool {
  801. return CommandLine.Parsed()
  802. }
  803. // CommandLine is the default set of command-line flags, parsed from os.Args.
  804. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
  805. // NewFlagSet returns a new, empty flag set with the specified name and
  806. // error handling property.
  807. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
  808. f := &FlagSet{
  809. name: name,
  810. errorHandling: errorHandling,
  811. argsLenAtDash: -1,
  812. interspersed: true,
  813. }
  814. return f
  815. }
  816. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  817. func (f *FlagSet) SetInterspersed(interspersed bool) {
  818. f.interspersed = interspersed
  819. }
  820. // Init sets the name and error handling property for a flag set.
  821. // By default, the zero FlagSet uses an empty name and the
  822. // ContinueOnError error handling policy.
  823. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
  824. f.name = name
  825. f.errorHandling = errorHandling
  826. f.argsLenAtDash = -1
  827. }