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
61 // add per-subcommand options
78 func newBoolValue(val bool, p *bool) *boolValue {
80 return (*boolValue)(p)
83 func (b *boolValue) Set(s string) bool {
84 v, err := strconv.Atob(s)
89 func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
94 func newIntValue(val int, p *int) *intValue {
99 func (i *intValue) Set(s string) bool {
100 v, err := strconv.Btoi64(s, 0)
105 func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
108 type int64Value int64
110 func newInt64Value(val int64, p *int64) *int64Value {
112 return (*int64Value)(p)
115 func (i *int64Value) Set(s string) bool {
116 v, err := strconv.Btoi64(s, 0)
121 func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
126 func newUintValue(val uint, p *uint) *uintValue {
128 return (*uintValue)(p)
131 func (i *uintValue) Set(s string) bool {
132 v, err := strconv.Btoui64(s, 0)
137 func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
140 type uint64Value uint64
142 func newUint64Value(val uint64, p *uint64) *uint64Value {
144 return (*uint64Value)(p)
147 func (i *uint64Value) Set(s string) bool {
148 v, err := strconv.Btoui64(s, 0)
153 func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
156 type stringValue string
158 func newStringValue(val string, p *string) *stringValue {
160 return (*stringValue)(p)
163 func (s *stringValue) Set(val string) bool {
164 *s = stringValue(val)
168 func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
171 type float64Value float64
173 func newFloat64Value(val float64, p *float64) *float64Value {
175 return (*float64Value)(p)
178 func (f *float64Value) Set(s string) bool {
179 v, err := strconv.Atof64(s)
184 func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
186 // Value is the interface to the dynamic value stored in a flag.
187 // (The default value is represented as a string.)
188 type Value interface {
193 // A Flag represents the state of a flag.
195 Name string // name as it appears on command line
196 Usage string // help message
197 Value Value // value as set
198 DefValue string // default value (as text); for usage message
201 type allFlags struct {
202 actual map[string]*Flag
203 formal map[string]*Flag
204 args []string // arguments after flags
209 // sortFlags returns the flags as a slice in lexicographical sorted order.
210 func sortFlags(flags map[string]*Flag) []*Flag {
211 list := make(sort.StringArray, len(flags))
213 for _, f := range flags {
218 result := make([]*Flag, len(list))
219 for i, name := range list {
220 result[i] = flags[name]
225 // VisitAll visits the flags in lexicographical order, calling fn for each.
226 // It visits all flags, even those not set.
227 func VisitAll(fn func(*Flag)) {
228 for _, f := range sortFlags(flags.formal) {
233 // Visit visits the flags in lexicographical order, calling fn for each.
234 // It visits only those flags that have been set.
235 func Visit(fn func(*Flag)) {
236 for _, f := range sortFlags(flags.actual) {
241 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
242 func Lookup(name string) *Flag {
243 return flags.formal[name]
246 // Set sets the value of the named flag. It returns true if the set succeeded; false if
247 // there is no such flag defined.
248 func Set(name, value string) bool {
249 f, ok := flags.formal[name]
253 ok = f.Value.Set(value)
257 flags.actual[name] = f
261 // PrintDefaults prints to standard error the default values of all defined flags.
262 func PrintDefaults() {
263 VisitAll(func(f *Flag) {
264 format := " -%s=%s: %s\n"
265 if _, ok := f.Value.(*stringValue); ok {
266 // put quotes on the value
267 format = " -%s=%q: %s\n"
269 fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage)
273 // Usage prints to standard error a default usage message documenting all defined flags.
274 // The function is a variable that may be changed to point to a custom function.
276 fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
280 var panicOnError = false
282 // failf prints to standard error a formatted error and Usage, and then exits the program.
283 func failf(format string, a ...interface{}) {
284 fmt.Fprintf(os.Stderr, format, a...)
287 panic("flag parse error")
292 // NFlag returns the number of flags that have been set.
293 func NFlag() int { return len(flags.actual) }
295 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
296 // after flags have been processed.
297 func Arg(i int) string {
298 if i < 0 || i >= len(flags.args) {
304 // NArg is the number of arguments remaining after flags have been processed.
305 func NArg() int { return len(flags.args) }
307 // Args returns the non-flag command-line arguments.
308 func Args() []string { return flags.args }
310 // BoolVar defines a bool flag with specified name, default value, and usage string.
311 // The argument p points to a bool variable in which to store the value of the flag.
312 func BoolVar(p *bool, name string, value bool, usage string) {
313 Var(newBoolValue(value, p), name, usage)
316 // Bool defines a bool flag with specified name, default value, and usage string.
317 // The return value is the address of a bool variable that stores the value of the flag.
318 func Bool(name string, value bool, usage string) *bool {
320 BoolVar(p, name, value, usage)
324 // IntVar defines an int flag with specified name, default value, and usage string.
325 // The argument p points to an int variable in which to store the value of the flag.
326 func IntVar(p *int, name string, value int, usage string) {
327 Var(newIntValue(value, p), name, usage)
330 // Int defines an int flag with specified name, default value, and usage string.
331 // The return value is the address of an int variable that stores the value of the flag.
332 func Int(name string, value int, usage string) *int {
334 IntVar(p, name, value, usage)
338 // Int64Var defines an int64 flag with specified name, default value, and usage string.
339 // The argument p points to an int64 variable in which to store the value of the flag.
340 func Int64Var(p *int64, name string, value int64, usage string) {
341 Var(newInt64Value(value, p), name, usage)
344 // Int64 defines an int64 flag with specified name, default value, and usage string.
345 // The return value is the address of an int64 variable that stores the value of the flag.
346 func Int64(name string, value int64, usage string) *int64 {
348 Int64Var(p, name, value, usage)
352 // UintVar defines a uint flag with specified name, default value, and usage string.
353 // The argument p points to a uint variable in which to store the value of the flag.
354 func UintVar(p *uint, name string, value uint, usage string) {
355 Var(newUintValue(value, p), name, usage)
358 // Uint defines a uint flag with specified name, default value, and usage string.
359 // The return value is the address of a uint variable that stores the value of the flag.
360 func Uint(name string, value uint, usage string) *uint {
362 UintVar(p, name, value, usage)
366 // Uint64Var defines a uint64 flag with specified name, default value, and usage string.
367 // The argument p points to a uint64 variable in which to store the value of the flag.
368 func Uint64Var(p *uint64, name string, value uint64, usage string) {
369 Var(newUint64Value(value, p), name, usage)
372 // Uint64 defines a uint64 flag with specified name, default value, and usage string.
373 // The return value is the address of a uint64 variable that stores the value of the flag.
374 func Uint64(name string, value uint64, usage string) *uint64 {
376 Uint64Var(p, name, value, usage)
380 // StringVar defines a string flag with specified name, default value, and usage string.
381 // The argument p points to a string variable in which to store the value of the flag.
382 func StringVar(p *string, name, value string, usage string) {
383 Var(newStringValue(value, p), name, usage)
386 // String defines a string flag with specified name, default value, and usage string.
387 // The return value is the address of a string variable that stores the value of the flag.
388 func String(name, value string, usage string) *string {
390 StringVar(p, name, value, usage)
394 // Float64Var defines a float64 flag with specified name, default value, and usage string.
395 // The argument p points to a float64 variable in which to store the value of the flag.
396 func Float64Var(p *float64, name string, value float64, usage string) {
397 Var(newFloat64Value(value, p), name, usage)
400 // Float64 defines a float64 flag with specified name, default value, and usage string.
401 // The return value is the address of a float64 variable that stores the value of the flag.
402 func Float64(name string, value float64, usage string) *float64 {
404 Float64Var(p, name, value, usage)
408 // Var defines a user-typed flag with specified name, default value, and usage string.
409 // The argument p points to a Value variable in which to store the value of the flag.
410 func Var(value Value, name string, usage string) {
411 // Remember the default value as a string; it won't change.
412 f := &Flag{name, usage, value, value.String()}
413 _, alreadythere := flags.formal[name]
415 fmt.Fprintln(os.Stderr, "flag redefined:", name)
416 panic("flag redefinition") // Happens only if flags are declared with identical names
418 flags.formal[name] = f
422 func (f *allFlags) parseOne() (ok bool) {
423 if len(f.args) == 0 {
427 if len(s) == 0 || s[0] != '-' || len(s) == 1 {
433 if len(s) == 2 { // "--" terminates the flags
438 name := s[num_minuses:]
439 if len(name) == 0 || name[0] == '-' || name[0] == '=' {
440 failf("bad flag syntax: %s\n", s)
443 // it's a flag. does it have an argument?
447 for i := 1; i < len(name); i++ { // equals cannot be first
456 flag, alreadythere := m[name] // BUG
458 failf("flag provided but not defined: -%s\n", name)
460 if fv, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
463 failf("invalid boolean value %q for flag: -%s\n", value, name)
469 // It must have a value, which might be the next argument.
470 if !has_value && len(f.args) > 0 {
471 // value is the next arg
473 value, f.args = f.args[0], f.args[1:]
476 failf("flag needs an argument: -%s\n", name)
478 ok = flag.Value.Set(value)
480 failf("invalid value %q for flag: -%s\n", value, name)
483 flags.actual[name] = flag
487 // Parse parses the command-line flags. Must be called after all flags are defined
488 // and before any are accessed by the program.
490 flags.args = os.Args[1:]
491 for flags.parseOne() {
496 flags = &allFlags{make(map[string]*Flag), make(map[string]*Flag), os.Args[1:]}