// 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 pflag is a drop-in replacement for Go's flag package, implementingPOSIX/GNU-style --flags.pflag is compatible with the GNU extensions to the POSIX recommendationsfor command-line options. Seehttp://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.htmlUsage:pflag is a drop-in replacement of Go's native flag package. If you importpflag under the name "flag" then all code should continue to functionwith no changes. import flag "github.com/spf13/pflag"There is one exception to this: if you directly instantiate the Flag structthere is one more field "Shorthand" that you will need to set.Most code never instantiates this struct directly, and instead usesfunctions such as String(), BoolVar(), and Var(), and is thereforeunaffected.Define flags using flag.String(), Bool(), Int(), etc.This declares an integer flag, -flagname, stored in the pointer ip, with type *int. 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 (withpointer 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 after the flag are available as theslice flag.Args() or individually as flag.Arg(i).The arguments are indexed from 0 through flag.NArg()-1.The pflag package also defines some new functions that are not in flag,that give one-letter shorthands for flags. You can use these by appending'P' to the name of any function that defines a flag. var ip = flag.IntP("flagname", "f", 1234, "help message") var flagvar bool func init() { flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") } flag.VarP(&flagval, "varname", "v", "help message")Shorthand letters can be used with single dashes on the command line.Boolean shorthand flags can be combined with other shorthand flags.Command line flag syntax: --flag // boolean flags only --flag=xUnlike the flag package, a single dash before an option means somethingdifferent than a double dash. Single dashes signify a series of shorthandletters for flags. All but the last shorthand letter must be boolean flags. // boolean flags -f -abc // non-boolean flags -n 1234 -Ifile // mixed -abcs "hello" -abcn1234Flag parsing stops after the terminator "--". Unlike the flag package,flags can be interspersed with arguments anywhere on the command linebefore this terminator.Integer flags accept 1234, 0664, 0x1234 and may be negative.Boolean flags (in their long form) accept 1, 0, 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 bytop-level functions. The FlagSet type allows one to defineindependent sets of flags, such as to implement subcommandsin a command-line interface. The methods of FlagSet areanalogous to the top-level functions for the command-lineflag set.*/
package pflagimport (goflag)// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.varErrHelp = errors.New("pflag: help requested")// ErrorHandling defines how to handle flag parsing errors.typeErrorHandlingintconst (// ContinueOnError will return an err from Parse() if an error is foundContinueOnErrorErrorHandling = iota// ExitOnError will call os.Exit(2) if an error is found when parsingExitOnError// PanicOnError will panic() if an error is found when parsing flagsPanicOnError)// ParseErrorsWhitelist defines the parsing errors that can be ignoredtypeParseErrorsWhiteliststruct {// UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags UnknownFlags bool}// NormalizedName is a flag name that has been normalized according to rules// for the FlagSet (e.g. making '-' and '_' equivalent).typeNormalizedNamestring// A FlagSet represents a set of defined flags.typeFlagSetstruct {// 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()// SortFlags is used to indicate, if user wants to have sorted flags in // help/usage messages. SortFlags bool// ParseErrorsWhitelist is used to configure a whitelist of errors ParseErrorsWhitelist ParseErrorsWhitelist name string parsed bool actual map[NormalizedName]*Flag orderedActual []*Flag sortedActual []*Flag formal map[NormalizedName]*Flag orderedFormal []*Flag sortedFormal []*Flag shorthands map[byte]*Flag args []string// arguments after flags argsLenAtDash int// len(args) when a '--' was located when parsing, or -1 if no -- errorHandling ErrorHandling output io.Writer// nil means stderr; use Output() accessor interspersed bool// allow interspersed option/non-option args normalizeNameFunc func(f *FlagSet, name string) NormalizedName addedGoFlagSets []*goflag.FlagSet}// A Flag represents the state of a flag.typeFlagstruct { Name string// name as it appears on command line Shorthand string// one-letter abbreviated flag Usage string// help message Value Value// value as set DefValue string// default value (as text); for usage message Changed bool// If the user set the value (or if left to default) NoOptDefVal string// default value (as text); if the flag is on the command line without any options Deprecated string// If this flag is deprecated, this string is the new or now thing to use Hidden bool// used by cobra.Command to allow flags to be hidden from help/usage text ShorthandDeprecated string// If the shorthand of this flag is deprecated, this string is the new or now thing to use Annotations map[string][]string// used by cobra.Command bash autocomple code}// Value is the interface to the dynamic value stored in a flag.// (The default value is represented as a string.)typeValueinterface {String() stringSet(string) errorType() string}// SliceValue is a secondary interface to all flags which hold a list// of values. This allows full control over the value of list flags,// and avoids complicated marshalling and unmarshalling to csv.typeSliceValueinterface {// Append adds the specified value to the end of the flag value list.Append(string) error// Replace will fully overwrite any data currently in the flag value list.Replace([]string) error// GetSlice returns the flag value list as an array of strings.GetSlice() []string}// sortFlags returns the flags as a slice in lexicographical sorted order.func sortFlags( map[NormalizedName]*Flag) []*Flag { := make(sort.StringSlice, len()) := 0for := range { [] = string() ++ } .Sort() := make([]*Flag, len())for , := range { [] = [NormalizedName()] }return}// SetNormalizeFunc allows you to add a function which can translate flag names.// Flags added to the FlagSet will be translated and then when anything tries to// look up the flag that will also be translated. So it would be possible to create// a flag named "getURL" and have it translated to "geturl". A user could then pass// "--getUrl" which may also be translated to "geturl" and everything will work.func ( *FlagSet) ( func( *FlagSet, string) NormalizedName) { .normalizeNameFunc = .sortedFormal = .sortedFormal[:0]for , := range .formal { := .normalizeFlagName(.Name)if == {continue } .Name = string()delete(.formal, ) .formal[] = if , := .actual[]; {delete(.actual, ) .actual[] = } }}// GetNormalizeFunc returns the previously set NormalizeFunc of a function which// does no translation, if not set previously.func ( *FlagSet) () func( *FlagSet, string) NormalizedName {if .normalizeNameFunc != nil {return .normalizeNameFunc }returnfunc( *FlagSet, string) NormalizedName { returnNormalizedName() }}func ( *FlagSet) ( string) NormalizedName { := .GetNormalizeFunc()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 {returnos.Stderr }return .output}// Name returns the name of the flag set.func ( *FlagSet) () string {return .name}// 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 or// in primordial order if f.SortFlags is false, calling fn for each.// It visits all flags, even those not set.func ( *FlagSet) ( func(*Flag)) {iflen(.formal) == 0 {return }var []*Flagif .SortFlags {iflen(.formal) != len(.sortedFormal) { .sortedFormal = sortFlags(.formal) } = .sortedFormal } else { = .orderedFormal }for , := range { () }}// HasFlags returns a bool to indicate if the FlagSet has any flags defined.func ( *FlagSet) () bool {returnlen(.formal) > 0}// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags// that are not hidden.func ( *FlagSet) () bool {for , := range .formal {if !.Hidden {returntrue } }returnfalse}// VisitAll visits the command-line flags in lexicographical order or// in primordial order if f.SortFlags is false, calling fn for each.// It visits all flags, even those not set.func ( func(*Flag)) {CommandLine.VisitAll()}// Visit visits the flags in lexicographical order or// in primordial order if f.SortFlags is false, calling fn for each.// It visits only those flags that have been set.func ( *FlagSet) ( func(*Flag)) {iflen(.actual) == 0 {return }var []*Flagif .SortFlags {iflen(.actual) != len(.sortedActual) { .sortedActual = sortFlags(.actual) } = .sortedActual } else { = .orderedActual }for , := range { () }}// Visit visits the command-line flags in lexicographical order or// in primordial order if f.SortFlags is false, 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 .lookup(.normalizeFlagName())}// ShorthandLookup returns the Flag structure of the short handed flag,// returning nil if none exists.// It panics, if len(name) > 1.func ( *FlagSet) ( string) *Flag {if == "" {returnnil }iflen() > 1 { := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", )fmt.Fprintf(.Output(), )panic() } := [0]return .shorthands[]}// lookup returns the Flag structure of the named flag, returning nil if none exists.func ( *FlagSet) ( NormalizedName) *Flag {return .formal[]}// func to return a given type for a given flag namefunc ( *FlagSet) ( string, string, func( string) (interface{}, error)) (interface{}, error) { := .Lookup()if == nil { := fmt.Errorf("flag accessed but not defined: %s", )returnnil, }if .Value.Type() != { := fmt.Errorf("trying to get %s value of flag of type %s", , .Value.Type())returnnil, } := .Value.String() , := ()if != nil {returnnil, }return , nil}// ArgsLenAtDash will return the length of f.Args at the moment when a -- was// found during arg parsing. This allows your program to know which args were// before the -- and which came after.func ( *FlagSet) () int {return .argsLenAtDash}// MarkDeprecated indicated that a flag is deprecated in your program. It will// continue to function but will not show up in help or usage messages. Using// this flag will also print the given usageMessage.func ( *FlagSet) ( string, string) error { := .Lookup()if == nil {returnfmt.Errorf("flag %q does not exist", ) }if == "" {returnfmt.Errorf("deprecated message for flag %q must be set", ) } .Deprecated = .Hidden = truereturnnil}// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your// program. It will continue to function but will not show up in help or usage// messages. Using this flag will also print the given usageMessage.func ( *FlagSet) ( string, string) error { := .Lookup()if == nil {returnfmt.Errorf("flag %q does not exist", ) }if == "" {returnfmt.Errorf("deprecated message for flag %q must be set", ) } .ShorthandDeprecated = returnnil}// MarkHidden sets a flag to 'hidden' in your program. It will continue to// function but will not show up in help or usage messages.func ( *FlagSet) ( string) error { := .Lookup()if == nil {returnfmt.Errorf("flag %q does not exist", ) } .Hidden = truereturnnil}// Lookup returns the Flag structure of the named command-line flag,// returning nil if none exists.func ( string) *Flag {returnCommandLine.Lookup()}// ShorthandLookup returns the Flag structure of the short handed flag,// returning nil if none exists.func ( string) *Flag {returnCommandLine.ShorthandLookup()}// Set sets the value of the named flag.func ( *FlagSet) (, string) error { := .normalizeFlagName() , := .formal[]if ! {returnfmt.Errorf("no such flag -%v", ) } := .Value.Set()if != nil {varstringif .Shorthand != "" && .ShorthandDeprecated == "" { = fmt.Sprintf("-%s, --%s", .Shorthand, .Name) } else { = fmt.Sprintf("--%s", .Name) }returnfmt.Errorf("invalid argument %q for %q flag: %v", , , ) }if !.Changed {if .actual == nil { .actual = make(map[NormalizedName]*Flag) } .actual[] = .orderedActual = append(.orderedActual, ) .Changed = true }if .Deprecated != "" {fmt.Fprintf(.Output(), "Flag --%s has been deprecated, %s\n", .Name, .Deprecated) }returnnil}// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.// This is sometimes used by spf13/cobra programs which want to generate additional// bash completion information.func ( *FlagSet) (, string, []string) error { := .normalizeFlagName() , := .formal[]if ! {returnfmt.Errorf("no such flag -%v", ) }if .Annotations == nil { .Annotations = map[string][]string{} } .Annotations[] = returnnil}// Changed returns true if the flag was explicitly set during Parse() and false// otherwisefunc ( *FlagSet) ( string) bool { := .Lookup()// If a flag doesn't exist, it wasn't changed....if == nil {returnfalse }return .Changed}// Set sets the value of the named command-line flag.func (, string) error {returnCommandLine.Set(, )}// PrintDefaults prints, to standard error unless configured// otherwise, the default values of all defined flags in the set.func ( *FlagSet) () { := .FlagUsages()fmt.Fprint(.Output(), )}// defaultIsZeroValue returns true if the default value for this flag represents// a zero value.func ( *Flag) () bool {switch .Value.(type) {caseboolFlag:return .DefValue == "false"case *durationValue:// Beginning in Go 1.7, duration zero values are "0s"return .DefValue == "0" || .DefValue == "0s"case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:return .DefValue == "0"case *stringValue:return .DefValue == ""case *ipValue, *ipMaskValue, *ipNetValue:return .DefValue == "<nil>"case *intSliceValue, *stringSliceValue, *stringArrayValue:return .DefValue == "[]"default:switch .Value.String() {case"false":returntruecase"<nil>":returntruecase"":returntruecase"0":returntrue }returnfalse }}// 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. = .Usagefor := 0; < len(); ++ {if [] == '`' {for := + 1; < len(); ++ {if [] == '`' { = [+1 : ] = [:] + + [+1:]return , } }break// Only one back quote; use type name. } } = .Value.Type()switch {case"bool": = ""case"float64": = "float"case"int64": = "int"case"uint64": = "uint"case"stringSlice": = "strings"case"intSlice": = "ints"case"uintSlice": = "uints"case"boolSlice": = "bools" }return}// Splits the string `s` on whitespace into an initial substring up to// `i` runes in length and the remainder. Will go `slop` over `i` if// that encompasses the entire string (which allows the caller to// avoid short orphan words on the final line).func wrapN(, int, string) (string, string) {if + > len() {return , "" } := strings.LastIndexAny([:], " \t\n")if <= 0 {return , "" } := strings.LastIndex([:], "\n")if > 0 && < {return [:], [+1:] }return [:], [+1:]}// Wraps the string `s` to a maximum width `w` with leading indent// `i`. The first line is not indented (this is assumed to be done by// caller). Pass `w` == 0 to do no wrappingfunc wrap(, int, string) string {if == 0 {returnstrings.Replace(, "\n", "\n"+strings.Repeat(" ", ), -1) }// space between indent i and end of line width w into which // we should wrap the text. := - var , string// Not enough space for sensible wrapping. Wrap as a block on // the next line instead.if < 24 { = 16 = - += "\n" + strings.Repeat(" ", ) }// If still not enough space then don't even try to wrap.if < 24 {returnstrings.Replace(, "\n", , -1) }// Try to avoid short orphan words on the final line, by // allowing wrapN to go a bit over if that would fit in the // remainder of the line. := 5 = - // Handle first line, which is indented by the caller (or the // special case above) , = wrapN(, , ) = + strings.Replace(, "\n", "\n"+strings.Repeat(" ", ), -1)// Now wrap the restfor != "" {varstring , = wrapN(, , ) = + "\n" + strings.Repeat(" ", ) + strings.Replace(, "\n", "\n"+strings.Repeat(" ", ), -1) }return}// FlagUsagesWrapped returns a string containing the usage information// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no// wrapping)func ( *FlagSet) ( int) string { := new(bytes.Buffer) := make([]string, 0, len(.formal)) := 0 .VisitAll(func( *Flag) {if .Hidden {return } := ""if .Shorthand != "" && .ShorthandDeprecated == "" { = fmt.Sprintf(" -%s, --%s", .Shorthand, .Name) } else { = fmt.Sprintf(" --%s", .Name) } , := UnquoteUsage()if != "" { += " " + }if .NoOptDefVal != "" {switch .Value.Type() {case"string": += fmt.Sprintf("[=\"%s\"]", .NoOptDefVal)case"bool":if .NoOptDefVal != "true" { += fmt.Sprintf("[=%s]", .NoOptDefVal) }case"count":if .NoOptDefVal != "+1" { += fmt.Sprintf("[=%s]", .NoOptDefVal) }default: += fmt.Sprintf("[=%s]", .NoOptDefVal) } }// This special character will be replaced with spacing once the // correct alignment is calculated += "\x00"iflen() > { = len() } += if !.defaultIsZeroValue() {if .Value.Type() == "string" { += fmt.Sprintf(" (default %q)", .DefValue) } else { += fmt.Sprintf(" (default %s)", .DefValue) } }iflen(.Deprecated) != 0 { += fmt.Sprintf(" (DEPRECATED: %s)", .Deprecated) } = append(, ) })for , := range { := strings.Index(, "\x00") := strings.Repeat(" ", -)// maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidxfmt.Fprintln(, [:], , wrap(+2, , [+1:])) }return .String()}// FlagUsages returns a string containing the usage information for all flags in// the FlagSetfunc ( *FlagSet) () string {return .FlagUsagesWrapped(0)}// PrintDefaults prints to standard error the default values of all defined command-line flags.func () {CommandLine.PrintDefaults()}// defaultUsage is the default function to print a usage message.func defaultUsage( *FlagSet) {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 to standard error a usage message documenting all defined command-line 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.varUsage = func() {fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])PrintDefaults()}// NFlag returns the number of flags that have been set.func ( *FlagSet) () int { returnlen(.actual) }// NFlag returns the number of command-line flags that have been set.func () int { returnlen(CommandLine.actual) }// Arg returns the i'th argument. Arg(0) is the first remaining argument// after flags have been processed.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.func ( int) string {returnCommandLine.Arg()}// NArg is the number of arguments remaining after flags have been processed.func ( *FlagSet) () int { returnlen(.args) }// NArg is the number of arguments remaining after flags have been processed.func () int { returnlen(CommandLine.args) }// Args returns the non-flag arguments.func ( *FlagSet) () []string { return .args }// Args returns the non-flag command-line arguments.func () []string { returnCommandLine.args }// 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) { .VarP(, , "", )}// VarPF is like VarP, but returns the flag createdfunc ( *FlagSet) ( Value, , , string) *Flag {// Remember the default value as a string; it won't change. := &Flag{Name: ,Shorthand: ,Usage: ,Value: ,DefValue: .String(), } .AddFlag()return}// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.func ( *FlagSet) ( Value, , , string) { .VarPF(, , , )}// AddFlag will add the flag to the FlagSetfunc ( *FlagSet) ( *Flag) { := .normalizeFlagName(.Name) , := .formal[]if { := fmt.Sprintf("%s flag redefined: %s", .name, .Name)fmt.Fprintln(.Output(), )panic() // Happens only if flags are declared with identical names }if .formal == nil { .formal = make(map[NormalizedName]*Flag) } .Name = string() .formal[] = .orderedFormal = append(.orderedFormal, )if .Shorthand == "" {return }iflen(.Shorthand) > 1 { := fmt.Sprintf("%q shorthand is more than one ASCII character", .Shorthand)fmt.Fprintf(.Output(), )panic() }if .shorthands == nil { .shorthands = make(map[byte]*Flag) } := .Shorthand[0] , := .shorthands[]if { := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", , .name, .Name)fmt.Fprintf(.Output(), )panic() } .shorthands[] = }// AddFlagSet adds one FlagSet to another. If a flag is already present in f// the flag from newSet will be ignored.func ( *FlagSet) ( *FlagSet) {if == nil {return } .VisitAll(func( *Flag) {if .Lookup(.Name) == nil { .AddFlag() } })}// 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.VarP(, , "", )}// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.func ( Value, , , string) {CommandLine.VarP(, , , )}// failf prints to standard error a formatted error and usage message and// returns the error.func ( *FlagSet) ( string, ...interface{}) error { := fmt.Errorf(, ...)if .errorHandling != ContinueOnError {fmt.Fprintln(.Output(), ) .usage() }return}// usage calls the Usage method for the flag set, or the usage function if// the flag set is CommandLine.func ( *FlagSet) () {if == CommandLine {Usage() } elseif .Usage == nil {defaultUsage() } else { .Usage() }}//--unknown (args will be empty)//--unknown --next-flag ... (args will be --next-flag ...)//--unknown arg ... (args will be arg ...)func stripUnknownFlagValue( []string) []string {iflen() == 0 {//--unknownreturn } := [0]iflen() > 0 && [0] == '-' {//--unknown --next-flag ...return }//--unknown arg ... (args will be arg ...)iflen() > 1 {return [1:] }returnnil}func ( *FlagSet) ( string, []string, parseFunc) ( []string, error) { = := [2:]iflen() == 0 || [0] == '-' || [0] == '=' { = .failf("bad flag syntax: %s", )return } := strings.SplitN(, "=", 2) = [0] , := .formal[.normalizeFlagName()]if ! {switch {case == "help": .usage()return , ErrHelpcase .ParseErrorsWhitelist.UnknownFlags:// --unknown=unknownval arg ... // we do not want to lose arg in this caseiflen() >= 2 {return , nil }returnstripUnknownFlagValue(), nildefault: = .failf("unknown flag: --%s", )return } }varstringiflen() == 2 {// '--flag=arg' = [1] } elseif .NoOptDefVal != "" {// '--flag' (arg was optional) = .NoOptDefVal } elseiflen() > 0 {// '--flag arg' = [0] = [1:] } else {// '--flag' (arg was required) = .failf("flag needs an argument: %s", )return } = (, )if != nil { .failf(.Error()) }return}func ( *FlagSet) ( string, []string, parseFunc) ( string, []string, error) { = ifstrings.HasPrefix(, "test.") {return } = [1:] := [0] , := .shorthands[]if ! {switch {case == 'h': .usage() = ErrHelpreturncase .ParseErrorsWhitelist.UnknownFlags:// '-f=arg arg ...' // we do not want to lose arg in this caseiflen() > 2 && [1] == '=' { = ""return } = stripUnknownFlagValue()returndefault: = .failf("unknown shorthand flag: %q in -%s", , )return } }varstringiflen() > 2 && [1] == '=' {// '-f=arg' = [2:] = "" } elseif .NoOptDefVal != "" {// '-f' (arg was optional) = .NoOptDefVal } elseiflen() > 1 {// '-farg' = [1:] = "" } elseiflen() > 0 {// '-f arg' = [0] = [1:] } else {// '-f' (arg was required) = .failf("flag needs an argument: %q in -%s", , )return }if .ShorthandDeprecated != "" {fmt.Fprintf(.Output(), "Flag shorthand -%s has been deprecated, %s\n", .Shorthand, .ShorthandDeprecated) } = (, )if != nil { .failf(.Error()) }return}func ( *FlagSet) ( string, []string, parseFunc) ( []string, error) { = := [1:]// "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").forlen() > 0 { , , = .parseSingleShortArg(, , )if != nil {return } }return}func ( *FlagSet) ( []string, parseFunc) ( error) {forlen() > 0 { := [0] = [1:]iflen() == 0 || [0] != '-' || len() == 1 {if !.interspersed { .args = append(.args, ) .args = append(.args, ...)returnnil } .args = append(.args, )continue }if [1] == '-' {iflen() == 2 { // "--" terminates the flags .argsLenAtDash = len(.args) .args = append(.args, ...)break } , = .parseLongArg(, , ) } else { , = .parseShortArg(, , ) }if != nil {return } }return}// 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 was set but not defined.func ( *FlagSet) ( []string) error {if .addedGoFlagSets != nil {for , := range .addedGoFlagSets { .Parse(nil) } } .parsed = trueiflen() < 0 {returnnil } .args = make([]string, 0, len()) := func( *Flag, string) error {return .Set(.Name, ) } := .parseArgs(, )if != nil {switch .errorHandling {caseContinueOnError:returncaseExitOnError:fmt.Println()os.Exit(2)casePanicOnError:panic() } }returnnil}type parseFunc func(flag *Flag, value string) error// ParseAll parses flag definitions from the argument list, which should not// include the command name. The arguments for fn are flag and value. 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 was set// but not defined.func ( *FlagSet) ( []string, func( *Flag, string) error) error { .parsed = true .args = make([]string, 0, len()) := .parseArgs(, )if != nil {switch .errorHandling {caseContinueOnError:returncaseExitOnError:os.Exit(2)casePanicOnError:panic() } }returnnil}// 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:])}// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.// The arguments for fn are flag and value. Must be called after all flags are// defined and before flags are accessed by the program.func ( func( *Flag, string) error) {// Ignore errors; CommandLine is set for ExitOnError.CommandLine.ParseAll(os.Args[1:], )}// SetInterspersed sets whether to support interspersed option/non-option arguments.func ( bool) {CommandLine.SetInterspersed()}// Parsed returns true if the command-line flags have been parsed.func () bool {returnCommandLine.Parsed()}// CommandLine is the default set of command-line flags, parsed from os.Args.varCommandLine = NewFlagSet(os.Args[0], ExitOnError)// NewFlagSet returns a new, empty flag set with the specified name,// error handling property and SortFlags set to true.func ( string, ErrorHandling) *FlagSet { := &FlagSet{name: ,errorHandling: ,argsLenAtDash: -1,interspersed: true,SortFlags: true, }return}// SetInterspersed sets whether to support interspersed option/non-option arguments.func ( *FlagSet) ( bool) { .interspersed = }// 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 = .argsLenAtDash = -1}
The pages are generated with Goldsv0.8.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.