1package cli 2 3import ( 4 "flag" 5 "fmt" 6 "time" 7) 8 9// DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration) 10type DurationFlag struct { 11 Name string 12 Usage string 13 EnvVar string 14 FilePath string 15 Required bool 16 Hidden bool 17 Value time.Duration 18 Destination *time.Duration 19} 20 21// String returns a readable representation of this value 22// (for usage defaults) 23func (f DurationFlag) String() string { 24 return FlagStringer(f) 25} 26 27// GetName returns the name of the flag 28func (f DurationFlag) GetName() string { 29 return f.Name 30} 31 32// IsRequired returns whether or not the flag is required 33func (f DurationFlag) IsRequired() bool { 34 return f.Required 35} 36 37// TakesValue returns true of the flag takes a value, otherwise false 38func (f DurationFlag) TakesValue() bool { 39 return true 40} 41 42// GetUsage returns the usage string for the flag 43func (f DurationFlag) GetUsage() string { 44 return f.Usage 45} 46 47// GetValue returns the flags value as string representation and an empty 48// string if the flag takes no value at all. 49func (f DurationFlag) GetValue() string { 50 return f.Value.String() 51} 52 53// Duration looks up the value of a local DurationFlag, returns 54// 0 if not found 55func (c *Context) Duration(name string) time.Duration { 56 return lookupDuration(name, c.flagSet) 57} 58 59// GlobalDuration looks up the value of a global DurationFlag, returns 60// 0 if not found 61func (c *Context) GlobalDuration(name string) time.Duration { 62 if fs := lookupGlobalFlagSet(name, c); fs != nil { 63 return lookupDuration(name, fs) 64 } 65 return 0 66} 67 68// Apply populates the flag given the flag set and environment 69// Ignores errors 70func (f DurationFlag) Apply(set *flag.FlagSet) { 71 _ = f.ApplyWithError(set) 72} 73 74// ApplyWithError populates the flag given the flag set and environment 75func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error { 76 if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { 77 envValDuration, err := time.ParseDuration(envVal) 78 if err != nil { 79 return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err) 80 } 81 82 f.Value = envValDuration 83 } 84 85 eachName(f.Name, func(name string) { 86 if f.Destination != nil { 87 set.DurationVar(f.Destination, name, f.Value, f.Usage) 88 return 89 } 90 set.Duration(name, f.Value, f.Usage) 91 }) 92 93 return nil 94} 95 96func lookupDuration(name string, set *flag.FlagSet) time.Duration { 97 f := set.Lookup(name) 98 if f != nil { 99 parsed, err := time.ParseDuration(f.Value.String()) 100 if err != nil { 101 return 0 102 } 103 return parsed 104 } 105 return 0 106} 107