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