flag.go 32.3 KB
Newer Older
Lars Wiegman's avatar
Lars Wiegman committed
1 2 3 4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/*
	Package flag implements command-line flag parsing.

	Usage:

	Define flags using flag.String(), Bool(), Int(), etc.

	This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
		import "flag"
		var ip = flag.Int("flagname", 1234, "help message for flagname")
	If you like, you can bind the flag to a variable using the Var() functions.
		var flagvar int
		func init() {
			flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
		}
	Or you can create custom flags that satisfy the Value interface (with
	pointer receivers) and couple them to flag parsing by
		flag.Var(&flagVal, "name", "help message for flagname")
	For such flags, the default value is just the initial value of the variable.

	After all flags are defined, call
		flag.Parse()
	to parse the command line into the defined flags.

	Flags may then be used directly. If you're using the flags themselves,
	they are all pointers; if you bind to variables, they're values.
		fmt.Println("ip has value ", *ip)
		fmt.Println("flagvar has value ", flagvar)

34
	After parsing, the arguments following the flags are available as the
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	slice flag.Args() or individually as flag.Arg(i).
	The arguments are indexed from 0 through flag.NArg()-1.

	Command line flag syntax:
		-flag
		-flag=x
		-flag x  // non-boolean flags only
	One or two minus signs may be used; they are equivalent.
	The last form is not permitted for boolean flags because the
	meaning of the command
		cmd -x *
	will change if there is a file called 0, false, etc.  You must
	use the -flag=false form to turn off a boolean flag.

	Flag parsing stops just before the first non-flag argument
	("-" is a non-flag argument) or after the terminator "--".

	Integer flags accept 1234, 0664, 0x1234 and may be negative.
53 54
	Boolean flags may be:
		1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
55 56 57 58 59 60 61 62
	Duration flags accept any input valid for time.ParseDuration.

	The default set of command-line flags is controlled by
	top-level functions.  The FlagSet type allows one to define
	independent sets of flags, such as to implement subcommands
	in a command-line interface. The methods of FlagSet are
	analogous to the top-level functions for the command-line
	flag set.
Lars Wiegman's avatar
Lars Wiegman committed
63 64 65 66
*/
package flag

import (
67 68 69 70
	"errors"
	"fmt"
	"io"
	"os"
71
	"reflect"
72 73 74 75
	"sort"
	"strconv"
	"strings"
	"time"
Lars Wiegman's avatar
Lars Wiegman committed
76 77
)

78 79
// ErrHelp is the error returned if the -help or -h flag is invoked
// but no such flag is defined.
Lars Wiegman's avatar
Lars Wiegman committed
80 81 82 83 84 85
var ErrHelp = errors.New("flag: help requested")

// -- bool Value
type boolValue bool

func newBoolValue(val bool, p *bool) *boolValue {
86 87
	*p = val
	return (*boolValue)(p)
Lars Wiegman's avatar
Lars Wiegman committed
88 89 90
}

func (b *boolValue) Set(s string) error {
91 92 93
	v, err := strconv.ParseBool(s)
	*b = boolValue(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
94 95 96 97 98 99 100 101 102 103 104
}

func (b *boolValue) Get() interface{} { return bool(*b) }

func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }

func (b *boolValue) IsBoolFlag() bool { return true }

// optional interface to indicate boolean flags that can be
// supplied without "=value" text
type boolFlag interface {
105 106
	Value
	IsBoolFlag() bool
Lars Wiegman's avatar
Lars Wiegman committed
107 108 109 110 111 112
}

// -- int Value
type intValue int

func newIntValue(val int, p *int) *intValue {
113 114
	*p = val
	return (*intValue)(p)
Lars Wiegman's avatar
Lars Wiegman committed
115 116 117
}

func (i *intValue) Set(s string) error {
118 119 120
	v, err := strconv.ParseInt(s, 0, 64)
	*i = intValue(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
121 122 123 124 125 126 127 128 129 130
}

func (i *intValue) Get() interface{} { return int(*i) }

func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }

// -- int64 Value
type int64Value int64

func newInt64Value(val int64, p *int64) *int64Value {
131 132
	*p = val
	return (*int64Value)(p)
Lars Wiegman's avatar
Lars Wiegman committed
133 134 135
}

