2016-08-05 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / libgo / go / flag / flag.go
blobfa0f05e96830128cdb2e8aac2a991c730f358ba2
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.
5 /*
6 Package flag implements command-line flag parsing.
8 Usage:
10 Define flags using flag.String(), Bool(), Int(), etc.
12 This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
13 import "flag"
14 var ip = flag.Int("flagname", 1234, "help message for flagname")
15 If you like, you can bind the flag to a variable using the Var() functions.
16 var flagvar int
17 func init() {
18 flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
20 Or you can create custom flags that satisfy the Value interface (with
21 pointer receivers) and couple them to flag parsing by
22 flag.Var(&flagVal, "name", "help message for flagname")
23 For such flags, the default value is just the initial value of the variable.
25 After all flags are defined, call
26 flag.Parse()
27 to parse the command line into the defined flags.
29 Flags may then be used directly. If you're using the flags themselves,
30 they are all pointers; if you bind to variables, they're values.
31 fmt.Println("ip has value ", *ip)
32 fmt.Println("flagvar has value ", flagvar)
34 After parsing, the arguments following the flags are available as the
35 slice flag.Args() or individually as flag.Arg(i).
36 The arguments are indexed from 0 through flag.NArg()-1.
38 Command line flag syntax:
39 -flag
40 -flag=x
41 -flag x // non-boolean flags only
42 One or two minus signs may be used; they are equivalent.
43 The last form is not permitted for boolean flags because the
44 meaning of the command
45 cmd -x *
46 will change if there is a file called 0, false, etc. You must
47 use the -flag=false form to turn off a boolean flag.
49 Flag parsing stops just before the first non-flag argument
50 ("-" is a non-flag argument) or after the terminator "--".
52 Integer flags accept 1234, 0664, 0x1234 and may be negative.
53 Boolean flags may be:
54 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
55 Duration flags accept any input valid for time.ParseDuration.
57 The default set of command-line flags is controlled by
58 top-level functions. The FlagSet type allows one to define
59 independent sets of flags, such as to implement subcommands
60 in a command-line interface. The methods of FlagSet are
61 analogous to the top-level functions for the command-line
62 flag set.
64 package flag
66 import (
67 "errors"
68 "fmt"
69 "io"
70 "os"
71 "reflect"
72 "sort"
73 "strconv"
74 "time"
77 // ErrHelp is the error returned if the -help or -h flag is invoked
78 // but no such flag is defined.
79 var ErrHelp = errors.New("flag: help requested")
81 // -- bool Value
82 type boolValue bool
84 func newBoolValue(val bool, p *bool) *boolValue {
85 *p = val
86 return (*boolValue)(p)
89 func (b *boolValue) Set(s string) error {
90 v, err := strconv.ParseBool(s)
91 *b = boolValue(v)
92 return err
95 func (b *boolValue) Get() interface{} { return bool(*b) }
97 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
99 func (b *boolValue) IsBoolFlag() bool { return true }
101 // optional interface to indicate boolean flags that can be
102 // supplied without "=value" text
103 type boolFlag interface {
104 Value
105 IsBoolFlag() bool
108 // -- int Value
109 type intValue int
111 func newIntValue(val int, p *int) *intValue {
112 *p = val
113 return (*intValue)(p)
116 func (i *intValue) Set(s string) error {
117 v, err := strconv.ParseInt(s, 0, 64)
118 *i = intValue(v)
119 return err
122 func (i *intValue) Get() interface{} { return int(*i) }
124 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
126 // -- int64 Value
127 type int64Value int64
129 func newInt64Value(val int64, p *int64) *int64Value {
130 *p = val
131 return (*int64Value)(p)
134 func (i *int64Value) Set(s string) error {
135 v, err := strconv.ParseInt(s, 0, 64)
136 *i = int64Value(v)
137 return err
140 func (i *int64Value) Get() interface{} { return int64(*i) }
142 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
144 // -- uint Value
145 type uintValue uint
147 func newUintValue(val uint, p *uint) *uintValue {
148 *p = val
149 return (*uintValue)(p)
152 func (i *uintValue) Set(s string) error {
153 v, err := strconv.ParseUint(s, 0, 64)
154 *i = uintValue(v)
155 return err
158 func (i *uintValue) Get() interface{} { return uint(*i) }
160 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
162 // -- uint64 Value
163 type uint64Value uint64
165 func newUint64Value(val uint64, p *uint64) *uint64Value {
166 *p = val
167 return (*uint64Value)(p)
170 func (i *uint64Value) Set(s string) error {
171 v, err := strconv.ParseUint(s, 0, 64)
172 *i = uint64Value(v)
173 return err
176 func (i *uint64Value) Get() interface{} { return uint64(*i) }
178 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
180 // -- string Value
181 type stringValue string
183 func newStringValue(val string, p *string) *stringValue {
184 *p = val
185 return (*stringValue)(p)
188 func (s *stringValue) Set(val string) error {
189 *s = stringValue(val)
190 return nil
193 func (s *stringValue) Get() interface{} { return string(*s) }
195 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
197 // -- float64 Value
198 type float64Value float64
200 func newFloat64Value(val float64, p *float64) *float64Value {
201 *p = val
202 return (*float64Value)(p)
205 func (f *float64Value) Set(s string) error {
206 v, err := strconv.ParseFloat(s, 64)
207 *f = float64Value(v)
208 return err
211 func (f *float64Value) Get() interface{} { return float64(*f) }
213 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
215 // -- time.Duration Value
216 type durationValue time.Duration
218 func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
219 *p = val
220 return (*durationValue)(p)
223 func (d *durationValue) Set(s string) error {
224 v, err := time.ParseDuration(s)
225 *d = durationValue(v)
226 return err
229 func (d *durationValue) Get() interface{} { return time.Duration(*d) }
231 func (d *durationValue) String() string { return (*time.Duration)(d).String() }
233 // Value is the interface to the dynamic value stored in a flag.
234 // (The default value is represented as a string.)
236 // If a Value has an IsBoolFlag() bool method returning true,
237 // the command-line parser makes -name equivalent to -name=true
238 // rather than using the next command-line argument.
240 // Set is called once, in command line order, for each flag present.
241 type Value interface {
242 String() string
243 Set(string) error
246 // Getter is an interface that allows the contents of a Value to be retrieved.
247 // It wraps the Value interface, rather than being part of it, because it
248 // appeared after Go 1 and its compatibility rules. All Value types provided
249 // by this package satisfy the Getter interface.
250 type Getter interface {
251 Value
252 Get() interface{}
255 // ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
256 type ErrorHandling int
258 // These constants cause FlagSet.Parse to behave as described if the parse fails.
259 const (
260 ContinueOnError ErrorHandling = iota // Return a descriptive error.
261 ExitOnError // Call os.Exit(2).
262 PanicOnError // Call panic with a descriptive error.
265 // A FlagSet represents a set of defined flags. The zero value of a FlagSet
266 // has no name and has ContinueOnError error handling.
267 type FlagSet struct {
268 // Usage is the function called when an error occurs while parsing flags.
269 // The field is a function (not a method) that may be changed to point to
270 // a custom error handler.
271 Usage func()
273 name string
274 parsed bool
275 actual map[string]*Flag
276 formal map[string]*Flag
277 args []string // arguments after flags
278 errorHandling ErrorHandling
279 output io.Writer // nil means stderr; use out() accessor
282 // A Flag represents the state of a flag.
283 type Flag struct {
284 Name string // name as it appears on command line
285 Usage string // help message
286 Value Value // value as set
287 DefValue string // default value (as text); for usage message
290 // sortFlags returns the flags as a slice in lexicographical sorted order.
291 func sortFlags(flags map[string]*Flag) []*Flag {
292 list := make(sort.StringSlice, len(flags))
293 i := 0
294 for _, f := range flags {
295 list[i] = f.Name
298 list.Sort()
299 result := make([]*Flag, len(list))
300 for i, name := range list {
301 result[i] = flags[name]
303 return result
306 func (f *FlagSet) out() io.Writer {
307 if f.output == nil {
308 return os.Stderr
310 return f.output
313 // SetOutput sets the destination for usage and error messages.
314 // If output is nil, os.Stderr is used.
315 func (f *FlagSet) SetOutput(output io.Writer) {
316 f.output = output
319 // VisitAll visits the flags in lexicographical order, calling fn for each.
320 // It visits all flags, even those not set.
321 func (f *FlagSet) VisitAll(fn func(*Flag)) {
322 for _, flag := range sortFlags(f.formal) {
323 fn(flag)
327 // VisitAll visits the command-line flags in lexicographical order, calling
328 // fn for each. It visits all flags, even those not set.
329 func VisitAll(fn func(*Flag)) {
330 CommandLine.VisitAll(fn)
333 // Visit visits the flags in lexicographical order, calling fn for each.
334 // It visits only those flags that have been set.
335 func (f *FlagSet) Visit(fn func(*Flag)) {
336 for _, flag := range sortFlags(f.actual) {
337 fn(flag)
341 // Visit visits the command-line flags in lexicographical order, calling fn
342 // for each. It visits only those flags that have been set.
343 func Visit(fn func(*Flag)) {
344 CommandLine.Visit(fn)
347 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
348 func (f *FlagSet) Lookup(name string) *Flag {
349 return f.formal[name]
352 // Lookup returns the Flag structure of the named command-line flag,
353 // returning nil if none exists.
354 func Lookup(name string) *Flag {
355 return CommandLine.formal[name]
358 // Set sets the value of the named flag.
359 func (f *FlagSet) Set(name, value string) error {
360 flag, ok := f.formal[name]
361 if !ok {
362 return fmt.Errorf("no such flag -%v", name)
364 err := flag.Value.Set(value)
365 if err != nil {
366 return err
368 if f.actual == nil {
369 f.actual = make(map[string]*Flag)
371 f.actual[name] = flag
372 return nil
375 // Set sets the value of the named command-line flag.
376 func Set(name, value string) error {
377 return CommandLine.Set(name, value)
380 // isZeroValue guesses whether the string represents the zero
381 // value for a flag. It is not accurate but in practice works OK.
382 func isZeroValue(flag *Flag, value string) bool {
383 // Build a zero value of the flag's Value type, and see if the
384 // result of calling its String method equals the value passed in.
385 // This works unless the Value type is itself an interface type.
386 typ := reflect.TypeOf(flag.Value)
387 var z reflect.Value
388 if typ.Kind() == reflect.Ptr {
389 z = reflect.New(typ.Elem())
390 } else {
391 z = reflect.Zero(typ)
393 if value == z.Interface().(Value).String() {
394 return true
397 switch value {
398 case "false":
399 return true
400 case "":
401 return true
402 case "0":
403 return true
405 return false
408 // UnquoteUsage extracts a back-quoted name from the usage
409 // string for a flag and returns it and the un-quoted usage.
410 // Given "a `name` to show" it returns ("name", "a name to show").
411 // If there are no back quotes, the name is an educated guess of the
412 // type of the flag's value, or the empty string if the flag is boolean.
413 func UnquoteUsage(flag *Flag) (name string, usage string) {
414 // Look for a back-quoted name, but avoid the strings package.
415 usage = flag.Usage
416 for i := 0; i < len(usage); i++ {
417 if usage[i] == '`' {
418 for j := i + 1; j < len(usage); j++ {
419 if usage[j] == '`' {
420 name = usage[i+1 : j]
421 usage = usage[:i] + name + usage[j+1:]
422 return name, usage
425 break // Only one back quote; use type name.
428 // No explicit name, so use type if we can find one.
429 name = "value"
430 switch flag.Value.(type) {
431 case boolFlag:
432 name = ""
433 case *durationValue:
434 name = "duration"
435 case *float64Value:
436 name = "float"
437 case *intValue, *int64Value:
438 name = "int"
439 case *stringValue:
440 name = "string"
441 case *uintValue, *uint64Value:
442 name = "uint"
444 return
447 // PrintDefaults prints to standard error the default values of all
448 // defined command-line flags in the set. See the documentation for
449 // the global function PrintDefaults for more information.
450 func (f *FlagSet) PrintDefaults() {
451 f.VisitAll(func(flag *Flag) {
452 s := fmt.Sprintf(" -%s", flag.Name) // Two spaces before -; see next two comments.
453 name, usage := UnquoteUsage(flag)
454 if len(name) > 0 {
455 s += " " + name
457 // Boolean flags of one ASCII letter are so common we
458 // treat them specially, putting their usage on the same line.
459 if len(s) <= 4 { // space, space, '-', 'x'.
460 s += "\t"
461 } else {
462 // Four spaces before the tab triggers good alignment
463 // for both 4- and 8-space tab stops.
464 s += "\n \t"
466 s += usage
467 if !isZeroValue(flag, flag.DefValue) {
468 if _, ok := flag.Value.(*stringValue); ok {
469 // put quotes on the value
470 s += fmt.Sprintf(" (default %q)", flag.DefValue)
471 } else {
472 s += fmt.Sprintf(" (default %v)", flag.DefValue)
475 fmt.Fprint(f.out(), s, "\n")
479 // PrintDefaults prints, to standard error unless configured otherwise,
480 // a usage message showing the default settings of all defined
481 // command-line flags.
482 // For an integer valued flag x, the default output has the form
483 // -x int
484 // usage-message-for-x (default 7)
485 // The usage message will appear on a separate line for anything but
486 // a bool flag with a one-byte name. For bool flags, the type is
487 // omitted and if the flag name is one byte the usage message appears
488 // on the same line. The parenthetical default is omitted if the
489 // default is the zero value for the type. The listed type, here int,
490 // can be changed by placing a back-quoted name in the flag's usage
491 // string; the first such item in the message is taken to be a parameter
492 // name to show in the message and the back quotes are stripped from
493 // the message when displayed. For instance, given
494 // flag.String("I", "", "search `directory` for include files")
495 // the output will be
496 // -I directory
497 // search directory for include files.
498 func PrintDefaults() {
499 CommandLine.PrintDefaults()
502 // defaultUsage is the default function to print a usage message.
503 func defaultUsage(f *FlagSet) {
504 if f.name == "" {
505 fmt.Fprintf(f.out(), "Usage:\n")
506 } else {
507 fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
509 f.PrintDefaults()
512 // NOTE: Usage is not just defaultUsage(CommandLine)
513 // because it serves (via godoc flag Usage) as the example
514 // for how to write your own usage function.
516 // Usage prints to standard error a usage message documenting all defined command-line flags.
517 // It is called when an error occurs while parsing flags.
518 // The function is a variable that may be changed to point to a custom function.
519 // By default it prints a simple header and calls PrintDefaults; for details about the
520 // format of the output and how to control it, see the documentation for PrintDefaults.
521 var Usage = func() {
522 fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
523 PrintDefaults()
526 // NFlag returns the number of flags that have been set.
527 func (f *FlagSet) NFlag() int { return len(f.actual) }
529 // NFlag returns the number of command-line flags that have been set.
530 func NFlag() int { return len(CommandLine.actual) }
532 // Arg returns the i'th argument. Arg(0) is the first remaining argument
533 // after flags have been processed. Arg returns an empty string if the
534 // requested element does not exist.
535 func (f *FlagSet) Arg(i int) string {
536 if i < 0 || i >= len(f.args) {
537 return ""
539 return f.args[i]
542 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
543 // after flags have been processed. Arg returns an empty string if the
544 // requested element does not exist.
545 func Arg(i int) string {
546 return CommandLine.Arg(i)
549 // NArg is the number of arguments remaining after flags have been processed.
550 func (f *FlagSet) NArg() int { return len(f.args) }
552 // NArg is the number of arguments remaining after flags have been processed.
553 func NArg() int { return len(CommandLine.args) }
555 // Args returns the non-flag arguments.
556 func (f *FlagSet) Args() []string { return f.args }
558 // Args returns the non-flag command-line arguments.
559 func Args() []string { return CommandLine.args }
561 // BoolVar defines a bool flag with specified name, default value, and usage string.
562 // The argument p points to a bool variable in which to store the value of the flag.
563 func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
564 f.Var(newBoolValue(value, p), name, usage)
567 // BoolVar defines a bool flag with specified name, default value, and usage string.
568 // The argument p points to a bool variable in which to store the value of the flag.
569 func BoolVar(p *bool, name string, value bool, usage string) {
570 CommandLine.Var(newBoolValue(value, p), name, usage)
573 // Bool defines a bool flag with specified name, default value, and usage string.
574 // The return value is the address of a bool variable that stores the value of the flag.
575 func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
576 p := new(bool)
577 f.BoolVar(p, name, value, usage)
578 return p
581 // Bool defines a bool flag with specified name, default value, and usage string.
582 // The return value is the address of a bool variable that stores the value of the flag.
583 func Bool(name string, value bool, usage string) *bool {
584 return CommandLine.Bool(name, value, usage)
587 // IntVar defines an int flag with specified name, default value, and usage string.
588 // The argument p points to an int variable in which to store the value of the flag.
589 func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
590 f.Var(newIntValue(value, p), name, usage)
593 // IntVar defines an int flag with specified name, default value, and usage string.
594 // The argument p points to an int variable in which to store the value of the flag.
595 func IntVar(p *int, name string, value int, usage string) {
596 CommandLine.Var(newIntValue(value, p), name, usage)
599 // Int defines an int flag with specified name, default value, and usage string.
600 // The return value is the address of an int variable that stores the value of the flag.
601 func (f *FlagSet) Int(name string, value int, usage string) *int {
602 p := new(int)
603 f.IntVar(p, name, value, usage)
604 return p
607 // Int defines an int flag with specified name, default value, and usage string.
608 // The return value is the address of an int variable that stores the value of the flag.
609 func Int(name string, value int, usage string) *int {
610 return CommandLine.Int(name, value, usage)
613 // Int64Var defines an int64 flag with specified name, default value, and usage string.
614 // The argument p points to an int64 variable in which to store the value of the flag.
615 func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
616 f.Var(newInt64Value(value, p), name, usage)
619 // Int64Var defines an int64 flag with specified name, default value, and usage string.
620 // The argument p points to an int64 variable in which to store the value of the flag.
621 func Int64Var(p *int64, name string, value int64, usage string) {
622 CommandLine.Var(newInt64Value(value, p), name, usage)
625 // Int64 defines an int64 flag with specified name, default value, and usage string.
626 // The return value is the address of an int64 variable that stores the value of the flag.
627 func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
628 p := new(int64)
629 f.Int64Var(p, name, value, usage)
630 return p
633 // Int64 defines an int64 flag with specified name, default value, and usage string.
634 // The return value is the address of an int64 variable that stores the value of the flag.
635 func Int64(name string, value int64, usage string) *int64 {
636 return CommandLine.Int64(name, value, usage)
639 // UintVar defines a uint flag with specified name, default value, and usage string.
640 // The argument p points to a uint variable in which to store the value of the flag.
641 func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
642 f.Var(newUintValue(value, p), name, usage)
645 // UintVar defines a uint flag with specified name, default value, and usage string.
646 // The argument p points to a uint variable in which to store the value of the flag.
647 func UintVar(p *uint, name string, value uint, usage string) {
648 CommandLine.Var(newUintValue(value, p), name, usage)
651 // Uint defines a uint flag with specified name, default value, and usage string.
652 // The return value is the address of a uint variable that stores the value of the flag.
653 func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
654 p := new(uint)
655 f.UintVar(p, name, value, usage)
656 return p
659 // Uint defines a uint flag with specified name, default value, and usage string.
660 // The return value is the address of a uint variable that stores the value of the flag.
661 func Uint(name string, value uint, usage string) *uint {
662 return CommandLine.Uint(name, value, usage)
665 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
666 // The argument p points to a uint64 variable in which to store the value of the flag.
667 func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
668 f.Var(newUint64Value(value, p), name, usage)
671 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
672 // The argument p points to a uint64 variable in which to store the value of the flag.
673 func Uint64Var(p *uint64, name string, value uint64, usage string) {
674 CommandLine.Var(newUint64Value(value, p), name, usage)
677 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
678 // The return value is the address of a uint64 variable that stores the value of the flag.
679 func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
680 p := new(uint64)
681 f.Uint64Var(p, name, value, usage)
682 return p
685 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
686 // The return value is the address of a uint64 variable that stores the value of the flag.
687 func Uint64(name string, value uint64, usage string) *uint64 {
688 return CommandLine.Uint64(name, value, usage)
691 // StringVar defines a string flag with specified name, default value, and usage string.
692 // The argument p points to a string variable in which to store the value of the flag.
693 func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
694 f.Var(newStringValue(value, p), name, usage)
697 // StringVar defines a string flag with specified name, default value, and usage string.
698 // The argument p points to a string variable in which to store the value of the flag.
699 func StringVar(p *string, name string, value string, usage string) {
700 CommandLine.Var(newStringValue(value, p), name, usage)
703 // String defines a string flag with specified name, default value, and usage string.
704 // The return value is the address of a string variable that stores the value of the flag.
705 func (f *FlagSet) String(name string, value string, usage string) *string {
706 p := new(string)
707 f.StringVar(p, name, value, usage)
708 return p
711 // String defines a string flag with specified name, default value, and usage string.
712 // The return value is the address of a string variable that stores the value of the flag.
713 func String(name string, value string, usage string) *string {
714 return CommandLine.String(name, value, usage)
717 // Float64Var defines a float64 flag with specified name, default value, and usage string.
718 // The argument p points to a float64 variable in which to store the value of the flag.
719 func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
720 f.Var(newFloat64Value(value, p), name, usage)
723 // Float64Var defines a float64 flag with specified name, default value, and usage string.
724 // The argument p points to a float64 variable in which to store the value of the flag.
725 func Float64Var(p *float64, name string, value float64, usage string) {
726 CommandLine.Var(newFloat64Value(value, p), name, usage)
729 // Float64 defines a float64 flag with specified name, default value, and usage string.
730 // The return value is the address of a float64 variable that stores the value of the flag.
731 func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
732 p := new(float64)
733 f.Float64Var(p, name, value, usage)
734 return p
737 // Float64 defines a float64 flag with specified name, default value, and usage string.
738 // The return value is the address of a float64 variable that stores the value of the flag.
739 func Float64(name string, value float64, usage string) *float64 {
740 return CommandLine.Float64(name, value, usage)
743 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
744 // The argument p points to a time.Duration variable in which to store the value of the flag.
745 // The flag accepts a value acceptable to time.ParseDuration.
746 func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
747 f.Var(newDurationValue(value, p), name, usage)
750 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
751 // The argument p points to a time.Duration variable in which to store the value of the flag.
752 // The flag accepts a value acceptable to time.ParseDuration.
753 func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
754 CommandLine.Var(newDurationValue(value, p), name, usage)
757 // Duration defines a time.Duration flag with specified name, default value, and usage string.
758 // The return value is the address of a time.Duration variable that stores the value of the flag.
759 // The flag accepts a value acceptable to time.ParseDuration.
760 func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
761 p := new(time.Duration)
762 f.DurationVar(p, name, value, usage)
763 return p
766 // Duration defines a time.Duration flag with specified name, default value, and usage string.
767 // The return value is the address of a time.Duration variable that stores the value of the flag.
768 // The flag accepts a value acceptable to time.ParseDuration.
769 func Duration(name string, value time.Duration, usage string) *time.Duration {
770 return CommandLine.Duration(name, value, usage)
773 // Var defines a flag with the specified name and usage string. The type and
774 // value of the flag are represented by the first argument, of type Value, which
775 // typically holds a user-defined implementation of Value. For instance, the
776 // caller could create a flag that turns a comma-separated string into a slice
777 // of strings by giving the slice the methods of Value; in particular, Set would
778 // decompose the comma-separated string into the slice.
779 func (f *FlagSet) Var(value Value, name string, usage string) {
780 // Remember the default value as a string; it won't change.
781 flag := &Flag{name, usage, value, value.String()}
782 _, alreadythere := f.formal[name]
783 if alreadythere {
784 var msg string
785 if f.name == "" {
786 msg = fmt.Sprintf("flag redefined: %s", name)
787 } else {
788 msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
790 fmt.Fprintln(f.out(), msg)
791 panic(msg) // Happens only if flags are declared with identical names
793 if f.formal == nil {
794 f.formal = make(map[string]*Flag)
796 f.formal[name] = flag
799 // Var defines a flag with the specified name and usage string. The type and
800 // value of the flag are represented by the first argument, of type Value, which
801 // typically holds a user-defined implementation of Value. For instance, the
802 // caller could create a flag that turns a comma-separated string into a slice
803 // of strings by giving the slice the methods of Value; in particular, Set would
804 // decompose the comma-separated string into the slice.
805 func Var(value Value, name string, usage string) {
806 CommandLine.Var(value, name, usage)
809 // failf prints to standard error a formatted error and usage message and
810 // returns the error.
811 func (f *FlagSet) failf(format string, a ...interface{}) error {
812 err := fmt.Errorf(format, a...)
813 fmt.Fprintln(f.out(), err)
814 f.usage()
815 return err
818 // usage calls the Usage method for the flag set if one is specified,
819 // or the appropriate default usage function otherwise.
820 func (f *FlagSet) usage() {
821 if f.Usage == nil {
822 if f == CommandLine {
823 Usage()
824 } else {
825 defaultUsage(f)
827 } else {
828 f.Usage()
832 // parseOne parses one flag. It reports whether a flag was seen.
833 func (f *FlagSet) parseOne() (bool, error) {
834 if len(f.args) == 0 {
835 return false, nil
837 s := f.args[0]
838 if len(s) == 0 || s[0] != '-' || len(s) == 1 {
839 return false, nil
841 numMinuses := 1
842 if s[1] == '-' {
843 numMinuses++
844 if len(s) == 2 { // "--" terminates the flags
845 f.args = f.args[1:]
846 return false, nil
849 name := s[numMinuses:]
850 if len(name) == 0 || name[0] == '-' || name[0] == '=' {
851 return false, f.failf("bad flag syntax: %s", s)
854 // it's a flag. does it have an argument?
855 f.args = f.args[1:]
856 hasValue := false
857 value := ""
858 for i := 1; i < len(name); i++ { // equals cannot be first
859 if name[i] == '=' {
860 value = name[i+1:]
861 hasValue = true
862 name = name[0:i]
863 break
866 m := f.formal
867 flag, alreadythere := m[name] // BUG
868 if !alreadythere {
869 if name == "help" || name == "h" { // special case for nice help message.
870 f.usage()
871 return false, ErrHelp
873 return false, f.failf("flag provided but not defined: -%s", name)
876 if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
877 if hasValue {
878 if err := fv.Set(value); err != nil {
879 return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
881 } else {
882 if err := fv.Set("true"); err != nil {
883 return false, f.failf("invalid boolean flag %s: %v", name, err)
886 } else {
887 // It must have a value, which might be the next argument.
888 if !hasValue && len(f.args) > 0 {
889 // value is the next arg
890 hasValue = true
891 value, f.args = f.args[0], f.args[1:]
893 if !hasValue {
894 return false, f.failf("flag needs an argument: -%s", name)
896 if err := flag.Value.Set(value); err != nil {
897 return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
900 if f.actual == nil {
901 f.actual = make(map[string]*Flag)
903 f.actual[name] = flag
904 return true, nil
907 // Parse parses flag definitions from the argument list, which should not
908 // include the command name. Must be called after all flags in the FlagSet
909 // are defined and before flags are accessed by the program.
910 // The return value will be ErrHelp if -help or -h were set but not defined.
911 func (f *FlagSet) Parse(arguments []string) error {
912 f.parsed = true
913 f.args = arguments
914 for {
915 seen, err := f.parseOne()
916 if seen {
917 continue
919 if err == nil {
920 break
922 switch f.errorHandling {
923 case ContinueOnError:
924 return err
925 case ExitOnError:
926 os.Exit(2)
927 case PanicOnError:
928 panic(err)
931 return nil
934 // Parsed reports whether f.Parse has been called.
935 func (f *FlagSet) Parsed() bool {
936 return f.parsed
939 // Parse parses the command-line flags from os.Args[1:]. Must be called
940 // after all flags are defined and before flags are accessed by the program.
941 func Parse() {
942 // Ignore errors; CommandLine is set for ExitOnError.
943 CommandLine.Parse(os.Args[1:])
946 // Parsed reports whether the command-line flags have been parsed.
947 func Parsed() bool {
948 return CommandLine.Parsed()
951 // CommandLine is the default set of command-line flags, parsed from os.Args.
952 // The top-level functions such as BoolVar, Arg, and so on are wrappers for the
953 // methods of CommandLine.
954 var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
956 // NewFlagSet returns a new, empty flag set with the specified name and
957 // error handling property.
958 func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
959 f := &FlagSet{
960 name: name,
961 errorHandling: errorHandling,
963 return f
966 // Init sets the name and error handling property for a flag set.
967 // By default, the zero FlagSet uses an empty name and the
968 // ContinueOnError error handling policy.
969 func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
970 f.name = name
971 f.errorHandling = errorHandling