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