flag.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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. // VisitAll visits the command-line flags in lexicographical order, calling
  211. // fn for each. It visits all flags, even those not set.
  212. func VisitAll(fn func(*Flag)) {
  213. CommandLine.VisitAll(fn)
  214. }
  215. // Visit visits the flags in lexicographical order, calling fn for each.
  216. // It visits only those flags that have been set.
  217. func (f *FlagSet) Visit(fn func(*Flag)) {
  218. for _, flag := range sortFlags(f.actual) {
  219. fn(flag)
  220. }
  221. }
  222. // Visit visits the command-line flags in lexicographical order, calling fn
  223. // for each. It visits only those flags that have been set.
  224. func Visit(fn func(*Flag)) {
  225. CommandLine.Visit(fn)
  226. }
  227. // Lookup returns the Flag structure of the named flag, returning nil if none exists.
  228. func (f *FlagSet) Lookup(name string) *Flag {
  229. return f.lookup(f.normalizeFlagName(name))
  230. }
  231. // lookup returns the Flag structure of the named flag, returning nil if none exists.
  232. func (f *FlagSet) lookup(name NormalizedName) *Flag {
  233. return f.formal[name]
  234. }
  235. // func to return a given type for a given flag name
  236. func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
  237. flag := f.Lookup(name)
  238. if flag == nil {
  239. err := fmt.Errorf("flag accessed but not defined: %s", name)
  240. return nil, err
  241. }
  242. if flag.Value.Type() != ftype {
  243. err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
  244. return nil, err
  245. }
  246. sval := flag.Value.String()
  247. result, err := convFunc(sval)
  248. if err != nil {
  249. return nil, err
  250. }
  251. return result, nil
  252. }
  253. // ArgsLenAtDash will return the length of f.Args at the moment when a -- was
  254. // found during arg parsing. This allows your program to know which args were
  255. // before the -- and which came after.
  256. func (f *FlagSet) ArgsLenAtDash() int {
  257. return f.argsLenAtDash
  258. }
  259. // MarkDeprecated indicated that a flag is deprecated in your program. It will
  260. // continue to function but will not show up in help or usage messages. Using
  261. // this flag will also print the given usageMessage.
  262. func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
  263. flag := f.Lookup(name)
  264. if flag == nil {
  265. return fmt.Errorf("flag %q does not exist", name)
  266. }
  267. if len(usageMessage) == 0 {
  268. return fmt.Errorf("deprecated message for flag %q must be set", name)
  269. }
  270. flag.Deprecated = usageMessage
  271. return nil
  272. }
  273. // MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
  274. // program. It will continue to function but will not show up in help or usage
  275. // messages. Using this flag will also print the given usageMessage.
  276. func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
  277. flag := f.Lookup(name)
  278. if flag == nil {
  279. return fmt.Errorf("flag %q does not exist", name)
  280. }
  281. if len(usageMessage) == 0 {
  282. return fmt.Errorf("deprecated message for flag %q must be set", name)
  283. }
  284. flag.ShorthandDeprecated = usageMessage
  285. return nil
  286. }
  287. // MarkHidden sets a flag to 'hidden' in your program. It will continue to
  288. // function but will not show up in help or usage messages.
  289. func (f *FlagSet) MarkHidden(name string) error {
  290. flag := f.Lookup(name)
  291. if flag == nil {
  292. return fmt.Errorf("flag %q does not exist", name)
  293. }
  294. flag.Hidden = true
  295. return nil
  296. }
  297. // Lookup returns the Flag structure of the named command-line flag,
  298. // returning nil if none exists.
  299. func Lookup(name string) *Flag {
  300. return CommandLine.Lookup(name)
  301. }
  302. // Set sets the value of the named flag.
  303. func (f *FlagSet) Set(name, value string) error {
  304. normalName := f.normalizeFlagName(name)
  305. flag, ok := f.formal[normalName]
  306. if !ok {
  307. return fmt.Errorf("no such flag -%v", name)
  308. }
  309. err := flag.Value.Set(value)
  310. if err != nil {
  311. return err
  312. }
  313. if f.actual == nil {
  314. f.actual = make(map[NormalizedName]*Flag)
  315. }
  316. f.actual[normalName] = flag
  317. flag.Changed = true
  318. if len(flag.Deprecated) > 0 {
  319. fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
  320. }
  321. return nil
  322. }
  323. // SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
  324. // This is sometimes used by spf13/cobra programs which want to generate additional
  325. // bash completion information.
  326. func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
  327. normalName := f.normalizeFlagName(name)
  328. flag, ok := f.formal[normalName]
  329. if !ok {
  330. return fmt.Errorf("no such flag -%v", name)
  331. }
  332. if flag.Annotations == nil {
  333. flag.Annotations = map[string][]string{}
  334. }
  335. flag.Annotations[key] = values
  336. return nil
  337. }
  338. // Changed returns true if the flag was explicitly set during Parse() and false
  339. // otherwise
  340. func (f *FlagSet) Changed(name string) bool {
  341. flag := f.Lookup(name)
  342. // If a flag doesn't exist, it wasn't changed....
  343. if flag == nil {
  344. return false
  345. }
  346. return flag.Changed
  347. }
  348. // Set sets the value of the named command-line flag.
  349. func Set(name, value string) error {
  350. return CommandLine.Set(name, value)
  351. }
  352. // PrintDefaults prints, to standard error unless configured
  353. // otherwise, the default values of all defined flags in the set.
  354. func (f *FlagSet) PrintDefaults() {
  355. usages := f.FlagUsages()
  356. fmt.Fprintf(f.out(), "%s", usages)
  357. }
  358. // FlagUsages Returns a string containing the usage information for all flags in
  359. // the FlagSet
  360. func (f *FlagSet) FlagUsages() string {
  361. x := new(bytes.Buffer)
  362. f.VisitAll(func(flag *Flag) {
  363. if len(flag.Deprecated) > 0 || flag.Hidden {
  364. return
  365. }
  366. format := ""
  367. if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
  368. format = " -%s, --%s"
  369. } else {
  370. format = " %s --%s"
  371. }
  372. if len(flag.NoOptDefVal) > 0 {
  373. format = format + "["
  374. }
  375. if flag.Value.Type() == "string" {
  376. // put quotes on the value
  377. format = format + "=%q"
  378. } else {
  379. format = format + "=%s"
  380. }
  381. if len(flag.NoOptDefVal) > 0 {
  382. format = format + "]"
  383. }
  384. format = format + ": %s\n"
  385. shorthand := flag.Shorthand
  386. if len(flag.ShorthandDeprecated) > 0 {
  387. shorthand = ""
  388. }
  389. fmt.Fprintf(x, format, shorthand, flag.Name, flag.DefValue, flag.Usage)
  390. })
  391. return x.String()
  392. }
  393. // PrintDefaults prints to standard error the default values of all defined command-line flags.
  394. func PrintDefaults() {
  395. CommandLine.PrintDefaults()
  396. }
  397. // defaultUsage is the default function to print a usage message.
  398. func defaultUsage(f *FlagSet) {
  399. fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
  400. f.PrintDefaults()
  401. }
  402. // NOTE: Usage is not just defaultUsage(CommandLine)
  403. // because it serves (via godoc flag Usage) as the example
  404. // for how to write your own usage function.
  405. // Usage prints to standard error a usage message documenting all defined command-line flags.
  406. // The function is a variable that may be changed to point to a custom function.
  407. var Usage = func() {
  408. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  409. PrintDefaults()
  410. }
  411. // NFlag returns the number of flags that have been set.
  412. func (f *FlagSet) NFlag() int { return len(f.actual) }
  413. // NFlag returns the number of command-line flags that have been set.
  414. func NFlag() int { return len(CommandLine.actual) }
  415. // Arg returns the i'th argument. Arg(0) is the first remaining argument
  416. // after flags have been processed.
  417. func (f *FlagSet) Arg(i int) string {
  418. if i < 0 || i >= len(f.args) {
  419. return ""
  420. }
  421. return f.args[i]
  422. }
  423. // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
  424. // after flags have been processed.
  425. func Arg(i int) string {
  426. return CommandLine.Arg(i)
  427. }
  428. // NArg is the number of arguments remaining after flags have been processed.
  429. func (f *FlagSet) NArg() int { return len(f.args) }
  430. // NArg is the number of arguments remaining after flags have been processed.
  431. func NArg() int { return len(CommandLine.args) }
  432. // Args returns the non-flag arguments.
  433. func (f *FlagSet) Args() []string { return f.args }
  434. // Args returns the non-flag command-line arguments.
  435. func Args() []string { return CommandLine.args }
  436. // Var defines a flag with the specified name and usage string. The type and
  437. // value of the flag are represented by the first argument, of type Value, which
  438. // typically holds a user-defined implementation of Value. For instance, the
  439. // caller could create a flag that turns a comma-separated string into a slice
  440. // of strings by giving the slice the methods of Value; in particular, Set would
  441. // decompose the comma-separated string into the slice.
  442. func (f *FlagSet) Var(value Value, name string, usage string) {
  443. f.VarP(value, name, "", usage)
  444. }
  445. // VarPF is like VarP, but returns the flag created
  446. func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
  447. // Remember the default value as a string; it won't change.
  448. flag := &Flag{
  449. Name: name,
  450. Shorthand: shorthand,
  451. Usage: usage,
  452. Value: value,
  453. DefValue: value.String(),
  454. }
  455. f.AddFlag(flag)
  456. return flag
  457. }
  458. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  459. func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
  460. _ = f.VarPF(value, name, shorthand, usage)
  461. }
  462. // AddFlag will add the flag to the FlagSet
  463. func (f *FlagSet) AddFlag(flag *Flag) {
  464. // Call normalizeFlagName function only once
  465. normalizedFlagName := f.normalizeFlagName(flag.Name)
  466. _, alreadythere := f.formal[normalizedFlagName]
  467. if alreadythere {
  468. msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
  469. fmt.Fprintln(f.out(), msg)
  470. panic(msg) // Happens only if flags are declared with identical names
  471. }
  472. if f.formal == nil {
  473. f.formal = make(map[NormalizedName]*Flag)
  474. }
  475. flag.Name = string(normalizedFlagName)
  476. f.formal[normalizedFlagName] = flag
  477. if len(flag.Shorthand) == 0 {
  478. return
  479. }
  480. if len(flag.Shorthand) > 1 {
  481. fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
  482. panic("shorthand is more than one character")
  483. }
  484. if f.shorthands == nil {
  485. f.shorthands = make(map[byte]*Flag)
  486. }
  487. c := flag.Shorthand[0]
  488. old, alreadythere := f.shorthands[c]
  489. if alreadythere {
  490. fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
  491. panic("shorthand redefinition")
  492. }
  493. f.shorthands[c] = flag
  494. }
  495. // AddFlagSet adds one FlagSet to another. If a flag is already present in f
  496. // the flag from newSet will be ignored
  497. func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
  498. if newSet == nil {
  499. return
  500. }
  501. newSet.VisitAll(func(flag *Flag) {
  502. if f.Lookup(flag.Name) == nil {
  503. f.AddFlag(flag)
  504. }
  505. })
  506. }
  507. // Var defines a flag with the specified name and usage string. The type and
  508. // value of the flag are represented by the first argument, of type Value, which
  509. // typically holds a user-defined implementation of Value. For instance, the
  510. // caller could create a flag that turns a comma-separated string into a slice
  511. // of strings by giving the slice the methods of Value; in particular, Set would
  512. // decompose the comma-separated string into the slice.
  513. func Var(value Value, name string, usage string) {
  514. CommandLine.VarP(value, name, "", usage)
  515. }
  516. // VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
  517. func VarP(value Value, name, shorthand, usage string) {
  518. CommandLine.VarP(value, name, shorthand, usage)
  519. }
  520. // failf prints to standard error a formatted error and usage message and
  521. // returns the error.
  522. func (f *FlagSet) failf(format string, a ...interface{}) error {
  523. err := fmt.Errorf(format, a...)
  524. fmt.Fprintln(f.out(), err)
  525. f.usage()
  526. return err
  527. }
  528. // usage calls the Usage method for the flag set, or the usage function if
  529. // the flag set is CommandLine.
  530. func (f *FlagSet) usage() {
  531. if f == CommandLine {
  532. Usage()
  533. } else if f.Usage == nil {
  534. defaultUsage(f)
  535. } else {
  536. f.Usage()
  537. }
  538. }
  539. func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
  540. if err := flag.Value.Set(value); err != nil {
  541. return f.failf("invalid argument %q for %s: %v", value, origArg, err)
  542. }
  543. // mark as visited for Visit()
  544. if f.actual == nil {
  545. f.actual = make(map[NormalizedName]*Flag)
  546. }
  547. f.actual[f.normalizeFlagName(flag.Name)] = flag
  548. flag.Changed = true
  549. if len(flag.Deprecated) > 0 {
  550. fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
  551. }
  552. if len(flag.ShorthandDeprecated) > 0 && containsShorthand(origArg, flag.Shorthand) {
  553. fmt.Fprintf(os.Stderr, "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
  554. }
  555. return nil
  556. }
  557. func containsShorthand(arg, shorthand string) bool {
  558. // filter out flags --<flag_name>
  559. if strings.HasPrefix(arg, "-") {
  560. return false
  561. }
  562. arg = strings.SplitN(arg, "=", 2)[0]
  563. return strings.Contains(arg, shorthand)
  564. }
  565. func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
  566. a = args
  567. name := s[2:]
  568. if len(name) == 0 || name[0] == '-' || name[0] == '=' {
  569. err = f.failf("bad flag syntax: %s", s)
  570. return
  571. }
  572. split := strings.SplitN(name, "=", 2)
  573. name = split[0]
  574. flag, alreadythere := f.formal[f.normalizeFlagName(name)]
  575. if !alreadythere {
  576. if name == "help" { // special case for nice help message.
  577. f.usage()
  578. return a, ErrHelp
  579. }
  580. err = f.failf("unknown flag: --%s", name)
  581. return
  582. }
  583. var value string
  584. if len(split) == 2 {
  585. // '--flag=arg'
  586. value = split[1]
  587. } else if len(flag.NoOptDefVal) > 0 {
  588. // '--flag' (arg was optional)
  589. value = flag.NoOptDefVal
  590. } else if len(a) > 0 {
  591. // '--flag arg'
  592. value = a[0]
  593. a = a[1:]
  594. } else {
  595. // '--flag' (arg was required)
  596. err = f.failf("flag needs an argument: %s", s)
  597. return
  598. }
  599. err = f.setFlag(flag, value, s)
  600. return
  601. }
  602. func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
  603. outArgs = args
  604. outShorts = shorthands[1:]
  605. c := shorthands[0]
  606. flag, alreadythere := f.shorthands[c]
  607. if !alreadythere {
  608. if c == 'h' { // special case for nice help message.
  609. f.usage()
  610. err = ErrHelp
  611. return
  612. }
  613. //TODO continue on error
  614. err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
  615. return
  616. }
  617. var value string
  618. if len(shorthands) > 2 && shorthands[1] == '=' {
  619. value = shorthands[2:]
  620. outShorts = ""
  621. } else if len(flag.NoOptDefVal) > 0 {
  622. value = flag.NoOptDefVal
  623. } else if len(shorthands) > 1 {
  624. value = shorthands[1:]
  625. outShorts = ""
  626. } else if len(args) > 0 {
  627. value = args[0]
  628. outArgs = args[1:]
  629. } else {
  630. err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
  631. return
  632. }
  633. err = f.setFlag(flag, value, shorthands)
  634. return
  635. }
  636. func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
  637. a = args
  638. shorthands := s[1:]
  639. for len(shorthands) > 0 {
  640. shorthands, a, err = f.parseSingleShortArg(shorthands, args)
  641. if err != nil {
  642. return
  643. }
  644. }
  645. return
  646. }
  647. func (f *FlagSet) parseArgs(args []string) (err error) {
  648. for len(args) > 0 {
  649. s := args[0]
  650. args = args[1:]
  651. if len(s) == 0 || s[0] != '-' || len(s) == 1 {
  652. if !f.interspersed {
  653. f.args = append(f.args, s)
  654. f.args = append(f.args, args...)
  655. return nil
  656. }
  657. f.args = append(f.args, s)
  658. continue
  659. }
  660. if s[1] == '-' {
  661. if len(s) == 2 { // "--" terminates the flags
  662. f.argsLenAtDash = len(f.args)
  663. f.args = append(f.args, args...)
  664. break
  665. }
  666. args, err = f.parseLongArg(s, args)
  667. } else {
  668. args, err = f.parseShortArg(s, args)
  669. }
  670. if err != nil {
  671. return
  672. }
  673. }
  674. return
  675. }
  676. // Parse parses flag definitions from the argument list, which should not
  677. // include the command name. Must be called after all flags in the FlagSet
  678. // are defined and before flags are accessed by the program.
  679. // The return value will be ErrHelp if -help was set but not defined.
  680. func (f *FlagSet) Parse(arguments []string) error {
  681. f.parsed = true
  682. f.args = make([]string, 0, len(arguments))
  683. err := f.parseArgs(arguments)
  684. if err != nil {
  685. switch f.errorHandling {
  686. case ContinueOnError:
  687. return err
  688. case ExitOnError:
  689. os.Exit(2)
  690. case PanicOnError:
  691. panic(err)
  692. }
  693. }
  694. return nil
  695. }
  696. // Parsed reports whether f.Parse has been called.
  697. func (f *FlagSet) Parsed() bool {
  698. return f.parsed
  699. }
  700. // Parse parses the command-line flags from os.Args[1:]. Must be called
  701. // after all flags are defined and before flags are accessed by the program.
  702. func Parse() {
  703. // Ignore errors; CommandLine is set for ExitOnError.
  704. CommandLine.Parse(os.Args[1:])
  705. }
  706. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  707. func SetInterspersed(interspersed bool) {
  708. CommandLine.SetInterspersed(interspersed)
  709. }
  710. // Parsed returns true if the command-line flags have been parsed.
  711. func Parsed() bool {
  712. return CommandLine.Parsed()
  713. }
  714. // The default set of command-line flags, parsed from os.Args.
  715. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
  716. // NewFlagSet returns a new, empty flag set with the specified name and
  717. // error handling property.
  718. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
  719. f := &FlagSet{
  720. name: name,
  721. errorHandling: errorHandling,
  722. argsLenAtDash: -1,
  723. interspersed: true,
  724. }
  725. return f
  726. }
  727. // SetInterspersed sets whether to support interspersed option/non-option arguments.
  728. func (f *FlagSet) SetInterspersed(interspersed bool) {
  729. f.interspersed = interspersed
  730. }
  731. // Init sets the name and error handling property for a flag set.
  732. // By default, the zero FlagSet uses an empty name and the
  733. // ContinueOnError error handling policy.
  734. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
  735. f.name = name
  736. f.errorHandling = errorHandling
  737. f.argsLenAtDash = -1
  738. }