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. Example:
12 var ip *int = flag.Int("flagname", 1234, "help message for flagname")
13 If you like, you can bind the flag to a variable using the Var() functions.
16 flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
18 Or you can create custom flags that satisfy the Value interface (with
19 pointer receivers) and couple them to flag parsing by
20 flag.Var(&flagVal, "name", "help message for flagname")
21 For such flags, the default value is just the initial value of the variable.
23 After all flags are defined, call
25 to parse the command line into the defined flags.
27 Flags may then be used directly. If you're using the flags themselves,
28 they are all pointers; if you bind to variables, they're values.
29 fmt.Println("ip has value ", *ip);
30 fmt.Println("flagvar has value ", flagvar);
32 After parsing, the arguments after the flag are available as the
33 slice flag.Args() or individually as flag.Arg(i).
34 The arguments are indexed from 0 up to flag.NArg().
36 Command line flag syntax:
39 -flag x // non-boolean flags only
40 One or two minus signs may be used; they are equivalent.
41 The last form is not permitted for boolean flags because the
42 meaning of the command
44 will change if there is a file called 0, false, etc. You must
45 use the -flag=false form to turn off a boolean flag.
47 Flag parsing stops just before the first non-flag argument
48 ("-" is a non-flag argument) or after the terminator "--".
50 Integer flags accept 1234, 0664, 0x1234 and may be negative.
51 Boolean flags may be 1, 0, t, f, true, false, TRUE, FALSE, True, False.
52 Duration flags accept any input valid for time.ParseDuration.
54 The default set of command-line flags is controlled by
55 top-level functions. The FlagSet type allows one to define
56 independent sets of flags, such as to implement subcommands
57 in a command-line interface. The methods of FlagSet are
58 analogous to the top-level functions for the command-line
73 // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
74 var ErrHelp = errors.New("flag: help requested")
79 func newBoolValue(val bool, p *bool) *boolValue {
81 return (*boolValue)(p)
84 func (b *boolValue) Set(s string) error {
85 v, err := strconv.ParseBool(s)
90 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
95 func newIntValue(val int, p *int) *intValue {
100 func (i *intValue) Set(s string) error {
101 v, err := strconv.ParseInt(s, 0, 64)
106 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
109 type int64Value int64
111 func newInt64Value(val int64, p *int64) *int64Value {
113 return (*int64Value)(p)
116 func (i *int64Value) Set(s string) error {
117 v, err := strconv.ParseInt(s, 0, 64)
122 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
127 func newUintValue(val uint, p *uint) *uintValue {
129 return (*uintValue)(p)
132 func (i *uintValue) Set(s string) error {
133 v, err := strconv.ParseUint(s, 0, 64)
138 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
141 type uint64Value uint64
143 func newUint64Value(val uint64, p *uint64) *uint64Value {
145 return (*uint64Value)(p)
148 func (i *uint64Value) Set(s string) error {
149 v, err := strconv.ParseUint(s, 0, 64)
154 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
157 type stringValue string
159 func newStringValue(val string, p *string) *stringValue {
161 return (*stringValue)(p)
164 func (s *stringValue) Set(val string) error {
165 *s = stringValue(val)
169 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
172 type float64Value float64
174 func newFloat64Value(val float64, p *float64) *float64Value {
176 return (*float64Value)(p)
179 func (f *float64Value) Set(s string) error {
180 v, err := strconv.ParseFloat(s, 64)
185 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
187 // -- time.Duration Value
188 type durationValue time.Duration
190 func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
192 return (*durationValue)(p)
195 func (d *durationValue) Set(s string) error {
196 v, err := time.ParseDuration(s)
197 *d = durationValue(v)
201 func (d *durationValue) String() string { return (*time.Duration)(d).String() }
203 // Value is the interface to the dynamic value stored in a flag.
204 // (The default value is represented as a string.)
205 type Value interface {
210 // ErrorHandling defines how to handle flag parsing errors.
211 type ErrorHandling int
214 ContinueOnError ErrorHandling = iota
219 // A FlagSet represents a set of defined flags.
220 type FlagSet struct {
221 // Usage is the function called when an error occurs while parsing flags.
222 // The field is a function (not a method) that may be changed to point to
223 // a custom error handler.
228 actual map[string]*Flag
229 formal map[string]*Flag
230 args []string // arguments after flags
231 exitOnError bool // does the program exit if there's an error?
232 errorHandling ErrorHandling
233 output io.Writer // nil means stderr; use out() accessor
236 // A Flag represents the state of a flag.
238 Name string // name as it appears on command line
239 Usage string // help message
240 Value Value // value as set
241 DefValue string // default value (as text); for usage message
244 // sortFlags returns the flags as a slice in lexicographical sorted order.
245 func sortFlags(flags map[string]*Flag) []*Flag {
246 list := make(sort.StringSlice, len(flags))
248 for _, f := range flags {
253 result := make([]*Flag, len(list))
254 for i, name := range list {
255 result[i] = flags[name]
260 func (f *FlagSet) out() io.Writer {
267 // SetOutput sets the destination for usage and error messages.
268 // If output is nil, os.Stderr is used.
269 func (f *FlagSet) SetOutput(output io.Writer) {
273 // VisitAll visits the flags in lexicographical order, calling fn for each.
274 // It visits all flags, even those not set.
275 func (f *FlagSet) VisitAll(fn func(*Flag)) {
276 for _, flag := range sortFlags(f.formal) {
281 // VisitAll visits the command-line flags in lexicographical order, calling
282 // fn for each. It visits all flags, even those not set.
283 func VisitAll(fn func(*Flag)) {
284 commandLine.VisitAll(fn)
287 // Visit visits the flags in lexicographical order, calling fn for each.
288 // It visits only those flags that have been set.
289 func (f *FlagSet) Visit(fn func(*Flag)) {
290 for _, flag := range sortFlags(f.actual) {
295 // Visit visits the command-line flags in lexicographical order, calling fn
296 // for each. It visits only those flags that have been set.
297 func Visit(fn func(*Flag)) {
298 commandLine.Visit(fn)
301 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
302 func (f *FlagSet) Lookup(name string) *Flag {
303 return f.formal[name]
306 // Lookup returns the Flag structure of the named command-line flag,
307 // returning nil if none exists.
308 func Lookup(name string) *Flag {
309 return commandLine.formal[name]
312 // Set sets the value of the named flag.
313 func (f *FlagSet) Set(name, value string) error {
314 flag, ok := f.formal[name]
316 return fmt.Errorf("no such flag -%v", name)
318 err := flag.Value.Set(value)
323 f.actual = make(map[string]*Flag)
325 f.actual[name] = flag
329 // Set sets the value of the named command-line flag.
330 func Set(name, value string) error {
331 return commandLine.Set(name, value)
334 // PrintDefaults prints, to standard error unless configured
335 // otherwise, the default values of all defined flags in the set.
336 func (f *FlagSet) PrintDefaults() {
337 f.VisitAll(func(flag *Flag) {
338 format := " -%s=%s: %s\n"
339 if _, ok := flag.Value.(*stringValue); ok {
340 // put quotes on the value
341 format = " -%s=%q: %s\n"
343 fmt.Fprintf(f.out(), format, flag.Name, flag.DefValue, flag.Usage)
347 // PrintDefaults prints to standard error the default values of all defined command-line flags.
348 func PrintDefaults() {
349 commandLine.PrintDefaults()
352 // defaultUsage is the default function to print a usage message.
353 func defaultUsage(f *FlagSet) {
354 fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
358 // NOTE: Usage is not just defaultUsage(commandLine)
359 // because it serves (via godoc flag Usage) as the example
360 // for how to write your own usage function.
362 // Usage prints to standard error a usage message documenting all defined command-line flags.
363 // The function is a variable that may be changed to point to a custom function.
365 fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
369 // NFlag returns the number of flags that have been set.
370 func (f *FlagSet) NFlag() int { return len(f.actual) }
372 // NFlag returns the number of command-line flags that have been set.
373 func NFlag() int { return len(commandLine.actual) }
375 // Arg returns the i'th argument. Arg(0) is the first remaining argument
376 // after flags have been processed.
377 func (f *FlagSet) Arg(i int) string {
378 if i < 0 || i >= len(f.args) {
384 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
385 // after flags have been processed.
386 func Arg(i int) string {
387 return commandLine.Arg(i)
390 // NArg is the number of arguments remaining after flags have been processed.
391 func (f *FlagSet) NArg() int { return len(f.args) }
393 // NArg is the number of arguments remaining after flags have been processed.
394 func NArg() int { return len(commandLine.args) }
396 // Args returns the non-flag arguments.
397 func (f *FlagSet) Args() []string { return f.args }
399 // Args returns the non-flag command-line arguments.
400 func Args() []string { return commandLine.args }
402 // BoolVar defines a bool flag with specified name, default value, and usage string.
403 // The argument p points to a bool variable in which to store the value of the flag.
404 func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
405 f.Var(newBoolValue(value, p), name, usage)
408 // BoolVar defines a bool flag with specified name, default value, and usage string.
409 // The argument p points to a bool variable in which to store the value of the flag.
410 func BoolVar(p *bool, name string, value bool, usage string) {
411 commandLine.Var(newBoolValue(value, p), name, usage)
414 // Bool defines a bool flag with specified name, default value, and usage string.
415 // The return value is the address of a bool variable that stores the value of the flag.
416 func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
418 f.BoolVar(p, name, value, usage)
422 // Bool defines a bool flag with specified name, default value, and usage string.
423 // The return value is the address of a bool variable that stores the value of the flag.
424 func Bool(name string, value bool, usage string) *bool {
425 return commandLine.Bool(name, value, usage)
428 // IntVar defines an int flag with specified name, default value, and usage string.
429 // The argument p points to an int variable in which to store the value of the flag.
430 func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
431 f.Var(newIntValue(value, p), name, usage)
434 // IntVar defines an int flag with specified name, default value, and usage string.
435 // The argument p points to an int variable in which to store the value of the flag.
436 func IntVar(p *int, name string, value int, usage string) {
437 commandLine.Var(newIntValue(value, p), name, usage)
440 // Int defines an int flag with specified name, default value, and usage string.
441 // The return value is the address of an int variable that stores the value of the flag.
442 func (f *FlagSet) Int(name string, value int, usage string) *int {
444 f.IntVar(p, name, value, usage)
448 // Int defines an int flag with specified name, default value, and usage string.
449 // The return value is the address of an int variable that stores the value of the flag.
450 func Int(name string, value int, usage string) *int {
451 return commandLine.Int(name, value, usage)
454 // Int64Var defines an int64 flag with specified name, default value, and usage string.
455 // The argument p points to an int64 variable in which to store the value of the flag.
456 func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
457 f.Var(newInt64Value(value, p), name, usage)
460 // Int64Var defines an int64 flag with specified name, default value, and usage string.
461 // The argument p points to an int64 variable in which to store the value of the flag.
462 func Int64Var(p *int64, name string, value int64, usage string) {
463 commandLine.Var(newInt64Value(value, p), name, usage)
466 // Int64 defines an int64 flag with specified name, default value, and usage string.
467 // The return value is the address of an int64 variable that stores the value of the flag.
468 func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
470 f.Int64Var(p, name, value, usage)
474 // Int64 defines an int64 flag with specified name, default value, and usage string.
475 // The return value is the address of an int64 variable that stores the value of the flag.
476 func Int64(name string, value int64, usage string) *int64 {
477 return commandLine.Int64(name, value, usage)
480 // UintVar defines a uint flag with specified name, default value, and usage string.
481 // The argument p points to a uint variable in which to store the value of the flag.
482 func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
483 f.Var(newUintValue(value, p), name, usage)
486 // UintVar defines a uint flag with specified name, default value, and usage string.
487 // The argument p points to a uint variable in which to store the value of the flag.
488 func UintVar(p *uint, name string, value uint, usage string) {
489 commandLine.Var(newUintValue(value, p), name, usage)
492 // Uint defines a uint flag with specified name, default value, and usage string.
493 // The return value is the address of a uint variable that stores the value of the flag.
494 func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
496 f.UintVar(p, name, value, usage)
500 // Uint defines a uint flag with specified name, default value, and usage string.
501 // The return value is the address of a uint variable that stores the value of the flag.
502 func Uint(name string, value uint, usage string) *uint {
503 return commandLine.Uint(name, value, usage)
506 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
507 // The argument p points to a uint64 variable in which to store the value of the flag.
508 func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
509 f.Var(newUint64Value(value, p), name, usage)
512 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
513 // The argument p points to a uint64 variable in which to store the value of the flag.
514 func Uint64Var(p *uint64, name string, value uint64, usage string) {
515 commandLine.Var(newUint64Value(value, p), name, usage)
518 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
519 // The return value is the address of a uint64 variable that stores the value of the flag.
520 func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
522 f.Uint64Var(p, name, value, usage)
526 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
527 // The return value is the address of a uint64 variable that stores the value of the flag.
528 func Uint64(name string, value uint64, usage string) *uint64 {
529 return commandLine.Uint64(name, value, usage)
532 // StringVar defines a string flag with specified name, default value, and usage string.
533 // The argument p points to a string variable in which to store the value of the flag.
534 func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
535 f.Var(newStringValue(value, p), name, usage)
538 // StringVar defines a string flag with specified name, default value, and usage string.
539 // The argument p points to a string variable in which to store the value of the flag.
540 func StringVar(p *string, name string, value string, usage string) {
541 commandLine.Var(newStringValue(value, p), name, usage)
544 // String defines a string flag with specified name, default value, and usage string.
545 // The return value is the address of a string variable that stores the value of the flag.
546 func (f *FlagSet) String(name string, value string, usage string) *string {
548 f.StringVar(p, name, value, usage)
552 // String defines a string flag with specified name, default value, and usage string.
553 // The return value is the address of a string variable that stores the value of the flag.
554 func String(name string, value string, usage string) *string {
555 return commandLine.String(name, value, usage)
558 // Float64Var defines a float64 flag with specified name, default value, and usage string.
559 // The argument p points to a float64 variable in which to store the value of the flag.
560 func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
561 f.Var(newFloat64Value(value, p), name, usage)
564 // Float64Var defines a float64 flag with specified name, default value, and usage string.
565 // The argument p points to a float64 variable in which to store the value of the flag.
566 func Float64Var(p *float64, name string, value float64, usage string) {
567 commandLine.Var(newFloat64Value(value, p), name, usage)
570 // Float64 defines a float64 flag with specified name, default value, and usage string.
571 // The return value is the address of a float64 variable that stores the value of the flag.
572 func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
574 f.Float64Var(p, name, value, usage)
578 // Float64 defines a float64 flag with specified name, default value, and usage string.
579 // The return value is the address of a float64 variable that stores the value of the flag.
580 func Float64(name string, value float64, usage string) *float64 {
581 return commandLine.Float64(name, value, usage)
584 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
585 // The argument p points to a time.Duration variable in which to store the value of the flag.
586 func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
587 f.Var(newDurationValue(value, p), name, usage)
590 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
591 // The argument p points to a time.Duration variable in which to store the value of the flag.
592 func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
593 commandLine.Var(newDurationValue(value, p), name, usage)
596 // Duration defines a time.Duration flag with specified name, default value, and usage string.
597 // The return value is the address of a time.Duration variable that stores the value of the flag.
598 func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
599 p := new(time.Duration)
600 f.DurationVar(p, name, value, usage)
604 // Duration defines a time.Duration flag with specified name, default value, and usage string.
605 // The return value is the address of a time.Duration variable that stores the value of the flag.
606 func Duration(name string, value time.Duration, usage string) *time.Duration {
607 return commandLine.Duration(name, value, usage)
610 // Var defines a flag with the specified name and usage string. The type and
611 // value of the flag are represented by the first argument, of type Value, which
612 // typically holds a user-defined implementation of Value. For instance, the
613 // caller could create a flag that turns a comma-separated string into a slice
614 // of strings by giving the slice the methods of Value; in particular, Set would
615 // decompose the comma-separated string into the slice.
616 func (f *FlagSet) Var(value Value, name string, usage string) {
617 // Remember the default value as a string; it won't change.
618 flag := &Flag{name, usage, value, value.String()}
619 _, alreadythere := f.formal[name]
621 fmt.Fprintf(f.out(), "%s flag redefined: %s\n", f.name, name)
622 panic("flag redefinition") // Happens only if flags are declared with identical names
625 f.formal = make(map[string]*Flag)
627 f.formal[name] = flag
630 // Var defines a flag with the specified name and usage string. The type and
631 // value of the flag are represented by the first argument, of type Value, which
632 // typically holds a user-defined implementation of Value. For instance, the
633 // caller could create a flag that turns a comma-separated string into a slice
634 // of strings by giving the slice the methods of Value; in particular, Set would
635 // decompose the comma-separated string into the slice.
636 func Var(value Value, name string, usage string) {
637 commandLine.Var(value, name, usage)
640 // failf prints to standard error a formatted error and usage message and
641 // returns the error.
642 func (f *FlagSet) failf(format string, a ...interface{}) error {
643 err := fmt.Errorf(format, a...)
644 fmt.Fprintln(f.out(), err)
649 // usage calls the Usage method for the flag set, or the usage function if
650 // the flag set is commandLine.
651 func (f *FlagSet) usage() {
652 if f == commandLine {
654 } else if f.Usage == nil {
661 // parseOne parses one flag. It returns whether a flag was seen.
662 func (f *FlagSet) parseOne() (bool, error) {
663 if len(f.args) == 0 {
667 if len(s) == 0 || s[0] != '-' || len(s) == 1 {
673 if len(s) == 2 { // "--" terminates the flags
678 name := s[num_minuses:]
679 if len(name) == 0 || name[0] == '-' || name[0] == '=' {
680 return false, f.failf("bad flag syntax: %s", s)
683 // it's a flag. does it have an argument?
687 for i := 1; i < len(name); i++ { // equals cannot be first
696 flag, alreadythere := m[name] // BUG
698 if name == "help" || name == "h" { // special case for nice help message.
700 return false, ErrHelp
702 return false, f.failf("flag provided but not defined: -%s", name)
704 if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
706 if err := fv.Set(value); err != nil {
707 f.failf("invalid boolean value %q for -%s: %v", value, name, err)
713 // It must have a value, which might be the next argument.
714 if !has_value && len(f.args) > 0 {
715 // value is the next arg
717 value, f.args = f.args[0], f.args[1:]
720 return false, f.failf("flag needs an argument: -%s", name)
722 if err := flag.Value.Set(value); err != nil {
723 return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
727 f.actual = make(map[string]*Flag)
729 f.actual[name] = flag
733 // Parse parses flag definitions from the argument list, which should not
734 // include the command name. Must be called after all flags in the FlagSet
735 // are defined and before flags are accessed by the program.
736 // The return value will be ErrHelp if -help was set but not defined.
737 func (f *FlagSet) Parse(arguments []string) error {
741 seen, err := f.parseOne()
748 switch f.errorHandling {
749 case ContinueOnError:
760 // Parsed reports whether f.Parse has been called.
761 func (f *FlagSet) Parsed() bool {
765 // Parse parses the command-line flags from os.Args[1:]. Must be called
766 // after all flags are defined and before flags are accessed by the program.
768 // Ignore errors; commandLine is set for ExitOnError.
769 commandLine.Parse(os.Args[1:])
772 // Parsed returns true if the command-line flags have been parsed.
774 return commandLine.Parsed()
777 // The default set of command-line flags, parsed from os.Args.
778 var commandLine = NewFlagSet(os.Args[0], ExitOnError)
780 // NewFlagSet returns a new, empty flag set with the specified name and
781 // error handling property.
782 func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
785 errorHandling: errorHandling,
790 // Init sets the name and error handling property for a flag set.
791 // By default, the zero FlagSet uses an empty name and the
792 // ContinueOnError error handling policy.
793 func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
795 f.errorHandling = errorHandling