func (i *int64Value) Set(s string) error {
136 137 138
	v, err := strconv.ParseInt(s, 0, 64)
	*i = int64Value(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
139 140 141 142 143 144 145 146 147 148
}

func (i *int64Value) Get() interface{} { return int64(*i) }

func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }

// -- uint Value
type uintValue uint

func newUintValue(val uint, p *uint) *uintValue {
149 150
	*p = val
	return (*uintValue)(p)
Lars Wiegman's avatar
Lars Wiegman committed
151 152 153
}

func (i *uintValue) Set(s string) error {
154 155 156
	v, err := strconv.ParseUint(s, 0, 64)
	*i = uintValue(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
157 158 159 160 161 162 163 164 165 166
}

func (i *uintValue) Get() interface{} { return uint(*i) }

func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }

// -- uint64 Value
type uint64Value uint64

func newUint64Value(val uint64, p *uint64) *uint64Value {
167 168
	*p = val
	return (*uint64Value)(p)
Lars Wiegman's avatar
Lars Wiegman committed
169 170 171
}

func (i *uint64Value) Set(s string) error {
172 173 174
	v, err := strconv.ParseUint(s, 0, 64)
	*i = uint64Value(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
175 176 177 178 179 180 181 182 183 184
}

func (i *uint64Value) Get() interface{} { return uint64(*i) }

func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }

// -- string Value
type stringValue string

func newStringValue(val string, p *string) *stringValue {
185 186
	*p = val
	return (*stringValue)(p)
Lars Wiegman's avatar
Lars Wiegman committed
187 188 189
}

func (s *stringValue) Set(val string) error {
190 191
	*s = stringValue(val)
	return nil
Lars Wiegman's avatar
Lars Wiegman committed
192 193 194 195 196 197 198 199 200 201
}

func (s *stringValue) Get() interface{} { return string(*s) }

func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }

// -- float64 Value
type float64Value float64

func newFloat64Value(val float64, p *float64) *float64Value {
202 203
	*p = val
	return (*float64Value)(p)
Lars Wiegman's avatar
Lars Wiegman committed
204 205 206
}

func (f *float64Value) Set(s string) error {
207 208 209
	v, err := strconv.ParseFloat(s, 64)
	*f = float64Value(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
210 211 212 213 214 215 216 217 218 219
}

func (f *float64Value) Get() interface{} { return float64(*f) }

func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }

// -- time.Duration Value
type durationValue time.Duration

func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
220 221
	*p = val
	return (*durationValue)(p)
Lars Wiegman's avatar
Lars Wiegman committed
222 223 224
}

func (d *durationValue) Set(s string) error {
225 226 227
	v, err := time.ParseDuration(s)
	*d = durationValue(v)
	return err
Lars Wiegman's avatar
Lars Wiegman committed
228 229 230 231 232 233 234 235 236 237 238 239
}

func (d *durationValue) Get() interface{} { return time.Duration(*d) }

func (d *durationValue) String() string { return (*time.Duration)(d).String() }

// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
//
// If a Value has an IsBoolFlag() bool method returning true,
// the command-line parser makes -name equivalent to -name=true
// rather than using the next command-line argument.
240 241
//
// Set is called once, in command line order, for each flag present.
Lars Wiegman's avatar
Lars Wiegman committed
242
type Value interface {
243 244
	String() string
	Set(string) error
Lars Wiegman's avatar
Lars Wiegman committed
245 246 247 248 249 250 251
}

// Getter is an interface that allows the contents of a Value to be retrieved.
// It wraps the Value interface, rather than being part of it, because it
// appeared after Go 1 and its compatibility rules. All Value types provided
// by this package satisfy the Getter interface.
type Getter interface {
252 253
	Value
	Get() interface{}
Lars Wiegman's avatar
Lars Wiegman committed
254 255
}

256
// ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
Lars Wiegman's avatar
Lars Wiegman committed
257 258
type ErrorHandling int

259
// These constants cause FlagSet.Parse to behave as described if the parse fails.
Lars Wiegman's avatar
Lars Wiegman committed
260
const (
261 262 263
	ContinueOnError ErrorHandling = iota // Return a descriptive error.
	ExitOnError                          // Call os.Exit(2).
	PanicOnError                         // Call panic with a descriptive error.
Lars Wiegman's avatar
Lars Wiegman committed
264 265
)

