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