flag源码

go/src/flag/flag.go

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
}

func (f *FlagSet) Arg(i int) string {
        if i < 0 || i >= len(f.args) {
                return ""
        }
        return f.args[i]
}

// 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) }

// 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 (f *FlagSet) Arg(i int) string {
        if i < 0 || i >= len(f.args) {
                return ""
        }
        return f.args[i]
}

// Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (f *FlagSet) Lookup(name string) *Flag {
        return f.formal[name]
}



func Parse() {
        // Ignore errors; CommandLine is set for ExitOnError.
        CommandLine.Parse(os.Args[1:])
}

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

// 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 NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
        f := &FlagSet{
                name:          name,
                errorHandling: errorHandling,
        }
        f.Usage = f.defaultUsage
        return f
}

 

posted @ 2021-02-01 16:58  牧 天  阅读(134)  评论(0)    收藏  举报