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 The flag package 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 It is safe to call flag.Parse multiple times, possibly after changing
54 os.Args. This makes it possible to implement command lines with
55 subcommands that enable additional flags, as in:
57 flag.Bool(...) // global options
58 flag.Parse() // parse leading command
59 subcmd := flag.Args(0)
61 // add per-subcommand options
77 func newBoolValue(val bool, p *bool) *boolValue {
79 return (*boolValue)(p)
82 func (b *boolValue) Set(s string) bool {
83 v, err := strconv.Atob(s)
88 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
93 func newIntValue(val int, p *int) *intValue {
98 func (i *intValue) Set(s string) bool {
99 v, err := strconv.Atoi(s)
104 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
107 type int64Value int64
109 func newInt64Value(val int64, p *int64) *int64Value {
111 return (*int64Value)(p)
114 func (i *int64Value) Set(s string) bool {
115 v, err := strconv.Atoi64(s)
120 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
125 func newUintValue(val uint, p *uint) *uintValue {
127 return (*uintValue)(p)
130 func (i *uintValue) Set(s string) bool {
131 v, err := strconv.Atoui(s)
136 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
139 type uint64Value uint64
141 func newUint64Value(val uint64, p *uint64) *uint64Value {
143 return (*uint64Value)(p)
146 func (i *uint64Value) Set(s string) bool {
147 v, err := strconv.Atoui64(s)
152 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
155 type stringValue string
157 func newStringValue(val string, p *string) *stringValue {
159 return (*stringValue)(p)
162 func (s *stringValue) Set(val string) bool {
163 *s = stringValue(val)
167 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
170 type float64Value float64
172 func newFloat64Value(val float64, p *float64) *float64Value {
174 return (*float64Value)(p)
177 func (f *float64Value) Set(s string) bool {
178 v, err := strconv.Atof64(s)
183 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
185 // Value is the interface to the dynamic value stored in a flag.
186 // (The default value is represented as a string.)
187 type Value interface {
192 // A Flag represents the state of a flag.
194 Name string // name as it appears on command line
195 Usage string // help message
196 Value Value // value as set
197 DefValue string // default value (as text); for usage message
200 type allFlags struct {
201 actual map[string]*Flag
202 formal map[string]*Flag
203 args []string // arguments after flags
208 // VisitAll visits the flags, calling fn for each. It visits all flags, even those not set.
209 func VisitAll(fn func(*Flag)) {
210 for _, f := range flags.formal {
215 // Visit visits the flags, calling fn for each. It visits only those flags that have been set.
216 func Visit(fn func(*Flag)) {
217 for _, f := range flags.actual {
222 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
223 func Lookup(name string) *Flag {
224 return flags.formal[name]
227 // Set sets the value of the named flag. It returns true if the set succeeded; false if
228 // there is no such flag defined.
229 func Set(name, value string) bool {
230 f, ok := flags.formal[name]
234 ok = f.Value.Set(value)
238 flags.actual[name] = f
242 // PrintDefaults prints to standard error the default values of all defined flags.
243 func PrintDefaults() {
244 VisitAll(func(f *Flag) {
245 format := " -%s=%s: %s\n"
246 if _, ok := f.Value.(*stringValue); ok {
247 // put quotes on the value
248 format = " -%s=%q: %s\n"
250 fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage)
254 // Usage prints to standard error a default usage message documenting all defined flags.
255 // The function is a variable that may be changed to point to a custom function.
257 fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
261 var panicOnError = false
266 panic("flag parse error")
271 func NFlag() int { return len(flags.actual) }
273 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
274 // after flags have been processed.
275 func Arg(i int) string {
276 if i < 0 || i >= len(flags.args) {
282 // NArg is the number of arguments remaining after flags have been processed.
283 func NArg() int { return len(flags.args) }
285 // Args returns the non-flag command-line arguments.
286 func Args() []string { return flags.args }
288 // BoolVar defines a bool flag with specified name, default value, and usage string.
289 // The argument p points to a bool variable in which to store the value of the flag.
290 func BoolVar(p *bool, name string, value bool, usage string) {
291 Var(newBoolValue(value, p), name, usage)
294 // Bool defines a bool flag with specified name, default value, and usage string.
295 // The return value is the address of a bool variable that stores the value of the flag.
296 func Bool(name string, value bool, usage string) *bool {
298 BoolVar(p, name, value, usage)
302 // IntVar defines an int flag with specified name, default value, and usage string.
303 // The argument p points to an int variable in which to store the value of the flag.
304 func IntVar(p *int, name string, value int, usage string) {
305 Var(newIntValue(value, p), name, usage)
308 // Int defines an int flag with specified name, default value, and usage string.
309 // The return value is the address of an int variable that stores the value of the flag.
310 func Int(name string, value int, usage string) *int {
312 IntVar(p, name, value, usage)
316 // Int64Var defines an int64 flag with specified name, default value, and usage string.
317 // The argument p points to an int64 variable in which to store the value of the flag.
318 func Int64Var(p *int64, name string, value int64, usage string) {
319 Var(newInt64Value(value, p), name, usage)
322 // Int64 defines an int64 flag with specified name, default value, and usage string.
323 // The return value is the address of an int64 variable that stores the value of the flag.
324 func Int64(name string, value int64, usage string) *int64 {
326 Int64Var(p, name, value, usage)
330 // UintVar defines a uint flag with specified name, default value, and usage string.
331 // The argument p points to a uint variable in which to store the value of the flag.
332 func UintVar(p *uint, name string, value uint, usage string) {
333 Var(newUintValue(value, p), name, usage)
336 // Uint defines a uint flag with specified name, default value, and usage string.
337 // The return value is the address of a uint variable that stores the value of the flag.
338 func Uint(name string, value uint, usage string) *uint {
340 UintVar(p, name, value, usage)
344 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
345 // The argument p points to a uint64 variable in which to store the value of the flag.
346 func Uint64Var(p *uint64, name string, value uint64, usage string) {
347 Var(newUint64Value(value, p), name, usage)
350 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
351 // The return value is the address of a uint64 variable that stores the value of the flag.
352 func Uint64(name string, value uint64, usage string) *uint64 {
354 Uint64Var(p, name, value, usage)
358 // StringVar defines a string flag with specified name, default value, and usage string.
359 // The argument p points to a string variable in which to store the value of the flag.
360 func StringVar(p *string, name, value string, usage string) {
361 Var(newStringValue(value, p), name, usage)
364 // String defines a string flag with specified name, default value, and usage string.
365 // The return value is the address of a string variable that stores the value of the flag.
366 func String(name, value string, usage string) *string {
368 StringVar(p, name, value, usage)
372 // Float64Var defines a float64 flag with specified name, default value, and usage string.
373 // The argument p points to a float64 variable in which to store the value of the flag.
374 func Float64Var(p *float64, name string, value float64, usage string) {
375 Var(newFloat64Value(value, p), name, usage)
378 // Float64 defines a float64 flag with specified name, default value, and usage string.
379 // The return value is the address of a float64 variable that stores the value of the flag.
380 func Float64(name string, value float64, usage string) *float64 {
382 Float64Var(p, name, value, usage)
386 // Var defines a user-typed flag with specified name, default value, and usage string.
387 // The argument p points to a Value variable in which to store the value of the flag.
388 func Var(value Value, name string, usage string) {
389 // Remember the default value as a string; it won't change.
390 f := &Flag{name, usage, value, value.String()}
391 _, alreadythere := flags.formal[name]
393 fmt.Fprintln(os.Stderr, "flag redefined:", name)
394 panic("flag redefinition") // Happens only if flags are declared with identical names
396 flags.formal[name] = f
400 func (f *allFlags) parseOne() (ok bool) {
401 if len(f.args) == 0 {
405 if len(s) == 0 || s[0] != '-' || len(s) == 1 {
411 if len(s) == 2 { // "--" terminates the flags
416 name := s[num_minuses:]
417 if len(name) == 0 || name[0] == '-' || name[0] == '=' {
418 fmt.Fprintln(os.Stderr, "bad flag syntax:", s)
422 // it's a flag. does it have an argument?
426 for i := 1; i < len(name); i++ { // equals cannot be first
435 flag, alreadythere := m[name] // BUG
437 fmt.Fprintf(os.Stderr, "flag provided but not defined: -%s\n", name)
440 if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
443 fmt.Fprintf(os.Stderr, "invalid boolean value %q for flag: -%s\n", value, name)
450 // It must have a value, which might be the next argument.
451 if !has_value && len(f.args) > 0 {
452 // value is the next arg
454 value, f.args = f.args[0], f.args[1:]
457 fmt.Fprintf(os.Stderr, "flag needs an argument: -%s\n", name)
460 ok = flag.Value.Set(value)
462 fmt.Fprintf(os.Stderr, "invalid value %q for flag: -%s\n", value, name)
466 flags.actual[name] = flag
470 // Parse parses the command-line flags. Must be called after all flags are defined
471 // and before any are accessed by the program.
473 flags.args = os.Args[1:]
474 for flags.parseOne() {
479 flags = &allFlags{make(map[string]*Flag), make(map[string]*Flag), os.Args[1:]}