266
// A FlagSet represents a set of defined flags. The zero value of a FlagSet
Lars Wiegman's avatar
Lars Wiegman committed
267 268
// has no name and has ContinueOnError error handling.
type FlagSet struct {
269 270 271 272
	// Usage is the function called when an error occurs while parsing flags.
	// The field is a function (not a method) that may be changed to point to
	// a custom error handler.
	Usage func()
Lars Wiegman's avatar
Lars Wiegman committed
273

274 275 276 277
	name          string
	parsed        bool
	actual        map[string]*Flag
	formal        map[string]*Flag
278
	envPrefix     string   // prefix to all env variable names
279 280 281
	args          []string // arguments after flags
	errorHandling ErrorHandling
	output        io.Writer // nil means stderr; use out() accessor
Lars Wiegman's avatar
Lars Wiegman committed
282 283 284 285
}

// A Flag represents the state of a flag.
type Flag struct {
286 287 288 289
	Name     string // name as it appears on command line
	Usage    string // help message
	Value    Value  // value as set
	DefValue string // default value (as text); for usage message
Lars Wiegman's avatar
Lars Wiegman committed
290 291 292 293
}

// sortFlags returns the flags as a slice in lexicographical sorted order.
func sortFlags(flags map[string]*Flag) []*Flag {
294 295 296 297 298 299 300 301 302 303 304 305
	list := make(sort.StringSlice, len(flags))
	i := 0
	for _, f := range flags {
		list[i] = f.Name
		i++
	}
	list.Sort()
	result := make([]*Flag, len(list))
	for i, name := range list {
		result[i] = flags[name]
	}
	return result
Lars Wiegman's avatar
Lars Wiegman committed
306 307 308
}

func (f *FlagSet) out() io.Writer {
309 310 311 312
	if f.output == nil {
		return os.Stderr
	}
	return f.output
Lars Wiegman's avatar
Lars Wiegman committed
313 314 315 316 317
}

// SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used.
func (f *FlagSet) SetOutput(output io.Writer) {
318
	f.output = output
Lars Wiegman's avatar
Lars Wiegman committed
319 320 321 322 323
}

// VisitAll visits the flags in lexicographical order, calling fn for each.
// It visits all flags, even those not set.
func (f *FlagSet) VisitAll(fn func(*Flag)) {
324 325 326
	for _, flag := range sortFlags(f.formal) {
		fn(flag)
	}
Lars Wiegman's avatar
Lars Wiegman committed
327 328 329
}

// VisitAll visits the command-line flags in lexicographical order, calling
330
// fn for each. It visits all flags, even those not set.
Lars Wiegman's avatar
Lars Wiegman committed
331
func VisitAll(fn func(*Flag)) {
332
	CommandLine.VisitAll(fn)
Lars Wiegman's avatar
Lars Wiegman committed
333 334 335 336 337
}

// Visit visits the flags in lexicographical order, calling fn for each.
// It visits only those flags that have been set.
func (f *FlagSet) Visit(fn func(*Flag)) {
338 339 340
	for _, flag := range sortFlags(f.actual) {
		fn(flag)
	}
Lars Wiegman's avatar
Lars Wiegman committed
341 342 343
}

// Visit visits the command-line flags in lexicographical order, calling fn
344
// for each. It visits only those flags that have been set.
Lars Wiegman's avatar
Lars Wiegman committed
345
func Visit(fn func(*Flag)) {
346
	CommandLine.Visit(fn)
Lars Wiegman's avatar
Lars Wiegman committed
347 348 349 350
}

// Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (f *FlagSet) Lookup(name string) *Flag {
351
	return f.formal[name]
Lars Wiegman's avatar
Lars Wiegman committed
352 353 354 355 356
}

// Lookup returns the Flag structure of the named command-line flag,
// returning nil if none exists.
func Lookup(name string) *Flag {
357
	return CommandLine.formal[name]
Lars Wiegman's avatar
Lars Wiegman committed
358 359 360 361
}

// Set sets the value of the named flag.
func (f *FlagSet) Set(name, value string) error {
362 363 364 365 366 367 368 369 370 371 372 373 374
	flag, ok := f.formal[name]
	if !ok {
		return fmt.Errorf("no such flag -%v", name)
	}
	err := flag.Value.Set(value)
	if err != nil {
		return err
	}
	if f.actual == nil {
		f.actual = make(map[string]*Flag)
	}
	f.actual[name] = flag
	return nil
Lars Wiegman's avatar
Lars Wiegman committed
375 376 377 378
}

