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.
6 Package flag implements command-line flag parsing.
10 Define flags using flag.String(), Bool(), Int(), etc.
12 This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
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.
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
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:
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
46 where * is a Unix shell wildcard, will change if there is a file
47 called 0, false, etc. You must use the -flag=false form to turn
50 Flag parsing stops just before the first non-flag argument
51 ("-" is a non-flag argument) or after the terminator "--".
53 Integer flags accept 1234, 0664, 0x1234 and may be negative.
55 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
56 Duration flags accept any input valid for time.ParseDuration.
58 The default set of command-line flags is controlled by
59 top-level functions. The FlagSet type allows one to define
60 independent sets of flags, such as to implement subcommands
61 in a command-line interface. The methods of FlagSet are
62 analogous to the top-level functions for the command-line
79 // ErrHelp is the error returned if the -help or -h flag is invoked
80 // but no such flag is defined.
81 var ErrHelp
= errors
.New("flag: help requested")
86 func newBoolValue(val
bool, p
*bool) *boolValue
{
88 return (*boolValue
)(p
)
91 func (b
*boolValue
) Set(s
string) error
{
92 v
, err
:= strconv
.ParseBool(s
)
97 func (b
*boolValue
) Get() interface{} { return bool(*b
) }
99 func (b
*boolValue
) String() string { return strconv
.FormatBool(bool(*b
)) }
101 func (b
*boolValue
) IsBoolFlag() bool { return true }
103 // optional interface to indicate boolean flags that can be
104 // supplied without "=value" text
105 type boolFlag
interface {
113 func newIntValue(val
int, p
*int) *intValue
{
115 return (*intValue
)(p
)
118 func (i
*intValue
) Set(s
string) error
{
119 v
, err
:= strconv
.ParseInt(s
, 0, strconv
.IntSize
)
124 func (i
*intValue
) Get() interface{} { return int(*i
) }
126 func (i
*intValue
) String() string { return strconv
.Itoa(int(*i
)) }
129 type int64Value
int64
131 func newInt64Value(val
int64, p
*int64) *int64Value
{
133 return (*int64Value
)(p
)
136 func (i
*int64Value
) Set(s
string) error
{
137 v
, err
:= strconv
.ParseInt(s
, 0, 64)
142 func (i
*int64Value
) Get() interface{} { return int64(*i
) }
144 func (i
*int64Value
) String() string { return strconv
.FormatInt(int64(*i
), 10) }
149 func newUintValue(val
uint, p
*uint) *uintValue
{
151 return (*uintValue
)(p
)
154 func (i
*uintValue
) Set(s
string) error
{
155 v
, err
:= strconv
.ParseUint(s
, 0, strconv
.IntSize
)
160 func (i
*uintValue
) Get() interface{} { return uint(*i
) }
162 func (i
*uintValue
) String() string { return strconv
.FormatUint(uint64(*i
), 10) }
165 type uint64Value
uint64
167 func newUint64Value(val
uint64, p
*uint64) *uint64Value
{
169 return (*uint64Value
)(p
)
172 func (i
*uint64Value
) Set(s
string) error
{
173 v
, err
:= strconv
.ParseUint(s
, 0, 64)
178 func (i
*uint64Value
) Get() interface{} { return uint64(*i
) }
180 func (i
*uint64Value
) String() string { return strconv
.FormatUint(uint64(*i
), 10) }
183 type stringValue
string
185 func newStringValue(val
string, p
*string) *stringValue
{
187 return (*stringValue
)(p
)
190 func (s
*stringValue
) Set(val
string) error
{
191 *s
= stringValue(val
)
195 func (s
*stringValue
) Get() interface{} { return string(*s
) }
197 func (s
*stringValue
) String() string { return string(*s
) }
200 type float64Value
float64
202 func newFloat64Value(val
float64, p
*float64) *float64Value
{
204 return (*float64Value
)(p
)
207 func (f
*float64Value
) Set(s
string) error
{
208 v
, err
:= strconv
.ParseFloat(s
, 64)
213 func (f
*float64Value
) Get() interface{} { return float64(*f
) }
215 func (f
*float64Value
) String() string { return strconv
.FormatFloat(float64(*f
), 'g', -1, 64) }
217 // -- time.Duration Value
218 type durationValue time
.Duration
220 func newDurationValue(val time
.Duration
, p
*time
.Duration
) *durationValue
{
222 return (*durationValue
)(p
)
225 func (d
*durationValue
) Set(s
string) error
{
226 v
, err
:= time
.ParseDuration(s
)
227 *d
= durationValue(v
)
231 func (d
*durationValue
) Get() interface{} { return time
.Duration(*d
) }
233 func (d
*durationValue
) String() string { return (*time
.Duration
)(d
).String() }
235 // Value is the interface to the dynamic value stored in a flag.
236 // (The default value is represented as a string.)
238 // If a Value has an IsBoolFlag() bool method returning true,
239 // the command-line parser makes -name equivalent to -name=true
240 // rather than using the next command-line argument.
242 // Set is called once, in command line order, for each flag present.
243 // The flag package may call the String method with a zero-valued receiver,
244 // such as a nil pointer.
245 type Value
interface {
250 // Getter is an interface that allows the contents of a Value to be retrieved.
251 // It wraps the Value interface, rather than being part of it, because it
252 // appeared after Go 1 and its compatibility rules. All Value types provided
253 // by this package satisfy the Getter interface.
254 type Getter
interface {
259 // ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
260 type ErrorHandling
int
262 // These constants cause FlagSet.Parse to behave as described if the parse fails.
264 ContinueOnError ErrorHandling
= iota // Return a descriptive error.
265 ExitOnError
// Call os.Exit(2).
266 PanicOnError
// Call panic with a descriptive error.
269 // A FlagSet represents a set of defined flags. The zero value of a FlagSet
270 // has no name and has ContinueOnError error handling.
271 type FlagSet
struct {
272 // Usage is the function called when an error occurs while parsing flags.
273 // The field is a function (not a method) that may be changed to point to
274 // a custom error handler. What happens after Usage is called depends
275 // on the ErrorHandling setting; for the command line, this defaults
276 // to ExitOnError, which exits the program after calling Usage.
281 actual
map[string]*Flag
282 formal
map[string]*Flag
283 args
[]string // arguments after flags
284 errorHandling ErrorHandling
285 output io
.Writer
// nil means stderr; use out() accessor
288 // A Flag represents the state of a flag.
290 Name
string // name as it appears on command line
291 Usage
string // help message
292 Value Value
// value as set
293 DefValue
string // default value (as text); for usage message
296 // sortFlags returns the flags as a slice in lexicographical sorted order.
297 func sortFlags(flags
map[string]*Flag
) []*Flag
{
298 list
:= make(sort
.StringSlice
, len(flags
))
300 for _
, f
:= range flags
{
305 result
:= make([]*Flag
, len(list
))
306 for i
, name
:= range list
{
307 result
[i
] = flags
[name
]
312 // Output returns the destination for usage and error messages. os.Stderr is returned if
313 // output was not set or was set to nil.
314 func (f
*FlagSet
) Output() io
.Writer
{
321 // Name returns the name of the flag set.
322 func (f
*FlagSet
) Name() string {
326 // ErrorHandling returns the error handling behavior of the flag set.
327 func (f
*FlagSet
) ErrorHandling() ErrorHandling
{
328 return f
.errorHandling
331 // SetOutput sets the destination for usage and error messages.
332 // If output is nil, os.Stderr is used.
333 func (f
*FlagSet
) SetOutput(output io
.Writer
) {
337 // VisitAll visits the flags in lexicographical order, calling fn for each.
338 // It visits all flags, even those not set.
339 func (f
*FlagSet
) VisitAll(fn
func(*Flag
)) {
340 for _
, flag
:= range sortFlags(f
.formal
) {
345 // VisitAll visits the command-line flags in lexicographical order, calling
346 // fn for each. It visits all flags, even those not set.
347 func VisitAll(fn
func(*Flag
)) {
348 CommandLine
.VisitAll(fn
)
351 // Visit visits the flags in lexicographical order, calling fn for each.
352 // It visits only those flags that have been set.
353 func (f
*FlagSet
) Visit(fn
func(*Flag
)) {
354 for _
, flag
:= range sortFlags(f
.actual
) {
359 // Visit visits the command-line flags in lexicographical order, calling fn
360 // for each. It visits only those flags that have been set.
361 func Visit(fn
func(*Flag
)) {
362 CommandLine
.Visit(fn
)
365 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
366 func (f
*FlagSet
) Lookup(name
string) *Flag
{
367 return f
.formal
[name
]
370 // Lookup returns the Flag structure of the named command-line flag,
371 // returning nil if none exists.
372 func Lookup(name
string) *Flag
{
373 return CommandLine
.formal
[name
]
376 // Set sets the value of the named flag.
377 func (f
*FlagSet
) Set(name
, value
string) error
{
378 flag
, ok
:= f
.formal
[name
]
380 return fmt
.Errorf("no such flag -%v", name
)
382 err
:= flag
.Value
.Set(value
)
387 f
.actual
= make(map[string]*Flag
)
389 f
.actual
[name
] = flag
393 // Set sets the value of the named command-line flag.
394 func Set(name
, value
string) error
{
395 return CommandLine
.Set(name
, value
)
398 // isZeroValue guesses whether the string represents the zero
399 // value for a flag. It is not accurate but in practice works OK.
400 func isZeroValue(flag
*Flag
, value
string) bool {
401 // Build a zero value of the flag's Value type, and see if the
402 // result of calling its String method equals the value passed in.
403 // This works unless the Value type is itself an interface type.
404 typ
:= reflect
.TypeOf(flag
.Value
)
406 if typ
.Kind() == reflect
.Ptr
{
407 z
= reflect
.New(typ
.Elem())
409 z
= reflect
.Zero(typ
)
411 if value
== z
.Interface().(Value
).String() {
416 case "false", "", "0":
422 // UnquoteUsage extracts a back-quoted name from the usage
423 // string for a flag and returns it and the un-quoted usage.
424 // Given "a `name` to show" it returns ("name", "a name to show").
425 // If there are no back quotes, the name is an educated guess of the
426 // type of the flag's value, or the empty string if the flag is boolean.
427 func UnquoteUsage(flag
*Flag
) (name
string, usage
string) {
428 // Look for a back-quoted name, but avoid the strings package.
430 for i
:= 0; i
< len(usage
); i
++ {
432 for j
:= i
+ 1; j
< len(usage
); j
++ {
434 name
= usage
[i
+1 : j
]
435 usage
= usage
[:i
] + name
+ usage
[j
+1:]
439 break // Only one back quote; use type name.
442 // No explicit name, so use type if we can find one.
444 switch flag
.Value
.(type) {
451 case *intValue
, *int64Value
:
455 case *uintValue
, *uint64Value
:
461 // PrintDefaults prints, to standard error unless configured otherwise, the
462 // default values of all defined command-line flags in the set. See the
463 // documentation for the global function PrintDefaults for more information.
464 func (f
*FlagSet
) PrintDefaults() {
465 f
.VisitAll(func(flag
*Flag
) {
466 s
:= fmt
.Sprintf(" -%s", flag
.Name
) // Two spaces before -; see next two comments.
467 name
, usage
:= UnquoteUsage(flag
)
471 // Boolean flags of one ASCII letter are so common we
472 // treat them specially, putting their usage on the same line.
473 if len(s
) <= 4 { // space, space, '-', 'x'.
476 // Four spaces before the tab triggers good alignment
477 // for both 4- and 8-space tab stops.
480 s
+= strings
.Replace(usage
, "\n", "\n \t", -1)
482 if !isZeroValue(flag
, flag
.DefValue
) {
483 if _
, ok
:= flag
.Value
.(*stringValue
); ok
{
484 // put quotes on the value
485 s
+= fmt
.Sprintf(" (default %q)", flag
.DefValue
)
487 s
+= fmt
.Sprintf(" (default %v)", flag
.DefValue
)
490 fmt
.Fprint(f
.Output(), s
, "\n")
494 // PrintDefaults prints, to standard error unless configured otherwise,
495 // a usage message showing the default settings of all defined
496 // command-line flags.
497 // For an integer valued flag x, the default output has the form
499 // usage-message-for-x (default 7)
500 // The usage message will appear on a separate line for anything but
501 // a bool flag with a one-byte name. For bool flags, the type is
502 // omitted and if the flag name is one byte the usage message appears
503 // on the same line. The parenthetical default is omitted if the
504 // default is the zero value for the type. The listed type, here int,
505 // can be changed by placing a back-quoted name in the flag's usage
506 // string; the first such item in the message is taken to be a parameter
507 // name to show in the message and the back quotes are stripped from
508 // the message when displayed. For instance, given
509 // flag.String("I", "", "search `directory` for include files")
510 // the output will be
512 // search directory for include files.
513 func PrintDefaults() {
514 CommandLine
.PrintDefaults()
517 // defaultUsage is the default function to print a usage message.
518 func (f
*FlagSet
) defaultUsage() {
520 fmt
.Fprintf(f
.Output(), "Usage:\n")
522 fmt
.Fprintf(f
.Output(), "Usage of %s:\n", f
.name
)
527 // NOTE: Usage is not just defaultUsage(CommandLine)
528 // because it serves (via godoc flag Usage) as the example
529 // for how to write your own usage function.
531 // Usage prints a usage message documenting all defined command-line flags
532 // to CommandLine's output, which by default is os.Stderr.
533 // It is called when an error occurs while parsing flags.
534 // The function is a variable that may be changed to point to a custom function.
535 // By default it prints a simple header and calls PrintDefaults; for details about the
536 // format of the output and how to control it, see the documentation for PrintDefaults.
537 // Custom usage functions may choose to exit the program; by default exiting
538 // happens anyway as the command line's error handling strategy is set to
541 fmt
.Fprintf(CommandLine
.Output(), "Usage of %s:\n", os
.Args
[0])
545 // NFlag returns the number of flags that have been set.
546 func (f
*FlagSet
) NFlag() int { return len(f
.actual
) }
548 // NFlag returns the number of command-line flags that have been set.
549 func NFlag() int { return len(CommandLine
.actual
) }
551 // Arg returns the i'th argument. Arg(0) is the first remaining argument
552 // after flags have been processed. Arg returns an empty string if the
553 // requested element does not exist.
554 func (f
*FlagSet
) Arg(i
int) string {
555 if i
< 0 || i
>= len(f
.args
) {
561 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
562 // after flags have been processed. Arg returns an empty string if the
563 // requested element does not exist.
564 func Arg(i
int) string {
565 return CommandLine
.Arg(i
)
568 // NArg is the number of arguments remaining after flags have been processed.
569 func (f
*FlagSet
) NArg() int { return len(f
.args
) }
571 // NArg is the number of arguments remaining after flags have been processed.
572 func NArg() int { return len(CommandLine
.args
) }
574 // Args returns the non-flag arguments.
575 func (f
*FlagSet
) Args() []string { return f
.args
}
577 // Args returns the non-flag command-line arguments.
578 func Args() []string { return CommandLine
.args
}
580 // BoolVar defines a bool flag with specified name, default value, and usage string.
581 // The argument p points to a bool variable in which to store the value of the flag.
582 func (f
*FlagSet
) BoolVar(p
*bool, name
string, value
bool, usage
string) {
583 f
.Var(newBoolValue(value
, p
), name
, usage
)
586 // BoolVar defines a bool flag with specified name, default value, and usage string.
587 // The argument p points to a bool variable in which to store the value of the flag.
588 func BoolVar(p
*bool, name
string, value
bool, usage
string) {
589 CommandLine
.Var(newBoolValue(value
, p
), name
, usage
)
592 // Bool defines a bool flag with specified name, default value, and usage string.
593 // The return value is the address of a bool variable that stores the value of the flag.
594 func (f
*FlagSet
) Bool(name
string, value
bool, usage
string) *bool {
596 f
.BoolVar(p
, name
, value
, usage
)
600 // Bool defines a bool flag with specified name, default value, and usage string.
601 // The return value is the address of a bool variable that stores the value of the flag.
602 func Bool(name
string, value
bool, usage
string) *bool {
603 return CommandLine
.Bool(name
, value
, usage
)
606 // IntVar defines an int flag with specified name, default value, and usage string.
607 // The argument p points to an int variable in which to store the value of the flag.
608 func (f
*FlagSet
) IntVar(p
*int, name
string, value
int, usage
string) {
609 f
.Var(newIntValue(value
, p
), name
, usage
)
612 // IntVar defines an int flag with specified name, default value, and usage string.
613 // The argument p points to an int variable in which to store the value of the flag.
614 func IntVar(p
*int, name
string, value
int, usage
string) {
615 CommandLine
.Var(newIntValue(value
, p
), name
, usage
)
618 // Int defines an int flag with specified name, default value, and usage string.
619 // The return value is the address of an int variable that stores the value of the flag.
620 func (f
*FlagSet
) Int(name
string, value
int, usage
string) *int {
622 f
.IntVar(p
, name
, value
, usage
)
626 // Int defines an int flag with specified name, default value, and usage string.
627 // The return value is the address of an int variable that stores the value of the flag.
628 func Int(name
string, value
int, usage
string) *int {
629 return CommandLine
.Int(name
, value
, usage
)
632 // Int64Var defines an int64 flag with specified name, default value, and usage string.
633 // The argument p points to an int64 variable in which to store the value of the flag.
634 func (f
*FlagSet
) Int64Var(p
*int64, name
string, value
int64, usage
string) {
635 f
.Var(newInt64Value(value
, p
), name
, usage
)
638 // Int64Var defines an int64 flag with specified name, default value, and usage string.
639 // The argument p points to an int64 variable in which to store the value of the flag.
640 func Int64Var(p
*int64, name
string, value
int64, usage
string) {
641 CommandLine
.Var(newInt64Value(value
, p
), name
, usage
)
644 // Int64 defines an int64 flag with specified name, default value, and usage string.
645 // The return value is the address of an int64 variable that stores the value of the flag.
646 func (f
*FlagSet
) Int64(name
string, value
int64, usage
string) *int64 {
648 f
.Int64Var(p
, name
, value
, usage
)
652 // Int64 defines an int64 flag with specified name, default value, and usage string.
653 // The return value is the address of an int64 variable that stores the value of the flag.
654 func Int64(name
string, value
int64, usage
string) *int64 {
655 return CommandLine
.Int64(name
, value
, usage
)
658 // UintVar defines a uint flag with specified name, default value, and usage string.
659 // The argument p points to a uint variable in which to store the value of the flag.
660 func (f
*FlagSet
) UintVar(p
*uint, name
string, value
uint, usage
string) {
661 f
.Var(newUintValue(value
, p
), name
, usage
)
664 // UintVar defines a uint flag with specified name, default value, and usage string.
665 // The argument p points to a uint variable in which to store the value of the flag.
666 func UintVar(p
*uint, name
string, value
uint, usage
string) {
667 CommandLine
.Var(newUintValue(value
, p
), name
, usage
)
670 // Uint defines a uint flag with specified name, default value, and usage string.
671 // The return value is the address of a uint variable that stores the value of the flag.
672 func (f
*FlagSet
) Uint(name
string, value
uint, usage
string) *uint {
674 f
.UintVar(p
, name
, value
, usage
)
678 // Uint defines a uint flag with specified name, default value, and usage string.
679 // The return value is the address of a uint variable that stores the value of the flag.
680 func Uint(name
string, value
uint, usage
string) *uint {
681 return CommandLine
.Uint(name
, value
, usage
)
684 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
685 // The argument p points to a uint64 variable in which to store the value of the flag.
686 func (f
*FlagSet
) Uint64Var(p
*uint64, name
string, value
uint64, usage
string) {
687 f
.Var(newUint64Value(value
, p
), name
, usage
)
690 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
691 // The argument p points to a uint64 variable in which to store the value of the flag.
692 func Uint64Var(p
*uint64, name
string, value
uint64, usage
string) {
693 CommandLine
.Var(newUint64Value(value
, p
), name
, usage
)
696 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
697 // The return value is the address of a uint64 variable that stores the value of the flag.
698 func (f
*FlagSet
) Uint64(name
string, value
uint64, usage
string) *uint64 {
700 f
.Uint64Var(p
, name
, value
, usage
)
704 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
705 // The return value is the address of a uint64 variable that stores the value of the flag.
706 func Uint64(name
string, value
uint64, usage
string) *uint64 {
707 return CommandLine
.Uint64(name
, value
, usage
)
710 // StringVar defines a string flag with specified name, default value, and usage string.
711 // The argument p points to a string variable in which to store the value of the flag.
712 func (f
*FlagSet
) StringVar(p
*string, name
string, value
string, usage
string) {
713 f
.Var(newStringValue(value
, p
), name
, usage
)
716 // StringVar defines a string flag with specified name, default value, and usage string.
717 // The argument p points to a string variable in which to store the value of the flag.
718 func StringVar(p
*string, name
string, value
string, usage
string) {
719 CommandLine
.Var(newStringValue(value
, p
), name
, usage
)
722 // String defines a string flag with specified name, default value, and usage string.
723 // The return value is the address of a string variable that stores the value of the flag.
724 func (f
*FlagSet
) String(name
string, value
string, usage
string) *string {
726 f
.StringVar(p
, name
, value
, usage
)
730 // String defines a string flag with specified name, default value, and usage string.
731 // The return value is the address of a string variable that stores the value of the flag.
732 func String(name
string, value
string, usage
string) *string {
733 return CommandLine
.String(name
, value
, usage
)
736 // Float64Var defines a float64 flag with specified name, default value, and usage string.
737 // The argument p points to a float64 variable in which to store the value of the flag.
738 func (f
*FlagSet
) Float64Var(p
*float64, name
string, value
float64, usage
string) {
739 f
.Var(newFloat64Value(value
, p
), name
, usage
)
742 // Float64Var defines a float64 flag with specified name, default value, and usage string.
743 // The argument p points to a float64 variable in which to store the value of the flag.
744 func Float64Var(p
*float64, name
string, value
float64, usage
string) {
745 CommandLine
.Var(newFloat64Value(value
, p
), name
, usage
)
748 // Float64 defines a float64 flag with specified name, default value, and usage string.
749 // The return value is the address of a float64 variable that stores the value of the flag.
750 func (f
*FlagSet
) Float64(name
string, value
float64, usage
string) *float64 {
752 f
.Float64Var(p
, name
, value
, usage
)
756 // Float64 defines a float64 flag with specified name, default value, and usage string.
757 // The return value is the address of a float64 variable that stores the value of the flag.
758 func Float64(name
string, value
float64, usage
string) *float64 {
759 return CommandLine
.Float64(name
, value
, usage
)
762 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
763 // The argument p points to a time.Duration variable in which to store the value of the flag.
764 // The flag accepts a value acceptable to time.ParseDuration.
765 func (f
*FlagSet
) DurationVar(p
*time
.Duration
, name
string, value time
.Duration
, usage
string) {
766 f
.Var(newDurationValue(value
, p
), name
, usage
)
769 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
770 // The argument p points to a time.Duration variable in which to store the value of the flag.
771 // The flag accepts a value acceptable to time.ParseDuration.
772 func DurationVar(p
*time
.Duration
, name
string, value time
.Duration
, usage
string) {
773 CommandLine
.Var(newDurationValue(value
, p
), name
, usage
)
776 // Duration defines a time.Duration flag with specified name, default value, and usage string.
777 // The return value is the address of a time.Duration variable that stores the value of the flag.
778 // The flag accepts a value acceptable to time.ParseDuration.
779 func (f
*FlagSet
) Duration(name
string, value time
.Duration
, usage
string) *time
.Duration
{
780 p
:= new(time
.Duration
)
781 f
.DurationVar(p
, name
, value
, usage
)
785 // Duration defines a time.Duration flag with specified name, default value, and usage string.
786 // The return value is the address of a time.Duration variable that stores the value of the flag.
787 // The flag accepts a value acceptable to time.ParseDuration.
788 func Duration(name
string, value time
.Duration
, usage
string) *time
.Duration
{
789 return CommandLine
.Duration(name
, value
, usage
)
792 // Var defines a flag with the specified name and usage string. The type and
793 // value of the flag are represented by the first argument, of type Value, which
794 // typically holds a user-defined implementation of Value. For instance, the
795 // caller could create a flag that turns a comma-separated string into a slice
796 // of strings by giving the slice the methods of Value; in particular, Set would
797 // decompose the comma-separated string into the slice.
798 func (f
*FlagSet
) Var(value Value
, name
string, usage
string) {
799 // Remember the default value as a string; it won't change.
800 flag
:= &Flag
{name
, usage
, value
, value
.String()}
801 _
, alreadythere
:= f
.formal
[name
]
805 msg
= fmt
.Sprintf("flag redefined: %s", name
)
807 msg
= fmt
.Sprintf("%s flag redefined: %s", f
.name
, name
)
809 fmt
.Fprintln(f
.Output(), msg
)
810 panic(msg
) // Happens only if flags are declared with identical names
813 f
.formal
= make(map[string]*Flag
)
815 f
.formal
[name
] = flag
818 // Var defines a flag with the specified name and usage string. The type and
819 // value of the flag are represented by the first argument, of type Value, which
820 // typically holds a user-defined implementation of Value. For instance, the
821 // caller could create a flag that turns a comma-separated string into a slice
822 // of strings by giving the slice the methods of Value; in particular, Set would
823 // decompose the comma-separated string into the slice.
824 func Var(value Value
, name
string, usage
string) {
825 CommandLine
.Var(value
, name
, usage
)
828 // failf prints to standard error a formatted error and usage message and
829 // returns the error.
830 func (f
*FlagSet
) failf(format
string, a
...interface{}) error
{
831 err
:= fmt
.Errorf(format
, a
...)
832 fmt
.Fprintln(f
.Output(), err
)
837 // usage calls the Usage method for the flag set if one is specified,
838 // or the appropriate default usage function otherwise.
839 func (f
*FlagSet
) usage() {
847 // parseOne parses one flag. It reports whether a flag was seen.
848 func (f
*FlagSet
) parseOne() (bool, error
) {
849 if len(f
.args
) == 0 {
853 if len(s
) < 2 || s
[0] != '-' {
859 if len(s
) == 2 { // "--" terminates the flags
864 name
:= s
[numMinuses
:]
865 if len(name
) == 0 || name
[0] == '-' || name
[0] == '=' {
866 return false, f
.failf("bad flag syntax: %s", s
)
869 // it's a flag. does it have an argument?
873 for i
:= 1; i
< len(name
); i
++ { // equals cannot be first
882 flag
, alreadythere
:= m
[name
] // BUG
884 if name
== "help" || name
== "h" { // special case for nice help message.
886 return false, ErrHelp
888 return false, f
.failf("flag provided but not defined: -%s", name
)
891 if fv
, ok
:= flag
.Value
.(boolFlag
); ok
&& fv
.IsBoolFlag() { // special case: doesn't need an arg
893 if err
:= fv
.Set(value
); err
!= nil {
894 return false, f
.failf("invalid boolean value %q for -%s: %v", value
, name
, err
)
897 if err
:= fv
.Set("true"); err
!= nil {
898 return false, f
.failf("invalid boolean flag %s: %v", name
, err
)
902 // It must have a value, which might be the next argument.
903 if !hasValue
&& len(f
.args
) > 0 {
904 // value is the next arg
906 value
, f
.args
= f
.args
[0], f
.args
[1:]
909 return false, f
.failf("flag needs an argument: -%s", name
)
911 if err
:= flag
.Value
.Set(value
); err
!= nil {
912 return false, f
.failf("invalid value %q for flag -%s: %v", value
, name
, err
)
916 f
.actual
= make(map[string]*Flag
)
918 f
.actual
[name
] = flag
922 // Parse parses flag definitions from the argument list, which should not
923 // include the command name. Must be called after all flags in the FlagSet
924 // are defined and before flags are accessed by the program.
925 // The return value will be ErrHelp if -help or -h were set but not defined.
926 func (f
*FlagSet
) Parse(arguments
[]string) error
{
930 seen
, err
:= f
.parseOne()
937 switch f
.errorHandling
{
938 case ContinueOnError
:
949 // Parsed reports whether f.Parse has been called.
950 func (f
*FlagSet
) Parsed() bool {
954 // Parse parses the command-line flags from os.Args[1:]. Must be called
955 // after all flags are defined and before flags are accessed by the program.
957 // Ignore errors; CommandLine is set for ExitOnError.
958 CommandLine
.Parse(os
.Args
[1:])
961 // Parsed reports whether the command-line flags have been parsed.
963 return CommandLine
.Parsed()
966 // CommandLine is the default set of command-line flags, parsed from os.Args.
967 // The top-level functions such as BoolVar, Arg, and so on are wrappers for the
968 // methods of CommandLine.
969 var CommandLine
= NewFlagSet(os
.Args
[0], ExitOnError
)
972 // Override generic FlagSet default Usage with call to global Usage.
973 // Note: This is not CommandLine.Usage = Usage,
974 // because we want any eventual call to use any updated value of Usage,
975 // not the value it has when this line is run.
976 CommandLine
.Usage
= commandLineUsage
979 func commandLineUsage() {
983 // NewFlagSet returns a new, empty flag set with the specified name and
984 // error handling property.
985 func NewFlagSet(name
string, errorHandling ErrorHandling
) *FlagSet
{
988 errorHandling
: errorHandling
,
990 f
.Usage
= f
.defaultUsage
994 // Init sets the name and error handling property for a flag set.
995 // By default, the zero FlagSet uses an empty name and the
996 // ContinueOnError error handling policy.
997 func (f
*FlagSet
) Init(name
string, errorHandling ErrorHandling
) {
999 f
.errorHandling
= errorHandling