// 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.

/* Package flag implements command-line flag parsing. Usage Define flags using flag.String(), Bool(), Int(), etc. This declares an integer flag, -n, stored in the pointer nFlag, with type *int: import "flag" var nFlag = flag.Int("n", 1234, "help message for flag n") 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) After parsing, the arguments following the flags are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1. Command line flag syntax The following forms are permitted: -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 * where * is a Unix shell wildcard, 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. Boolean flags may be: 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False 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. */
package flag import ( ) // ErrHelp is the error returned if the -help or -h flag is invoked // but no such flag is defined. var ErrHelp = errors.New("flag: help requested") // errParse is returned by Set if a flag's value fails to parse, such as with an invalid integer for Int. // It then gets wrapped through failf to provide more information. var errParse = errors.New("parse error") // errRange is returned by Set if a flag's value is out of range. // It then gets wrapped through failf to provide more information. var errRange = errors.New("value out of range") func numError( error) error { , := .(*strconv.NumError) if ! { return } if .Err == strconv.ErrSyntax { return errParse } if .Err == strconv.ErrRange { return errRange } return } // -- bool Value type boolValue bool func newBoolValue( bool, *bool) *boolValue { * = return (*boolValue)() } func ( *boolValue) ( string) error { , := strconv.ParseBool() if != nil { = errParse } * = boolValue() return } func ( *boolValue) () interface{} { return bool(*) } func ( *boolValue) () string { return strconv.FormatBool(bool(*)) } func ( *boolValue) () bool { return true } // optional interface to indicate boolean flags that can be // supplied without "=value" text type boolFlag interface { Value IsBoolFlag() bool } // -- int Value type intValue int func newIntValue( int, *int) *intValue { * = return (*intValue)() } func ( *intValue) ( string) error { , := strconv.ParseInt(, 0, strconv.IntSize) if != nil { = numError() } * = intValue() return } func ( *intValue) () interface{} { return int(*) } func ( *intValue) () string { return strconv.Itoa(int(*)) } // -- int64 Value type int64Value int64 func newInt64Value( int64, *int64) *int64Value { * = return (*int64Value)() } func ( *int64Value) ( string) error { , := strconv.ParseInt(, 0, 64) if != nil { = numError() } * = int64Value() return } func ( *int64Value) () interface{} { return int64(*) } func ( *int64Value) () string { return strconv.FormatInt(int64(*), 10) } // -- uint Value type uintValue uint func newUintValue( uint, *uint) *uintValue { * = return (*uintValue)() } func ( *uintValue) ( string) error { , := strconv.ParseUint(, 0, strconv.IntSize) if != nil { = numError() } * = uintValue() return } func ( *uintValue) () interface{} { return uint(*) } func ( *uintValue) () string { return strconv.FormatUint(uint64(*), 10) } // -- uint64 Value type uint64Value uint64 func newUint64Value( uint64, *uint64) *uint64Value { * = return (*uint64Value)() } func ( *uint64Value) ( string) error { , := strconv.ParseUint(, 0, 64) if != nil { = numError() } * = uint64Value() return } func ( *uint64Value) () interface{} { return uint64(*) } func ( *uint64Value) () string { return strconv.FormatUint(uint64(*), 10) } // -- string Value type stringValue string func newStringValue( string, *string) *stringValue { * = return (*stringValue)() } func ( *stringValue) ( string) error { * = stringValue() return nil } func ( *stringValue) () interface{} { return string(*) } func ( *stringValue) () string { return string(*) } // -- float64 Value type float64Value float64 func newFloat64Value( float64, *float64) *float64Value { * = return (*float64Value)() } func ( *float64Value) ( string) error { , := strconv.ParseFloat(, 64) if != nil { = numError() } * = float64Value() return } func ( *float64Value) () interface{} { return float64(*) } func ( *float64Value) () string { return strconv.FormatFloat(float64(*), 'g', -1, 64) } // -- time.Duration Value type durationValue time.Duration func newDurationValue( time.Duration, *time.Duration) *durationValue { * = return (*durationValue)() } func ( *durationValue) ( string) error { , := time.ParseDuration() if != nil { = errParse } * = durationValue() return } func ( *durationValue) () interface{} { return time.Duration(*) } func ( *durationValue) () string { return (*time.Duration)().String() } type funcValue func(string) error func ( funcValue) ( string) error { return () } func ( funcValue) () string { return "" } // 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. // // Set is called once, in command line order, for each flag present. // The flag package may call the String method with a zero-valued receiver, // such as a nil pointer. type Value interface { String() string Set(string) error } // 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, except the type used by Func. type Getter interface { Value Get() interface{} } // ErrorHandling defines how FlagSet.Parse behaves if the parse fails. type ErrorHandling int // These constants cause FlagSet.Parse to behave as described if the parse fails. const ( ContinueOnError ErrorHandling = iota // Return a descriptive error. ExitOnError // Call os.Exit(2) or for -h/-help Exit(0). PanicOnError // Call panic with a descriptive error. ) // A FlagSet represents a set of defined flags. The zero value of a FlagSet // has no name and has ContinueOnError error handling. // // Flag names must be unique within a FlagSet. An attempt to define a flag whose // name is already in use will cause a panic. type FlagSet struct { // 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. What happens after Usage is called depends // on the ErrorHandling setting; for the command line, this defaults // to ExitOnError, which exits the program after calling Usage. Usage func() name string parsed bool actual map[string]*Flag formal map[string]*Flag args []string // arguments after flags errorHandling ErrorHandling output io.Writer // nil means stderr; use Output() accessor } // A Flag represents the state of a flag. type Flag struct { 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 } // sortFlags returns the flags as a slice in lexicographical sorted order. func sortFlags( map[string]*Flag) []*Flag { := make([]*Flag, len()) := 0 for , := range { [] = ++ } sort.Slice(, func(, int) bool { return [].Name < [].Name }) return } // Output returns the destination for usage and error messages. os.Stderr is returned if // output was not set or was set to nil. func ( *FlagSet) () io.Writer { if .output == nil { return os.Stderr } return .output } // Name returns the name of the flag set. func ( *FlagSet) () string { return .name } // ErrorHandling returns the error handling behavior of the flag set. func ( *FlagSet) () ErrorHandling { return .errorHandling } // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func ( *FlagSet) ( io.Writer) { .output = } // VisitAll visits the flags in lexicographical order, calling fn for each. // It visits all flags, even those not set. func ( *FlagSet) ( func(*Flag)) { for , := range sortFlags(.formal) { () } } // VisitAll visits the command-line flags in lexicographical order, calling // fn for each. It visits all flags, even those not set. func ( func(*Flag)) { CommandLine.VisitAll() } // Visit visits the flags in lexicographical order, calling fn for each. // It visits only those flags that have been set. func ( *FlagSet) ( func(*Flag)) { for , := range sortFlags(.actual) { () } } // Visit visits the command-line flags in lexicographical order, calling fn // for each. It visits only those flags that have been set. func ( func(*Flag)) { CommandLine.Visit() } // Lookup returns the Flag structure of the named flag, returning nil if none exists. func ( *FlagSet) ( string) *Flag { return .formal[] } // Lookup returns the Flag structure of the named command-line flag, // returning nil if none exists. func ( string) *Flag { return CommandLine.formal[] } // Set sets the value of the named flag. func ( *FlagSet) (, string) error { , := .formal[] if ! { return fmt.Errorf("no such flag -%v", ) } := .Value.Set() if != nil { return } if .actual == nil { .actual = make(map[string]*Flag) } .actual[] = return nil } // Set sets the value of the named command-line flag. func (, string) error { return CommandLine.Set(, ) } // isZeroValue determines whether the string represents the zero // value for a flag. func isZeroValue( *Flag, 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. := reflect.TypeOf(.Value) var reflect.Value if .Kind() == reflect.Ptr { = reflect.New(.Elem()) } else { = reflect.Zero() } return == .Interface().(Value).String() } // 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 ( *Flag) ( string, string) { // Look for a back-quoted name, but avoid the strings package. = .Usage for := 0; < len(); ++ { if [] == '`' { for := + 1; < len(); ++ { if [] == '`' { = [+1 : ] = [:] + + [+1:] return , } } break // Only one back quote; use type name. } } // No explicit name, so use type if we can find one. = "value" switch .Value.(type) { case boolFlag: = "" case *durationValue: = "duration" case *float64Value: = "float" case *intValue, *int64Value: = "int" case *stringValue: = "string" case *uintValue, *uint64Value: = "uint" } return } // PrintDefaults prints, to standard error unless configured otherwise, the // default values of all defined command-line flags in the set. See the // documentation for the global function PrintDefaults for more information. func ( *FlagSet) () { .VisitAll(func( *Flag) { var strings.Builder fmt.Fprintf(&, " -%s", .Name) // Two spaces before -; see next two comments. , := UnquoteUsage() if len() > 0 { .WriteString(" ") .WriteString() } // Boolean flags of one ASCII letter are so common we // treat them specially, putting their usage on the same line. if .Len() <= 4 { // space, space, '-', 'x'. .WriteString("\t") } else { // Four spaces before the tab triggers good alignment // for both 4- and 8-space tab stops. .WriteString("\n \t") } .WriteString(strings.ReplaceAll(, "\n", "\n \t")) if !isZeroValue(, .DefValue) { if , := .Value.(*stringValue); { // put quotes on the value fmt.Fprintf(&, " (default %q)", .DefValue) } else { fmt.Fprintf(&, " (default %v)", .DefValue) } } fmt.Fprint(.Output(), .String(), "\n") }) } // 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. // // To change the destination for flag messages, call CommandLine.SetOutput. func () { CommandLine.PrintDefaults() } // defaultUsage is the default function to print a usage message. func ( *FlagSet) () { if .name == "" { fmt.Fprintf(.Output(), "Usage:\n") } else { fmt.Fprintf(.Output(), "Usage of %s:\n", .name) } .PrintDefaults() } // 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 a usage message documenting all defined command-line flags // to CommandLine's output, which by default is os.Stderr. // It is called when an error occurs while parsing flags. // The function is a variable that may be changed to point to a custom function. // 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. // Custom usage functions may choose to exit the program; by default exiting // happens anyway as the command line's error handling strategy is set to // ExitOnError. var Usage = func() { fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0]) PrintDefaults() } // NFlag returns the number of flags that have been set. func ( *FlagSet) () int { return len(.actual) } // NFlag returns the number of command-line flags that have been set. func () int { return len(CommandLine.actual) } // 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. func ( *FlagSet) ( int) string { if < 0 || >= len(.args) { return "" } return .args[] } // 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. func ( int) string { return CommandLine.Arg() } // NArg is the number of arguments remaining after flags have been processed. func ( *FlagSet) () int { return len(.args) } // NArg is the number of arguments remaining after flags have been processed. func () int { return len(CommandLine.args) } // Args returns the non-flag arguments. func ( *FlagSet) () []string { return .args } // Args returns the non-flag command-line arguments. func () []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 ( *FlagSet) ( *bool, string, bool, string) { .Var(newBoolValue(, ), , ) } // 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 ( *bool, string, bool, string) { CommandLine.Var(newBoolValue(, ), , ) } // 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 ( *FlagSet) ( string, bool, string) *bool { := new(bool) .BoolVar(, , , ) return } // 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 ( string, bool, string) *bool { return CommandLine.Bool(, , ) } // 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 ( *FlagSet) ( *int, string, int, string) { .Var(newIntValue(, ), , ) } // 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 ( *int, string, int, string) { CommandLine.Var(newIntValue(, ), , ) } // 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 ( *FlagSet) ( string, int, string) *int { := new(int) .IntVar(, , , ) return } // 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 ( string, int, string) *int { return CommandLine.Int(, , ) } // 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 ( *FlagSet) ( *int64, string, int64, string) { .Var(newInt64Value(, ), , ) } // 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 ( *int64, string, int64, string) { CommandLine.Var(newInt64Value(, ), , ) } // 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 ( *FlagSet) ( string, int64, string) *int64 { := new(int64) .Int64Var(, , , ) return } // 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 ( string, int64, string) *int64 { return CommandLine.Int64(, , ) } // 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 ( *FlagSet) ( *uint, string, uint, string) { .Var(newUintValue(, ), , ) } // 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 ( *uint, string, uint, string) { CommandLine.Var(newUintValue(, ), , ) } // 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 ( *FlagSet) ( string, uint, string) *uint { := new(uint) .UintVar(, , , ) return } // 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 ( string, uint, string) *uint { return CommandLine.Uint(, , ) } // 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 ( *FlagSet) ( *uint64, string, uint64, string) { .Var(newUint64Value(, ), , ) } // 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 ( *uint64, string, uint64, string) { CommandLine.Var(newUint64Value(, ), , ) } // 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 ( *FlagSet) ( string, uint64, string) *uint64 { := new(uint64) .Uint64Var(, , , ) return } // 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 ( string, uint64, string) *uint64 { return CommandLine.Uint64(, , ) } // 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 ( *FlagSet) ( *string, string, string, string) { .Var(newStringValue(, ), , ) } // 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 ( *string, string, string, string) { CommandLine.Var(newStringValue(, ), , ) } // 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 ( *FlagSet) ( string, string, string) *string { := new(string) .StringVar(, , , ) return } // 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, string, string) *string { return CommandLine.String(, , ) } // 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 ( *FlagSet) ( *float64, string, float64, string) { .Var(newFloat64Value(, ), , ) } // 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 ( *float64, string, float64, string) { CommandLine.Var(newFloat64Value(, ), , ) } // 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 ( *FlagSet) ( string, float64, string) *float64 { := new(float64) .Float64Var(, , , ) return } // 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 ( string, float64, string) *float64 { return CommandLine.Float64(, , ) } // 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. // The flag accepts a value acceptable to time.ParseDuration. func ( *FlagSet) ( *time.Duration, string, time.Duration, string) { .Var(newDurationValue(, ), , ) } // 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. // The flag accepts a value acceptable to time.ParseDuration. func ( *time.Duration, string, time.Duration, string) { CommandLine.Var(newDurationValue(, ), , ) } // 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. // The flag accepts a value acceptable to time.ParseDuration. func ( *FlagSet) ( string, time.Duration, string) *time.Duration { := new(time.Duration) .DurationVar(, , , ) return } // 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. // The flag accepts a value acceptable to time.ParseDuration. func ( string, time.Duration, string) *time.Duration { return CommandLine.Duration(, , ) } // Func defines a flag with the specified name and usage string. // Each time the flag is seen, fn is called with the value of the flag. // If fn returns a non-nil error, it will be treated as a flag value parsing error. func ( *FlagSet) (, string, func(string) error) { .Var(funcValue(), , ) } // Func defines a flag with the specified name and usage string. // Each time the flag is seen, fn is called with the value of the flag. // If fn returns a non-nil error, it will be treated as a flag value parsing error. func (, string, func(string) error) { CommandLine.Func(, , ) } // 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 ( *FlagSet) ( Value, string, string) { // Flag must not begin "-" or contain "=". if strings.HasPrefix(, "-") { panic(.sprintf("flag %q begins with -", )) } else if strings.Contains(, "=") { panic(.sprintf("flag %q contains =", )) } // Remember the default value as a string; it won't change. := &Flag{, , , .String()} , := .formal[] if { var string if .name == "" { = .sprintf("flag redefined: %s", ) } else { = .sprintf("%s flag redefined: %s", .name, ) } panic() // Happens only if flags are declared with identical names } if .formal == nil { .formal = make(map[string]*Flag) } .formal[] = } // 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 ( Value, string, string) { CommandLine.Var(, , ) } // sprintf formats the message, prints it to output, and returns it. func ( *FlagSet) ( string, ...interface{}) string { := fmt.Sprintf(, ...) fmt.Fprintln(.Output(), ) return } // failf prints to standard error a formatted error and usage message and // returns the error. func ( *FlagSet) ( string, ...interface{}) error { := .sprintf(, ...) .usage() return errors.New() } // usage calls the Usage method for the flag set if one is specified, // or the appropriate default usage function otherwise. func ( *FlagSet) () { if .Usage == nil { .defaultUsage() } else { .Usage() } } // parseOne parses one flag. It reports whether a flag was seen. func ( *FlagSet) () (bool, error) { if len(.args) == 0 { return false, nil } := .args[0] if len() < 2 || [0] != '-' { return false, nil } := 1 if [1] == '-' { ++ if len() == 2 { // "--" terminates the flags .args = .args[1:] return false, nil } } := [:] if len() == 0 || [0] == '-' || [0] == '=' { return false, .failf("bad flag syntax: %s", ) } // it's a flag. does it have an argument? .args = .args[1:] := false := "" for := 1; < len(); ++ { // equals cannot be first if [] == '=' { = [+1:] = true = [0:] break } } := .formal , := [] // BUG if ! { if == "help" || == "h" { // special case for nice help message. .usage() return false, ErrHelp } return false, .failf("flag provided but not defined: -%s", ) } if , := .Value.(boolFlag); && .IsBoolFlag() { // special case: doesn't need an arg if { if := .Set(); != nil { return false, .failf("invalid boolean value %q for -%s: %v", , , ) } } else { if := .Set("true"); != nil { return false, .failf("invalid boolean flag %s: %v", , ) } } } else { // It must have a value, which might be the next argument. if ! && len(.args) > 0 { // value is the next arg = true , .args = .args[0], .args[1:] } if ! { return false, .failf("flag needs an argument: -%s", ) } if := .Value.Set(); != nil { return false, .failf("invalid value %q for flag -%s: %v", , , ) } } if .actual == nil { .actual = make(map[string]*Flag) } .actual[] = return true, nil } // Parse parses flag definitions from the argument list, which should not // include the command name. Must be called after all flags in the FlagSet // are defined and before flags are accessed by the program. // The return value will be ErrHelp if -help or -h were set but not defined. func ( *FlagSet) ( []string) error { .parsed = true .args = for { , := .parseOne() if { continue } if == nil { break } switch .errorHandling { case ContinueOnError: return case ExitOnError: if == ErrHelp { os.Exit(0) } os.Exit(2) case PanicOnError: panic() } } return nil } // Parsed reports whether f.Parse has been called. func ( *FlagSet) () bool { return .parsed } // 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 () { // Ignore errors; CommandLine is set for ExitOnError. CommandLine.Parse(os.Args[1:]) } // Parsed reports whether the command-line flags have been parsed. func () bool { return CommandLine.Parsed() } // CommandLine is the default set of command-line flags, parsed from os.Args. // The top-level functions such as BoolVar, Arg, and so on are wrappers for the // methods of CommandLine. var CommandLine = NewFlagSet(os.Args[0], ExitOnError) func init() { // Override generic FlagSet default Usage with call to global Usage. // Note: This is not CommandLine.Usage = Usage, // because we want any eventual call to use any updated value of Usage, // not the value it has when this line is run. CommandLine.Usage = commandLineUsage } func commandLineUsage() { Usage() } // NewFlagSet returns a new, empty flag set with the specified name and // error handling property. If the name is not empty, it will be printed // in the default usage message and in error messages. func ( string, ErrorHandling) *FlagSet { := &FlagSet{ name: , errorHandling: , } .Usage = .defaultUsage return } // Init sets the name and error handling property for a flag set. // By default, the zero FlagSet uses an empty name and the // ContinueOnError error handling policy. func ( *FlagSet) ( string, ErrorHandling) { .name = .errorHandling = }