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 after the flag 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.
53 Boolean flags may be 1, 0, t, f, true, false, TRUE, FALSE, True, False.
54 Duration flags accept any input valid for time.ParseDuration.
56 The default set of command-line flags is controlled by
57 top-level functions. The FlagSet type allows one to define
58 independent sets of flags, such as to implement subcommands
59 in a command-line interface. The methods of FlagSet are
60 analogous to the top-level functions for the command-line
75 // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
76 var ErrHelp = errors.New("flag: help requested")
81 func newBoolValue(val bool, p *bool) *boolValue {
83 return (*boolValue)(p)
86 func (b *boolValue) Set(s string) error {
87 v, err := strconv.ParseBool(s)
92 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
97 func newIntValue(val int, p *int) *intValue {
102 func (i *intValue) Set(s string) error {
103 v, err := strconv.ParseInt(s, 0, 64)
108 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
111 type int64Value int64
113 func newInt64Value(val int64, p *int64) *int64Value {
115 return (*int64Value)(p)
118 func (i *int64Value) Set(s string) error {
119 v, err := strconv.ParseInt(s, 0, 64)
124 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
129 func newUintValue(val uint, p *uint) *uintValue {
131 return (*uintValue)(p)
134 func (i *uintValue) Set(s string) error {
135 v, err := strconv.ParseUint(s, 0, 64)
140 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
143 type uint64Value uint64
145 func newUint64Value(val uint64, p *uint64) *uint64Value {
147 return (*uint64Value)(p)
150 func (i *uint64Value) Set(s string) error {
151 v, err := strconv.ParseUint(s, 0, 64)
156 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
159 type stringValue string
161 func newStringValue(val string, p *string) *stringValue {
163 return (*stringValue)(p)
166 func (s *stringValue) Set(val string) error {
167 *s = stringValue(val)
171 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
174 type float64Value float64
176 func newFloat64Value(val float64, p *float64) *float64Value {
178 return (*float64Value)(p)
181 func (f *float64Value) Set(s string) error {
182 v, err := strconv.ParseFloat(s, 64)
187 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
189 // -- time.Duration Value
190 type durationValue time.Duration
192 func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
194 return (*durationValue)(p)
197 func (d *durationValue) Set(s string) error {
198 v, err := time.ParseDuration(s)
199 *d = durationValue(v)
203 func (d *durationValue) String() string { return (*time.Duration)(d).String() }
205 // Value is the interface to the dynamic value stored in a flag.
206 // (The default value is represented as a string.)
207 type Value interface {
212 // ErrorHandling defines how to handle flag parsing errors.
213 type ErrorHandling int
216 ContinueOnError ErrorHandling = iota
221 // A FlagSet represents a set of defined flags.
222 type FlagSet struct {
223 // Usage is the function called when an error occurs while parsing flags.
224 // The field is a function (not a method) that may be changed to point to
225 // a custom error handler.
230 actual map[string]*Flag
231 formal map[string]*Flag
232 args []string // arguments after flags
233 exitOnError bool // does the program exit if there's an error?
234 errorHandling ErrorHandling
235 output io.Writer // nil means stderr; use out() accessor
238 // A Flag represents the state of a flag.
240 Name string // name as it appears on command line
241 Usage string // help message
242 Value Value // value as set
243 DefValue string // default value (as text); for usage message
246 // sortFlags returns the flags as a slice in lexicographical sorted order.
247 func sortFlags(flags map[string]*Flag) []*Flag {
248 list := make(sort.StringSlice, len(flags))
250 for _, f := range flags {
255 result := make([]*Flag, len(list))
256 for i, name := range list {
257 result[i] = flags[name]
262 func (f *FlagSet) out() io.Writer {
269 // SetOutput sets the destination for usage and error messages.
270 // If output is nil, os.Stderr is used.
271 func (f *FlagSet) SetOutput(output io.Writer) {
275 // VisitAll visits the flags in lexicographical order, calling fn for each.
276 // It visits all flags, even those not set.
277 func (f *FlagSet) VisitAll(fn func(*Flag)) {
278 for _, flag := range sortFlags(f.formal) {
283 // VisitAll visits the command-line flags in lexicographical order, calling
284 // fn for each. It visits all flags, even those not set.
285 func VisitAll(fn func(*Flag)) {
286 commandLine.VisitAll(fn)
289 // Visit visits the flags in lexicographical order, calling fn for each.
290 // It visits only those flags that have been set.
291 func (f *FlagSet) Visit(fn func(*Flag)) {
292 for _, flag := range sortFlags(f.actual) {
297 // Visit visits the command-line flags in lexicographical order, calling fn
298 // for each. It visits only those flags that have been set.
299 func Visit(fn func(*Flag)) {
300 commandLine.Visit(fn)
303 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
304 func (f *FlagSet) Lookup(name string) *Flag {
305 return f.formal[name]
308 // Lookup returns the Flag structure of the named command-line flag,
309 // returning nil if none exists.
310 func Lookup(name string) *Flag {
311 return commandLine.formal[name]
314 // Set sets the value of the named flag.
315 func (f *FlagSet) Set(name, value string) error {
316 flag, ok := f.formal[name]
318 return fmt.Errorf("no such flag -%v", name)
320 err := flag.Value.Set(value)
325 f.actual = make(map[string]*Flag)
327 f.actual[name] = flag
331 // Set sets the value of the named command-line flag.
332 func Set(name, value string) error {
333 return commandLine.Set(name, value)
336 // PrintDefaults prints, to standard error unless configured
337 // otherwise, the default values of all defined flags in the set.
338 func (f *FlagSet) PrintDefaults() {
339 f.VisitAll(func(flag *Flag) {
340 format := " -%s=%s: %s\n"
341 if _, ok := flag.Value.(*stringValue); ok {
342 // put quotes on the value
343 format = " -%s=%q: %s\n"
345 fmt.Fprintf(f.out(), format, flag.Name, flag.DefValue, flag.Usage)
349 // PrintDefaults prints to standard error the default values of all defined command-line flags.
350 func PrintDefaults() {
351 commandLine.PrintDefaults()
354 // defaultUsage is the default function to print a usage message.
355 func defaultUsage(f *FlagSet) {
356 fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
360 // NOTE: Usage is not just defaultUsage(commandLine)
361 // because it serves (via godoc flag Usage) as the example
362 // for how to write your own usage function.
364 // Usage prints to standard error a usage message documenting all defined command-line flags.
365 // The function is a variable that may be changed to point to a custom function.
367 fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
371 // NFlag returns the number of flags that have been set.
372 func (f *FlagSet) NFlag() int { return len(f.actual) }
374 // NFlag returns the number of command-line flags that have been set.
375 func NFlag() int { return len(commandLine.actual) }
377 // Arg returns the i'th argument. Arg(0) is the first remaining argument
378 // after flags have been processed.
379 func (f *FlagSet) Arg(i int) string {
380 if i < 0 || i >= len(f.args) {
386 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
387 // after flags have been processed.
388 func Arg(i int) string {
389 return commandLine.Arg(i)
392 // NArg is the number of arguments remaining after flags have been processed.
393 func (f *FlagSet) NArg() int { return len(f.args) }
395 // NArg is the number of arguments remaining after flags have been processed.
396 func NArg() int { return len(commandLine.args) }
398 // Args returns the non-flag arguments.
399 func (f *FlagSet) Args() []string { return f.args }
401 // Args returns the non-flag command-line arguments.
402 func Args() []string { return commandLine.args }
404 // BoolVar defines a bool flag with specified name, default value, and usage string.
405 // The argument p points to a bool variable in which to store the value of the flag.
406 func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
407 f.Var(newBoolValue(value, p), name, usage)
410 // BoolVar defines a bool flag with specified name, default value, and usage string.
411 // The argument p points to a bool variable in which to store the value of the flag.
412 func BoolVar(p *bool, name string, value bool, usage string) {
413 commandLine.Var(newBoolValue(value, p), name, usage)
416 // Bool defines a bool flag with specified name, default value, and usage string.
417 // The return value is the address of a bool variable that stores the value of the flag.
418 func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
420 f.BoolVar(p, name, value, usage)
424 // Bool defines a bool flag with specified name, default value, and usage string.
425 // The return value is the address of a bool variable that stores the value of the flag.
426 func Bool(name string, value bool, usage string) *bool {
427 return commandLine.Bool(name, value, usage)
430 // IntVar defines an int flag with specified name, default value, and usage string.
431 // The argument p points to an int variable in which to store the value of the flag.
432 func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
433 f.Var(newIntValue(value, p), name, usage)
436 // IntVar defines an int flag with specified name, default value, and usage string.
437 // The argument p points to an int variable in which to store the value of the flag.
438 func IntVar(p *int, name string, value int, usage string) {
439 commandLine.Var(newIntValue(value, p), name, usage)
442 // Int defines an int flag with specified name, default value, and usage string.
443 // The return value is the address of an int variable that stores the value of the flag.
444 func (f *FlagSet) Int(name string, value int, usage string) *int {
446 f.IntVar(p, name, value, usage)
450 // Int defines an int flag with specified name, default value, and usage string.
451 // The return value is the address of an int variable that stores the value of the flag.
452 func Int(name string, value int, usage string) *int {
453 return commandLine.Int(name, value, usage)
456 // Int64Var defines an int64 flag with specified name, default value, and usage string.
457 // The argument p points to an int64 variable in which to store the value of the flag.
458 func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
459 f.Var(newInt64Value(value, p), name, usage)
462 // Int64Var defines an int64 flag with specified name, default value, and usage string.
463 // The argument p points to an int64 variable in which to store the value of the flag.
464 func Int64Var(p *int64, name string, value int64, usage string) {
465 commandLine.Var(newInt64Value(value, p), name, usage)
468 // Int64 defines an int64 flag with specified name, default value, and usage string.
469 // The return value is the address of an int64 variable that stores the value of the flag.
470 func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
472 f.Int64Var(p, name, value, usage)
476 // Int64 defines an int64 flag with specified name, default value, and usage string.
477 // The return value is the address of an int64 variable that stores the value of the flag.
478 func Int64(name string, value int64, usage string) *int64 {
479 return commandLine.Int64(name, value, usage)
482 // UintVar defines a uint flag with specified name, default value, and usage string.
483 // The argument p points to a uint variable in which to store the value of the flag.
484 func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
485 f.Var(newUintValue(value, p), name, usage)
488 // UintVar defines a uint flag with specified name, default value, and usage string.
489 // The argument p points to a uint variable in which to store the value of the flag.
490 func UintVar(p *uint, name string, value uint, usage string) {
491 commandLine.Var(newUintValue(value, p), name, usage)
494 // Uint defines a uint flag with specified name, default value, and usage string.
495 // The return value is the address of a uint variable that stores the value of the flag.
496 func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
498 f.UintVar(p, name, value, usage)
502 // Uint defines a uint flag with specified name, default value, and usage string.
503 // The return value is the address of a uint variable that stores the value of the flag.
504 func Uint(name string, value uint, usage string) *uint {
505 return commandLine.Uint(name, value, usage)
508 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
509 // The argument p points to a uint64 variable in which to store the value of the flag.
510 func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
511 f.Var(newUint64Value(value, p), name, usage)
514 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
515 // The argument p points to a uint64 variable in which to store the value of the flag.
516 func Uint64Var(p *uint64, name string, value uint64, usage string) {
517 commandLine.Var(newUint64Value(value, p), name, usage)
520 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
521 // The return value is the address of a uint64 variable that stores the value of the flag.
522 func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
524 f.Uint64Var(p, name, value, usage)
528 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
529 // The return value is the address of a uint64 variable that stores the value of the flag.
530 func Uint64(name string, value uint64, usage string) *uint64 {
531 return commandLine.Uint64(name, value, usage)
534 // StringVar defines a string flag with specified name, default value, and usage string.
535 // The argument p points to a string variable in which to store the value of the flag.
536 func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
537 f.Var(newStringValue(value, p), name, usage)
540 // StringVar defines a string flag with specified name, default value, and usage string.
541 // The argument p points to a string variable in which to store the value of the flag.
542 func StringVar(p *string, name string, value string, usage string) {
543 commandLine.Var(newStringValue(value, p), name, usage)
546 // String defines a string flag with specified name, default value, and usage string.
547 // The return value is the address of a string variable that stores the value of the flag.
548 func (f *FlagSet) String(name string, value string, usage string) *string {
550 f.StringVar(p, name, value, usage)
554 // String defines a string flag with specified name, default value, and usage string.
555 // The return value is the address of a string variable that stores the value of the flag.
556 func String(name string, value string, usage string) *string {
557 return commandLine.String(name, value, usage)
560 // Float64Var defines a float64 flag with specified name, default value, and usage string.
561 // The argument p points to a float64 variable in which to store the value of the flag.
562 func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
563 f.Var(newFloat64Value(value, p), name, usage)
566 // Float64Var defines a float64 flag with specified name, default value, and usage string.
567 // The argument p points to a float64 variable in which to store the value of the flag.
568 func Float64Var(p *float64, name string, value float64, usage string) {
569 commandLine.Var(newFloat64Value(value, p), name, usage)
572 // Float64 defines a float64 flag with specified name, default value, and usage string.
573 // The return value is the address of a float64 variable that stores the value of the flag.
574 func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
576 f.Float64Var(p, name, value, usage)
580 // Float64 defines a float64 flag with specified name, default value, and usage string.
581 // The return value is the address of a float64 variable that stores the value of the flag.
582 func Float64(name string, value float64, usage string) *float64 {
583 return commandLine.Float64(name, value, usage)
586 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
587 // The argument p points to a time.Duration variable in which to store the value of the flag.
588 func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
589 f.Var(newDurationValue(value, p), name, usage)
592 // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
593 // The argument p points to a time.Duration variable in which to store the value of the flag.
594 func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
595 commandLine.Var(newDurationValue(value, p), name, usage)
598 // Duration defines a time.Duration flag with specified name, default value, and usage string.
599 // The return value is the address of a time.Duration variable that stores the value of the flag.
600 func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
601 p := new(time.Duration)
602 f.DurationVar(p, name, value, usage)
606 // Duration defines a time.Duration flag with specified name, default value, and usage string.
607 // The return value is the address of a time.Duration variable that stores the value of the flag.
608 func Duration(name string, value time.Duration, usage string) *time.Duration {
609 return commandLine.Duration(name, value, usage)
612 // Var defines a flag with the specified name and usage string. The type and
613 // value of the flag are represented by the first argument, of type Value, which
614 // typically holds a user-defined implementation of Value. For instance, the
615 // caller could create a flag that turns a comma-separated string into a slice
616 // of strings by giving the slice the methods of Value; in particular, Set would
617 // decompose the comma-separated string into the slice.
618 func (f *FlagSet) Var(value Value, name string, usage string) {
619 // Remember the default value as a string; it won't change.
620 flag := &Flag{name, usage, value, value.String()}
621 _, alreadythere := f.formal[name]
623 msg := fmt.Sprintf("%s flag redefined: %s", f.name, name)
624 fmt.Fprintln(f.out(), msg)
625 panic(msg) // Happens only if flags are declared with identical names
628 f.formal = make(map[string]*Flag)
630 f.formal[name] = flag
633 // Var defines a flag with the specified name and usage string. The type and
634 // value of the flag are represented by the first argument, of type Value, which
635 // typically holds a user-defined implementation of Value. For instance, the
636 // caller could create a flag that turns a comma-separated string into a slice
637 // of strings by giving the slice the methods of Value; in particular, Set would
638 // decompose the comma-separated string into the slice.
639 func Var(value Value, name string, usage string) {
640 commandLine.Var(value, name, usage)
643 // failf prints to standard error a formatted error and usage message and
644 // returns the error.
645 func (f *FlagSet) failf(format string, a ...interface{}) error {
646 err := fmt.Errorf(format, a...)
647 fmt.Fprintln(f.out(), err)
652 // usage calls the Usage method for the flag set, or the usage function if
653 // the flag set is commandLine.
654 func (f *FlagSet) usage() {
655 if f == commandLine {
657 } else if f.Usage == nil {
664 // parseOne parses one flag. It returns whether a flag was seen.
665 func (f *FlagSet) parseOne() (bool, error) {
666 if len(f.args) == 0 {
670 if len(s) == 0 || s[0] != '-' || len(s) == 1 {
676 if len(s) == 2 { // "--" terminates the flags
681 name := s[num_minuses:]
682 if len(name) == 0 || name[0] == '-' || name[0] == '=' {
683 return false, f.failf("bad flag syntax: %s", s)
686 // it's a flag. does it have an argument?
690 for i := 1; i < len(name); i++ { // equals cannot be first
699 flag, alreadythere := m[name] // BUG
701 if name == "help" || name == "h" { // special case for nice help message.
703 return false, ErrHelp
705 return false, f.failf("flag provided but not defined: -%s", name)
707 if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
709 if err := fv.Set(value); err != nil {
710 return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
716 // It must have a value, which might be the next argument.
717 if !has_value && len(f.args) > 0 {
718 // value is the next arg
720 value, f.args = f.args[0], f.args[1:]
723 return false, f.failf("flag needs an argument: -%s", name)
725 if err := flag.Value.Set(value); err != nil {
726 return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
730 f.actual = make(map[string]*Flag)
732 f.actual[name] = flag
736 // Parse parses flag definitions from the argument list, which should not
737 // include the command name. Must be called after all flags in the FlagSet
738 // are defined and before flags are accessed by the program.
739 // The return value will be ErrHelp if -help was set but not defined.
740 func (f *FlagSet) Parse(arguments []string) error {
744 seen, err := f.parseOne()
751 switch f.errorHandling {
752 case ContinueOnError:
763 // Parsed reports whether f.Parse has been called.
764 func (f *FlagSet) Parsed() bool {
768 // Parse parses the command-line flags from os.Args[1:]. Must be called
769 // after all flags are defined and before flags are accessed by the program.
771 // Ignore errors; commandLine is set for ExitOnError.
772 commandLine.Parse(os.Args[1:])
775 // Parsed returns true if the command-line flags have been parsed.
777 return commandLine.Parsed()
780 // The default set of command-line flags, parsed from os.Args.
781 var commandLine = NewFlagSet(os.Args[0], ExitOnError)
783 // NewFlagSet returns a new, empty flag set with the specified name and
784 // error handling property.
785 func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
788 errorHandling: errorHandling,
793 // Init sets the name and error handling property for a flag set.
794 // By default, the zero FlagSet uses an empty name and the
795 // ContinueOnError error handling policy.
796 func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
798 f.errorHandling = errorHandling