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