flag.go 35 KB

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