github.com/c9s/go@v0.0.0-20180120015821-984e81f64e0c/src/flag/flag.go (about) 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 /* 6 Package flag implements command-line flag parsing. 7 8 Usage: 9 10 Define flags using flag.String(), Bool(), Int(), etc. 11 12 This declares an integer flag, -flagname, stored in the pointer ip, with type *int. 13 import "flag" 14 var ip = flag.Int("flagname", 1234, "help message for flagname") 15 If you like, you can bind the flag to a variable using the Var() functions. 16 var flagvar int 17 func init() { 18 flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") 19 } 20 Or you can create custom flags that satisfy the Value interface (with 21 pointer receivers) and couple them to flag parsing by 22 flag.Var(&flagVal, "name", "help message for flagname") 23 For such flags, the default value is just the initial value of the variable. 24 25 After all flags are defined, call 26 flag.Parse() 27 to parse the command line into the defined flags. 28 29 Flags may then be used directly. If you're using the flags themselves, 30 they are all pointers; if you bind to variables, they're values. 31 fmt.Println("ip has value ", *ip) 32 fmt.Println("flagvar has value ", flagvar) 33 34 After parsing, the arguments following the flags are available as the 35 slice flag.Args() or individually as flag.Arg(i). 36 The arguments are indexed from 0 through flag.NArg()-1. 37 38 Command line flag syntax: 39 -flag 40 -flag=x 41 -flag x // non-boolean flags only 42 One or two minus signs may be used; they are equivalent. 43 The last form is not permitted for boolean flags because the 44 meaning of the command 45 cmd -x * 46 where * is a Unix shell wildcard, will change if there is a file 47 called 0, false, etc. You must use the -flag=false form to turn 48 off a boolean flag. 49 50 Flag parsing stops just before the first non-flag argument 51 ("-" is a non-flag argument) or after the terminator "--". 52 53 Integer flags accept 1234, 0664, 0x1234 and may be negative. 54 Boolean flags may be: 55 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False 56 Duration flags accept any input valid for time.ParseDuration. 57 58 The default set of command-line flags is controlled by 59 top-level functions. The FlagSet type allows one to define 60 independent sets of flags, such as to implement subcommands 61 in a command-line interface. The methods of FlagSet are 62 analogous to the top-level functions for the command-line 63 flag set. 64 */ 65 package flag 66 67 import ( 68 "errors" 69 "fmt" 70 "io" 71 "os" 72 "reflect" 73 "sort" 74 "strconv" 75 "strings" 76 "time" 77 ) 78 79 // ErrHelp is the error returned if the -help or -h flag is invoked 80 // but no such flag is defined. 81 var ErrHelp = errors.New("flag: help requested") 82 83 // -- bool Value 84 type boolValue bool 85 86 func newBoolValue(val bool, p *bool) *boolValue { 87 *p = val 88 return (*boolValue)(p) 89 } 90 91 func (b *boolValue) Set(s string) error { 92 v, err := strconv.ParseBool(s) 93 *b = boolValue(v) 94 return err 95 } 96 97 func (b *boolValue) Get() interface{} { return bool(*b) } 98 99 func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } 100 101 func (b *boolValue) IsBoolFlag() bool { return true } 102 103 // optional interface to indicate boolean flags that can be 104 // supplied without "=value" text 105 type boolFlag interface { 106 Value 107 IsBoolFlag() bool 108 } 109 110 // -- int Value 111 type intValue int 112 113 func newIntValue(val int, p *int) *intValue { 114 *p = val 115 return (*intValue)(p) 116 } 117 118 func (i *intValue) Set(s string) error { 119 v, err := strconv.ParseInt(s, 0, strconv.IntSize) 120 *i = intValue(v) 121 return err 122 } 123 124 func (i *intValue) Get() interface{} { return int(*i) } 125 126 func (i *intValue) String() string { return strconv.Itoa(int(*i)) } 127 128 // -- int64 Value 129 type int64Value int64 130 131 func newInt64Value(val int64, p *int64) *int64Value { 132 *p = val 133 return (*int64Value)(p) 134 } 135 136 func (i *int64Value) Set(s string) error { 137 v, err := strconv.ParseInt(s, 0, 64) 138 *i = int64Value(v) 139 return err 140 } 141 142 func (i *int64Value) Get() interface{} { return int64(*i) } 143 144 func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } 145 146 // -- uint Value 147 type uintValue uint 148 149 func newUintValue(val uint, p *uint) *uintValue { 150 *p = val 151 return (*uintValue)(p) 152 } 153 154 func (i *uintValue) Set(s string) error { 155 v, err := strconv.ParseUint(s, 0, strconv.IntSize) 156 *i = uintValue(v) 157 return err 158 } 159 160 func (i *uintValue) Get() interface{} { return uint(*i) } 161 162 func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } 163 164 // -- uint64 Value 165 type uint64Value uint64 166 167 func newUint64Value(val uint64, p *uint64) *uint64Value { 168 *p = val 169 return (*uint64Value)(p) 170 } 171 172 func (i *uint64Value) Set(s string) error { 173 v, err := strconv.ParseUint(s, 0, 64) 174 *i = uint64Value(v) 175 return err 176 } 177 178 func (i *uint64Value) Get() interface{} { return uint64(*i) } 179 180 func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } 181 182 // -- string Value 183 type stringValue string 184 185 func newStringValue(val string, p *string) *stringValue { 186 *p = val 187 return (*stringValue)(p) 188 } 189 190 func (s *stringValue) Set(val string) error { 191 *s = stringValue(val) 192 return nil 193 } 194 195 func (s *stringValue) Get() interface{} { return string(*s) } 196 197 func (s *stringValue) String() string { return string(*s) } 198 199 // -- float64 Value 200 type float64Value float64 201 202 func newFloat64Value(val float64, p *float64) *float64Value { 203 *p = val 204 return (*float64Value)(p) 205 } 206 207 func (f *float64Value) Set(s string) error { 208 v, err := strconv.ParseFloat(s, 64) 209 *f = float64Value(v) 210 return err 211 } 212 213 func (f *float64Value) Get() interface{} { return float64(*f) } 214 215 func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } 216 217 // -- time.Duration Value 218 type durationValue time.Duration 219 220 func newDurationValue(val time.Duration, p *time.Duration) *durationValue { 221 *p = val 222 return (*durationValue)(p) 223 } 224 225 func (d *durationValue) Set(s string) error { 226 v, err := time.ParseDuration(s) 227 *d = durationValue(v) 228 return err 229 } 230 231 func (d *durationValue) Get() interface{} { return time.Duration(*d) } 232 233 func (d *durationValue) String() string { return (*time.Duration)(d).String() } 234 235 // Value is the interface to the dynamic value stored in a flag. 236 // (The default value is represented as a string.) 237 // 238 // If a Value has an IsBoolFlag() bool method returning true, 239 // the command-line parser makes -name equivalent to -name=true 240 // rather than using the next command-line argument. 241 // 242 // Set is called once, in command line order, for each flag present. 243 // The flag package may call the String method with a zero-valued receiver, 244 // such as a nil pointer. 245 type Value interface { 246 String() string 247 Set(string) error 248 } 249 250 // Getter is an interface that allows the contents of a Value to be retrieved. 251 // It wraps the Value interface, rather than being part of it, because it 252 // appeared after Go 1 and its compatibility rules. All Value types provided 253 // by this package satisfy the Getter interface. 254 type Getter interface { 255 Value 256 Get() interface{} 257 } 258 259 // ErrorHandling defines how FlagSet.Parse behaves if the parse fails. 260 type ErrorHandling int 261 262 // These constants cause FlagSet.Parse to behave as described if the parse fails. 263 const ( 264 ContinueOnError ErrorHandling = iota // Return a descriptive error. 265 ExitOnError // Call os.Exit(2). 266 PanicOnError // Call panic with a descriptive error. 267 ) 268 269 // A FlagSet represents a set of defined flags. The zero value of a FlagSet 270 // has no name and has ContinueOnError error handling. 271 type FlagSet struct { 272 // Usage is the function called when an error occurs while parsing flags. 273 // The field is a function (not a method) that may be changed to point to 274 // a custom error handler. What happens after Usage is called depends 275 // on the ErrorHandling setting; for the command line, this defaults 276 // to ExitOnError, which exits the program after calling Usage. 277 Usage func() 278 279 name string 280 parsed bool 281 actual map[string]*Flag 282 formal map[string]*Flag 283 args []string // arguments after flags 284 errorHandling ErrorHandling 285 output io.Writer // nil means stderr; use out() accessor 286 } 287 288 // A Flag represents the state of a flag. 289 type Flag struct { 290 Name string // name as it appears on command line 291 Usage string // help message 292 Value Value // value as set 293 DefValue string // default value (as text); for usage message 294 } 295 296 // sortFlags returns the flags as a slice in lexicographical sorted order. 297 func sortFlags(flags map[string]*Flag) []*Flag { 298 list := make(sort.StringSlice, len(flags)) 299 i := 0 300 for _, f := range flags { 301 list[i] = f.Name 302 i++ 303 } 304 list.Sort() 305 result := make([]*Flag, len(list)) 306 for i, name := range list { 307 result[i] = flags[name] 308 } 309 return result 310 } 311 312 // Output returns the destination for usage and error messages. os.Stderr is returned if 313 // output was not set or was set to nil. 314 func (f *FlagSet) Output() io.Writer { 315 if f.output == nil { 316 return os.Stderr 317 } 318 return f.output 319 } 320 321 // Name returns the name of the flag set. 322 func (f *FlagSet) Name() string { 323 return f.name 324 } 325 326 // ErrorHandling returns the error handling behavior of the flag set. 327 func (f *FlagSet) ErrorHandling() ErrorHandling { 328 return f.errorHandling 329 } 330 331 // SetOutput sets the destination for usage and error messages. 332 // If output is nil, os.Stderr is used. 333 func (f *FlagSet) SetOutput(output io.Writer) { 334 f.output = output 335 } 336 337 // VisitAll visits the flags in lexicographical order, calling fn for each. 338 // It visits all flags, even those not set. 339 func (f *FlagSet) VisitAll(fn func(*Flag)) { 340 for _, flag := range sortFlags(f.formal) { 341 fn(flag) 342 } 343 } 344 345 // VisitAll visits the command-line flags in lexicographical order, calling 346 // fn for each. It visits all flags, even those not set. 347 func VisitAll(fn func(*Flag)) { 348 CommandLine.VisitAll(fn) 349 } 350 351 // Visit visits the flags in lexicographical order, calling fn for each. 352 // It visits only those flags that have been set. 353 func (f *FlagSet) Visit(fn func(*Flag)) { 354 for _, flag := range sortFlags(f.actual) { 355 fn(flag) 356 } 357 } 358 359 // Visit visits the command-line flags in lexicographical order, calling fn 360 // for each. It visits only those flags that have been set. 361 func Visit(fn func(*Flag)) { 362 CommandLine.Visit(fn) 363 } 364 365 // Lookup returns the Flag structure of the named flag, returning nil if none exists. 366 func (f *FlagSet) Lookup(name string) *Flag { 367 return f.formal[name] 368 } 369 370 // Lookup returns the Flag structure of the named command-line flag, 371 // returning nil if none exists. 372 func Lookup(name string) *Flag { 373 return CommandLine.formal[name] 374 } 375 376 // Set sets the value of the named flag. 377 func (f *FlagSet) Set(name, value string) error { 378 flag, ok := f.formal[name] 379 if !ok { 380 return fmt.Errorf("no such flag -%v", name) 381 } 382 err := flag.Value.Set(value) 383 if err != nil { 384 return err 385 } 386 if f.actual == nil { 387 f.actual = make(map[string]*Flag) 388 } 389 f.actual[name] = flag 390 return nil 391 } 392 393 // Set sets the value of the named command-line flag. 394 func Set(name, value string) error { 395 return CommandLine.Set(name, value) 396 } 397 398 // isZeroValue guesses whether the string represents the zero 399 // value for a flag. It is not accurate but in practice works OK. 400 func isZeroValue(flag *Flag, value string) bool { 401 // Build a zero value of the flag's Value type, and see if the 402 // result of calling its String method equals the value passed in. 403 // This works unless the Value type is itself an interface type. 404 typ := reflect.TypeOf(flag.Value) 405 var z reflect.Value 406 if typ.Kind() == reflect.Ptr { 407 z = reflect.New(typ.Elem()) 408 } else { 409 z = reflect.Zero(typ) 410 } 411 if value == z.Interface().(Value).String() { 412 return true 413 } 414 415 switch value { 416 case "false", "", "0": 417 return true 418 } 419 return false 420 } 421 422 // UnquoteUsage extracts a back-quoted name from the usage 423 // string for a flag and returns it and the un-quoted usage. 424 // Given "a `name` to show" it returns ("name", "a name to show"). 425 // If there are no back quotes, the name is an educated guess of the 426 // type of the flag's value, or the empty string if the flag is boolean. 427 func UnquoteUsage(flag *Flag) (name string, usage string) { 428 // Look for a back-quoted name, but avoid the strings package. 429 usage = flag.Usage 430 for i := 0; i < len(usage); i++ { 431 if usage[i] == '`' { 432 for j := i + 1; j < len(usage); j++ { 433 if usage[j] == '`' { 434 name = usage[i+1 : j] 435 usage = usage[:i] + name + usage[j+1:] 436 return name, usage 437 } 438 } 439 break // Only one back quote; use type name. 440 } 441 } 442 // No explicit name, so use type if we can find one. 443 name = "value" 444 switch flag.Value.(type) { 445 case boolFlag: 446 name = "" 447 case *durationValue: 448 name = "duration" 449 case *float64Value: 450 name = "float" 451 case *intValue, *int64Value: 452 name = "int" 453 case *stringValue: 454 name = "string" 455 case *uintValue, *uint64Value: 456 name = "uint" 457 } 458 return 459 } 460 461 // PrintDefaults prints, to standard error unless configured otherwise, the 462 // default values of all defined command-line flags in the set. See the 463 // documentation for the global function PrintDefaults for more information. 464 func (f *FlagSet) PrintDefaults() { 465 f.VisitAll(func(flag *Flag) { 466 s := fmt.Sprintf(" -%s", flag.Name) // Two spaces before -; see next two comments. 467 name, usage := UnquoteUsage(flag) 468 if len(name) > 0 { 469 s += " " + name 470 } 471 // Boolean flags of one ASCII letter are so common we 472 // treat them specially, putting their usage on the same line. 473 if len(s) <= 4 { // space, space, '-', 'x'. 474 s += "\t" 475 } else { 476 // Four spaces before the tab triggers good alignment 477 // for both 4- and 8-space tab stops. 478 s += "\n \t" 479 } 480 s += strings.Replace(usage, "\n", "\n \t", -1) 481 482 if !isZeroValue(flag, flag.DefValue) { 483 if _, ok := flag.Value.(*stringValue); ok { 484 // put quotes on the value 485 s += fmt.Sprintf(" (default %q)", flag.DefValue) 486 } else { 487 s += fmt.Sprintf(" (default %v)", flag.DefValue) 488 } 489 } 490 fmt.Fprint(f.Output(), s, "\n") 491 }) 492 } 493 494 // PrintDefaults prints, to standard error unless configured otherwise, 495 // a usage message showing the default settings of all defined 496 // command-line flags. 497 // For an integer valued flag x, the default output has the form 498 // -x int 499 // usage-message-for-x (default 7) 500 // The usage message will appear on a separate line for anything but 501 // a bool flag with a one-byte name. For bool flags, the type is 502 // omitted and if the flag name is one byte the usage message appears 503 // on the same line. The parenthetical default is omitted if the 504 // default is the zero value for the type. The listed type, here int, 505 // can be changed by placing a back-quoted name in the flag's usage 506 // string; the first such item in the message is taken to be a parameter 507 // name to show in the message and the back quotes are stripped from 508 // the message when displayed. For instance, given 509 // flag.String("I", "", "search `directory` for include files") 510 // the output will be 511 // -I directory 512 // search directory for include files. 513 func PrintDefaults() { 514 CommandLine.PrintDefaults() 515 } 516 517 // defaultUsage is the default function to print a usage message. 518 func (f *FlagSet) defaultUsage() { 519 if f.name == "" { 520 fmt.Fprintf(f.Output(), "Usage:\n") 521 } else { 522 fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name) 523 } 524 f.PrintDefaults() 525 } 526 527 // NOTE: Usage is not just defaultUsage(CommandLine) 528 // because it serves (via godoc flag Usage) as the example 529 // for how to write your own usage function. 530 531 // Usage prints a usage message documenting all defined command-line flags 532 // to CommandLine's output, which by default is os.Stderr. 533 // It is called when an error occurs while parsing flags. 534 // The function is a variable that may be changed to point to a custom function. 535 // By default it prints a simple header and calls PrintDefaults; for details about the 536 // format of the output and how to control it, see the documentation for PrintDefaults. 537 // Custom usage functions may choose to exit the program; by default exiting 538 // happens anyway as the command line's error handling strategy is set to 539 // ExitOnError. 540 var Usage = func() { 541 fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0]) 542 PrintDefaults() 543 } 544 545 // NFlag returns the number of flags that have been set. 546 func (f *FlagSet) NFlag() int { return len(f.actual) } 547 548 // NFlag returns the number of command-line flags that have been set. 549 func NFlag() int { return len(CommandLine.actual) } 550 551 // Arg returns the i'th argument. Arg(0) is the first remaining argument 552 // after flags have been processed. Arg returns an empty string if the 553 // requested element does not exist. 554 func (f *FlagSet) Arg(i int) string { 555 if i < 0 || i >= len(f.args) { 556 return "" 557 } 558 return f.args[i] 559 } 560 561 // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument 562 // after flags have been processed. Arg returns an empty string if the 563 // requested element does not exist. 564 func Arg(i int) string { 565 return CommandLine.Arg(i) 566 } 567 568 // NArg is the number of arguments remaining after flags have been processed. 569 func (f *FlagSet) NArg() int { return len(f.args) } 570 571 // NArg is the number of arguments remaining after flags have been processed. 572 func NArg() int { return len(CommandLine.args) } 573 574 // Args returns the non-flag arguments. 575 func (f *FlagSet) Args() []string { return f.args } 576 577 // Args returns the non-flag command-line arguments. 578 func Args() []string { return CommandLine.args } 579 580 // BoolVar defines a bool flag with specified name, default value, and usage string. 581 // The argument p points to a bool variable in which to store the value of the flag. 582 func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { 583 f.Var(newBoolValue(value, p), name, usage) 584 } 585 586 // BoolVar defines a bool flag with specified name, default value, and usage string. 587 // The argument p points to a bool variable in which to store the value of the flag. 588 func BoolVar(p *bool, name string, value bool, usage string) { 589 CommandLine.Var(newBoolValue(value, p), name, usage) 590 } 591 592 // Bool defines a bool flag with specified name, default value, and usage string. 593 // The return value is the address of a bool variable that stores the value of the flag. 594 func (f *FlagSet) Bool(name string, value bool, usage string) *bool { 595 p := new(bool) 596 f.BoolVar(p, name, value, usage) 597 return p 598 } 599 600 // Bool defines a bool flag with specified name, default value, and usage string. 601 // The return value is the address of a bool variable that stores the value of the flag. 602 func Bool(name string, value bool, usage string) *bool { 603 return CommandLine.Bool(name, value, usage) 604 } 605 606 // IntVar defines an int flag with specified name, default value, and usage string. 607 // The argument p points to an int variable in which to store the value of the flag. 608 func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { 609 f.Var(newIntValue(value, p), name, usage) 610 } 611 612 // IntVar defines an int flag with specified name, default value, and usage string. 613 // The argument p points to an int variable in which to store the value of the flag. 614 func IntVar(p *int, name string, value int, usage string) { 615 CommandLine.Var(newIntValue(value, p), name, usage) 616 } 617 618 // Int defines an int flag with specified name, default value, and usage string. 619 // The return value is the address of an int variable that stores the value of the flag. 620 func (f *FlagSet) Int(name string, value int, usage string) *int { 621 p := new(int) 622 f.IntVar(p, name, value, usage) 623 return p 624 } 625 626 // Int defines an int flag with specified name, default value, and usage string. 627 // The return value is the address of an int variable that stores the value of the flag. 628 func Int(name string, value int, usage string) *int { 629 return CommandLine.Int(name, value, usage) 630 } 631 632 // Int64Var defines an int64 flag with specified name, default value, and usage string. 633 // The argument p points to an int64 variable in which to store the value of the flag. 634 func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { 635 f.Var(newInt64Value(value, p), name, usage) 636 } 637 638 // Int64Var defines an int64 flag with specified name, default value, and usage string. 639 // The argument p points to an int64 variable in which to store the value of the flag. 640 func Int64Var(p *int64, name string, value int64, usage string) { 641 CommandLine.Var(newInt64Value(value, p), name, usage) 642 } 643 644 // Int64 defines an int64 flag with specified name, default value, and usage string. 645 // The return value is the address of an int64 variable that stores the value of the flag. 646 func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { 647 p := new(int64) 648 f.Int64Var(p, name, value, usage) 649 return p 650 } 651 652 // Int64 defines an int64 flag with specified name, default value, and usage string. 653 // The return value is the address of an int64 variable that stores the value of the flag. 654 func Int64(name string, value int64, usage string) *int64 { 655 return CommandLine.Int64(name, value, usage) 656 } 657 658 // UintVar defines a uint flag with specified name, default value, and usage string. 659 // The argument p points to a uint variable in which to store the value of the flag. 660 func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { 661 f.Var(newUintValue(value, p), name, usage) 662 } 663 664 // UintVar defines a uint flag with specified name, default value, and usage string. 665 // The argument p points to a uint variable in which to store the value of the flag. 666 func UintVar(p *uint, name string, value uint, usage string) { 667 CommandLine.Var(newUintValue(value, p), name, usage) 668 } 669 670 // Uint defines a uint flag with specified name, default value, and usage string. 671 // The return value is the address of a uint variable that stores the value of the flag. 672 func (f *FlagSet) Uint(name string, value uint, usage string) *uint { 673 p := new(uint) 674 f.UintVar(p, name, value, usage) 675 return p 676 } 677 678 // Uint defines a uint flag with specified name, default value, and usage string. 679 // The return value is the address of a uint variable that stores the value of the flag. 680 func Uint(name string, value uint, usage string) *uint { 681 return CommandLine.Uint(name, value, usage) 682 } 683 684 // Uint64Var defines a uint64 flag with specified name, default value, and usage string. 685 // The argument p points to a uint64 variable in which to store the value of the flag. 686 func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { 687 f.Var(newUint64Value(value, p), name, usage) 688 } 689 690 // Uint64Var defines a uint64 flag with specified name, default value, and usage string. 691 // The argument p points to a uint64 variable in which to store the value of the flag. 692 func Uint64Var(p *uint64, name string, value uint64, usage string) { 693 CommandLine.Var(newUint64Value(value, p), name, usage) 694 } 695 696 // Uint64 defines a uint64 flag with specified name, default value, and usage string. 697 // The return value is the address of a uint64 variable that stores the value of the flag. 698 func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { 699 p := new(uint64) 700 f.Uint64Var(p, name, value, usage) 701 return p 702 } 703 704 // Uint64 defines a uint64 flag with specified name, default value, and usage string. 705 // The return value is the address of a uint64 variable that stores the value of the flag. 706 func Uint64(name string, value uint64, usage string) *uint64 { 707 return CommandLine.Uint64(name, value, usage) 708 } 709 710 // StringVar defines a string flag with specified name, default value, and usage string. 711 // The argument p points to a string variable in which to store the value of the flag. 712 func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { 713 f.Var(newStringValue(value, p), name, usage) 714 } 715 716 // StringVar defines a string flag with specified name, default value, and usage string. 717 // The argument p points to a string variable in which to store the value of the flag. 718 func StringVar(p *string, name string, value string, usage string) { 719 CommandLine.Var(newStringValue(value, p), name, usage) 720 } 721 722 // String defines a string flag with specified name, default value, and usage string. 723 // The return value is the address of a string variable that stores the value of the flag. 724 func (f *FlagSet) String(name string, value string, usage string) *string { 725 p := new(string) 726 f.StringVar(p, name, value, usage) 727 return p 728 } 729 730 // String defines a string flag with specified name, default value, and usage string. 731 // The return value is the address of a string variable that stores the value of the flag. 732 func String(name string, value string, usage string) *string { 733 return CommandLine.String(name, value, usage) 734 } 735 736 // Float64Var defines a float64 flag with specified name, default value, and usage string. 737 // The argument p points to a float64 variable in which to store the value of the flag. 738 func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { 739 f.Var(newFloat64Value(value, p), name, usage) 740 } 741 742 // Float64Var defines a float64 flag with specified name, default value, and usage string. 743 // The argument p points to a float64 variable in which to store the value of the flag. 744 func Float64Var(p *float64, name string, value float64, usage string) { 745 CommandLine.Var(newFloat64Value(value, p), name, usage) 746 } 747 748 // Float64 defines a float64 flag with specified name, default value, and usage string. 749 // The return value is the address of a float64 variable that stores the value of the flag. 750 func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { 751 p := new(float64) 752 f.Float64Var(p, name, value, usage) 753 return p 754 } 755 756 // Float64 defines a float64 flag with specified name, default value, and usage string. 757 // The return value is the address of a float64 variable that stores the value of the flag. 758 func Float64(name string, value float64, usage string) *float64 { 759 return CommandLine.Float64(name, value, usage) 760 } 761 762 // DurationVar defines a time.Duration flag with specified name, default value, and usage string. 763 // The argument p points to a time.Duration variable in which to store the value of the flag. 764 // The flag accepts a value acceptable to time.ParseDuration. 765 func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { 766 f.Var(newDurationValue(value, p), name, usage) 767 } 768 769 // DurationVar defines a time.Duration flag with specified name, default value, and usage string. 770 // The argument p points to a time.Duration variable in which to store the value of the flag. 771 // The flag accepts a value acceptable to time.ParseDuration. 772 func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { 773 CommandLine.Var(newDurationValue(value, p), name, usage) 774 } 775 776 // Duration defines a time.Duration flag with specified name, default value, and usage string. 777 // The return value is the address of a time.Duration variable that stores the value of the flag. 778 // The flag accepts a value acceptable to time.ParseDuration. 779 func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { 780 p := new(time.Duration) 781 f.DurationVar(p, name, value, usage) 782 return p 783 } 784 785 // Duration defines a time.Duration flag with specified name, default value, and usage string. 786 // The return value is the address of a time.Duration variable that stores the value of the flag. 787 // The flag accepts a value acceptable to time.ParseDuration. 788 func Duration(name string, value time.Duration, usage string) *time.Duration { 789 return CommandLine.Duration(name, value, usage) 790 } 791 792 // Var defines a flag with the specified name and usage string. The type and 793 // value of the flag are represented by the first argument, of type Value, which 794 // typically holds a user-defined implementation of Value. For instance, the 795 // caller could create a flag that turns a comma-separated string into a slice 796 // of strings by giving the slice the methods of Value; in particular, Set would 797 // decompose the comma-separated string into the slice. 798 func (f *FlagSet) Var(value Value, name string, usage string) { 799 // Remember the default value as a string; it won't change. 800 flag := &Flag{name, usage, value, value.String()} 801 _, alreadythere := f.formal[name] 802 if alreadythere { 803 var msg string 804 if f.name == "" { 805 msg = fmt.Sprintf("flag redefined: %s", name) 806 } else { 807 msg = fmt.Sprintf("%s flag redefined: %s", f.name, name) 808 } 809 fmt.Fprintln(f.Output(), msg) 810 panic(msg) // Happens only if flags are declared with identical names 811 } 812 if f.formal == nil { 813 f.formal = make(map[string]*Flag) 814 } 815 f.formal[name] = flag 816 } 817 818 // Var defines a flag with the specified name and usage string. The type and 819 // value of the flag are represented by the first argument, of type Value, which 820 // typically holds a user-defined implementation of Value. For instance, the 821 // caller could create a flag that turns a comma-separated string into a slice 822 // of strings by giving the slice the methods of Value; in particular, Set would 823 // decompose the comma-separated string into the slice. 824 func Var(value Value, name string, usage string) { 825 CommandLine.Var(value, name, usage) 826 } 827 828 // failf prints to standard error a formatted error and usage message and 829 // returns the error. 830 func (f *FlagSet) failf(format string, a ...interface{}) error { 831 err := fmt.Errorf(format, a...) 832 fmt.Fprintln(f.Output(), err) 833 f.usage() 834 return err 835 } 836 837 // usage calls the Usage method for the flag set if one is specified, 838 // or the appropriate default usage function otherwise. 839 func (f *FlagSet) usage() { 840 if f.Usage == nil { 841 f.defaultUsage() 842 } else { 843 f.Usage() 844 } 845 } 846 847 // parseOne parses one flag. It reports whether a flag was seen. 848 func (f *FlagSet) parseOne() (bool, error) { 849 if len(f.args) == 0 { 850 return false, nil 851 } 852 s := f.args[0] 853 if len(s) < 2 || s[0] != '-' { 854 return false, nil 855 } 856 numMinuses := 1 857 if s[1] == '-' { 858 numMinuses++ 859 if len(s) == 2 { // "--" terminates the flags 860 f.args = f.args[1:] 861 return false, nil 862 } 863 } 864 name := s[numMinuses:] 865 if len(name) == 0 || name[0] == '-' || name[0] == '=' { 866 return false, f.failf("bad flag syntax: %s", s) 867 } 868 869 // it's a flag. does it have an argument? 870 f.args = f.args[1:] 871 hasValue := false 872 value := "" 873 for i := 1; i < len(name); i++ { // equals cannot be first 874 if name[i] == '=' { 875 value = name[i+1:] 876 hasValue = true 877 name = name[0:i] 878 break 879 } 880 } 881 m := f.formal 882 flag, alreadythere := m[name] // BUG 883 if !alreadythere { 884 if name == "help" || name == "h" { // special case for nice help message. 885 f.usage() 886 return false, ErrHelp 887 } 888 return false, f.failf("flag provided but not defined: -%s", name) 889 } 890 891 if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg 892 if hasValue { 893 if err := fv.Set(value); err != nil { 894 return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err) 895 } 896 } else { 897 if err := fv.Set("true"); err != nil { 898 return false, f.failf("invalid boolean flag %s: %v", name, err) 899 } 900 } 901 } else { 902 // It must have a value, which might be the next argument. 903 if !hasValue && len(f.args) > 0 { 904 // value is the next arg 905 hasValue = true 906 value, f.args = f.args[0], f.args[1:] 907 } 908 if !hasValue { 909 return false, f.failf("flag needs an argument: -%s", name) 910 } 911 if err := flag.Value.Set(value); err != nil { 912 return false, f.failf("invalid value %q for flag -%s: %v", value, name, err) 913 } 914 } 915 if f.actual == nil { 916 f.actual = make(map[string]*Flag) 917 } 918 f.actual[name] = flag 919 return true, nil 920 } 921 922 // Parse parses flag definitions from the argument list, which should not 923 // include the command name. Must be called after all flags in the FlagSet 924 // are defined and before flags are accessed by the program. 925 // The return value will be ErrHelp if -help or -h were set but not defined. 926 func (f *FlagSet) Parse(arguments []string) error { 927 f.parsed = true 928 f.args = arguments 929 for { 930 seen, err := f.parseOne() 931 if seen { 932 continue 933 } 934 if err == nil { 935 break 936 } 937 switch f.errorHandling { 938 case ContinueOnError: 939 return err 940 case ExitOnError: 941 os.Exit(2) 942 case PanicOnError: 943 panic(err) 944 } 945 } 946 return nil 947 } 948 949 // Parsed reports whether f.Parse has been called. 950 func (f *FlagSet) Parsed() bool { 951 return f.parsed 952 } 953 954 // Parse parses the command-line flags from os.Args[1:]. Must be called 955 // after all flags are defined and before flags are accessed by the program. 956 func Parse() { 957 // Ignore errors; CommandLine is set for ExitOnError. 958 CommandLine.Parse(os.Args[1:]) 959 } 960 961 // Parsed reports whether the command-line flags have been parsed. 962 func Parsed() bool { 963 return CommandLine.Parsed() 964 } 965 966 // CommandLine is the default set of command-line flags, parsed from os.Args. 967 // The top-level functions such as BoolVar, Arg, and so on are wrappers for the 968 // methods of CommandLine. 969 var CommandLine = NewFlagSet(os.Args[0], ExitOnError) 970 971 func init() { 972 // Override generic FlagSet default Usage with call to global Usage. 973 // Note: This is not CommandLine.Usage = Usage, 974 // because we want any eventual call to use any updated value of Usage, 975 // not the value it has when this line is run. 976 CommandLine.Usage = commandLineUsage 977 } 978 979 func commandLineUsage() { 980 Usage() 981 } 982 983 // NewFlagSet returns a new, empty flag set with the specified name and 984 // error handling property. 985 func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { 986 f := &FlagSet{ 987 name: name, 988 errorHandling: errorHandling, 989 } 990 f.Usage = f.defaultUsage 991 return f 992 } 993 994 // Init sets the name and error handling property for a flag set. 995 // By default, the zero FlagSet uses an empty name and the 996 // ContinueOnError error handling policy. 997 func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { 998 f.name = name 999 f.errorHandling = errorHandling 1000 }