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.
53 The default set of command-line flags is controlled by
54 top-level functions. The FlagSet type allows one to define
55 independent sets of flags, such as to implement subcommands
56 in a command-line interface. The methods of FlagSet are
57 analogous to the top-level functions for the command-line
69 // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
70 var ErrHelp = os.NewError("flag: help requested")
75 func newBoolValue(val bool, p *bool) *boolValue {
77 return (*boolValue)(p)
80 func (b *boolValue) Set(s string) bool {
81 v, err := strconv.Atob(s)
86 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
91 func newIntValue(val int, p *int) *intValue {
96 func (i *intValue) Set(s string) bool {
97 v, err := strconv.Btoi64(s, 0)
102 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
105 type int64Value int64
107 func newInt64Value(val int64, p *int64) *int64Value {
109 return (*int64Value)(p)
112 func (i *int64Value) Set(s string) bool {
113 v, err := strconv.Btoi64(s, 0)
118 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
123 func newUintValue(val uint, p *uint) *uintValue {
125 return (*uintValue)(p)
128 func (i *uintValue) Set(s string) bool {
129 v, err := strconv.Btoui64(s, 0)
134 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
137 type uint64Value uint64
139 func newUint64Value(val uint64, p *uint64) *uint64Value {
141 return (*uint64Value)(p)
144 func (i *uint64Value) Set(s string) bool {
145 v, err := strconv.Btoui64(s, 0)
150 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
153 type stringValue string
155 func newStringValue(val string, p *string) *stringValue {
157 return (*stringValue)(p)
160 func (s *stringValue) Set(val string) bool {
161 *s = stringValue(val)
165 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
168 type float64Value float64
170 func newFloat64Value(val float64, p *float64) *float64Value {
172 return (*float64Value)(p)
175 func (f *float64Value) Set(s string) bool {
176 v, err := strconv.Atof64(s)
181 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
183 // Value is the interface to the dynamic value stored in a flag.
184 // (The default value is represented as a string.)
185 type Value interface {
190 // ErrorHandling defines how to handle flag parsing errors.
191 type ErrorHandling int
194 ContinueOnError ErrorHandling = iota
199 // A FlagSet represents a set of defined flags.
200 type FlagSet struct {
201 // Usage is the function called when an error occurs while parsing flags.
202 // The field is a function (not a method) that may be changed to point to
203 // a custom error handler.
207 actual map[string]*Flag
208 formal map[string]*Flag
209 args []string // arguments after flags
210 exitOnError bool // does the program exit if there's an error?
211 errorHandling ErrorHandling
214 // A Flag represents the state of a flag.
216 Name string // name as it appears on command line
217 Usage string // help message
218 Value Value // value as set
219 DefValue string // default value (as text); for usage message
222 // sortFlags returns the flags as a slice in lexicographical sorted order.
223 func sortFlags(flags map[string]*Flag) []*Flag {
224 list := make(sort.StringSlice, len(flags))
226 for _, f := range flags {
231 result := make([]*Flag, len(list))
232 for i, name := range list {
233 result[i] = flags[name]
238 // VisitAll visits the flags in lexicographical order, calling fn for each.
239 // It visits all flags, even those not set.
240 func (f *FlagSet) VisitAll(fn func(*Flag)) {
241 for _, flag := range sortFlags(f.formal) {
246 // VisitAll visits the command-line flags in lexicographical order, calling
247 // fn for each. It visits all flags, even those not set.
248 func VisitAll(fn func(*Flag)) {
249 commandLine.VisitAll(fn)
252 // Visit visits the flags in lexicographical order, calling fn for each.
253 // It visits only those flags that have been set.
254 func (f *FlagSet) Visit(fn func(*Flag)) {
255 for _, flag := range sortFlags(f.actual) {
260 // Visit visits the command-line flags in lexicographical order, calling fn
261 // for each. It visits only those flags that have been set.
262 func Visit(fn func(*Flag)) {
263 commandLine.Visit(fn)
266 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
267 func (f *FlagSet) Lookup(name string) *Flag {
268 return f.formal[name]
271 // Lookup returns the Flag structure of the named command-line flag,
272 // returning nil if none exists.
273 func Lookup(name string) *Flag {
274 return commandLine.formal[name]
277 // Set sets the value of the named flag. It returns true if the set succeeded; false if
278 // there is no such flag defined.
279 func (f *FlagSet) Set(name, value string) bool {
280 flag, ok := f.formal[name]
284 ok = flag.Value.Set(value)
288 f.actual[name] = flag
292 // Set sets the value of the named command-line flag. It returns true if the
293 // set succeeded; false if there is no such flag defined.
294 func Set(name, value string) bool {
295 return commandLine.Set(name, value)
298 // PrintDefaults prints to standard error the default values of all defined flags in the set.
299 func (f *FlagSet) PrintDefaults() {
300 f.VisitAll(func(f *Flag) {
301 format := " -%s=%s: %s\n"
302 if _, ok := f.Value.(*stringValue); ok {
303 // put quotes on the value
304 format = " -%s=%q: %s\n"
306 fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage)
310 // PrintDefaults prints to standard error the default values of all defined command-line flags.
311 func PrintDefaults() {
312 commandLine.PrintDefaults()
315 // defaultUsage is the default function to print a usage message.
316 func defaultUsage(f *FlagSet) {
317 fmt.Fprintf(os.Stderr, "Usage of %s:\n", f.name)
321 // Usage prints to standard error a usage message documenting all defined command-line flags.
322 // The function is a variable that may be changed to point to a custom function.
324 defaultUsage(commandLine)
327 // NFlag returns the number of flags that have been set.
328 func (f *FlagSet) NFlag() int { return len(f.actual) }
330 // NFlag returns the number of command-line flags that have been set.
331 func NFlag() int { return len(commandLine.actual) }
333 // Arg returns the i'th argument. Arg(0) is the first remaining argument
334 // after flags have been processed.
335 func (f *FlagSet) Arg(i int) string {
336 if i < 0 || i >= len(f.args) {
342 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
343 // after flags have been processed.
344 func Arg(i int) string {
345 return commandLine.Arg(i)
348 // NArg is the number of arguments remaining after flags have been processed.
349 func (f *FlagSet) NArg() int { return len(f.args) }
351 // NArg is the number of arguments remaining after flags have been processed.
352 func NArg() int { return len(commandLine.args) }
354 // Args returns the non-flag arguments.
355 func (f *FlagSet) Args() []string { return f.args }
357 // Args returns the non-flag command-line arguments.
358 func Args() []string { return commandLine.args }
360 // BoolVar defines a bool flag with specified name, default value, and usage string.
361 // The argument p points to a bool variable in which to store the value of the flag.
362 func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
363 f.Var(newBoolValue(value, p), name, usage)
366 // BoolVar defines a bool flag with specified name, default value, and usage string.
367 // The argument p points to a bool variable in which to store the value of the flag.
368 func BoolVar(p *bool, name string, value bool, usage string) {
369 commandLine.Var(newBoolValue(value, p), name, usage)
372 // Bool defines a bool flag with specified name, default value, and usage string.
373 // The return value is the address of a bool variable that stores the value of the flag.
374 func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
376 f.BoolVar(p, name, value, usage)
380 // Bool defines a bool flag with specified name, default value, and usage string.
381 // The return value is the address of a bool variable that stores the value of the flag.
382 func Bool(name string, value bool, usage string) *bool {
383 return commandLine.Bool(name, value, usage)
386 // IntVar defines an int flag with specified name, default value, and usage string.
387 // The argument p points to an int variable in which to store the value of the flag.
388 func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
389 f.Var(newIntValue(value, p), name, usage)
392 // IntVar defines an int flag with specified name, default value, and usage string.
393 // The argument p points to an int variable in which to store the value of the flag.
394 func IntVar(p *int, name string, value int, usage string) {
395 commandLine.Var(newIntValue(value, p), name, usage)
398 // Int defines an int flag with specified name, default value, and usage string.
399 // The return value is the address of an int variable that stores the value of the flag.
400 func (f *FlagSet) Int(name string, value int, usage string) *int {
402 f.IntVar(p, name, value, usage)
406 // Int defines an int flag with specified name, default value, and usage string.
407 // The return value is the address of an int variable that stores the value of the flag.
408 func Int(name string, value int, usage string) *int {
409 return commandLine.Int(name, value, usage)
412 // Int64Var defines an int64 flag with specified name, default value, and usage string.
413 // The argument p points to an int64 variable in which to store the value of the flag.
414 func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
415 f.Var(newInt64Value(value, p), name, usage)
418 // Int64Var defines an int64 flag with specified name, default value, and usage string.
419 // The argument p points to an int64 variable in which to store the value of the flag.
420 func Int64Var(p *int64, name string, value int64, usage string) {
421 commandLine.Var(newInt64Value(value, p), name, usage)
424 // Int64 defines an int64 flag with specified name, default value, and usage string.
425 // The return value is the address of an int64 variable that stores the value of the flag.
426 func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
428 f.Int64Var(p, name, value, usage)
432 // Int64 defines an int64 flag with specified name, default value, and usage string.
433 // The return value is the address of an int64 variable that stores the value of the flag.
434 func Int64(name string, value int64, usage string) *int64 {
435 return commandLine.Int64(name, value, usage)
438 // UintVar defines a uint flag with specified name, default value, and usage string.
439 // The argument p points to a uint variable in which to store the value of the flag.
440 func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
441 f.Var(newUintValue(value, p), name, usage)
444 // UintVar defines a uint flag with specified name, default value, and usage string.
445 // The argument p points to a uint variable in which to store the value of the flag.
446 func UintVar(p *uint, name string, value uint, usage string) {
447 commandLine.Var(newUintValue(value, p), name, usage)
450 // Uint defines a uint flag with specified name, default value, and usage string.
451 // The return value is the address of a uint variable that stores the value of the flag.
452 func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
454 f.UintVar(p, name, value, usage)
458 // Uint defines a uint flag with specified name, default value, and usage string.
459 // The return value is the address of a uint variable that stores the value of the flag.
460 func Uint(name string, value uint, usage string) *uint {
461 return commandLine.Uint(name, value, usage)
464 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
465 // The argument p points to a uint64 variable in which to store the value of the flag.
466 func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
467 f.Var(newUint64Value(value, p), name, usage)
470 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
471 // The argument p points to a uint64 variable in which to store the value of the flag.
472 func Uint64Var(p *uint64, name string, value uint64, usage string) {
473 commandLine.Var(newUint64Value(value, p), name, usage)
476 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
477 // The return value is the address of a uint64 variable that stores the value of the flag.
478 func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
480 f.Uint64Var(p, name, value, usage)
484 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
485 // The return value is the address of a uint64 variable that stores the value of the flag.
486 func Uint64(name string, value uint64, usage string) *uint64 {
487 return commandLine.Uint64(name, value, usage)
490 // StringVar defines a string flag with specified name, default value, and usage string.
491 // The argument p points to a string variable in which to store the value of the flag.
492 func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
493 f.Var(newStringValue(value, p), name, usage)
496 // StringVar defines a string flag with specified name, default value, and usage string.
497 // The argument p points to a string variable in which to store the value of the flag.
498 func StringVar(p *string, name string, value string, usage string) {
499 commandLine.Var(newStringValue(value, p), name, usage)
502 // String defines a string flag with specified name, default value, and usage string.
503 // The return value is the address of a string variable that stores the value of the flag.
504 func (f *FlagSet) String(name string, value string, usage string) *string {
506 f.StringVar(p, name, value, usage)
510 // String defines a string flag with specified name, default value, and usage string.
511 // The return value is the address of a string variable that stores the value of the flag.
512 func String(name string, value string, usage string) *string {
513 return commandLine.String(name, value, usage)
516 // Float64Var defines a float64 flag with specified name, default value, and usage string.
517 // The argument p points to a float64 variable in which to store the value of the flag.
518 func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
519 f.Var(newFloat64Value(value, p), name, usage)
522 // Float64Var defines a float64 flag with specified name, default value, and usage string.
523 // The argument p points to a float64 variable in which to store the value of the flag.
524 func Float64Var(p *float64, name string, value float64, usage string) {
525 commandLine.Var(newFloat64Value(value, p), name, usage)
528 // Float64 defines a float64 flag with specified name, default value, and usage string.
529 // The return value is the address of a float64 variable that stores the value of the flag.
530 func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
532 f.Float64Var(p, name, value, usage)
536 // Float64 defines an int flag with specified name, default value, and usage string.
537 // The return value is the address of a float64 variable that stores the value of the flag.
538 func Float64(name string, value float64, usage string) *float64 {
539 return commandLine.Float64(name, value, usage)
542 // Var defines a flag with the specified name and usage string. The type and
543 // value of the flag are represented by the first argument, of type Value, which
544 // typically holds a user-defined implementation of Value. For instance, the
545 // caller could create a flag that turns a comma-separated string into a slice
546 // of strings by giving the slice the methods of Value; in particular, Set would
547 // decompose the comma-separated string into the slice.
548 func (f *FlagSet) Var(value Value, name string, usage string) {
549 // Remember the default value as a string; it won't change.
550 flag := &Flag{name, usage, value, value.String()}
551 _, alreadythere := f.formal[name]
553 fmt.Fprintf(os.Stderr, "%s flag redefined: %s\n", f.name, name)
554 panic("flag redefinition") // Happens only if flags are declared with identical names
556 f.formal[name] = flag
559 // Var defines a flag with the specified name and usage string. The type and
560 // value of the flag are represented by the first argument, of type Value, which
561 // typically holds a user-defined implementation of Value. For instance, the
562 // caller could create a flag that turns a comma-separated string into a slice
563 // of strings by giving the slice the methods of Value; in particular, Set would
564 // decompose the comma-separated string into the slice.
565 func Var(value Value, name string, usage string) {
566 commandLine.Var(value, name, usage)
569 // failf prints to standard error a formatted error and usage message and
570 // returns the error.
571 func (f *FlagSet) failf(format string, a ...interface{}) os.Error {
572 err := fmt.Errorf(format, a...)
573 fmt.Fprintln(os.Stderr, err)
578 // usage calls the Usage method for the flag set, or the usage function if
579 // the flag set is commandLine.
580 func (f *FlagSet) usage() {
581 if f == commandLine {
588 // parseOne parses one flag. It returns whether a flag was seen.
589 func (f *FlagSet) parseOne() (bool, os.Error) {
590 if len(f.args) == 0 {
594 if len(s) == 0 || s[0] != '-' || len(s) == 1 {
600 if len(s) == 2 { // "--" terminates the flags
605 name := s[num_minuses:]
606 if len(name) == 0 || name[0] == '-' || name[0] == '=' {
607 return false, f.failf("bad flag syntax: %s", s)
610 // it's a flag. does it have an argument?
614 for i := 1; i < len(name); i++ { // equals cannot be first
623 flag, alreadythere := m[name] // BUG
625 if name == "help" || name == "h" { // special case for nice help message.
627 return false, ErrHelp
629 return false, f.failf("flag provided but not defined: -%s", name)
631 if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
634 f.failf("invalid boolean value %q for flag: -%s", value, name)
640 // It must have a value, which might be the next argument.
641 if !has_value && len(f.args) > 0 {
642 // value is the next arg
644 value, f.args = f.args[0], f.args[1:]
647 return false, f.failf("flag needs an argument: -%s", name)
649 ok = flag.Value.Set(value)
651 return false, f.failf("invalid value %q for flag: -%s", value, name)
654 f.actual[name] = flag
658 // Parse parses flag definitions from the argument list, which should not
659 // include the command name. Must be called after all flags in the FlagSet
660 // are defined and before flags are accessed by the program.
661 // The return value will be ErrHelp if -help was set but not defined.
662 func (f *FlagSet) Parse(arguments []string) os.Error {
665 seen, err := f.parseOne()
672 switch f.errorHandling {
673 case ContinueOnError:
684 // Parse parses the command-line flags from os.Args[1:]. Must be called
685 // after all flags are defined and before flags are accessed by the program.
687 // Ignore errors; commandLine is set for ExitOnError.
688 commandLine.Parse(os.Args[1:])
691 // The default set of command-line flags, parsed from os.Args.
692 var commandLine = NewFlagSet(os.Args[0], ExitOnError)
694 // NewFlagSet returns a new, empty flag set with the specified name and
695 // error handling property.
696 func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
699 actual: make(map[string]*Flag),
700 formal: make(map[string]*Flag),
701 errorHandling: errorHandling,
703 f.Usage = func() { defaultUsage(f) }