You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1148 lines
36 KiB

4 years ago
  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 flag implements command-line flag parsing.
  6. Usage:
  7. Define flags using flag.String(), Bool(), Int(), etc.
  8. This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
  9. import "flag"
  10. var ip = flag.Int("flagname", 1234, "help message for flagname")
  11. If you like, you can bind the flag to a variable using the Var() functions.
  12. var flagvar int
  13. func init() {
  14. flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
  15. }
  16. Or you can create custom flags that satisfy the Value interface (with
  17. pointer receivers) and couple them to flag parsing by
  18. flag.Var(&flagVal, "name", "help message for flagname")
  19. For such flags, the default value is just the initial value of the variable.
  20. After all flags are defined, call
  21. flag.Parse()
  22. to parse the command line into the defined flags.
  23. Flags may then be used directly. If you're using the flags themselves,
  24. they are all pointers; if you bind to variables, they're values.
  25. fmt.Println("ip has value ", *ip)
  26. fmt.Println("flagvar has value ", flagvar)
  27. After parsing, the arguments following the flags are available as the
  28. slice flag.Args() or individually as flag.Arg(i).
  29. The arguments are indexed from 0 through flag.NArg()-1.
  30. Command line flag syntax:
  31. -flag
  32. -flag=x
  33. -flag x // non-boolean flags only
  34. One or two minus signs may be used; they are equivalent.
  35. The last form is not permitted for boolean flags because the
  36. meaning of the command
  37. cmd -x *
  38. will change if there is a file called 0, false, etc. You must
  39. use the -flag=false form to turn off a boolean flag.
  40. Flag parsing stops just before the first non-flag argument
  41. ("-" is a non-flag argument) or after the terminator "--".
  42. Integer flags accept 1234, 0664, 0x1234 and may be negative.
  43. Boolean flags may be:
  44. 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
  45. Duration flags accept any input valid for time.ParseDuration.
  46. The default set of command-line flags is controlled by
  47. top-level functions. The FlagSet type allows one to define
  48. independent sets of flags, such as to implement subcommands
  49. in a command-line interface. The methods of FlagSet are
  50. analogous to the top-level functions for the command-line
  51. flag set.
  52. */
  53. package fla9
  54. import (
  55. "bufio"
  56. "errors"
  57. "fmt"
  58. "io"
  59. "os"
  60. "reflect"
  61. "sort"
  62. "strconv"
  63. "strings"
  64. "time"
  65. )
  66. // ErrHelp is the error returned if the -help or -h flag is invoked
  67. // but no such flag is defined.
  68. var ErrHelp = errors.New("flag: help requested")
  69. // -- bool Value
  70. type boolValue bool
  71. func newBoolValue(val bool, p *bool) *boolValue {
  72. *p = val
  73. return (*boolValue)(p)
  74. }
  75. func (b *boolValue) Set(s string) error {
  76. v, err := strconv.ParseBool(s)
  77. *b = boolValue(v)
  78. return err
  79. }
  80. func (b *boolValue) Get() interface{} { return bool(*b) }
  81. func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
  82. func (b *boolValue) IsBoolFlag() bool { return true }
  83. // optional interface to indicate boolean flags that can be
  84. // supplied without "=value" text
  85. type boolFlag interface {
  86. Value
  87. IsBoolFlag() bool
  88. }
  89. // -- int Value
  90. type intValue int
  91. func newIntValue(val int, p *int) *intValue {
  92. *p = val
  93. return (*intValue)(p)
  94. }
  95. func (i *intValue) Set(s string) error {
  96. v, err := strconv.ParseInt(s, 0, 64)
  97. *i = intValue(v)
  98. return err
  99. }
  100. func (i *intValue) Get() interface{} { return int(*i) }
  101. func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
  102. // -- int64 Value
  103. type int64Value int64
  104. func newInt64Value(val int64, p *int64) *int64Value {
  105. *p = val
  106. return (*int64Value)(p)
  107. }
  108. func (i *int64Value) Set(s string) error {
  109. v, err := strconv.ParseInt(s, 0, 64)
  110. *i = int64Value(v)
  111. return err
  112. }
  113. func (i *int64Value) Get() interface{} { return int64(*i) }
  114. func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
  115. // -- uint Value
  116. type uintValue uint
  117. func newUintValue(val uint, p *uint) *uintValue {
  118. *p = val
  119. return (*uintValue)(p)
  120. }
  121. func (i *uintValue) Set(s string) error {
  122. v, err := strconv.ParseUint(s, 0, 64)
  123. *i = uintValue(v)
  124. return err
  125. }
  126. func (i *uintValue) Get() interface{} { return uint(*i) }
  127. func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
  128. // -- uint64 Value
  129. type uint64Value uint64
  130. func newUint64Value(val uint64, p *uint64) *uint64Value {
  131. *p = val
  132. return (*uint64Value)(p)
  133. }
  134. func (i *uint64Value) Set(s string) error {
  135. v, err := strconv.ParseUint(s, 0, 64)
  136. *i = uint64Value(v)
  137. return err
  138. }
  139. func (i *uint64Value) Get() interface{} { return uint64(*i) }
  140. func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
  141. // -- string Value
  142. type stringValue string
  143. func newStringValue(val string, p *string) *stringValue {
  144. *p = val
  145. return (*stringValue)(p)
  146. }
  147. func (s *stringValue) Set(val string) error {
  148. *s = stringValue(val)
  149. return nil
  150. }
  151. func (s *stringValue) Get() interface{} { return string(*s) }
  152. func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
  153. // -- float64 Value
  154. type float64Value float64
  155. func newFloat64Value(val float64, p *float64) *float64Value {
  156. *p = val
  157. return (*float64Value)(p)
  158. }
  159. func (f *float64Value) Set(s string) error {
  160. v, err := strconv.ParseFloat(s, 64)
  161. *f = float64Value(v)
  162. return err
  163. }
  164. func (f *float64Value) Get() interface{} { return float64(*f) }
  165. func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
  166. // -- time.Duration Value
  167. type durationValue time.Duration
  168. func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
  169. *p = val
  170. return (*durationValue)(p)
  171. }
  172. func (d *durationValue) Set(s string) error {
  173. v, err := time.ParseDuration(s)
  174. *d = durationValue(v)
  175. return err
  176. }
  177. func (d *durationValue) Get() interface{} { return time.Duration(*d) }
  178. func (d *durationValue) String() string { return (*time.Duration)(d).String() }
  179. // Value is the interface to the dynamic value stored in a flag.
  180. // (The default value is represented as a string.)
  181. //
  182. // If a Value has an IsBoolFlag() bool method returning true,
  183. // the command-line parser makes -name equivalent to -name=true
  184. // rather than using the next command-line argument.
  185. //
  186. // Set is called once, in command line order, for each flag present.
  187. type Value interface {
  188. String() string
  189. Set(string) error
  190. }
  191. // Getter is an interface that allows the contents of a Value to be retrieved.
  192. // It wraps the Value interface, rather than being part of it, because it
  193. // appeared after Go 1 and its compatibility rules. All Value types provided
  194. // by this package satisfy the Getter interface.
  195. type Getter interface {
  196. Value
  197. Get() interface{}
  198. }
  199. // ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
  200. type ErrorHandling int
  201. // These constants cause FlagSet.Parse to behave as described if the parse fails.
  202. const (
  203. ContinueOnError ErrorHandling = iota // Return a descriptive error.
  204. ExitOnError // Call os.Exit(2).
  205. PanicOnError // Call panic with a descriptive error.
  206. )
  207. // A FlagSet represents a set of defined flags. The zero value of a FlagSet
  208. // has no name and has ContinueOnError error handling.
  209. type FlagSet struct {
  210. // Usage is the function called when an error occurs while parsing flags.
  211. // The field is a function (not a method) that may be changed to point to
  212. // a custom error handler.
  213. Usage func()
  214. name string
  215. parsed bool
  216. actual map[string]*Flag
  217. formal map[string]*Flag
  218. envPrefix string // prefix to all env variable names
  219. args []string // arguments after flags
  220. errorHandling ErrorHandling
  221. output io.Writer // nil means stderr; use out() accessor
  222. }
  223. // A Flag represents the state of a flag.
  224. type Flag struct {
  225. Name string // name as it appears on command line
  226. Usage string // help message
  227. Value Value // value as set
  228. DefValue string // default value (as text); for usage message
  229. }
  230. // sortFlags returns the flags as a slice in lexicographical sorted order.
  231. func sortFlags(flags map[string]*Flag) []*Flag {
  232. list := make(sort.StringSlice, len(flags))
  233. i := 0
  234. for _, f := range flags {
  235. list[i] = f.Name
  236. i++
  237. }
  238. list.Sort()
  239. result := make([]*Flag, len(list))
  240. for i, name := range list {
  241. result[i] = flags[name]
  242. }
  243. return result
  244. }
  245. func (f *FlagSet) out() io.Writer {
  246. if f.output == nil {
  247. return os.Stderr
  248. }
  249. return f.output
  250. }
  251. // SetOutput sets the destination for usage and error messages.
  252. // If output is nil, os.Stderr is used.
  253. func (f *FlagSet) SetOutput(output io.Writer) { f.output = output }
  254. // VisitAll visits the flags in lexicographical order, calling fn for each.
  255. // It visits all flags, even those not set.
  256. func (f *FlagSet) VisitAll(fn func(*Flag)) {
  257. for _, flag := range sortFlags(f.formal) {
  258. fn(flag)
  259. }
  260. }
  261. // VisitAll visits the command-line flags in lexicographical order, calling
  262. // fn for each. It visits all flags, even those not set.
  263. func VisitAll(fn func(*Flag)) { CommandLine.VisitAll(fn) }
  264. // Visit visits the flags in lexicographical order, calling fn for each.
  265. // It visits only those flags that have been set.
  266. func (f *FlagSet) Visit(fn func(*Flag)) {
  267. for _, flag := range sortFlags(f.actual) {
  268. fn(flag)
  269. }
  270. }
  271. // Visit visits the command-line flags in lexicographical order, calling fn
  272. // for each. It visits only those flags that have been set.
  273. func Visit(fn func(*Flag)) { CommandLine.Visit(fn) }
  274. // Lookup returns the Flag structure of the named flag, returning nil if none exists.
  275. func (f *FlagSet) Lookup(name string) *Flag { return f.formal[name] }
  276. // Lookup returns the Flag structure of the named command-line flag,
  277. // returning nil if none exists.
  278. func Lookup(name string) *Flag { return CommandLine.formal[name] }
  279. // Set sets the value of the named flag.
  280. func (f *FlagSet) Set(name, value string) error {
  281. flag, ok := f.formal[name]
  282. if !ok {
  283. return fmt.Errorf("no such flag -%v", name)
  284. }
  285. err := flag.Value.Set(value)
  286. if err != nil {
  287. return err
  288. }
  289. if f.actual == nil {
  290. f.actual = make(map[string]*Flag)
  291. }
  292. f.actual[name] = flag
  293. return nil
  294. }
  295. // Set sets the value of the named command-line flag.
  296. func Set(name, value string) error { return CommandLine.Set(name, value) }
  297. // isZeroValue guesses whether the string represents the zero
  298. // value for a flag. It is not accurate but in practice works OK.
  299. func isZeroValue(flag *Flag, value string) bool {
  300. // Build a zero value of the flag's Value type, and see if the
  301. // result of calling its String method equals the value passed in.
  302. // This works unless the Value type is itself an interface type.
  303. typ := reflect.TypeOf(flag.Value)
  304. var z reflect.Value
  305. if typ.Kind() == reflect.Ptr {
  306. z = reflect.New(typ.Elem())
  307. } else {
  308. z = reflect.Zero(typ)
  309. }
  310. if value == z.Interface().(Value).String() {
  311. return true
  312. }
  313. switch value {
  314. case "false", "", "0":
  315. return true
  316. }
  317. return false
  318. }
  319. // UnquoteUsage extracts a back-quoted name from the usage
  320. // string for a flag and returns it and the un-quoted usage.
  321. // Given "a `name` to show" it returns ("name", "a name to show").
  322. // If there are no back quotes, the name is an educated guess of the
  323. // type of the flag's value, or the empty string if the flag is boolean.
  324. func UnquoteUsage(flag *Flag) (name string, usage string) {
  325. // Look for a back-quoted name, but avoid the strings package.
  326. usage = flag.Usage
  327. for i := 0; i < len(usage); i++ {
  328. if usage[i] == '`' {
  329. for j := i + 1; j < len(usage); j++ {
  330. if usage[j] == '`' {
  331. name = usage[i+1 : j]
  332. usage = usage[:i] + name + usage[j+1:]
  333. return name, usage
  334. }
  335. }
  336. break // Only one back quote; use type name.
  337. }
  338. }
  339. // No explicit name, so use type if we can find one.
  340. name = "value"
  341. switch flag.Value.(type) {
  342. case boolFlag:
  343. name = ""
  344. case *durationValue:
  345. name = "duration"
  346. case *float64Value:
  347. name = "float"
  348. case *intValue, *int64Value:
  349. name = "int"
  350. case *stringValue:
  351. name = "string"
  352. case *uintValue, *uint64Value:
  353. name = "uint"
  354. }
  355. return
  356. }
  357. // PrintDefaults prints to standard error the default values of all
  358. // defined command-line flags in the set. See the documentation for
  359. // the global function PrintDefaults for more information.
  360. func (f *FlagSet) PrintDefaults() {
  361. f.VisitAll(func(flag *Flag) {
  362. s := fmt.Sprintf(" -%s", flag.Name) // Two spaces before -; see next two comments.
  363. name, usage := UnquoteUsage(flag)
  364. if len(name) > 0 {
  365. s += " " + name
  366. }
  367. // Boolean flags of one ASCII letter are so common we
  368. // treat them specially, putting their usage on the same line.
  369. if len(s) <= 4 { // space, space, '-', 'x'.
  370. s += "\t"
  371. } else {
  372. // Four spaces before the tab triggers good alignment
  373. // for both 4- and 8-space tab stops.
  374. s += "\n \t"
  375. }
  376. s += usage
  377. if !isZeroValue(flag, flag.DefValue) {
  378. if _, ok := flag.Value.(*stringValue); ok {
  379. // put quotes on the value
  380. s += fmt.Sprintf(" (default %q)", flag.DefValue)
  381. } else {
  382. s += fmt.Sprintf(" (default %v)", flag.DefValue)
  383. }
  384. }
  385. fmt.Fprint(f.out(), s, "\n")
  386. })
  387. }
  388. // PrintDefaults prints, to standard error unless configured otherwise,
  389. // a usage message showing the default settings of all defined
  390. // command-line flags.
  391. // For an integer valued flag x, the default output has the form
  392. // -x int
  393. // usage-message-for-x (default 7)
  394. // The usage message will appear on a separate line for anything but
  395. // a bool flag with a one-byte name. For bool flags, the type is
  396. // omitted and if the flag name is one byte the usage message appears
  397. // on the same line. The parenthetical default is omitted if the
  398. // default is the zero value for the type. The listed type, here int,
  399. // can be changed by placing a back-quoted name in the flag's usage
  400. // string; the first such item in the message is taken to be a parameter
  401. // name to show in the message and the back quotes are stripped from
  402. // the message when displayed. For instance, given
  403. // flag.String("I", "", "search `directory` for include files")
  404. // the output will be
  405. // -I directory
  406. // search directory for include files.
  407. func PrintDefaults() { CommandLine.PrintDefaults() }
  408. // defaultUsage is the default function to print a usage message.
  409. func defaultUsage(f *FlagSet) {
  410. if f.name == "" {
  411. fmt.Fprintf(f.out(), "Usage:\n")
  412. } else {
  413. fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
  414. }
  415. f.PrintDefaults()
  416. }
  417. // NOTE: Usage is not just defaultUsage(CommandLine)
  418. // because it serves (via godoc flag Usage) as the example
  419. // for how to write your own usage function.
  420. // Usage prints to standard error a usage message documenting all defined command-line flags.
  421. // It is called when an error occurs while parsing flags.
  422. // The function is a variable that may be changed to point to a custom function.
  423. // By default it prints a simple header and calls PrintDefaults; for details about the
  424. // format of the output and how to control it, see the documentation for PrintDefaults.
  425. var Usage = func() {
  426. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  427. PrintDefaults()
  428. }
  429. // NFlag returns the number of flags that have been set.
  430. func (f *FlagSet) NFlag() int { return len(f.actual) }
  431. // NFlag returns the number of command-line flags that have been set.
  432. func NFlag() int { return len(CommandLine.actual) }
  433. // Arg returns the i'th argument. Arg(0) is the first remaining argument
  434. // after flags have been processed. Arg returns an empty string if the
  435. // requested element does not exist.
  436. func (f *FlagSet) Arg(i int) string {
  437. if i < 0 || i >= len(f.args) {
  438. return ""
  439. }
  440. return f.args[i]
  441. }
  442. // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
  443. // after flags have been processed. Arg returns an empty string if the
  444. // requested element does not exist.
  445. func Arg(i int) string { return CommandLine.Arg(i) }
  446. // NArg is the number of arguments remaining after flags have been processed.
  447. func (f *FlagSet) NArg() int { return len(f.args) }
  448. // NArg is the number of arguments remaining after flags have been processed.
  449. func NArg() int { return len(CommandLine.args) }
  450. // Args returns the non-flag arguments.
  451. func (f *FlagSet) Args() []string { return f.args }
  452. // Args returns the non-flag command-line arguments.
  453. func Args() []string { return CommandLine.args }
  454. // BoolVar defines a bool flag with specified name, default value, and usage string.
  455. // The argument p points to a bool variable in which to store the value of the flag.
  456. func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
  457. f.Var(newBoolValue(value, p), name, usage)
  458. }
  459. // BoolVar defines a bool flag with specified name, default value, and usage string.
  460. // The argument p points to a bool variable in which to store the value of the flag.
  461. func BoolVar(p *bool, name string, value bool, usage string) {
  462. CommandLine.Var(newBoolValue(value, p), name, usage)
  463. }
  464. // Bool defines a bool flag with specified name, default value, and usage string.
  465. // The return value is the address of a bool variable that stores the value of the flag.
  466. func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
  467. p := new(bool)
  468. f.BoolVar(p, name, value, usage)
  469. return p
  470. }
  471. // Bool defines a bool flag with specified name, default value, and usage string.
  472. // The return value is the address of a bool variable that stores the value of the flag.
  473. func Bool(name string, value bool, usage string) *bool {
  474. return CommandLine.Bool(name, value, usage)
  475. }
  476. // IntVar defines an int flag with specified name, default value, and usage string.
  477. // The argument p points to an int variable in which to store the value of the flag.
  478. func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
  479. f.Var(newIntValue(value, p), name, usage)
  480. }
  481. // IntVar defines an int flag with specified name, default value, and usage string.
  482. // The argument p points to an int variable in which to store the value of the flag.
  483. func IntVar(p *int, name string, value int, usage string) {
  484. CommandLine.Var(newIntValue(value, p), name, usage)
  485. }
  486. // Int defines an int flag with specified name, default value, and usage string.
  487. // The return value is the address of an int variable that stores the value of the flag.
  488. func (f *FlagSet) Int(name string, value int, usage string) *int {
  489. p := new(int)
  490. f.IntVar(p, name, value, usage)
  491. return p
  492. }
  493. // Int defines an int flag with specified name, default value, and usage string.
  494. // The return value is the address of an int variable that stores the value of the flag.
  495. func Int(name string, value int, usage string) *int {
  496. return CommandLine.Int(name, value, usage)
  497. }
  498. // Int64Var defines an int64 flag with specified name, default value, and usage string.
  499. // The argument p points to an int64 variable in which to store the value of the flag.
  500. func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
  501. f.Var(newInt64Value(value, p), name, usage)
  502. }
  503. // Int64Var defines an int64 flag with specified name, default value, and usage string.
  504. // The argument p points to an int64 variable in which to store the value of the flag.
  505. func Int64Var(p *int64, name string, value int64, usage string) {
  506. CommandLine.Var(newInt64Value(value, p), name, usage)
  507. }
  508. // Int64 defines an int64 flag with specified name, default value, and usage string.
  509. // The return value is the address of an int64 variable that stores the value of the flag.
  510. func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
  511. p := new(int64)
  512. f.Int64Var(p, name, value, usage)
  513. return p
  514. }
  515. // Int64 defines an int64 flag with specified name, default value, and usage string.
  516. // The return value is the address of an int64 variable that stores the value of the flag.
  517. func Int64(name string, value int64, usage string) *int64 {
  518. return CommandLine.Int64(name, value, usage)
  519. }
  520. // UintVar defines a uint flag with specified name, default value, and usage string.
  521. // The argument p points to a uint variable in which to store the value of the flag.
  522. func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
  523. f.Var(newUintValue(value, p), name, usage)
  524. }
  525. // UintVar defines a uint flag with specified name, default value, and usage string.
  526. // The argument p points to a uint variable in which to store the value of the flag.
  527. func UintVar(p *uint, name string, value uint, usage string) {
  528. CommandLine.Var(newUintValue(value, p), name, usage)
  529. }
  530. // Uint defines a uint flag with specified name, default value, and usage string.
  531. // The return value is the address of a uint variable that stores the value of the flag.
  532. func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
  533. p := new(uint)
  534. f.UintVar(p, name, value, usage)
  535. return p
  536. }
  537. // Uint defines a uint flag with specified name, default value, and usage string.
  538. // The return value is the address of a uint variable that stores the value of the flag.
  539. func Uint(name string, value uint, usage string) *uint { return CommandLine.Uint(name, value, usage) }
  540. // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
  541. // The argument p points to a uint64 variable in which to store the value of the flag.
  542. func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
  543. f.Var(newUint64Value(value, p), name, usage)
  544. }
  545. // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
  546. // The argument p points to a uint64 variable in which to store the value of the flag.
  547. func Uint64Var(p *uint64, name string, value uint64, usage string) {
  548. CommandLine.Var(newUint64Value(value, p), name, usage)
  549. }
  550. // Uint64 defines a uint64 flag with specified name, default value, and usage string.
  551. // The return value is the address of a uint64 variable that stores the value of the flag.
  552. func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
  553. p := new(uint64)
  554. f.Uint64Var(p, name, value, usage)
  555. return p
  556. }
  557. // Uint64 defines a uint64 flag with specified name, default value, and usage string.
  558. // The return value is the address of a uint64 variable that stores the value of the flag.
  559. func Uint64(name string, value uint64, usage string) *uint64 {
  560. return CommandLine.Uint64(name, value, usage)
  561. }
  562. // StringVar defines a string flag with specified name, default value, and usage string.
  563. // The argument p points to a string variable in which to store the value of the flag.
  564. func (f *FlagSet) StringVar(p *string, name, value, usage string) {
  565. f.Var(newStringValue(value, p), name, usage)
  566. }
  567. // StringVar defines a string flag with specified name, default value, and usage string.
  568. // The argument p points to a string variable in which to store the value of the flag.
  569. func StringVar(p *string, name, value, usage string) {
  570. CommandLine.Var(newStringValue(value, p), name, usage)
  571. }
  572. // String defines a string flag with specified name, default value, and usage string.
  573. // The return value is the address of a string variable that stores the value of the flag.
  574. func (f *FlagSet) String(name, value, usage string) *string {
  575. p := new(string)
  576. f.StringVar(p, name, value, usage)
  577. return p
  578. }
  579. // String defines a string flag with specified name, default value, and usage string.
  580. // The return value is the address of a string variable that stores the value of the flag.
  581. func String(name, value, usage string) *string {
  582. return CommandLine.String(name, value, usage)
  583. }
  584. // Float64Var defines a float64 flag with specified name, default value, and usage string.
  585. // The argument p points to a float64 variable in which to store the value of the flag.
  586. func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
  587. f.Var(newFloat64Value(value, p), name, usage)
  588. }
  589. // Float64Var defines a float64 flag with specified name, default value, and usage string.
  590. // The argument p points to a float64 variable in which to store the value of the flag.
  591. func Float64Var(p *float64, name string, value float64, usage string) {
  592. CommandLine.Var(newFloat64Value(value, p), name, usage)
  593. }
  594. // Float64 defines a float64 flag with specified name, default value, and usage string.
  595. // The return value is the address of a float64 variable that stores the value of the flag.
  596. func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
  597. p := new(float64)
  598. f.Float64Var(p, name, value, usage)
  599. return p
  600. }
  601. // Float64 defines a float64 flag with specified name, default value, and usage string.
  602. // The return value is the address of a float64 variable that stores the value of the flag.
  603. func Float64(name string, value float64, usage string) *float64 {
  604. return CommandLine.Float64(name, value, usage)
  605. }
  606. // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
  607. // The argument p points to a time.Duration variable in which to store the value of the flag.
  608. // The flag accepts a value acceptable to time.ParseDuration.
  609. func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
  610. f.Var(newDurationValue(value, p), name, usage)
  611. }
  612. // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
  613. // The argument p points to a time.Duration variable in which to store the value of the flag.
  614. // The flag accepts a value acceptable to time.ParseDuration.
  615. func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
  616. CommandLine.Var(newDurationValue(value, p), name, usage)
  617. }
  618. // Duration defines a time.Duration flag with specified name, default value, and usage string.
  619. // The return value is the address of a time.Duration variable that stores the value of the flag.
  620. // The flag accepts a value acceptable to time.ParseDuration.
  621. func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
  622. p := new(time.Duration)
  623. f.DurationVar(p, name, value, usage)
  624. return p
  625. }
  626. // Duration defines a time.Duration flag with specified name, default value, and usage string.
  627. // The return value is the address of a time.Duration variable that stores the value of the flag.
  628. // The flag accepts a value acceptable to time.ParseDuration.
  629. func Duration(name string, value time.Duration, usage string) *time.Duration {
  630. return CommandLine.Duration(name, value, usage)
  631. }
  632. // Var defines a flag with the specified name and usage string. The type and
  633. // value of the flag are represented by the first argument, of type Value, which
  634. // typically holds a user-defined implementation of Value. For instance, the
  635. // caller could create a flag that turns a comma-separated string into a slice
  636. // of strings by giving the slice the methods of Value; in particular, Set would
  637. // decompose the comma-separated string into the slice.
  638. func (f *FlagSet) Var(value Value, name string, usage string) {
  639. // Remember the default value as a string; it won't change.
  640. flag := &Flag{name, usage, value, value.String()}
  641. _, alreadythere := f.formal[name]
  642. if alreadythere {
  643. var msg string
  644. if f.name == "" {
  645. msg = fmt.Sprintf("flag redefined: %s", name)
  646. } else {
  647. msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
  648. }
  649. fmt.Fprintln(f.out(), msg)
  650. panic(msg) // Happens only if flags are declared with identical names
  651. }
  652. if f.formal == nil {
  653. f.formal = make(map[string]*Flag)
  654. }
  655. f.formal[name] = flag
  656. }
  657. // Var defines a flag with the specified name and usage string. The type and
  658. // value of the flag are represented by the first argument, of type Value, which
  659. // typically holds a user-defined implementation of Value. For instance, the
  660. // caller could create a flag that turns a comma-separated string into a slice
  661. // of strings by giving the slice the methods of Value; in particular, Set would
  662. // decompose the comma-separated string into the slice.
  663. func Var(value Value, name, usage string) {
  664. CommandLine.Var(value, name, usage)
  665. }
  666. // failf prints to standard error a formatted error and usage message and
  667. // returns the error.
  668. func (f *FlagSet) failf(format string, a ...interface{}) error {
  669. err := fmt.Errorf(format, a...)
  670. fmt.Fprintln(f.out(), err)
  671. f.usage()
  672. return err
  673. }
  674. // usage calls the Usage method for the flag set if one is specified,
  675. // or the appropriate default usage function otherwise.
  676. func (f *FlagSet) usage() {
  677. if f.Usage == nil {
  678. if f == CommandLine {
  679. Usage()
  680. } else {
  681. defaultUsage(f)
  682. }
  683. } else {
  684. f.Usage()
  685. }
  686. }
  687. // parseOne parses one flag. It reports whether a flag was seen.
  688. func (f *FlagSet) parseOne() (bool, error) {
  689. if len(f.args) == 0 {
  690. return false, nil
  691. }
  692. s := f.args[0]
  693. if len(s) < 2 || s[0] != '-' {
  694. return false, nil
  695. }
  696. numMinuses := 1
  697. if s[1] == '-' {
  698. numMinuses++
  699. if len(s) == 2 { // "--" terminates the flags
  700. f.args = f.args[1:]
  701. return false, nil
  702. }
  703. }
  704. name := s[numMinuses:]
  705. if len(name) == 0 || name[0] == '-' || name[0] == '=' {
  706. return false, f.failf("bad flag syntax: %s", s)
  707. }
  708. // ignore go test flags
  709. if strings.HasPrefix(name, "test.") {
  710. return false, nil
  711. }
  712. // it's a flag. does it have an argument?
  713. f.args = f.args[1:]
  714. hasValue := false
  715. value := ""
  716. for i := 1; i < len(name); i++ { // equals cannot be first
  717. if name[i] == '=' {
  718. value = name[i+1:]
  719. hasValue = true
  720. name = name[0:i]
  721. break
  722. }
  723. }
  724. m := f.formal
  725. flag, alreadythere := m[name] // BUG
  726. if !alreadythere {
  727. if name == "help" || name == "h" { // special case for nice help message.
  728. f.usage()
  729. return false, ErrHelp
  730. }
  731. return false, f.failf("flag provided but not defined: -%s", name)
  732. }
  733. if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
  734. if hasValue {
  735. if err := fv.Set(value); err != nil {
  736. return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
  737. }
  738. } else {
  739. if err := fv.Set("true"); err != nil {
  740. return false, f.failf("invalid boolean flag %s: %v", name, err)
  741. }
  742. }
  743. } else {
  744. // It must have a value, which might be the next argument.
  745. if !hasValue && len(f.args) > 0 {
  746. // value is the next arg
  747. hasValue = true
  748. value, f.args = f.args[0], f.args[1:]
  749. }
  750. if !hasValue {
  751. return false, f.failf("flag needs an argument: -%s", name)
  752. }
  753. if err := flag.Value.Set(value); err != nil {
  754. return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
  755. }
  756. }
  757. if f.actual == nil {
  758. f.actual = make(map[string]*Flag)
  759. }
  760. f.actual[name] = flag
  761. return true, nil
  762. }
  763. // Parse parses flag definitions from the argument list, which should not
  764. // include the command name. Must be called after all flags in the FlagSet
  765. // are defined and before flags are accessed by the program.
  766. // The return value will be ErrHelp if -help or -h were set but not defined.
  767. func (f *FlagSet) Parse(arguments []string) error {
  768. if _, ok := f.formal[DefaultConfigFlagName]; !ok {
  769. f.String(DefaultConfigFlagName, "", "file with command line options with each line in optionName=optionValue format")
  770. }
  771. f.parsed = true
  772. f.args = arguments
  773. for {
  774. seen, err := f.parseOne()
  775. if seen {
  776. continue
  777. }
  778. if err == nil {
  779. break
  780. }
  781. switch f.errorHandling {
  782. case ContinueOnError:
  783. return err
  784. case ExitOnError:
  785. os.Exit(2)
  786. case PanicOnError:
  787. panic(err)
  788. }
  789. }
  790. // Parse environment variables
  791. if err := f.ParseEnv(os.Environ()); err != nil {
  792. switch f.errorHandling {
  793. case ContinueOnError:
  794. return err
  795. case ExitOnError:
  796. os.Exit(2)
  797. case PanicOnError:
  798. panic(err)
  799. }
  800. return err
  801. }
  802. // Parse configuration from file
  803. var cFile string
  804. if cf := f.formal[DefaultConfigFlagName]; cf != nil {
  805. cFile = cf.Value.String()
  806. }
  807. if cf := f.actual[DefaultConfigFlagName]; cf != nil {
  808. cFile = cf.Value.String()
  809. }
  810. if cFile == "" {
  811. cFile = f.findConfigArgInUnresolved()
  812. }
  813. if cFile != "" {
  814. if err := f.ParseFile(cFile, true); err != nil {
  815. switch f.errorHandling {
  816. case ContinueOnError:
  817. return err
  818. case ExitOnError:
  819. os.Exit(2)
  820. case PanicOnError:
  821. panic(err)
  822. }
  823. return err
  824. }
  825. }
  826. return nil
  827. }
  828. func (f *FlagSet) findConfigArgInUnresolved() string {
  829. configArg := "-" + DefaultConfigFlagName
  830. for i := 0; i < len(f.args); i++ {
  831. if strings.HasPrefix(f.args[i], configArg) {
  832. if f.args[i] == configArg && i+1 < len(f.args) {
  833. return f.args[i+1]
  834. }
  835. if strings.HasPrefix(f.args[i], configArg+"=") {
  836. return f.args[i][len(configArg)+1:]
  837. break
  838. }
  839. }
  840. }
  841. return ""
  842. }
  843. // Parsed reports whether f.Parse has been called.
  844. func (f *FlagSet) Parsed() bool { return f.parsed }
  845. // Parse parses the command-line flags from os.Args[1:]. Must be called
  846. // after all flags are defined and before flags are accessed by the program.
  847. func Parse() {
  848. // Ignore errors; CommandLine is set for ExitOnError.
  849. CommandLine.Parse(os.Args[1:])
  850. }
  851. // Parsed reports whether the command-line flags have been parsed.
  852. func Parsed() bool {
  853. return CommandLine.Parsed()
  854. }
  855. // CommandLine is the default set of command-line flags, parsed from os.Args.
  856. // The top-level functions such as BoolVar, Arg, and so on are wrappers for the
  857. // methods of CommandLine.
  858. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
  859. // NewFlagSet returns a new, empty flag set with the specified name and
  860. // error handling property.
  861. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
  862. f := &FlagSet{
  863. name: name,
  864. errorHandling: errorHandling,
  865. }
  866. return f
  867. }
  868. // Init sets the name and error handling property for a flag set.
  869. // By default, the zero FlagSet uses an empty name, EnvPrefix, and the
  870. // ContinueOnError error handling policy.
  871. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
  872. f.name = name
  873. f.envPrefix = EnvPrefix
  874. f.errorHandling = errorHandling
  875. }
  876. // EnvPrefix defines a string that will be implicitly prefixed to a
  877. // flag name before looking it up in the environment variables.
  878. var EnvPrefix = "WEED"
  879. // ParseEnv parses flags from environment variables.
  880. // Flags already set will be ignored.
  881. func (f *FlagSet) ParseEnv(environ []string) error {
  882. env := make(map[string]string)
  883. for _, s := range environ {
  884. if i := strings.Index(s, "="); i >= 1 {
  885. env[s[0:i]] = s[i+1:]
  886. }
  887. }
  888. for _, flag := range f.formal {
  889. name := flag.Name
  890. if _, set := f.actual[name]; set {
  891. continue
  892. }
  893. flag, alreadyThere := f.formal[name]
  894. if !alreadyThere {
  895. if name == "help" || name == "h" { // special case for nice help message.
  896. f.usage()
  897. return ErrHelp
  898. }
  899. return f.failf("environment variable provided but not defined: %s", name)
  900. }
  901. envKey := strings.ToUpper(flag.Name)
  902. if f.envPrefix != "" {
  903. envKey = f.envPrefix + "_" + envKey
  904. }
  905. envKey = strings.Replace(envKey, "-", "_", -1)
  906. value, isSet := env[envKey]
  907. if !isSet {
  908. continue
  909. }
  910. if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() && value == "" {
  911. // special case: doesn't need an arg
  912. // flag without value is regarded a bool
  913. value = ("true")
  914. }
  915. if err := flag.Value.Set(value); err != nil {
  916. return f.failf("invalid value %q for environment variable %s: %v", value, name, err)
  917. }
  918. // update f.actual
  919. if f.actual == nil {
  920. f.actual = make(map[string]*Flag)
  921. }
  922. f.actual[name] = flag
  923. }
  924. return nil
  925. }
  926. // NewFlagSetWithEnvPrefix returns a new empty flag set with the specified name,
  927. // environment variable prefix, and error handling property.
  928. func NewFlagSetWithEnvPrefix(name string, prefix string, errorHandling ErrorHandling) *FlagSet {
  929. f := NewFlagSet(name, errorHandling)
  930. f.envPrefix = prefix
  931. return f
  932. }
  933. // DefaultConfigFlagName defines the flag name of the optional config file
  934. // path. Used to lookup and parse the config file when a default is set and
  935. // available on disk.
  936. var DefaultConfigFlagName = "options"
  937. // ParseFile parses flags from the file in path.
  938. // Same format as commandline arguments, newlines and lines beginning with a
  939. // "#" character are ignored. Flags already set will be ignored.
  940. func (f *FlagSet) ParseFile(path string, ignoreUndefinedConf bool) error {
  941. fp, err := os.Open(path) // Extract arguments from file
  942. if err != nil {
  943. return err
  944. }
  945. defer fp.Close()
  946. scanner := bufio.NewScanner(fp)
  947. for scanner.Scan() {
  948. line := strings.TrimSpace(scanner.Text())
  949. // Ignore empty lines or comments
  950. if line == "" || line[:1] == "#" || line[:1] == "//" || line[:1] == "--" {
  951. continue
  952. }
  953. // Match `key=value` and `key value`
  954. name, value := line, ""
  955. for i, v := range line {
  956. if v == '=' || v == ' ' || v == ':' {
  957. name, value = strings.TrimSpace(line[:i]), strings.TrimSpace(line[i+1:])
  958. break
  959. }
  960. }
  961. name = strings.TrimPrefix(name, "-")
  962. // Ignore flag when already set; arguments have precedence over file
  963. if f.actual[name] != nil {
  964. continue
  965. }
  966. flag, alreadyThere := f.formal[name]
  967. if !alreadyThere {
  968. if ignoreUndefinedConf {
  969. continue
  970. }
  971. if name == "help" || name == "h" { // special case for nice help message.
  972. f.usage()
  973. return ErrHelp
  974. }
  975. return f.failf("configuration variable provided but not defined: %s", name)
  976. }
  977. if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() && value == "" {
  978. // special case: doesn't need an arg
  979. value = "true"
  980. }
  981. if err := flag.Value.Set(value); err != nil {
  982. return f.failf("invalid value %q for configuration variable %s: %v", value, name, err)
  983. }
  984. // update f.actual
  985. if f.actual == nil {
  986. f.actual = make(map[string]*Flag)
  987. }
  988. f.actual[name] = flag
  989. }
  990. return scanner.Err()
  991. }