...
1 package cli
2
3 import (
4 "flag"
5 "fmt"
6 "strconv"
7 )
8
9
10 func (f *IntFlag) TakesValue() bool {
11 return true
12 }
13
14
15 func (f *IntFlag) GetUsage() string {
16 return f.Usage
17 }
18
19
20 func (f *IntFlag) GetCategory() string {
21 return f.Category
22 }
23
24
25
26 func (f *IntFlag) GetValue() string {
27 return fmt.Sprintf("%d", f.Value)
28 }
29
30
31 func (f *IntFlag) GetDefaultText() string {
32 if f.DefaultText != "" {
33 return f.DefaultText
34 }
35 if f.defaultValueSet {
36 return fmt.Sprintf("%d", f.defaultValue)
37 }
38 return fmt.Sprintf("%d", f.Value)
39 }
40
41
42 func (f *IntFlag) GetEnvVars() []string {
43 return f.EnvVars
44 }
45
46
47 func (f *IntFlag) Apply(set *flag.FlagSet) error {
48
49 f.defaultValue = f.Value
50 f.defaultValueSet = true
51
52 if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found {
53 if val != "" {
54 valInt, err := strconv.ParseInt(val, f.Base, 64)
55
56 if err != nil {
57 return fmt.Errorf("could not parse %q as int value from %s for flag %s: %s", val, source, f.Name, err)
58 }
59
60 f.Value = int(valInt)
61 f.HasBeenSet = true
62 }
63 }
64
65 for _, name := range f.Names() {
66 if f.Destination != nil {
67 set.IntVar(f.Destination, name, f.Value, f.Usage)
68 continue
69 }
70 set.Int(name, f.Value, f.Usage)
71 }
72
73 return nil
74 }
75
76
77 func (f *IntFlag) Get(ctx *Context) int {
78 return ctx.Int(f.Name)
79 }
80
81
82 func (f *IntFlag) RunAction(c *Context) error {
83 if f.Action != nil {
84 return f.Action(c, c.Int(f.Name))
85 }
86
87 return nil
88 }
89
90
91
92 func (cCtx *Context) Int(name string) int {
93 if fs := cCtx.lookupFlagSet(name); fs != nil {
94 return lookupInt(name, fs)
95 }
96 return 0
97 }
98
99 func lookupInt(name string, set *flag.FlagSet) int {
100 f := set.Lookup(name)
101 if f != nil {
102 parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
103 if err != nil {
104 return 0
105 }
106 return int(parsed)
107 }
108 return 0
109 }
110
View as plain text