// Set sets the value of the named command-line flag.
func Set(name, value string) error {
379
	return CommandLine.Set(name, value)
Lars Wiegman's avatar
Lars Wiegman committed
380 381
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
// isZeroValue guesses whether the string represents the zero
// value for a flag. It is not accurate but in practice works OK.
func isZeroValue(flag *Flag, value string) bool {
	// Build a zero value of the flag's Value type, and see if the
	// result of calling its String method equals the value passed in.
	// This works unless the Value type is itself an interface type.
	typ := reflect.TypeOf(flag.Value)
	var z reflect.Value
	if typ.Kind() == reflect.Ptr {
		z = reflect.New(typ.Elem())
	} else {
		z = reflect.Zero(typ)
	}
	if value == z.Interface().(Value).String() {
		return true
	}

	switch value {
	case "false":
		return true
	case "":
		return true
	case "0":
		return true
	}
	return false
}

// UnquoteUsage extracts a back-quoted name from the usage
// string for a flag and returns it and the un-quoted usage.
// Given "a `name` to show" it returns ("name", "a name to show").
// If there are no back quotes, the name is an educated guess of the
// type of the flag's value, or the empty string if the flag is boolean.
func UnquoteUsage(flag *Flag) (name string, usage string) {
	// Look for a back-quoted name, but avoid the strings package.
	usage = flag.Usage
	for i := 0; i < len(usage); i++ {
		if usage[i] == '`' {
			for j := i + 1; j < len(usage); j++ {
				if usage[j] == '`' {
					name = usage[i+1 : j]
					usage = usage[:i] + name + usage[j+1:]
					return name, usage
				}
			}
			break // Only one back quote; use type name.
		}
	}
	// No explicit name, so use type if we can find one.
	name = "value"
	switch flag.Value.(type) {
	case boolFlag:
		name = ""
	case *durationValue:
		name = "duration"
	case *float64Value:
		name = "float"
	case *intValue, *int64Value:
		name = "int"
	case *stringValue:
		name = "string"
	case *uintValue, *uint64Value:
		name = "uint"
	}
	return
}

// PrintDefaults prints to standard error the default values of all
// defined command-line flags in the set. See the documentation for
// the global function PrintDefaults for more information.
Lars Wiegman's avatar
Lars Wiegman committed
452
func (f *FlagSet) PrintDefaults() {
453
	f.VisitAll(func(flag *Flag) {
454 455 456 457
		s := fmt.Sprintf("  -%s", flag.Name) // Two spaces before -; see next two comments.
		name, usage := UnquoteUsage(flag)
		if len(name) > 0 {
			s += " " + name
458
		}
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
		// Boolean flags of one ASCII letter are so common we
		// treat them specially, putting their usage on the same line.
		if len(s) <= 4 { // space, space, '-', 'x'.
			s += "\t"
		} else {
			// Four spaces before the tab triggers good alignment
			// for both 4- and 8-space tab stops.
			s += "\n    \t"
		}
		s += usage
		if !isZeroValue(flag, flag.DefValue) {
			if _, ok := flag.Value.(*stringValue); ok {
				// put quotes on the value
				s += fmt.Sprintf(" (default %q)", flag.DefValue)
			} else {
				s += fmt.Sprintf(" (default %v)", flag.DefValue)
			}
		}
		fmt.Fprint(f.out(), s, "\n")
478
	})
Lars Wiegman's avatar
Lars Wiegman committed
479 480
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
// PrintDefaults prints, to standard error unless configured otherwise,
// a usage message showing the default settings of all defined
// command-line flags.
// For an integer valued flag x, the default output has the form
//	-x int
//		usage-message-for-x (default 7)
// The usage message will appear on a separate line for anything but
// a bool flag with a one-byte name. For bool flags, the type is
// omitted and if the flag name is one byte the usage message appears
// on the same line. The parenthetical default is omitted if the
// default is the zero value for the type. The listed type, here int,
// can be changed by placing a back-quoted name in the flag's usage
// string; the first such item in the message is taken to be a parameter
// name to show in the message and the back quotes are stripped from
// the message when displayed. For instance, given
//	flag.String("I", "", "search `directory` for include files")
// the output will be
//	-I directory
//		search directory for include files.
Lars Wiegman's avatar
Lars Wiegman committed
500
func PrintDefaults() {
501
	CommandLine.PrintDefaults()
Lars Wiegman's avatar
Lars Wiegman committed
502 503 504 505
}

// defaultUsage is the default function to print a usage message.
func defaultUsage(f *FlagSet) {
506 507 508 509 510 511
	if f.name == "" {
		fmt.Fprintf(f.out(), "Usage:\n")
	} else {
		fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
	}
	f.PrintDefaults()
Lars Wiegman's avatar
Lars Wiegman committed
512 513 514 515 516 517 518
}

// NOTE: Usage is not just defaultUsage(CommandLine)
// because it serves (via godoc flag Usage) as the example
// for how to write your own usage function.

// Usage prints to standard error a usage message documenting all defined command-line flags.
519
// It is called when an error occurs while parsing flags.
Lars Wiegman's avatar
Lars Wiegman committed
520
// The function is a variable that may be changed to point to a custom function.
521 522
// By default it prints a simple header and calls PrintDefaults; for details about the
// format of the output and how to control it, see the documentation for PrintDefaults.
Lars Wiegman's avatar
Lars Wiegman committed
523
var Usage = func() {
524 525
	fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
	PrintDefaults()
Lars Wiegman's avatar
Lars Wiegman committed
526 527 528 529 530 531 532 533
}

// NFlag returns the number of flags that have been set.
func (f *FlagSet) NFlag() int { return len(f.actual) }

// NFlag returns the number of command-line flags that have been set.
func NFlag() int { return len(CommandLine.actual) }

534 535 536
// Arg returns the i'th argument. Arg(0) is the first remaining argument
// after flags have been processed. Arg returns an empty string if the
// requested element does not exist.
Lars Wiegman's avatar
Lars Wiegman committed
537
func (f *FlagSet) Arg(i int) string {
538 539 540 541
	if i < 0 || i >= len(f.args) {
		return ""
	}
	return f.args[i]
Lars Wiegman's avatar
Lars Wiegman committed
542 543
}

544 545 546
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
// after flags have been processed. Arg returns an empty string if the
// requested element does not exist.
Lars Wiegman's avatar
Lars Wiegman committed
547
func Arg(i int) string {
548
	return CommandLine.Arg(i)
Lars Wiegman's avatar
Lars Wiegman committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
}

// NArg is the number of arguments remaining after flags have been processed.
func (f *FlagSet) NArg() int { return len(f.args) }

// NArg is the number of arguments remaining after flags have been processed.
func NArg() int { return len(CommandLine.args) }

// Args returns the non-flag arguments.
func (f *FlagSet) Args() []string { return f.args }

// Args returns the non-flag command-line arguments.
func Args() []string { return CommandLine.args }

// BoolVar defines a bool flag with specified name, default value, and usage string.
// The argument p points to a bool variable in which to store the value of the flag.
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
566
	f.Var(newBoolValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
567 568 569 570 571
}

// BoolVar defines a bool flag with specified name, default value, and usage string.
// The argument p points to a bool variable in which to store the value of the flag.
func BoolVar(p *bool, name string, value bool, usage string) {
572
	CommandLine.Var(newBoolValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
573 574 575 576 577
}

// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
578 579 580
	p := new(bool)
	f.BoolVar(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
581 582 583 584 585
}

// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func Bool(name string, value bool, usage string) *bool {
586
	return CommandLine.Bool(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
587 588 589 590 591
}

// IntVar defines an int flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
592
	f.Var(newIntValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
593 594 595 596 597
}

// IntVar defines an int flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
func IntVar(p *int, name string, value int, usage string) {
598
	CommandLine.Var(newIntValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
599 600 601 602 603
}

// Int defines an int flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
func (f *FlagSet) Int(name string, value int, usage string) *int {
604 605 606
	p := new(int)
	f.IntVar(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
607 608 609 610 611
}

// Int defines an int flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
func Int(name string, value int, usage string) *int {
612
	return CommandLine.Int(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
613 614 615 616 617
}

// Int64Var defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
618
	f.Var(newInt64Value(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
619 620 621 622 623
}

// Int64Var defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func Int64Var(p *int64, name string, value int64, usage string) {
624
	CommandLine.Var(newInt64Value(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
625 626 627 628 629
}

// Int64 defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
630 631 632
	p := new(int64)
	f.Int64Var(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
633 634 635 636 637
}

// Int64 defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func Int64(name string, value int64, usage string) *int64 {
638
	return CommandLine.Int64(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
639 640 641 642 643
}

// UintVar defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
644
	f.Var(newUintValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
645 646 647 648 649
}

// UintVar defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint  variable in which to store the value of the flag.
func UintVar(p *uint, name string, value uint, usage string) {
650
	CommandLine.Var(newUintValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
651 652 653 654 655
}

// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint  variable that stores the value of the flag.
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
656 657 658
	p := new(uint)
	f.UintVar(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
659 660 661 662 663
}

// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint  variable that stores the value of the flag.
func Uint(name string, value uint, usage string) *uint {
664
	return CommandLine.Uint(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
665 666 667 668 669
}

// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
// The argument p points to a uint64 variable in which to store the value of the flag.
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
670
	f.Var(newUint64Value(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
671 672 673 674 675
}

// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
// The argument p points to a uint64 variable in which to store the value of the flag.
func Uint64Var(p *uint64, name string, value uint64, usage string) {
676
	CommandLine.Var(newUint64Value(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
677 678 679 680 681
}

// Uint64 defines a uint64 flag with specified name, default value, and usage string.
// The return value is the address of a uint64 variable that stores the value of the flag.
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
682 683 684
	p := new(uint64)
	f.Uint64Var(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
685 686 687 688 689
}

// Uint64 defines a uint64 flag with specified name, default value, and usage string.
// The return value is the address of a uint64 variable that stores the value of the flag.
func Uint64(name string, value uint64, usage string) *uint64 {
690
	return CommandLine.Uint64(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
691 692 693 694 695
}

// StringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a string variable in which to store the value of the flag.
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
696
	f.Var(newStringValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
697 698 699 700 701
}

// StringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a string variable in which to store the value of the flag.
func StringVar(p *string, name string, value string, usage string) {
702
	CommandLine.Var(newStringValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
703 704 705 706 707
}

// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func (f *FlagSet) String(name string, value string, usage string) *string {
708 709 710
	p := new(string)
	f.StringVar(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
711 712 713 714 715
}

// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func String(name string, value string, usage string) *string {
716
	return CommandLine.String(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
717 718 719 720 721
}

// Float64Var defines a float64 flag with specified name, default value, and usage string.
// The argument p points to a float64 variable in which to store the value of the flag.
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
722
	f.Var(newFloat64Value(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
723 724 725 726 727
}

// Float64Var defines a float64 flag with specified name, default value, and usage string.
// The argument p points to a float64 variable in which to store the value of the flag.
func Float64Var(p *float64, name string, value float64, usage string) {
728
	CommandLine.Var(newFloat64Value(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
729 730 731 732 733
}

// Float64 defines a float64 flag with specified name, default value, and usage string.
// The return value is the address of a float64 variable that stores the value of the flag.
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
734 735 736
	p := new(float64)
	f.Float64Var(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
737 738 739 740 741
}

// Float64 defines a float64 flag with specified name, default value, and usage string.
// The return value is the address of a float64 variable that stores the value of the flag.
func Float64(name string, value float64, usage string) *float64 {
742
	return CommandLine.Float64(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
743 744 745 746
}

// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
747
// The flag accepts a value acceptable to time.ParseDuration.
Lars Wiegman's avatar
Lars Wiegman committed
748
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
749
	f.Var(newDurationValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
750 751 752 753
}

// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
754
// The flag accepts a value acceptable to time.ParseDuration.
Lars Wiegman's avatar
Lars Wiegman committed
755
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
756
	CommandLine.Var(newDurationValue(value, p), name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
757 758 759 760
}

// Duration defines a time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a time.Duration variable that stores the value of the flag.
761
// The flag accepts a value acceptable to time.ParseDuration.
Lars Wiegman's avatar
Lars Wiegman committed
762
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
763 764 765
	p := new(time.Duration)
	f.DurationVar(p, name, value, usage)
	return p
Lars Wiegman's avatar
Lars Wiegman committed
766 767 768 769
}

// Duration defines a time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a time.Duration variable that stores the value of the flag.
770
// The flag accepts a value acceptable to time.ParseDuration.
Lars Wiegman's avatar
Lars Wiegman committed
771
func Duration(name string, value time.Duration, usage string) *time.Duration {
772
	return CommandLine.Duration(name, value, usage)
Lars Wiegman's avatar
Lars Wiegman committed
773 774 775 776 777 778 779 780 781
}

// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func (f *FlagSet) Var(value Value, name string, usage string) {
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
	// Remember the default value as a string; it won't change.
	flag := &Flag{name, usage, value, value.String()}
	_, alreadythere := f.formal[name]
	if alreadythere {
		var msg string
		if f.name == "" {
			msg = fmt.Sprintf("flag redefined: %s", name)
		} else {
			msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
		}
		fmt.Fprintln(f.out(), msg)
		panic(msg) // Happens only if flags are declared with identical names
	}
	if f.formal == nil {
		f.formal = make(map[string]*Flag)
	}
	f.formal[name] = flag
Lars Wiegman's avatar
Lars Wiegman committed
799 800 801 802 803 804 805 806 807
}

// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func Var(value Value, name string, usage string) {
808
	CommandLine.Var(value, name, usage)
Lars Wiegman's avatar
Lars Wiegman committed
809 810 811 812 813
}

// failf prints to standard error a formatted error and usage message and
// returns the error.
func (f *FlagSet) failf(format string, a ...interface{}) error {
814 815 816 817
	err := fmt.Errorf(format, a...)
	fmt.Fprintln(f.out(), err)
	f.usage()
	return err
Lars Wiegman's avatar
Lars Wiegman committed
818 819
}

820 821
// usage calls the Usage method for the flag set if one is specified,
// or the appropriate default usage function otherwise.
Lars Wiegman's avatar
Lars Wiegman committed
822
func (f *FlagSet) usage() {
823 824 825 826 827 828
	if f.Usage == nil {
		if f == CommandLine {
			Usage()
		} else {
			defaultUsage(f)
		}
829 830 831
	} else {
		f.Usage()
	}
Lars Wiegman's avatar
Lars Wiegman committed
832 833 834 835
}

// parseOne parses one flag. It reports whether a flag was seen.
func (f *FlagSet) parseOne() (bool, error) {
836 837 838 839 840 841 842
	if len(f.args) == 0 {
		return false, nil
	}
	s := f.args[0]
	if len(s) == 0 || s[0] != '-' || len(s) == 1 {
		return false, nil
	}
Mohamed Attahri's avatar
Mohamed Attahri committed
843
	numMinuses := 1
844
	if s[1] == '-' {
Mohamed Attahri's avatar
Mohamed Attahri committed
845
		numMinuses++
846 847 848 849 850
		if len(s) == 2 { // "--" terminates the flags
			f.args = f.args[1:]
			return false, nil
		}
	}
Mohamed Attahri's avatar
Mohamed Attahri committed
851
	name := s[numMinuses:]
852 853 854 855
	if len(name) == 0 || name[0] == '-' || name[0] == '=' {
		return false, f.failf("bad flag syntax: %s", s)
	}

856 857 858 859 860
	// ignore go test flags
	if strings.HasPrefix(name, "test.") {
		return false, nil
	}

861 862
	// it's a flag. does it have an argument?
	f.args = f.args[1:]
Mohamed Attahri's avatar
Mohamed Attahri committed
863
	hasValue := false
864 865 866 867
	value := ""
	for i := 1; i < len(name); i++ { // equals cannot be first
		if name[i] == '=' {
			value = name[i+1:]
Mohamed Attahri's avatar
Mohamed Attahri committed
868
			hasValue = true
869 870 871 872 873 874 875 876 877 878 879 880 881 882
			name = name[0:i]
			break
		}
	}
	m := f.formal
	flag, alreadythere := m[name] // BUG
	if !alreadythere {
		if name == "help" || name == "h" { // special case for nice help message.
			f.usage()
			return false, ErrHelp
		}
		return false, f.failf("flag provided but not defined: -%s", name)
	}
	if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
Mohamed Attahri's avatar
Mohamed Attahri committed
883
		if hasValue {
884
			if err := fv.Set(value); err != nil {
885
				return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
886 887
			}
		} else {
888 889 890
			if err := fv.Set("true"); err != nil {
				return false, f.failf("invalid boolean flag %s: %v", name, err)
			}
891 892 893
		}
	} else {
		// It must have a value, which might be the next argument.
Mohamed Attahri's avatar
Mohamed Attahri committed
894
		if !hasValue && len(f.args) > 0 {
895
			// value is the next arg
Mohamed Attahri's avatar
Mohamed Attahri committed
896
			hasValue = true
897 898
			value, f.args = f.args[0], f.args[1:]
		}
Mohamed Attahri's avatar
Mohamed Attahri committed
899
		if !hasValue {
900 901 902 903 904 905 906 907 908 909 910
			return false, f.failf("flag needs an argument: -%s", name)
		}
		if err := flag.Value.Set(value); err != nil {
			return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
		}
	}
	if f.actual == nil {
		f.actual = make(map[string]*Flag)
	}
	f.actual[name] = flag
	return true, nil
Lars Wiegman's avatar
Lars Wiegman committed
911 912 913
}

// Parse parses flag definitions from the argument list, which should not
914
// include the command name. Must be called after all flags in the FlagSet
Lars Wiegman's avatar
Lars Wiegman committed
915
// are defined and before flags are accessed by the program.
916
// The return value will be ErrHelp if -help or -h were set but not defined.
Lars Wiegman's avatar
Lars Wiegman committed
917
func (f *FlagSet) Parse(arguments []string) error {
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
	f.parsed = true
	f.args = arguments
	for {
		seen, err := f.parseOne()
		if seen {
			continue
		}
		if err == nil {
			break
		}
		switch f.errorHandling {
		case ContinueOnError:
			return err
		case ExitOnError:
			os.Exit(2)
		case PanicOnError:
			panic(err)
		}
	}

	// Parse environment variables
939
	if err := f.ParseEnv(os.Environ()); err != nil {
940 941 942 943 944 945 946 947
		switch f.errorHandling {
		case ContinueOnError:
			return err
		case ExitOnError:
			os.Exit(2)
		case PanicOnError:
			panic(err)
		}
948 949
		return err
	}
950 951

	// Parse configuration from file
952 953 954 955 956 957
	var cFile string
	if cf := f.formal[DefaultConfigFlagname]; cf != nil {
		cFile = cf.Value.String()
	}
	if cf := f.actual[DefaultConfigFlagname]; cf != nil {
		cFile = cf.Value.String()
958
	}
959 960
	if cFile != "" {
		if err := f.ParseFile(cFile); err != nil {
961 962 963 964 965 966 967 968
			switch f.errorHandling {
			case ContinueOnError:
				return err
			case ExitOnError:
				os.Exit(2)
			case PanicOnError:
				panic(err)
			}
969 970
			return err
		}
971 972 973
	}

	return nil
Lars Wiegman's avatar
Lars Wiegman committed
974 975 976 977
}

// Parsed reports whether f.Parse has been called.
func (f *FlagSet) Parsed() bool {
978
	return f.parsed
Lars Wiegman's avatar
Lars Wiegman committed
979 980 981 982 983
}

// Parse parses the command-line flags from os.Args[1:].  Must be called
// after all flags are defined and before flags are accessed by the program.
func Parse() {
984 985
	// Ignore errors; CommandLine is set for ExitOnError.
	CommandLine.Parse(os.Args[1:])
Lars Wiegman's avatar
Lars Wiegman committed
986 987
}

988
// Parsed reports whether the command-line flags have been parsed.
Lars Wiegman's avatar
Lars Wiegman committed
989
func Parsed() bool {
990
	return CommandLine.Parsed()
Lars Wiegman's avatar
Lars Wiegman committed
991 992 993
}

// CommandLine is the default set of command-line flags, parsed from os.Args.
994
// The top-level functions such as BoolVar, Arg, and so on are wrappers for the
Lars Wiegman's avatar
Lars Wiegman committed
995 996 997 998 999 1000
// methods of CommandLine.
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)

// NewFlagSet returns a new, empty flag set with the specified name and
// error handling property.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
1001 1002 1003 1004 1005
	f := &FlagSet{
		name:          name,
		errorHandling: errorHandling,
	}
	return f
Lars Wiegman's avatar
Lars Wiegman committed
1006 1007
}

1008
// Init sets the name and error handling property for a flag set.
1009
// By default, the zero FlagSet uses an empty name, EnvironmentPrefix, and the
Lars Wiegman's avatar
Lars Wiegman committed
1010 1011
// ContinueOnError error handling policy.
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
1012
	f.name = name
1013
	f.envPrefix = EnvironmentPrefix
1014 1015
	f.errorHandling = errorHandling
}