1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| # flag.Parse
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
func Parse() { CommandLine.Parse(os.Args[1:]) }
# FlagSet.Parse > parse异常分流处理
func (f *FlagSet) Parse(arguments []string) error { f.parsed = true f.args = arguments for { seen, err := f.parseOne() if seen { continue } if err == nil { break } switch f.errorHandling { case ContinueOnError: return err case ExitOnError: if err == ErrHelp { os.Exit(0) } os.Exit(2) case PanicOnError: panic(err) } } return nil }
# FlagSet.parseOne
func (f *FlagSet) parseOne() (bool, error) { if len(f.args) == 0 { return false, nil } s := f.args[0] if len(s) < 2 || s[0] != '-' { return false, nil } numMinuses := 1 if s[1] == '-' { numMinuses++ if len(s) == 2 { f.args = f.args[1:] return false, nil } } name := s[numMinuses:] if len(name) == 0 || name[0] == '-' || name[0] == '=' { return false, f.failf("bad flag syntax: %s", s) }
f.args = f.args[1:] hasValue := false value := "" for i := 1; i < len(name); i++ { if name[i] == '=' { value = name[i+1:] hasValue = true name = name[0:i] break } } m := f.formal flag, alreadythere := m[name] if !alreadythere { if name == "help" || name == "h" { f.usage() return false, ErrHelp } return false, f.failf("flag provided but not defined: -%s", name) }
if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { if hasValue { if err := fv.Set(value); err != nil { return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err) } } else { if err := fv.Set("true"); err != nil { return false, f.failf("invalid boolean flag %s: %v", name, err) } } } else { if !hasValue && len(f.args) > 0 { hasValue = true value, f.args = f.args[0], f.args[1:] } if !hasValue { return false, f.failf("flag needs an argument: -%s", name) } if err := flag.Value.Set(value); err != nil { return false, f.failf("invalid value %q for flag -%s: %v", value, name, err) } } if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag return true, nil }
|