OSDN Git Service

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