podman
1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5/*
6Package pflag is a drop-in replacement for Go's flag package, implementing
7POSIX/GNU-style --flags.
8
9pflag is compatible with the GNU extensions to the POSIX recommendations
10for command-line options. See
11http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
12
13Usage:
14
15pflag is a drop-in replacement of Go's native flag package. If you import
16pflag under the name "flag" then all code should continue to function
17with no changes.
18
19import flag "github.com/spf13/pflag"
20
21There is one exception to this: if you directly instantiate the Flag struct
22there is one more field "Shorthand" that you will need to set.
23Most code never instantiates this struct directly, and instead uses
24functions such as String(), BoolVar(), and Var(), and is therefore
25unaffected.
26
27Define flags using flag.String(), Bool(), Int(), etc.
28
29This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
30var ip = flag.Int("flagname", 1234, "help message for flagname")
31If you like, you can bind the flag to a variable using the Var() functions.
32var flagvar int
33func init() {
34flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
35}
36Or you can create custom flags that satisfy the Value interface (with
37pointer receivers) and couple them to flag parsing by
38flag.Var(&flagVal, "name", "help message for flagname")
39For such flags, the default value is just the initial value of the variable.
40
41After all flags are defined, call
42flag.Parse()
43to parse the command line into the defined flags.
44
45Flags may then be used directly. If you're using the flags themselves,
46they are all pointers; if you bind to variables, they're values.
47fmt.Println("ip has value ", *ip)
48fmt.Println("flagvar has value ", flagvar)
49
50After parsing, the arguments after the flag are available as the
51slice flag.Args() or individually as flag.Arg(i).
52The arguments are indexed from 0 through flag.NArg()-1.
53
54The pflag package also defines some new functions that are not in flag,
55that give one-letter shorthands for flags. You can use these by appending
56'P' to the name of any function that defines a flag.
57var ip = flag.IntP("flagname", "f", 1234, "help message")
58var flagvar bool
59func init() {
60flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
61}
62flag.VarP(&flagval, "varname", "v", "help message")
63Shorthand letters can be used with single dashes on the command line.
64Boolean shorthand flags can be combined with other shorthand flags.
65
66Command line flag syntax:
67--flag // boolean flags only
68--flag=x
69
70Unlike the flag package, a single dash before an option means something
71different than a double dash. Single dashes signify a series of shorthand
72letters for flags. All but the last shorthand letter must be boolean flags.
73// boolean flags
74-f
75-abc
76// non-boolean flags
77-n 1234
78-Ifile
79// mixed
80-abcs "hello"
81-abcn1234
82
83Flag parsing stops after the terminator "--". Unlike the flag package,
84flags can be interspersed with arguments anywhere on the command line
85before this terminator.
86
87Integer flags accept 1234, 0664, 0x1234 and may be negative.
88Boolean flags (in their long form) accept 1, 0, t, f, true, false,
89TRUE, FALSE, True, False.
90Duration flags accept any input valid for time.ParseDuration.
91
92The default set of command-line flags is controlled by
93top-level functions. The FlagSet type allows one to define
94independent sets of flags, such as to implement subcommands
95in a command-line interface. The methods of FlagSet are
96analogous to the top-level functions for the command-line
97flag set.
98*/
99package pflag100
101import (102"bytes"103"errors"104goflag "flag"105"fmt"106"io"107"os"108"sort"109"strings"110)
111
112// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
113var ErrHelp = errors.New("pflag: help requested")114
115// ErrorHandling defines how to handle flag parsing errors.
116type ErrorHandling int117
118const (119// ContinueOnError will return an err from Parse() if an error is found120ContinueOnError ErrorHandling = iota121// ExitOnError will call os.Exit(2) if an error is found when parsing122ExitOnError
123// PanicOnError will panic() if an error is found when parsing flags124PanicOnError
125)
126
127// ParseErrorsWhitelist defines the parsing errors that can be ignored
128type ParseErrorsWhitelist struct {129// UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags130UnknownFlags bool131}
132
133// NormalizedName is a flag name that has been normalized according to rules
134// for the FlagSet (e.g. making '-' and '_' equivalent).
135type NormalizedName string136
137// A FlagSet represents a set of defined flags.
138type FlagSet struct {139// Usage is the function called when an error occurs while parsing flags.140// The field is a function (not a method) that may be changed to point to141// a custom error handler.142Usage func()143
144// SortFlags is used to indicate, if user wants to have sorted flags in145// help/usage messages.146SortFlags bool147
148// ParseErrorsWhitelist is used to configure a whitelist of errors149ParseErrorsWhitelist ParseErrorsWhitelist
150
151name string152parsed bool153actual map[NormalizedName]*Flag154orderedActual []*Flag155sortedActual []*Flag156formal map[NormalizedName]*Flag157orderedFormal []*Flag158sortedFormal []*Flag159shorthands map[byte]*Flag160args []string // arguments after flags161argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --162errorHandling ErrorHandling
163output io.Writer // nil means stderr; use out() accessor164interspersed bool // allow interspersed option/non-option args165normalizeNameFunc func(f *FlagSet, name string) NormalizedName166
167addedGoFlagSets []*goflag.FlagSet168}
169
170// A Flag represents the state of a flag.
171type Flag struct {172Name string // name as it appears on command line173Shorthand string // one-letter abbreviated flag174Usage string // help message175Value Value // value as set176DefValue string // default value (as text); for usage message177Changed bool // If the user set the value (or if left to default)178NoOptDefVal string // default value (as text); if the flag is on the command line without any options179Deprecated string // If this flag is deprecated, this string is the new or now thing to use180Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text181ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use182Annotations map[string][]string // used by cobra.Command bash autocomple code183}
184
185// Value is the interface to the dynamic value stored in a flag.
186// (The default value is represented as a string.)
187type Value interface {188String() string189Set(string) error190Type() string191}
192
193// SliceValue is a secondary interface to all flags which hold a list
194// of values. This allows full control over the value of list flags,
195// and avoids complicated marshalling and unmarshalling to csv.
196type SliceValue interface {197// Append adds the specified value to the end of the flag value list.198Append(string) error199// Replace will fully overwrite any data currently in the flag value list.200Replace([]string) error201// GetSlice returns the flag value list as an array of strings.202GetSlice() []string203}
204
205// sortFlags returns the flags as a slice in lexicographical sorted order.
206func sortFlags(flags map[NormalizedName]*Flag) []*Flag {207list := make(sort.StringSlice, len(flags))208i := 0209for k := range flags {210list[i] = string(k)211i++212}213list.Sort()214result := make([]*Flag, len(list))215for i, name := range list {216result[i] = flags[NormalizedName(name)]217}218return result219}
220
221// SetNormalizeFunc allows you to add a function which can translate flag names.
222// Flags added to the FlagSet will be translated and then when anything tries to
223// look up the flag that will also be translated. So it would be possible to create
224// a flag named "getURL" and have it translated to "geturl". A user could then pass
225// "--getUrl" which may also be translated to "geturl" and everything will work.
226func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {227f.normalizeNameFunc = n228f.sortedFormal = f.sortedFormal[:0]229for fname, flag := range f.formal {230nname := f.normalizeFlagName(flag.Name)231if fname == nname {232continue233}234flag.Name = string(nname)235delete(f.formal, fname)236f.formal[nname] = flag237if _, set := f.actual[fname]; set {238delete(f.actual, fname)239f.actual[nname] = flag240}241}242}
243
244// GetNormalizeFunc returns the previously set NormalizeFunc of a function which
245// does no translation, if not set previously.
246func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {247if f.normalizeNameFunc != nil {248return f.normalizeNameFunc249}250return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }251}
252
253func (f *FlagSet) normalizeFlagName(name string) NormalizedName {254n := f.GetNormalizeFunc()255return n(f, name)256}
257
258func (f *FlagSet) out() io.Writer {259if f.output == nil {260return os.Stderr261}262return f.output263}
264
265// SetOutput sets the destination for usage and error messages.
266// If output is nil, os.Stderr is used.
267func (f *FlagSet) SetOutput(output io.Writer) {268f.output = output269}
270
271// VisitAll visits the flags in lexicographical order or
272// in primordial order if f.SortFlags is false, calling fn for each.
273// It visits all flags, even those not set.
274func (f *FlagSet) VisitAll(fn func(*Flag)) {275if len(f.formal) == 0 {276return277}278
279var flags []*Flag280if f.SortFlags {281if len(f.formal) != len(f.sortedFormal) {282f.sortedFormal = sortFlags(f.formal)283}284flags = f.sortedFormal285} else {286flags = f.orderedFormal287}288
289for _, flag := range flags {290fn(flag)291}292}
293
294// HasFlags returns a bool to indicate if the FlagSet has any flags defined.
295func (f *FlagSet) HasFlags() bool {296return len(f.formal) > 0297}
298
299// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
300// that are not hidden.
301func (f *FlagSet) HasAvailableFlags() bool {302for _, flag := range f.formal {303if !flag.Hidden {304return true305}306}307return false308}
309
310// VisitAll visits the command-line flags in lexicographical order or
311// in primordial order if f.SortFlags is false, calling fn for each.
312// It visits all flags, even those not set.
313func VisitAll(fn func(*Flag)) {314CommandLine.VisitAll(fn)315}
316
317// Visit visits the flags in lexicographical order or
318// in primordial order if f.SortFlags is false, calling fn for each.
319// It visits only those flags that have been set.
320func (f *FlagSet) Visit(fn func(*Flag)) {321if len(f.actual) == 0 {322return323}324
325var flags []*Flag326if f.SortFlags {327if len(f.actual) != len(f.sortedActual) {328f.sortedActual = sortFlags(f.actual)329}330flags = f.sortedActual331} else {332flags = f.orderedActual333}334
335for _, flag := range flags {336fn(flag)337}338}
339
340// Visit visits the command-line flags in lexicographical order or
341// in primordial order if f.SortFlags is false, calling fn for each.
342// It visits only those flags that have been set.
343func Visit(fn func(*Flag)) {344CommandLine.Visit(fn)345}
346
347// Lookup returns the Flag structure of the named flag, returning nil if none exists.
348func (f *FlagSet) Lookup(name string) *Flag {349return f.lookup(f.normalizeFlagName(name))350}
351
352// ShorthandLookup returns the Flag structure of the short handed flag,
353// returning nil if none exists.
354// It panics, if len(name) > 1.
355func (f *FlagSet) ShorthandLookup(name string) *Flag {356if name == "" {357return nil358}359if len(name) > 1 {360msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)361fmt.Fprintf(f.out(), msg)362panic(msg)363}364c := name[0]365return f.shorthands[c]366}
367
368// lookup returns the Flag structure of the named flag, returning nil if none exists.
369func (f *FlagSet) lookup(name NormalizedName) *Flag {370return f.formal[name]371}
372
373// func to return a given type for a given flag name
374func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {375flag := f.Lookup(name)376if flag == nil {377err := fmt.Errorf("flag accessed but not defined: %s", name)378return nil, err379}380
381if flag.Value.Type() != ftype {382err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())383return nil, err384}385
386sval := flag.Value.String()387result, err := convFunc(sval)388if err != nil {389return nil, err390}391return result, nil392}
393
394// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
395// found during arg parsing. This allows your program to know which args were
396// before the -- and which came after.
397func (f *FlagSet) ArgsLenAtDash() int {398return f.argsLenAtDash399}
400
401// MarkDeprecated indicated that a flag is deprecated in your program. It will
402// continue to function but will not show up in help or usage messages. Using
403// this flag will also print the given usageMessage.
404func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {405flag := f.Lookup(name)406if flag == nil {407return fmt.Errorf("flag %q does not exist", name)408}409if usageMessage == "" {410return fmt.Errorf("deprecated message for flag %q must be set", name)411}412flag.Deprecated = usageMessage413flag.Hidden = true414return nil415}
416
417// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
418// program. It will continue to function but will not show up in help or usage
419// messages. Using this flag will also print the given usageMessage.
420func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {421flag := f.Lookup(name)422if flag == nil {423return fmt.Errorf("flag %q does not exist", name)424}425if usageMessage == "" {426return fmt.Errorf("deprecated message for flag %q must be set", name)427}428flag.ShorthandDeprecated = usageMessage429return nil430}
431
432// MarkHidden sets a flag to 'hidden' in your program. It will continue to
433// function but will not show up in help or usage messages.
434func (f *FlagSet) MarkHidden(name string) error {435flag := f.Lookup(name)436if flag == nil {437return fmt.Errorf("flag %q does not exist", name)438}439flag.Hidden = true440return nil441}
442
443// Lookup returns the Flag structure of the named command-line flag,
444// returning nil if none exists.
445func Lookup(name string) *Flag {446return CommandLine.Lookup(name)447}
448
449// ShorthandLookup returns the Flag structure of the short handed flag,
450// returning nil if none exists.
451func ShorthandLookup(name string) *Flag {452return CommandLine.ShorthandLookup(name)453}
454
455// Set sets the value of the named flag.
456func (f *FlagSet) Set(name, value string) error {457normalName := f.normalizeFlagName(name)458flag, ok := f.formal[normalName]459if !ok {460return fmt.Errorf("no such flag -%v", name)461}462
463err := flag.Value.Set(value)464if err != nil {465var flagName string466if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {467flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name)468} else {469flagName = fmt.Sprintf("--%s", flag.Name)470}471return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)472}473
474if !flag.Changed {475if f.actual == nil {476f.actual = make(map[NormalizedName]*Flag)477}478f.actual[normalName] = flag479f.orderedActual = append(f.orderedActual, flag)480
481flag.Changed = true482}483
484if flag.Deprecated != "" {485fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)486}487return nil488}
489
490// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
491// This is sometimes used by spf13/cobra programs which want to generate additional
492// bash completion information.
493func (f *FlagSet) SetAnnotation(name, key string, values []string) error {494normalName := f.normalizeFlagName(name)495flag, ok := f.formal[normalName]496if !ok {497return fmt.Errorf("no such flag -%v", name)498}499if flag.Annotations == nil {500flag.Annotations = map[string][]string{}501}502flag.Annotations[key] = values503return nil504}
505
506// Changed returns true if the flag was explicitly set during Parse() and false
507// otherwise
508func (f *FlagSet) Changed(name string) bool {509flag := f.Lookup(name)510// If a flag doesn't exist, it wasn't changed....511if flag == nil {512return false513}514return flag.Changed515}
516
517// Set sets the value of the named command-line flag.
518func Set(name, value string) error {519return CommandLine.Set(name, value)520}
521
522// PrintDefaults prints, to standard error unless configured
523// otherwise, the default values of all defined flags in the set.
524func (f *FlagSet) PrintDefaults() {525usages := f.FlagUsages()526fmt.Fprint(f.out(), usages)527}
528
529// defaultIsZeroValue returns true if the default value for this flag represents
530// a zero value.
531func (f *Flag) defaultIsZeroValue() bool {532switch f.Value.(type) {533case boolFlag:534return f.DefValue == "false"535case *durationValue:536// Beginning in Go 1.7, duration zero values are "0s"537return f.DefValue == "0" || f.DefValue == "0s"538case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:539return f.DefValue == "0"540case *stringValue:541return f.DefValue == ""542case *ipValue, *ipMaskValue, *ipNetValue:543return f.DefValue == "<nil>"544case *intSliceValue, *stringSliceValue, *stringArrayValue:545return f.DefValue == "[]"546default:547switch f.Value.String() {548case "false":549return true550case "<nil>":551return true552case "":553return true554case "0":555return true556}557return false558}559}
560
561// UnquoteUsage extracts a back-quoted name from the usage
562// string for a flag and returns it and the un-quoted usage.
563// Given "a `name` to show" it returns ("name", "a name to show").
564// If there are no back quotes, the name is an educated guess of the
565// type of the flag's value, or the empty string if the flag is boolean.
566func UnquoteUsage(flag *Flag) (name string, usage string) {567// Look for a back-quoted name, but avoid the strings package.568usage = flag.Usage569for i := 0; i < len(usage); i++ {570if usage[i] == '`' {571for j := i + 1; j < len(usage); j++ {572if usage[j] == '`' {573name = usage[i+1 : j]574usage = usage[:i] + name + usage[j+1:]575return name, usage576}577}578break // Only one back quote; use type name.579}580}581
582name = flag.Value.Type()583switch name {584case "bool":585name = ""586case "float64":587name = "float"588case "int64":589name = "int"590case "uint64":591name = "uint"592case "stringSlice":593name = "strings"594case "intSlice":595name = "ints"596case "uintSlice":597name = "uints"598case "boolSlice":599name = "bools"600}601
602return603}
604
605// Splits the string `s` on whitespace into an initial substring up to
606// `i` runes in length and the remainder. Will go `slop` over `i` if
607// that encompasses the entire string (which allows the caller to
608// avoid short orphan words on the final line).
609func wrapN(i, slop int, s string) (string, string) {610if i+slop > len(s) {611return s, ""612}613
614w := strings.LastIndexAny(s[:i], " \t\n")615if w <= 0 {616return s, ""617}618nlPos := strings.LastIndex(s[:i], "\n")619if nlPos > 0 && nlPos < w {620return s[:nlPos], s[nlPos+1:]621}622return s[:w], s[w+1:]623}
624
625// Wraps the string `s` to a maximum width `w` with leading indent
626// `i`. The first line is not indented (this is assumed to be done by
627// caller). Pass `w` == 0 to do no wrapping
628func wrap(i, w int, s string) string {629if w == 0 {630return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)631}632
633// space between indent i and end of line width w into which634// we should wrap the text.635wrap := w - i636
637var r, l string638
639// Not enough space for sensible wrapping. Wrap as a block on640// the next line instead.641if wrap < 24 {642i = 16643wrap = w - i644r += "\n" + strings.Repeat(" ", i)645}646// If still not enough space then don't even try to wrap.647if wrap < 24 {648return strings.Replace(s, "\n", r, -1)649}650
651// Try to avoid short orphan words on the final line, by652// allowing wrapN to go a bit over if that would fit in the653// remainder of the line.654slop := 5655wrap = wrap - slop656
657// Handle first line, which is indented by the caller (or the658// special case above)659l, s = wrapN(wrap, slop, s)660r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)661
662// Now wrap the rest663for s != "" {664var t string665
666t, s = wrapN(wrap, slop, s)667r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)668}669
670return r671
672}
673
674// FlagUsagesWrapped returns a string containing the usage information
675// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
676// wrapping)
677func (f *FlagSet) FlagUsagesWrapped(cols int) string {678buf := new(bytes.Buffer)679
680lines := make([]string, 0, len(f.formal))681
682maxlen := 0683f.VisitAll(func(flag *Flag) {684if flag.Hidden {685return686}687
688line := ""689if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {690line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)691} else {692line = fmt.Sprintf(" --%s", flag.Name)693}694
695varname, usage := UnquoteUsage(flag)696if varname != "" {697line += " " + varname698}699if flag.NoOptDefVal != "" {700switch flag.Value.Type() {701case "string":702line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)703case "bool":704if flag.NoOptDefVal != "true" {705line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)706}707case "count":708if flag.NoOptDefVal != "+1" {709line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)710}711default:712line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)713}714}715
716// This special character will be replaced with spacing once the717// correct alignment is calculated718line += "\x00"719if len(line) > maxlen {720maxlen = len(line)721}722
723line += usage724if !flag.defaultIsZeroValue() {725if flag.Value.Type() == "string" {726line += fmt.Sprintf(" (default %q)", flag.DefValue)727} else {728line += fmt.Sprintf(" (default %s)", flag.DefValue)729}730}731if len(flag.Deprecated) != 0 {732line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)733}734
735lines = append(lines, line)736})737
738for _, line := range lines {739sidx := strings.Index(line, "\x00")740spacing := strings.Repeat(" ", maxlen-sidx)741// maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx742fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))743}744
745return buf.String()746}
747
748// FlagUsages returns a string containing the usage information for all flags in
749// the FlagSet
750func (f *FlagSet) FlagUsages() string {751return f.FlagUsagesWrapped(0)752}
753
754// PrintDefaults prints to standard error the default values of all defined command-line flags.
755func PrintDefaults() {756CommandLine.PrintDefaults()757}
758
759// defaultUsage is the default function to print a usage message.
760func defaultUsage(f *FlagSet) {761fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)762f.PrintDefaults()763}
764
765// NOTE: Usage is not just defaultUsage(CommandLine)
766// because it serves (via godoc flag Usage) as the example
767// for how to write your own usage function.
768
769// Usage prints to standard error a usage message documenting all defined command-line flags.
770// The function is a variable that may be changed to point to a custom function.
771// By default it prints a simple header and calls PrintDefaults; for details about the
772// format of the output and how to control it, see the documentation for PrintDefaults.
773var Usage = func() {774fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])775PrintDefaults()776}
777
778// NFlag returns the number of flags that have been set.
779func (f *FlagSet) NFlag() int { return len(f.actual) }780
781// NFlag returns the number of command-line flags that have been set.
782func NFlag() int { return len(CommandLine.actual) }783
784// Arg returns the i'th argument. Arg(0) is the first remaining argument
785// after flags have been processed.
786func (f *FlagSet) Arg(i int) string {787if i < 0 || i >= len(f.args) {788return ""789}790return f.args[i]791}
792
793// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
794// after flags have been processed.
795func Arg(i int) string {796return CommandLine.Arg(i)797}
798
799// NArg is the number of arguments remaining after flags have been processed.
800func (f *FlagSet) NArg() int { return len(f.args) }801
802// NArg is the number of arguments remaining after flags have been processed.
803func NArg() int { return len(CommandLine.args) }804
805// Args returns the non-flag arguments.
806func (f *FlagSet) Args() []string { return f.args }807
808// Args returns the non-flag command-line arguments.
809func Args() []string { return CommandLine.args }810
811// Var defines a flag with the specified name and usage string. The type and
812// value of the flag are represented by the first argument, of type Value, which
813// typically holds a user-defined implementation of Value. For instance, the
814// caller could create a flag that turns a comma-separated string into a slice
815// of strings by giving the slice the methods of Value; in particular, Set would
816// decompose the comma-separated string into the slice.
817func (f *FlagSet) Var(value Value, name string, usage string) {818f.VarP(value, name, "", usage)819}
820
821// VarPF is like VarP, but returns the flag created
822func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {823// Remember the default value as a string; it won't change.824flag := &Flag{825Name: name,826Shorthand: shorthand,827Usage: usage,828Value: value,829DefValue: value.String(),830}831f.AddFlag(flag)832return flag833}
834
835// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
836func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {837f.VarPF(value, name, shorthand, usage)838}
839
840// AddFlag will add the flag to the FlagSet
841func (f *FlagSet) AddFlag(flag *Flag) {842normalizedFlagName := f.normalizeFlagName(flag.Name)843
844_, alreadyThere := f.formal[normalizedFlagName]845if alreadyThere {846msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)847fmt.Fprintln(f.out(), msg)848panic(msg) // Happens only if flags are declared with identical names849}850if f.formal == nil {851f.formal = make(map[NormalizedName]*Flag)852}853
854flag.Name = string(normalizedFlagName)855f.formal[normalizedFlagName] = flag856f.orderedFormal = append(f.orderedFormal, flag)857
858if flag.Shorthand == "" {859return860}861if len(flag.Shorthand) > 1 {862msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)863fmt.Fprintf(f.out(), msg)864panic(msg)865}866if f.shorthands == nil {867f.shorthands = make(map[byte]*Flag)868}869c := flag.Shorthand[0]870used, alreadyThere := f.shorthands[c]871if alreadyThere {872msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)873fmt.Fprintf(f.out(), msg)874panic(msg)875}876f.shorthands[c] = flag877}
878
879// AddFlagSet adds one FlagSet to another. If a flag is already present in f
880// the flag from newSet will be ignored.
881func (f *FlagSet) AddFlagSet(newSet *FlagSet) {882if newSet == nil {883return884}885newSet.VisitAll(func(flag *Flag) {886if f.Lookup(flag.Name) == nil {887f.AddFlag(flag)888}889})890}
891
892// Var defines a flag with the specified name and usage string. The type and
893// value of the flag are represented by the first argument, of type Value, which
894// typically holds a user-defined implementation of Value. For instance, the
895// caller could create a flag that turns a comma-separated string into a slice
896// of strings by giving the slice the methods of Value; in particular, Set would
897// decompose the comma-separated string into the slice.
898func Var(value Value, name string, usage string) {899CommandLine.VarP(value, name, "", usage)900}
901
902// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
903func VarP(value Value, name, shorthand, usage string) {904CommandLine.VarP(value, name, shorthand, usage)905}
906
907// failf prints to standard error a formatted error and usage message and
908// returns the error.
909func (f *FlagSet) failf(format string, a ...interface{}) error {910err := fmt.Errorf(format, a...)911if f.errorHandling != ContinueOnError {912fmt.Fprintln(f.out(), err)913f.usage()914}915return err916}
917
918// usage calls the Usage method for the flag set, or the usage function if
919// the flag set is CommandLine.
920func (f *FlagSet) usage() {921if f == CommandLine {922Usage()923} else if f.Usage == nil {924defaultUsage(f)925} else {926f.Usage()927}928}
929
930//--unknown (args will be empty)
931//--unknown --next-flag ... (args will be --next-flag ...)
932//--unknown arg ... (args will be arg ...)
933func stripUnknownFlagValue(args []string) []string {934if len(args) == 0 {935//--unknown936return args937}938
939first := args[0]940if len(first) > 0 && first[0] == '-' {941//--unknown --next-flag ...942return args943}944
945//--unknown arg ... (args will be arg ...)946if len(args) > 1 {947return args[1:]948}949return nil950}
951
952func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {953a = args954name := s[2:]955if len(name) == 0 || name[0] == '-' || name[0] == '=' {956err = f.failf("bad flag syntax: %s", s)957return958}959
960split := strings.SplitN(name, "=", 2)961name = split[0]962flag, exists := f.formal[f.normalizeFlagName(name)]963
964if !exists {965switch {966case name == "help":967f.usage()968return a, ErrHelp969case f.ParseErrorsWhitelist.UnknownFlags:970// --unknown=unknownval arg ...971// we do not want to lose arg in this case972if len(split) >= 2 {973return a, nil974}975
976return stripUnknownFlagValue(a), nil977default:978err = f.failf("unknown flag: --%s", name)979return980}981}982
983var value string984if len(split) == 2 {985// '--flag=arg'986value = split[1]987} else if flag.NoOptDefVal != "" {988// '--flag' (arg was optional)989value = flag.NoOptDefVal990} else if len(a) > 0 {991// '--flag arg'992value = a[0]993a = a[1:]994} else {995// '--flag' (arg was required)996err = f.failf("flag needs an argument: %s", s)997return998}999
1000err = fn(flag, value)1001if err != nil {1002f.failf(err.Error())1003}1004return1005}
1006
1007func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {1008outArgs = args1009
1010if strings.HasPrefix(shorthands, "test.") {1011return1012}1013
1014outShorts = shorthands[1:]1015c := shorthands[0]1016
1017flag, exists := f.shorthands[c]1018if !exists {1019switch {1020case c == 'h':1021f.usage()1022err = ErrHelp1023return1024case f.ParseErrorsWhitelist.UnknownFlags:1025// '-f=arg arg ...'1026// we do not want to lose arg in this case1027if len(shorthands) > 2 && shorthands[1] == '=' {1028outShorts = ""1029return1030}1031
1032outArgs = stripUnknownFlagValue(outArgs)1033return1034default:1035err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)1036return1037}1038}1039
1040var value string1041if len(shorthands) > 2 && shorthands[1] == '=' {1042// '-f=arg'1043value = shorthands[2:]1044outShorts = ""1045} else if flag.NoOptDefVal != "" {1046// '-f' (arg was optional)1047value = flag.NoOptDefVal1048} else if len(shorthands) > 1 {1049// '-farg'1050value = shorthands[1:]1051outShorts = ""1052} else if len(args) > 0 {1053// '-f arg'1054value = args[0]1055outArgs = args[1:]1056} else {1057// '-f' (arg was required)1058err = f.failf("flag needs an argument: %q in -%s", c, shorthands)1059return1060}1061
1062if flag.ShorthandDeprecated != "" {1063fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)1064}1065
1066err = fn(flag, value)1067if err != nil {1068f.failf(err.Error())1069}1070return1071}
1072
1073func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {1074a = args1075shorthands := s[1:]1076
1077// "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").1078for len(shorthands) > 0 {1079shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)1080if err != nil {1081return1082}1083}1084
1085return1086}
1087
1088func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {1089for len(args) > 0 {1090s := args[0]1091args = args[1:]1092if len(s) == 0 || s[0] != '-' || len(s) == 1 {1093if !f.interspersed {1094f.args = append(f.args, s)1095f.args = append(f.args, args...)1096return nil1097}1098f.args = append(f.args, s)1099continue1100}1101
1102if s[1] == '-' {1103if len(s) == 2 { // "--" terminates the flags1104f.argsLenAtDash = len(f.args)1105f.args = append(f.args, args...)1106break1107}1108args, err = f.parseLongArg(s, args, fn)1109} else {1110args, err = f.parseShortArg(s, args, fn)1111}1112if err != nil {1113return1114}1115}1116return1117}
1118
1119// Parse parses flag definitions from the argument list, which should not
1120// include the command name. Must be called after all flags in the FlagSet
1121// are defined and before flags are accessed by the program.
1122// The return value will be ErrHelp if -help was set but not defined.
1123func (f *FlagSet) Parse(arguments []string) error {1124if f.addedGoFlagSets != nil {1125for _, goFlagSet := range f.addedGoFlagSets {1126goFlagSet.Parse(nil)1127}1128}1129f.parsed = true1130
1131if len(arguments) < 0 {1132return nil1133}1134
1135f.args = make([]string, 0, len(arguments))1136
1137set := func(flag *Flag, value string) error {1138return f.Set(flag.Name, value)1139}1140
1141err := f.parseArgs(arguments, set)1142if err != nil {1143switch f.errorHandling {1144case ContinueOnError:1145return err1146case ExitOnError:1147fmt.Println(err)1148os.Exit(2)1149case PanicOnError:1150panic(err)1151}1152}1153return nil1154}
1155
1156type parseFunc func(flag *Flag, value string) error1157
1158// ParseAll parses flag definitions from the argument list, which should not
1159// include the command name. The arguments for fn are flag and value. Must be
1160// called after all flags in the FlagSet are defined and before flags are
1161// accessed by the program. The return value will be ErrHelp if -help was set
1162// but not defined.
1163func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {1164f.parsed = true1165f.args = make([]string, 0, len(arguments))1166
1167err := f.parseArgs(arguments, fn)1168if err != nil {1169switch f.errorHandling {1170case ContinueOnError:1171return err1172case ExitOnError:1173os.Exit(2)1174case PanicOnError:1175panic(err)1176}1177}1178return nil1179}
1180
1181// Parsed reports whether f.Parse has been called.
1182func (f *FlagSet) Parsed() bool {1183return f.parsed1184}
1185
1186// Parse parses the command-line flags from os.Args[1:]. Must be called
1187// after all flags are defined and before flags are accessed by the program.
1188func Parse() {1189// Ignore errors; CommandLine is set for ExitOnError.1190CommandLine.Parse(os.Args[1:])1191}
1192
1193// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
1194// The arguments for fn are flag and value. Must be called after all flags are
1195// defined and before flags are accessed by the program.
1196func ParseAll(fn func(flag *Flag, value string) error) {1197// Ignore errors; CommandLine is set for ExitOnError.1198CommandLine.ParseAll(os.Args[1:], fn)1199}
1200
1201// SetInterspersed sets whether to support interspersed option/non-option arguments.
1202func SetInterspersed(interspersed bool) {1203CommandLine.SetInterspersed(interspersed)1204}
1205
1206// Parsed returns true if the command-line flags have been parsed.
1207func Parsed() bool {1208return CommandLine.Parsed()1209}
1210
1211// CommandLine is the default set of command-line flags, parsed from os.Args.
1212var CommandLine = NewFlagSet(os.Args[0], ExitOnError)1213
1214// NewFlagSet returns a new, empty flag set with the specified name,
1215// error handling property and SortFlags set to true.
1216func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {1217f := &FlagSet{1218name: name,1219errorHandling: errorHandling,1220argsLenAtDash: -1,1221interspersed: true,1222SortFlags: true,1223}1224return f1225}
1226
1227// SetInterspersed sets whether to support interspersed option/non-option arguments.
1228func (f *FlagSet) SetInterspersed(interspersed bool) {1229f.interspersed = interspersed1230}
1231
1232// Init sets the name and error handling property for a flag set.
1233// By default, the zero FlagSet uses an empty name and the
1234// ContinueOnError error handling policy.
1235func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {1236f.name = name1237f.errorHandling = errorHandling1238f.argsLenAtDash = -11239}
1240