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