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 in the GNU style.
7
It is almost exactly the same as the standard flag package,
8
the only difference being the extra argument to Parse.
10
Command line flag syntax:
11
-f // single letter flag
12
-fg // two single letter flags together
13
--flag // multiple letter flag
14
--flag x // non-boolean flags only
15
-f x // non-boolean flags only
16
-fx // if f is a non-boolean flag, x is its argument.
18
The last three forms are not permitted for boolean flags because the
19
meaning of the command
21
will change if there is a file called 0, false, etc. There is currently
22
no way to turn off a boolean flag.
24
Flag parsing stops after the terminator "--", or just before the first
25
non-flag argument ("-" is a non-flag argument) if the interspersed
26
argument to Parse is false.
43
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
44
var ErrHelp = errors.New("flag: help requested")
49
func newBoolValue(val bool, p *bool) *boolValue {
51
return (*boolValue)(p)
54
func (b *boolValue) Set(s string) error {
55
v, err := strconv.ParseBool(s)
60
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
65
func newIntValue(val int, p *int) *intValue {
70
func (i *intValue) Set(s string) error {
71
v, err := strconv.ParseInt(s, 0, 64)
76
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
81
func newInt64Value(val int64, p *int64) *int64Value {
83
return (*int64Value)(p)
86
func (i *int64Value) Set(s string) error {
87
v, err := strconv.ParseInt(s, 0, 64)
92
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
97
func newUintValue(val uint, p *uint) *uintValue {
99
return (*uintValue)(p)
102
func (i *uintValue) Set(s string) error {
103
v, err := strconv.ParseUint(s, 0, 64)
108
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
111
type uint64Value uint64
113
func newUint64Value(val uint64, p *uint64) *uint64Value {
115
return (*uint64Value)(p)
118
func (i *uint64Value) Set(s string) error {
119
v, err := strconv.ParseUint(s, 0, 64)
124
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
127
type stringValue string
129
func newStringValue(val string, p *string) *stringValue {
131
return (*stringValue)(p)
134
func (s *stringValue) Set(val string) error {
135
*s = stringValue(val)
139
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
142
type float64Value float64
144
func newFloat64Value(val float64, p *float64) *float64Value {
146
return (*float64Value)(p)
149
func (f *float64Value) Set(s string) error {
150
v, err := strconv.ParseFloat(s, 64)
155
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
157
// -- time.Duration Value
158
type durationValue time.Duration
160
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
162
return (*durationValue)(p)
165
func (d *durationValue) Set(s string) error {
166
v, err := time.ParseDuration(s)
167
*d = durationValue(v)
171
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
173
// Value is the interface to the dynamic value stored in a flag.
174
// (The default value is represented as a string.)
175
type Value interface {
180
// ErrorHandling defines how to handle flag parsing errors.
181
type ErrorHandling int
184
ContinueOnError ErrorHandling = iota
189
// A FlagSet represents a set of defined flags.
190
type FlagSet struct {
191
// Usage is the function called when an error occurs while parsing flags.
192
// The field is a function (not a method) that may be changed to point to
193
// a custom error handler.
198
actual map[string]*Flag
199
formal map[string]*Flag
200
args []string // arguments after flags
201
procArgs []string // arguments being processed (gnu only)
202
procFlag string // flag being processed (gnu only)
203
allowIntersperse bool // (gnu only)
204
exitOnError bool // does the program exit if there's an error?
205
errorHandling ErrorHandling
206
output io.Writer // nil means stderr; use out() accessor
209
// A Flag represents the state of a flag.
211
Name string // name as it appears on command line
212
Usage string // help message
213
Value Value // value as set
214
DefValue string // default value (as text); for usage message
217
// sortFlags returns the flags as a slice in lexicographical sorted order.
218
func sortFlags(flags map[string]*Flag) []*Flag {
219
list := make(sort.StringSlice, len(flags))
221
for _, f := range flags {
226
result := make([]*Flag, len(list))
227
for i, name := range list {
228
result[i] = flags[name]
233
func (f *FlagSet) out() io.Writer {
240
// SetOutput sets the destination for usage and error messages.
241
// If output is nil, os.Stderr is used.
242
func (f *FlagSet) SetOutput(output io.Writer) {
246
// VisitAll visits the flags in lexicographical order, calling fn for each.
247
// It visits all flags, even those not set.
248
func (f *FlagSet) VisitAll(fn func(*Flag)) {
249
for _, flag := range sortFlags(f.formal) {
254
// VisitAll visits the command-line flags in lexicographical order, calling
255
// fn for each. It visits all flags, even those not set.
256
func VisitAll(fn func(*Flag)) {
257
commandLine.VisitAll(fn)
260
// Visit visits the flags in lexicographical order, calling fn for each.
261
// It visits only those flags that have been set.
262
func (f *FlagSet) Visit(fn func(*Flag)) {
263
for _, flag := range sortFlags(f.actual) {
268
// Visit visits the command-line flags in lexicographical order, calling fn
269
// for each. It visits only those flags that have been set.
270
func Visit(fn func(*Flag)) {
271
commandLine.Visit(fn)
274
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
275
func (f *FlagSet) Lookup(name string) *Flag {
276
return f.formal[name]
279
// Lookup returns the Flag structure of the named command-line flag,
280
// returning nil if none exists.
281
func Lookup(name string) *Flag {
282
return commandLine.formal[name]
285
// Set sets the value of the named flag.
286
func (f *FlagSet) Set(name, value string) error {
287
flag, ok := f.formal[name]
289
return fmt.Errorf("no such flag -%v", name)
291
err := flag.Value.Set(value)
296
f.actual = make(map[string]*Flag)
298
f.actual[name] = flag
302
// Set sets the value of the named command-line flag.
303
func Set(name, value string) error {
304
return commandLine.Set(name, value)
307
// flagsByLength is a slice of flags implementing sort.Interface,
308
// sorting primarily by the length of the flag, and secondarily
310
type flagsByLength []*Flag
312
func (f flagsByLength) Less(i, j int) bool {
313
s1, s2 := f[i].Name, f[j].Name
314
if len(s1) != len(s2) {
315
return len(s1) < len(s2)
319
func (f flagsByLength) Swap(i, j int) {
320
f[i], f[j] = f[j], f[i]
322
func (f flagsByLength) Len() int {
326
// flagsByName is a slice of slices of flags implementing sort.Interface,
327
// alphabetically sorting by the name of the first flag in each slice.
328
type flagsByName [][]*Flag
330
func (f flagsByName) Less(i, j int) bool {
331
return f[i][0].Name < f[j][0].Name
333
func (f flagsByName) Swap(i, j int) {
334
f[i], f[j] = f[j], f[i]
336
func (f flagsByName) Len() int {
340
// PrintDefaults prints, to standard error unless configured
341
// otherwise, the default values of all defined flags in the set.
342
// If there is more than one name for a given flag, the usage information and
343
// default value from the shortest will be printed (or the least alphabetically
344
// if there are several equally short flag names).
345
func (f *FlagSet) PrintDefaults() {
346
// group together all flags for a given value
347
flags := make(map[interface{}]flagsByLength)
348
f.VisitAll(func(f *Flag) {
349
flags[f.Value] = append(flags[f.Value], f)
352
// sort the output flags by shortest name for each group.
353
var byName flagsByName
354
for _, f := range flags {
356
byName = append(byName, f)
360
var line bytes.Buffer
361
for _, fs := range byName {
363
for i, f := range fs {
365
line.WriteString(", ")
367
line.WriteString(flagWithMinus(f.Name))
369
format := "%s (= %s)\n %s\n"
370
if _, ok := fs[0].Value.(*stringValue); ok {
371
// put quotes on the value
372
format = "%s (= %q)\n %s\n"
374
fmt.Fprintf(f.out(), format, line.Bytes(), fs[0].DefValue, fs[0].Usage)
378
// PrintDefaults prints to standard error the default values of all defined command-line flags.
379
func PrintDefaults() {
380
commandLine.PrintDefaults()
383
// defaultUsage is the default function to print a usage message.
384
func defaultUsage(f *FlagSet) {
385
fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
389
// NOTE: Usage is not just defaultUsage(commandLine)
390
// because it serves (via godoc flag Usage) as the example
391
// for how to write your own usage function.
393
// Usage prints to standard error a usage message documenting all defined command-line flags.
394
// The function is a variable that may be changed to point to a custom function.
396
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
400
// NFlag returns the number of flags that have been set.
401
func (f *FlagSet) NFlag() int { return len(f.actual) }
403
// NFlag returns the number of command-line flags that have been set.
404
func NFlag() int { return len(commandLine.actual) }
406
// Arg returns the i'th argument. Arg(0) is the first remaining argument
407
// after flags have been processed.
408
func (f *FlagSet) Arg(i int) string {
409
if i < 0 || i >= len(f.args) {
415
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
416
// after flags have been processed.
417
func Arg(i int) string {
418
return commandLine.Arg(i)
421
// NArg is the number of arguments remaining after flags have been processed.
422
func (f *FlagSet) NArg() int { return len(f.args) }
424
// NArg is the number of arguments remaining after flags have been processed.
425
func NArg() int { return len(commandLine.args) }
427
// Args returns the non-flag arguments.
428
func (f *FlagSet) Args() []string { return f.args }
430
// Args returns the non-flag command-line arguments.
431
func Args() []string { return commandLine.args }
433
// BoolVar defines a bool flag with specified name, default value, and usage string.
434
// The argument p points to a bool variable in which to store the value of the flag.
435
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
436
f.Var(newBoolValue(value, p), name, usage)
439
// BoolVar defines a bool flag with specified name, default value, and usage string.
440
// The argument p points to a bool variable in which to store the value of the flag.
441
func BoolVar(p *bool, name string, value bool, usage string) {
442
commandLine.Var(newBoolValue(value, p), name, usage)
445
// Bool defines a bool flag with specified name, default value, and usage string.
446
// The return value is the address of a bool variable that stores the value of the flag.
447
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
449
f.BoolVar(p, name, value, usage)
453
// Bool defines a bool flag with specified name, default value, and usage string.
454
// The return value is the address of a bool variable that stores the value of the flag.
455
func Bool(name string, value bool, usage string) *bool {
456
return commandLine.Bool(name, value, usage)
459
// IntVar defines an int flag with specified name, default value, and usage string.
460
// The argument p points to an int variable in which to store the value of the flag.
461
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
462
f.Var(newIntValue(value, p), name, usage)
465
// IntVar defines an int flag with specified name, default value, and usage string.
466
// The argument p points to an int variable in which to store the value of the flag.
467
func IntVar(p *int, name string, value int, usage string) {
468
commandLine.Var(newIntValue(value, p), name, usage)
471
// Int defines an int flag with specified name, default value, and usage string.
472
// The return value is the address of an int variable that stores the value of the flag.
473
func (f *FlagSet) Int(name string, value int, usage string) *int {
475
f.IntVar(p, name, value, usage)
479
// Int defines an int flag with specified name, default value, and usage string.
480
// The return value is the address of an int variable that stores the value of the flag.
481
func Int(name string, value int, usage string) *int {
482
return commandLine.Int(name, value, usage)
485
// Int64Var defines an int64 flag with specified name, default value, and usage string.
486
// The argument p points to an int64 variable in which to store the value of the flag.
487
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
488
f.Var(newInt64Value(value, p), name, usage)
491
// Int64Var defines an int64 flag with specified name, default value, and usage string.
492
// The argument p points to an int64 variable in which to store the value of the flag.
493
func Int64Var(p *int64, name string, value int64, usage string) {
494
commandLine.Var(newInt64Value(value, p), name, usage)
497
// Int64 defines an int64 flag with specified name, default value, and usage string.
498
// The return value is the address of an int64 variable that stores the value of the flag.
499
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
501
f.Int64Var(p, name, value, usage)
505
// Int64 defines an int64 flag with specified name, default value, and usage string.
506
// The return value is the address of an int64 variable that stores the value of the flag.
507
func Int64(name string, value int64, usage string) *int64 {
508
return commandLine.Int64(name, value, usage)
511
// UintVar defines a uint flag with specified name, default value, and usage string.
512
// The argument p points to a uint variable in which to store the value of the flag.
513
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
514
f.Var(newUintValue(value, p), name, usage)
517
// UintVar defines a uint flag with specified name, default value, and usage string.
518
// The argument p points to a uint variable in which to store the value of the flag.
519
func UintVar(p *uint, name string, value uint, usage string) {
520
commandLine.Var(newUintValue(value, p), name, usage)
523
// Uint defines a uint flag with specified name, default value, and usage string.
524
// The return value is the address of a uint variable that stores the value of the flag.
525
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
527
f.UintVar(p, name, value, usage)
531
// Uint defines a uint flag with specified name, default value, and usage string.
532
// The return value is the address of a uint variable that stores the value of the flag.
533
func Uint(name string, value uint, usage string) *uint {
534
return commandLine.Uint(name, value, usage)
537
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
538
// The argument p points to a uint64 variable in which to store the value of the flag.
539
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
540
f.Var(newUint64Value(value, p), name, usage)
543
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
544
// The argument p points to a uint64 variable in which to store the value of the flag.
545
func Uint64Var(p *uint64, name string, value uint64, usage string) {
546
commandLine.Var(newUint64Value(value, p), name, usage)
549
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
550
// The return value is the address of a uint64 variable that stores the value of the flag.
551
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
553
f.Uint64Var(p, name, value, usage)
557
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
558
// The return value is the address of a uint64 variable that stores the value of the flag.
559
func Uint64(name string, value uint64, usage string) *uint64 {
560
return commandLine.Uint64(name, value, usage)
563
// StringVar defines a string flag with specified name, default value, and usage string.
564
// The argument p points to a string variable in which to store the value of the flag.
565
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
566
f.Var(newStringValue(value, p), name, usage)
569
// StringVar defines a string flag with specified name, default value, and usage string.
570
// The argument p points to a string variable in which to store the value of the flag.
571
func StringVar(p *string, name string, value string, usage string) {
572
commandLine.Var(newStringValue(value, p), name, usage)
575
// String defines a string flag with specified name, default value, and usage string.
576
// The return value is the address of a string variable that stores the value of the flag.
577
func (f *FlagSet) String(name string, value string, usage string) *string {
579
f.StringVar(p, name, value, usage)
583
// String defines a string flag with specified name, default value, and usage string.
584
// The return value is the address of a string variable that stores the value of the flag.
585
func String(name string, value string, usage string) *string {
586
return commandLine.String(name, value, usage)
589
// Float64Var defines a float64 flag with specified name, default value, and usage string.
590
// The argument p points to a float64 variable in which to store the value of the flag.
591
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
592
f.Var(newFloat64Value(value, p), name, usage)
595
// Float64Var defines a float64 flag with specified name, default value, and usage string.
596
// The argument p points to a float64 variable in which to store the value of the flag.
597
func Float64Var(p *float64, name string, value float64, usage string) {
598
commandLine.Var(newFloat64Value(value, p), name, usage)
601
// Float64 defines a float64 flag with specified name, default value, and usage string.
602
// The return value is the address of a float64 variable that stores the value of the flag.
603
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
605
f.Float64Var(p, name, value, usage)
609
// Float64 defines a float64 flag with specified name, default value, and usage string.
610
// The return value is the address of a float64 variable that stores the value of the flag.
611
func Float64(name string, value float64, usage string) *float64 {
612
return commandLine.Float64(name, value, usage)
615
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
616
// The argument p points to a time.Duration variable in which to store the value of the flag.
617
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
618
f.Var(newDurationValue(value, p), name, usage)
621
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
622
// The argument p points to a time.Duration variable in which to store the value of the flag.
623
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
624
commandLine.Var(newDurationValue(value, p), name, usage)
627
// Duration defines a time.Duration flag with specified name, default value, and usage string.
628
// The return value is the address of a time.Duration variable that stores the value of the flag.
629
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
630
p := new(time.Duration)
631
f.DurationVar(p, name, value, usage)
635
// Duration defines a time.Duration flag with specified name, default value, and usage string.
636
// The return value is the address of a time.Duration variable that stores the value of the flag.
637
func Duration(name string, value time.Duration, usage string) *time.Duration {
638
return commandLine.Duration(name, value, usage)
641
// Var defines a flag with the specified name and usage string. The type and
642
// value of the flag are represented by the first argument, of type Value, which
643
// typically holds a user-defined implementation of Value. For instance, the
644
// caller could create a flag that turns a comma-separated string into a slice
645
// of strings by giving the slice the methods of Value; in particular, Set would
646
// decompose the comma-separated string into the slice.
647
func (f *FlagSet) Var(value Value, name string, usage string) {
648
// Remember the default value as a string; it won't change.
649
flag := &Flag{name, usage, value, value.String()}
650
_, alreadythere := f.formal[name]
652
fmt.Fprintf(f.out(), "%s flag redefined: %s\n", f.name, name)
653
panic("flag redefinition") // Happens only if flags are declared with identical names
656
f.formal = make(map[string]*Flag)
658
f.formal[name] = flag
661
// Var defines a flag with the specified name and usage string. The type and
662
// value of the flag are represented by the first argument, of type Value, which
663
// typically holds a user-defined implementation of Value. For instance, the
664
// caller could create a flag that turns a comma-separated string into a slice
665
// of strings by giving the slice the methods of Value; in particular, Set would
666
// decompose the comma-separated string into the slice.
667
func Var(value Value, name string, usage string) {
668
commandLine.Var(value, name, usage)
671
// failf prints to standard error a formatted error and usage message and
672
// returns the error.
673
func (f *FlagSet) failf(format string, a ...interface{}) error {
674
err := fmt.Errorf(format, a...)
675
fmt.Fprintln(f.out(), err)
680
// usage calls the Usage method for the flag set, or the usage function if
681
// the flag set is commandLine.
682
func (f *FlagSet) usage() {
683
if f == commandLine {
685
} else if f.Usage == nil {
692
func (f *FlagSet) parseOneGnu() (flagName string, long, finished bool, err error) {
693
if len(f.procArgs) == 0 {
698
// processing previously encountered single-rune flag
699
if flag := f.procFlag; len(flag) > 0 {
700
_, n := utf8.DecodeRuneInString(flag)
701
f.procFlag = flag[n:]
708
// one non-flag argument
709
if a == "-" || a == "" || a[0] != '-' {
710
if f.allowIntersperse {
711
f.args = append(f.args, a)
712
f.procArgs = f.procArgs[1:]
715
f.args = append(f.args, f.procArgs...)
722
if f.procArgs[0] == "--" {
723
f.args = append(f.args, f.procArgs[1:]...)
729
// long flag signified with "--" prefix
732
i := strings.Index(a, "=")
734
f.procArgs = f.procArgs[1:]
740
err = fmt.Errorf("empty flag in argument %q", a)
743
f.procArgs = f.procArgs[1:]
748
// some number of single-rune flags
750
_, n := utf8.DecodeRuneInString(a)
753
f.procArgs = f.procArgs[1:]
757
func flagWithMinus(name string) string {
764
func (f *FlagSet) parseGnuFlagArg(name string, long bool) (finished bool, err error) {
766
flag, alreadythere := m[name] // BUG
768
if name == "help" || name == "h" { // special case for nice help message.
770
return false, ErrHelp
772
// TODO print --xxx when flag is more than one rune.
773
return false, f.failf("flag provided but not defined: %s", flagWithMinus(name))
775
if fv, ok := flag.Value.(*boolValue); ok && !strings.HasPrefix(f.procFlag, "=") {
776
// special case: doesn't need an arg, and an arg hasn't
777
// been provided explicitly.
780
// It must have a value, which might be the next argument.
783
if f.procFlag != "" {
784
// value directly follows flag
788
panic("no leading '=' in long flag")
795
if !hasValue && len(f.procArgs) > 0 {
796
// value is the next arg
798
value, f.procArgs = f.procArgs[0], f.procArgs[1:]
801
return false, f.failf("flag needs an argument: %s", flagWithMinus(name))
803
if err := flag.Value.Set(value); err != nil {
804
return false, f.failf("invalid value %q for flag %s: %v", value, flagWithMinus(name), err)
808
f.actual = make(map[string]*Flag)
810
f.actual[name] = flag
814
// Parse parses flag definitions from the argument list, which should not
815
// include the command name. Must be called after all flags in the FlagSet
816
// are defined and before flags are accessed by the program.
817
// The return value will be ErrHelp if --help was set but not defined.
818
// If allowIntersperse is set, arguments and flags can be interspersed, that
819
// is flags can follow positional arguments.
820
func (f *FlagSet) Parse(allowIntersperse bool, arguments []string) error {
822
f.procArgs = arguments
825
f.allowIntersperse = allowIntersperse
827
name, long, finished, err := f.parseOneGnu()
830
finished, err = f.parseGnuFlagArg(name, long)
834
switch f.errorHandling {
835
case ContinueOnError:
853
// Parsed reports whether f.Parse has been called.
854
func (f *FlagSet) Parsed() bool {
858
// Parse parses the command-line flags from os.Args[1:]. Must be called
859
// after all flags are defined and before flags are accessed by the program.
860
// If allowIntersperse is set, arguments and flags can be interspersed, that
861
// is flags can follow positional arguments.
862
func Parse(allowIntersperse bool) {
863
// Ignore errors; commandLine is set for ExitOnError.
864
commandLine.Parse(allowIntersperse, os.Args[1:])
867
// Parsed returns true if the command-line flags have been parsed.
869
return commandLine.Parsed()
872
// The default set of command-line flags, parsed from os.Args.
873
var commandLine = NewFlagSet(os.Args[0], ExitOnError)
875
// NewFlagSet returns a new, empty flag set with the specified name and
876
// error handling property.
877
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
880
errorHandling: errorHandling,
885
// Init sets the name and error handling property for a flag set.
886
// By default, the zero FlagSet uses an empty name and the
887
// ContinueOnError error handling policy.
888
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
890
f.errorHandling = errorHandling