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