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 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.
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
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")
84 func newBoolValue(val
bool, p
*bool) *boolValue
{
86 return (*boolValue
)(p
)
89 func (b
*boolValue
) Set(s
string) error
{
90 v
, err
:= strconv
.ParseBool(s
)
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 {
111 func newIntValue(val
int, p
*int) *intValue
{
113 return (*intValue
)(p
)
116 func (i
*intValue
) Set(s
string) error
{
117 v
, err
:= strconv
.ParseInt(s
, 0, 64)
122 func (i
*intValue
) Get() interface{} { return int(*i
) }
124 func (i
*intValue
) String() string { return fmt
.Sprintf("%v", *i
) }
127 type int64Value
int64
129 func newInt64Value(val
int64, p
*int64) *int64Value
{
131 return (*int64Value
)(p
)
134 func (i
*int64Value
) Set(s
string) error
{
135 v
, err
:= strconv
.ParseInt(s
, 0, 64)
140 func (i
*int64Value
) Get() interface{} { return int64(*i
) }
142 func (i
*int64Value
) String() string { return fmt
.Sprintf("%v", *i
) }
147 func newUintValue(val
uint, p
*uint) *uintValue
{
149 return (*uintValue
)(p
)
152 func (i
*uintValue
) Set(s
string) error
{
153 v
, err
:= strconv
.ParseUint(s
, 0, 64)
158 func (i
*uintValue
) Get() interface{} { return uint(*i
) }
160 func (i
*uintValue
) String() string { return fmt
.Sprintf("%v", *i
) }
163 type uint64Value
uint64
165 func newUint64Value(val
uint64, p
*uint64) *uint64Value
{
167 return (*uint64Value
)(p
)
170 func (i
*uint64Value
) Set(s
string) error
{
171 v
, err
:= strconv
.ParseUint(s
, 0, 64)
176 func (i
*uint64Value
) Get() interface{} { return uint64(*i
) }
178 func (i
*uint64Value
) String() string { return fmt
.Sprintf("%v", *i
) }
181 type stringValue
string
183 func newStringValue(val
string, p
*string) *stringValue
{
185 return (*stringValue
)(p
)
188 func (s
*stringValue
) Set(val
string) error
{
189 *s
= stringValue(val
)
193 func (s
*stringValue
) Get() interface{} { return string(*s
) }
195 func (s
*stringValue
) String() string { return fmt
.Sprintf("%s", *s
) }
198 type float64Value
float64
200 func newFloat64Value(val
float64, p
*float64) *float64Value
{
202 return (*float64Value
)(p
)
205 func (f
*float64Value
) Set(s
string) error
{
206 v
, err
:= strconv
.ParseFloat(s
, 64)
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
{
220 return (*durationValue
)(p
)
223 func (d
*durationValue
) Set(s
string) error
{
224 v
, err
:= time
.ParseDuration(s
)
225 *d
= durationValue(v
)
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 {
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 {
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.
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.
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.
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
))
294 for _
, f
:= range flags
{
299 result
:= make([]*Flag
, len(list
))
300 for i
, name
:= range list
{
301 result
[i
] = flags
[name
]
306 func (f
*FlagSet
) out() io
.Writer
{
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
) {
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
) {
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
) {
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
]
362 return fmt
.Errorf("no such flag -%v", name
)
364 err
:= flag
.Value
.Set(value
)
369 f
.actual
= make(map[string]*Flag
)
371 f
.actual
[name
] = flag
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
)
388 if typ
.Kind() == reflect
.Ptr
{
389 z
= reflect
.New(typ
.Elem())
391 z
= reflect
.Zero(typ
)
393 if value
== z
.Interface().(Value
).String() {
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.
416 for i
:= 0; i
< len(usage
); i
++ {
418 for j
:= i
+ 1; j
< len(usage
); j
++ {
420 name
= usage
[i
+1 : j
]
421 usage
= usage
[:i
] + name
+ usage
[j
+1:]
425 break // Only one back quote; use type name.
428 // No explicit name, so use type if we can find one.
430 switch flag
.Value
.(type) {
437 case *intValue
, *int64Value
:
441 case *uintValue
, *uint64Value
:
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
)
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'.
462 // Four spaces before the tab triggers good alignment
463 // for both 4- and 8-space tab stops.
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
)
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
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
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
) {
505 fmt
.Fprintf(f
.out(), "Usage:\n")
507 fmt
.Fprintf(f
.out(), "Usage of %s:\n", f
.name
)
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.
522 fmt
.Fprintf(os
.Stderr
, "Usage of %s:\n", os
.Args
[0])
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
) {
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 {
577 f
.BoolVar(p
, name
, value
, usage
)
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 {
603 f
.IntVar(p
, name
, value
, usage
)
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 {
629 f
.Int64Var(p
, name
, value
, usage
)
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 {
655 f
.UintVar(p
, name
, value
, usage
)
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 {
681 f
.Uint64Var(p
, name
, value
, usage
)
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 {
707 f
.StringVar(p
, name
, value
, usage
)
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 {
733 f
.Float64Var(p
, name
, value
, usage
)
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
)
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
]
786 msg
= fmt
.Sprintf("flag redefined: %s", name
)
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
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
)
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() {
822 if f
== CommandLine
{
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 {
838 if len(s
) == 0 || s
[0] != '-' ||
len(s
) == 1 {
844 if len(s
) == 2 { // "--" terminates the flags
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?
858 for i
:= 1; i
< len(name
); i
++ { // equals cannot be first
867 flag
, alreadythere
:= m
[name
] // BUG
869 if name
== "help" || name
== "h" { // special case for nice help message.
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
878 if err
:= fv
.Set(value
); err
!= nil {
879 return false, f
.failf("invalid boolean value %q for -%s: %v", value
, name
, err
)
882 if err
:= fv
.Set("true"); err
!= nil {
883 return false, f
.failf("invalid boolean flag %s: %v", name
, err
)
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
891 value
, f
.args
= f
.args
[0], f
.args
[1:]
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
)
901 f
.actual
= make(map[string]*Flag
)
903 f
.actual
[name
] = flag
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
{
915 seen
, err
:= f
.parseOne()
922 switch f
.errorHandling
{
923 case ContinueOnError
:
934 // Parsed reports whether f.Parse has been called.
935 func (f
*FlagSet
) Parsed() bool {
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.
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.
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
{
961 errorHandling
: errorHandling
,
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
) {
971 f
.errorHandling
= errorHandling