fla9.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. //
  393. // -x int
  394. // usage-message-for-x (default 7)
  395. //
  396. // The usage message will appear on a separate line for anything but
  397. // a bool flag with a one-byte name. For bool flags, the type is
  398. // omitted and if the flag name is one byte the usage message appears
  399. // on the same line. The parenthetical default is omitted if the
  400. // default is the zero value for the type. The listed type, here int,
  401. // can be changed by placing a back-quoted name in the flag's usage
  402. // string; the first such item in the message is taken to be a parameter
  403. // name to show in the message and the back quotes are stripped from
  404. // the message when displayed. For instance, given
  405. //
  406. // flag.String("I", "", "search `directory` for include files")
  407. //
  408. // the output will be
  409. //
  410. // -I directory
  411. // search directory for include files.
  412. func PrintDefaults() { CommandLine.PrintDefaults() }
  413. // defaultUsage is the default function to print a usage message.
  414. func defaultUsage(f *FlagSet) {
  415. if f.name == "" {
  416. fmt.Fprintf(f.out(), "Usage:\n")
  417. } else {
  418. fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
  419. }
  420. f.PrintDefaults()
  421. }
  422. // NOTE: Usage is not just defaultUsage(CommandLine)
  423. // because it serves (via godoc flag Usage) as the example
  424. // for how to write your own usage function.
  425. // Usage prints to standard error a usage message documenting all defined command-line flags.
  426. // It is called when an error occurs while parsing flags.
  427. // The function is a variable that may be changed to point to a custom function.
  428. // By default it prints a simple header and calls PrintDefaults; for details about the
  429. // format of the output and how to control it, see the documentation for PrintDefaults.
  430. var Usage = func() {
  431. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  432. PrintDefaults()
  433. }
  434. // NFlag returns the number of flags that have been set.
  435. func (f *FlagSet) NFlag() int { return len(f.actual) }
  436. // NFlag returns the number of command-line flags that have been set.
  437. func NFlag() int { return len(CommandLine.actual) }
  438. // Arg returns the i'th argument. Arg(0) is the first remaining argument
  439. // after flags have been processed. Arg returns an empty string if the
  440. // requested element does not exist.
  441. func (f *FlagSet) Arg(i int) string {
  442. if i < 0 || i >= len(f.args) {
  443. return ""
  444. }
  445. return f.args[i]
  446. }
  447. // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
  448. // after flags have been processed. Arg returns an empty string if the
  449. // requested element does not exist.
  450. func Arg(i int) string { return CommandLine.Arg(i) }
  451. // NArg is the number of arguments remaining after flags have been processed.
  452. func (f *FlagSet) NArg() int { return len(f.args) }
  453. // NArg is the number of arguments remaining after flags have been processed.
  454. func NArg() int { return len(CommandLine.args) }
  455. // Args returns the non-flag arguments.
  456. func (f *FlagSet) Args() []string { return f.args }
  457. // Args returns the non-flag command-line arguments.
  458. func Args() []string { return CommandLine.args }
  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 (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
  462. f.Var(newBoolValue(value, p), name, usage)
  463. }
  464. // BoolVar defines a bool flag with specified name, default value, and usage string.
  465. // The argument p points to a bool variable in which to store the value of the flag.
  466. func BoolVar(p *bool, name string, value bool, usage string) {
  467. CommandLine.Var(newBoolValue(value, p), name, usage)
  468. }
  469. // Bool defines a bool flag with specified name, default value, and usage string.
  470. // The return value is the address of a bool variable that stores the value of the flag.
  471. func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
  472. p := new(bool)
  473. f.BoolVar(p, name, value, usage)
  474. return p
  475. }
  476. // Bool defines a bool flag with specified name, default value, and usage string.
  477. // The return value is the address of a bool variable that stores the value of the flag.
  478. func Bool(name string, value bool, usage string) *bool {
  479. return CommandLine.Bool(name, value, 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 (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
  484. f.Var(newIntValue(value, p), name, usage)
  485. }
  486. // IntVar defines an int flag with specified name, default value, and usage string.
  487. // The argument p points to an int variable in which to store the value of the flag.
  488. func IntVar(p *int, name string, value int, usage string) {
  489. CommandLine.Var(newIntValue(value, p), name, usage)
  490. }
  491. // Int defines an int flag with specified name, default value, and usage string.
  492. // The return value is the address of an int variable that stores the value of the flag.
  493. func (f *FlagSet) Int(name string, value int, usage string) *int {
  494. p := new(int)
  495. f.IntVar(p, name, value, usage)
  496. return p
  497. }
  498. // Int defines an int flag with specified name, default value, and usage string.
  499. // The return value is the address of an int variable that stores the value of the flag.
  500. func Int(name string, value int, usage string) *int {
  501. return CommandLine.Int(name, value, 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 (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
  506. f.Var(newInt64Value(value, p), name, usage)
  507. }
  508. // Int64Var defines an int64 flag with specified name, default value, and usage string.
  509. // The argument p points to an int64 variable in which to store the value of the flag.
  510. func Int64Var(p *int64, name string, value int64, usage string) {
  511. CommandLine.Var(newInt64Value(value, p), name, usage)
  512. }
  513. // Int64 defines an int64 flag with specified name, default value, and usage string.
  514. // The return value is the address of an int64 variable that stores the value of the flag.
  515. func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
  516. p := new(int64)
  517. f.Int64Var(p, name, value, usage)
  518. return p
  519. }
  520. // Int64 defines an int64 flag with specified name, default value, and usage string.
  521. // The return value is the address of an int64 variable that stores the value of the flag.
  522. func Int64(name string, value int64, usage string) *int64 {
  523. return CommandLine.Int64(name, value, 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 (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
  528. f.Var(newUintValue(value, p), name, usage)
  529. }
  530. // UintVar defines a uint flag with specified name, default value, and usage string.
  531. // The argument p points to a uint variable in which to store the value of the flag.
  532. func UintVar(p *uint, name string, value uint, usage string) {
  533. CommandLine.Var(newUintValue(value, p), name, usage)
  534. }
  535. // Uint defines a uint flag with specified name, default value, and usage string.
  536. // The return value is the address of a uint variable that stores the value of the flag.
  537. func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
  538. p := new(uint)
  539. f.UintVar(p, name, value, usage)
  540. return p
  541. }
  542. // Uint defines a uint flag with specified name, default value, and usage string.
  543. // The return value is the address of a uint variable that stores the value of the flag.
  544. func Uint(name string, value uint, usage string) *uint { return CommandLine.Uint(name, value, usage) }
  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 (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
  548. f.Var(newUint64Value(value, p), name, usage)
  549. }
  550. // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
  551. // The argument p points to a uint64 variable in which to store the value of the flag.
  552. func Uint64Var(p *uint64, name string, value uint64, usage string) {
  553. CommandLine.Var(newUint64Value(value, p), name, usage)
  554. }
  555. // Uint64 defines a uint64 flag with specified name, default value, and usage string.
  556. // The return value is the address of a uint64 variable that stores the value of the flag.
  557. func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
  558. p := new(uint64)
  559. f.Uint64Var(p, name, value, usage)
  560. return p
  561. }
  562. // Uint64 defines a uint64 flag with specified name, default value, and usage string.
  563. // The return value is the address of a uint64 variable that stores the value of the flag.
  564. func Uint64(name string, value uint64, usage string) *uint64 {
  565. return CommandLine.Uint64(name, value, 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 (f *FlagSet) StringVar(p *string, name, value, usage string) {
  570. f.Var(newStringValue(value, p), name, usage)
  571. }
  572. // StringVar defines a string flag with specified name, default value, and usage string.
  573. // The argument p points to a string variable in which to store the value of the flag.
  574. func StringVar(p *string, name, value, usage string) {
  575. CommandLine.Var(newStringValue(value, p), name, usage)
  576. }
  577. // String defines a string flag with specified name, default value, and usage string.
  578. // The return value is the address of a string variable that stores the value of the flag.
  579. func (f *FlagSet) String(name, value, usage string) *string {
  580. p := new(string)
  581. f.StringVar(p, name, value, usage)
  582. return p
  583. }
  584. // String defines a string flag with specified name, default value, and usage string.
  585. // The return value is the address of a string variable that stores the value of the flag.
  586. func String(name, value, usage string) *string {
  587. return CommandLine.String(name, value, 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 (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
  592. f.Var(newFloat64Value(value, p), name, usage)
  593. }
  594. // Float64Var defines a float64 flag with specified name, default value, and usage string.
  595. // The argument p points to a float64 variable in which to store the value of the flag.
  596. func Float64Var(p *float64, name string, value float64, usage string) {
  597. CommandLine.Var(newFloat64Value(value, p), name, usage)
  598. }
  599. // Float64 defines a float64 flag with specified name, default value, and usage string.
  600. // The return value is the address of a float64 variable that stores the value of the flag.
  601. func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
  602. p := new(float64)
  603. f.Float64Var(p, name, value, usage)
  604. return p
  605. }
  606. // Float64 defines a float64 flag with specified name, default value, and usage string.
  607. // The return value is the address of a float64 variable that stores the value of the flag.
  608. func Float64(name string, value float64, usage string) *float64 {
  609. return CommandLine.Float64(name, value, usage)
  610. }
  611. // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
  612. // The argument p points to a time.Duration variable in which to store the value of the flag.
  613. // The flag accepts a value acceptable to time.ParseDuration.
  614. func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
  615. f.Var(newDurationValue(value, p), name, usage)
  616. }
  617. // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
  618. // The argument p points to a time.Duration variable in which to store the value of the flag.
  619. // The flag accepts a value acceptable to time.ParseDuration.
  620. func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
  621. CommandLine.Var(newDurationValue(value, p), name, usage)
  622. }
  623. // Duration defines a time.Duration flag with specified name, default value, and usage string.
  624. // The return value is the address of a time.Duration variable that stores the value of the flag.
  625. // The flag accepts a value acceptable to time.ParseDuration.
  626. func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
  627. p := new(time.Duration)
  628. f.DurationVar(p, name, value, usage)
  629. return p
  630. }
  631. // Duration defines a time.Duration flag with specified name, default value, and usage string.
  632. // The return value is the address of a time.Duration variable that stores the value of the flag.
  633. // The flag accepts a value acceptable to time.ParseDuration.
  634. func Duration(name string, value time.Duration, usage string) *time.Duration {
  635. return CommandLine.Duration(name, value, usage)
  636. }
  637. // Var defines a flag with the specified name and usage string. The type and
  638. // value of the flag are represented by the first argument, of type Value, which
  639. // typically holds a user-defined implementation of Value. For instance, the
  640. // caller could create a flag that turns a comma-separated string into a slice
  641. // of strings by giving the slice the methods of Value; in particular, Set would
  642. // decompose the comma-separated string into the slice.
  643. func (f *FlagSet) Var(value Value, name string, usage string) {
  644. // Remember the default value as a string; it won't change.
  645. flag := &Flag{name, usage, value, value.String()}
  646. _, alreadythere := f.formal[name]
  647. if alreadythere {
  648. var msg string
  649. if f.name == "" {
  650. msg = fmt.Sprintf("flag redefined: %s", name)
  651. } else {
  652. msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
  653. }
  654. fmt.Fprintln(f.out(), msg)
  655. panic(msg) // Happens only if flags are declared with identical names
  656. }
  657. if f.formal == nil {
  658. f.formal = make(map[string]*Flag)
  659. }
  660. f.formal[name] = flag
  661. }
  662. // Var defines a flag with the specified name and usage string. The type and
  663. // value of the flag are represented by the first argument, of type Value, which
  664. // typically holds a user-defined implementation of Value. For instance, the
  665. // caller could create a flag that turns a comma-separated string into a slice
  666. // of strings by giving the slice the methods of Value; in particular, Set would
  667. // decompose the comma-separated string into the slice.
  668. func Var(value Value, name, usage string) {
  669. CommandLine.Var(value, name, usage)
  670. }
  671. // failf prints to standard error a formatted error and usage message and
  672. // returns the error.
  673. func (f *FlagSet) failf(format string, a ...interface{}) error {
  674. err := fmt.Errorf(format, a...)
  675. fmt.Fprintln(f.out(), err)
  676. f.usage()
  677. return err
  678. }
  679. // usage calls the Usage method for the flag set if one is specified,
  680. // or the appropriate default usage function otherwise.
  681. func (f *FlagSet) usage() {
  682. if f.Usage == nil {
  683. if f == CommandLine {
  684. Usage()
  685. } else {
  686. defaultUsage(f)
  687. }
  688. } else {
  689. f.Usage()
  690. }
  691. }
  692. // parseOne parses one flag. It reports whether a flag was seen.
  693. func (f *FlagSet) parseOne() (bool, error) {
  694. if len(f.args) == 0 {
  695. return false, nil
  696. }
  697. s := f.args[0]
  698. if len(s) < 2 || s[0] != '-' {
  699. return false, nil
  700. }
  701. numMinuses := 1
  702. if s[1] == '-' {
  703. numMinuses++
  704. if len(s) == 2 { // "--" terminates the flags
  705. f.args = f.args[1:]
  706. return false, nil
  707. }
  708. }
  709. name := s[numMinuses:]
  710. if len(name) == 0 || name[0] == '-' || name[0] == '=' {
  711. return false, f.failf("bad flag syntax: %s", s)
  712. }
  713. // ignore go test flags
  714. if strings.HasPrefix(name, "test.") {
  715. return false, nil
  716. }
  717. // it's a flag. does it have an argument?
  718. f.args = f.args[1:]
  719. hasValue := false
  720. value := ""
  721. for i := 1; i < len(name); i++ { // equals cannot be first
  722. if name[i] == '=' {
  723. value = name[i+1:]
  724. hasValue = true
  725. name = name[0:i]
  726. break
  727. }
  728. }
  729. m := f.formal
  730. flag, alreadythere := m[name] // BUG
  731. if !alreadythere {
  732. if name == "help" || name == "h" { // special case for nice help message.
  733. f.usage()
  734. return false, ErrHelp
  735. }
  736. return false, f.failf("flag provided but not defined: -%s", name)
  737. }
  738. if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
  739. if hasValue {
  740. if err := fv.Set(value); err != nil {
  741. return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
  742. }
  743. } else {
  744. if err := fv.Set("true"); err != nil {
  745. return false, f.failf("invalid boolean flag %s: %v", name, err)
  746. }
  747. }
  748. } else {
  749. // It must have a value, which might be the next argument.
  750. if !hasValue && len(f.args) > 0 {
  751. // value is the next arg
  752. hasValue = true
  753. value, f.args = f.args[0], f.args[1:]
  754. }
  755. if !hasValue {
  756. return false, f.failf("flag needs an argument: -%s", name)
  757. }
  758. if err := flag.Value.Set(value); err != nil {
  759. return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
  760. }
  761. }
  762. if f.actual == nil {
  763. f.actual = make(map[string]*Flag)
  764. }
  765. f.actual[name] = flag
  766. return true, nil
  767. }
  768. // Parse parses flag definitions from the argument list, which should not
  769. // include the command name. Must be called after all flags in the FlagSet
  770. // are defined and before flags are accessed by the program.
  771. // The return value will be ErrHelp if -help or -h were set but not defined.
  772. func (f *FlagSet) Parse(arguments []string) error {
  773. if _, ok := f.formal[DefaultConfigFlagName]; !ok {
  774. f.String(DefaultConfigFlagName, "", "a file of command line options, each line in optionName=optionValue format")
  775. }
  776. f.parsed = true
  777. f.args = arguments
  778. for {
  779. seen, err := f.parseOne()
  780. if seen {
  781. continue
  782. }
  783. if err == nil {
  784. break
  785. }
  786. switch f.errorHandling {
  787. case ContinueOnError:
  788. return err
  789. case ExitOnError:
  790. os.Exit(2)
  791. case PanicOnError:
  792. panic(err)
  793. }
  794. }
  795. // Parse environment variables
  796. if err := f.ParseEnv(os.Environ()); err != nil {
  797. switch f.errorHandling {
  798. case ContinueOnError:
  799. return err
  800. case ExitOnError:
  801. os.Exit(2)
  802. case PanicOnError:
  803. panic(err)
  804. }
  805. return err
  806. }
  807. // Parse configuration from file
  808. var cFile string
  809. if cf := f.formal[DefaultConfigFlagName]; cf != nil {
  810. cFile = cf.Value.String()
  811. }
  812. if cf := f.actual[DefaultConfigFlagName]; cf != nil {
  813. cFile = cf.Value.String()
  814. }
  815. if cFile == "" {
  816. cFile = f.findConfigArgInUnresolved()
  817. }
  818. if cFile != "" {
  819. if err := f.ParseFile(cFile, true); err != nil {
  820. switch f.errorHandling {
  821. case ContinueOnError:
  822. return err
  823. case ExitOnError:
  824. os.Exit(2)
  825. case PanicOnError:
  826. panic(err)
  827. }
  828. return err
  829. }
  830. }
  831. return nil
  832. }
  833. func (f *FlagSet) findConfigArgInUnresolved() string {
  834. configArg := "-" + DefaultConfigFlagName
  835. for i := 0; i < len(f.args); i++ {
  836. if strings.HasPrefix(f.args[i], configArg) {
  837. if f.args[i] == configArg && i+1 < len(f.args) {
  838. return f.args[i+1]
  839. }
  840. if strings.HasPrefix(f.args[i], configArg+"=") {
  841. return f.args[i][len(configArg)+1:]
  842. }
  843. }
  844. }
  845. return ""
  846. }
  847. // Parsed reports whether f.Parse has been called.
  848. func (f *FlagSet) Parsed() bool { return f.parsed }
  849. // Parse parses the command-line flags from os.Args[1:]. Must be called
  850. // after all flags are defined and before flags are accessed by the program.
  851. func Parse() {
  852. // Ignore errors; CommandLine is set for ExitOnError.
  853. CommandLine.Parse(os.Args[1:])
  854. }
  855. // Parsed reports whether the command-line flags have been parsed.
  856. func Parsed() bool {
  857. return CommandLine.Parsed()
  858. }
  859. // CommandLine is the default set of command-line flags, parsed from os.Args.
  860. // The top-level functions such as BoolVar, Arg, and so on are wrappers for the
  861. // methods of CommandLine.
  862. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
  863. // NewFlagSet returns a new, empty flag set with the specified name and
  864. // error handling property.
  865. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
  866. f := &FlagSet{
  867. name: name,
  868. errorHandling: errorHandling,
  869. envPrefix: EnvPrefix,
  870. }
  871. return f
  872. }
  873. // Init sets the name and error handling property for a flag set.
  874. // By default, the zero FlagSet uses an empty name, EnvPrefix, and the
  875. // ContinueOnError error handling policy.
  876. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
  877. f.name = name
  878. f.envPrefix = EnvPrefix
  879. f.errorHandling = errorHandling
  880. }
  881. // EnvPrefix defines a string that will be implicitly prefixed to a
  882. // flag name before looking it up in the environment variables.
  883. var EnvPrefix = "WEED"
  884. // ParseEnv parses flags from environment variables.
  885. // Flags already set will be ignored.
  886. func (f *FlagSet) ParseEnv(environ []string) error {
  887. env := make(map[string]string)
  888. for _, s := range environ {
  889. if i := strings.Index(s, "="); i >= 1 {
  890. env[s[0:i]] = s[i+1:]
  891. }
  892. }
  893. for _, flag := range f.formal {
  894. name := flag.Name
  895. if _, set := f.actual[name]; set {
  896. continue
  897. }
  898. flag, alreadyThere := f.formal[name]
  899. if !alreadyThere {
  900. if name == "help" || name == "h" { // special case for nice help message.
  901. f.usage()
  902. return ErrHelp
  903. }
  904. return f.failf("environment variable provided but not defined: %s", name)
  905. }
  906. envKey := strings.ToUpper(flag.Name)
  907. if f.envPrefix != "" {
  908. envKey = f.envPrefix + "_" + envKey
  909. }
  910. envKey = strings.Replace(envKey, "-", "_", -1)
  911. envKey = strings.Replace(envKey, ".", "_", -1)
  912. value, isSet := env[envKey]
  913. if !isSet {
  914. continue
  915. }
  916. if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() && value == "" {
  917. // special case: doesn't need an arg
  918. // flag without value is regarded a bool
  919. value = ("true")
  920. }
  921. if err := flag.Value.Set(value); err != nil {
  922. return f.failf("invalid value %q for environment variable %s: %v", value, name, err)
  923. }
  924. // update f.actual
  925. if f.actual == nil {
  926. f.actual = make(map[string]*Flag)
  927. }
  928. f.actual[name] = flag
  929. }
  930. return nil
  931. }
  932. // NewFlagSetWithEnvPrefix returns a new empty flag set with the specified name,
  933. // environment variable prefix, and error handling property.
  934. func NewFlagSetWithEnvPrefix(name string, prefix string, errorHandling ErrorHandling) *FlagSet {
  935. f := NewFlagSet(name, errorHandling)
  936. f.envPrefix = prefix
  937. return f
  938. }
  939. // DefaultConfigFlagName defines the flag name of the optional config file
  940. // path. Used to lookup and parse the config file when a default is set and
  941. // available on disk.
  942. var DefaultConfigFlagName = "options"
  943. // ParseFile parses flags from the file in path.
  944. // Same format as commandline arguments, newlines and lines beginning with a
  945. // "#" character are ignored. Flags already set will be ignored.
  946. func (f *FlagSet) ParseFile(path string, ignoreUndefinedConf bool) error {
  947. fp, err := os.Open(path) // Extract arguments from file
  948. if err != nil {
  949. return err
  950. }
  951. defer fp.Close()
  952. scanner := bufio.NewScanner(fp)
  953. for scanner.Scan() {
  954. line := strings.TrimSpace(scanner.Text())
  955. // Ignore empty lines or comments
  956. if line == "" || line[:1] == "#" || line[:1] == "//" || line[:1] == "--" {
  957. continue
  958. }
  959. // Match `key=value` and `key value`
  960. name, value := line, ""
  961. for i, v := range line {
  962. if v == '=' || v == ' ' || v == ':' {
  963. name, value = strings.TrimSpace(line[:i]), strings.TrimSpace(line[i+1:])
  964. break
  965. }
  966. }
  967. name = strings.TrimPrefix(name, "-")
  968. // Ignore flag when already set; arguments have precedence over file
  969. if f.actual[name] != nil {
  970. continue
  971. }
  972. flag, alreadyThere := f.formal[name]
  973. if !alreadyThere {
  974. if ignoreUndefinedConf {
  975. continue
  976. }
  977. if name == "help" || name == "h" { // special case for nice help message.
  978. f.usage()
  979. return ErrHelp
  980. }
  981. return f.failf("configuration variable provided but not defined: %s", name)
  982. }
  983. if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() && value == "" {
  984. // special case: doesn't need an arg
  985. value = "true"
  986. }
  987. if err := flag.Value.Set(value); err != nil {
  988. return f.failf("invalid value %q for configuration variable %s: %v", value, name, err)
  989. }
  990. // update f.actual
  991. if f.actual == nil {
  992. f.actual = make(map[string]*Flag)
  993. }
  994. f.actual[name] = flag
  995. }
  996. return scanner.Err()
  997. }