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