-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathitem.go
248 lines (227 loc) · 5.52 KB
/
item.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package opts
import (
"encoding"
"errors"
"fmt"
"reflect"
"time"
)
//item group represents a single "Options" block
//in the help text ouput
type itemGroup struct {
name string
flags []*item
}
const defaultGroup = ""
//item is the structure representing a
//an opt item. it also implements flag.Value
//generically using reflect.
type item struct {
val reflect.Value
mode string
name string
shortName string
envName string
useEnv bool
help string
defstr string
slice bool
min, max int //valid if slice
noarg bool
completer Completer
sets int
}
func newItem(val reflect.Value) (*item, error) {
if !val.IsValid() {
return nil, fmt.Errorf("invalid value")
}
i := &item{}
supported := false
//take interface value V
v := val.Interface()
pv := interface{}(nil)
if val.CanAddr() {
pv = val.Addr().Interface()
}
//convert V or &V into a setter:
for _, t := range []interface{}{v, pv} {
if tm, ok := t.(encoding.TextUnmarshaler); ok {
v = &textValue{tm}
} else if bm, ok := t.(encoding.BinaryUnmarshaler); ok {
v = &binaryValue{bm}
} else if d, ok := t.(*time.Duration); ok {
v = newDurationValue(d)
} else if s, ok := t.(Setter); ok {
v = s
}
}
//implements setter (flag.Value)?
if s, ok := v.(Setter); ok {
supported = true
//NOTE: replacing val removes our ability to set
//the value, resolved by flag.Value handling all Set calls.
val = reflect.ValueOf(s)
}
//implements completer?
if c, ok := v.(Completer); ok {
i.completer = c
}
//val must be concrete at this point
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
//lock in val
i.val = val
i.slice = val.Kind() == reflect.Slice
//prevent defaults on slices (should vals be appended? should it be reset? how to display defaults?)
if i.slice && val.Len() > 0 {
return nil, fmt.Errorf("slices cannot have default values")
}
//type checks
t := i.elemType()
if t.Kind() == reflect.Ptr {
return nil, fmt.Errorf("slice elem (%s) cannot be a pointer", t.Kind())
} else if i.slice && t.Kind() == reflect.Bool {
return nil, fmt.Errorf("slice of bools not supported")
}
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.String, reflect.Bool:
supported = true
}
//use the inner bool flag, if defined, otherwise if bool
if bf, ok := v.(interface{ IsBoolFlag() bool }); ok {
i.noarg = bf.IsBoolFlag()
} else if t.Kind() == reflect.Bool {
i.noarg = true
}
if !supported {
return nil, fmt.Errorf("field type not supported: %s", t.Kind())
}
return i, nil
}
func (i *item) set() bool {
return i.sets != 0
}
func (i *item) elemType() reflect.Type {
t := i.val.Type()
if i.slice {
t = t.Elem()
}
return t
}
func (i *item) String() string {
if !i.val.IsValid() {
return ""
}
v := i.val.Interface()
if s, ok := v.(fmt.Stringer); ok {
return s.String()
}
return fmt.Sprintf("%v", v)
}
func (i *item) Set(s string) error {
//can only set singles once
if i.sets != 0 && !i.slice {
return errors.New("already set")
}
//set has two modes, slice and inplace.
// when slice, create a new zero value, scan into it, append to slice
// when inplace, take pointer, scan into it
var elem reflect.Value
if i.slice {
elem = reflect.New(i.elemType()) //ptr
} else if i.val.CanAddr() {
elem = i.val.Addr() //pointer to concrete type
} else {
elem = i.val //possibly interface type
}
v := elem.Interface()
//convert string into value
if fv, ok := v.(Setter); ok {
//addr implements set
if err := fv.Set(s); err != nil {
return err
}
} else if elem.Kind() == reflect.Ptr && elem.Elem().Kind() == reflect.String {
src := reflect.ValueOf(s)
dst := elem.Elem()
//convert custom string types
st := src.Type()
dt := dst.Type()
if !st.AssignableTo(dt) {
//should always be convertable since kind==string
if !st.ConvertibleTo(dt) {
return fmt.Errorf("cannot convert %s to %s", st, dt)
}
src = src.Convert(dt)
}
dst.Set(src)
} else if elem.Kind() == reflect.Ptr {
//magic set with scanf
n, err := fmt.Sscanf(s, "%v", v)
if err != nil {
return err
} else if n == 0 {
return errors.New("could not be parsed")
}
} else {
return errors.New("could not be set")
}
//slice? append!
if i.slice {
//no pointer elems
if elem.Kind() == reflect.Ptr {
elem = elem.Elem()
}
//append!
i.val.Set(reflect.Append(i.val, elem))
}
//mark item as set!
i.sets++
//done
return nil
}
//IsBoolFlag implements the hidden interface
//documented here https://golang.org/pkg/flag/#Value
func (i *item) IsBoolFlag() bool {
return i.noarg
}
//noopValue defines a flag value which does nothing
var noopValue = noopValueType(0)
type noopValueType int
func (noopValueType) String() string {
return ""
}
func (noopValueType) Set(s string) error {
return nil
}
//textValue wraps marshaller into a setter
type textValue struct {
encoding.TextUnmarshaler
}
func (t textValue) Set(s string) error {
return t.UnmarshalText([]byte(s))
}
//binaryValue wraps marshaller into a setter
type binaryValue struct {
encoding.BinaryUnmarshaler
}
func (t binaryValue) Set(s string) error {
return t.UnmarshalBinary([]byte(s))
}
//borrowed from the stdlib :)
type durationValue time.Duration
func newDurationValue(p *time.Duration) *durationValue {
return (*durationValue)(p)
}
func (d *durationValue) Set(s string) error {
v, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = durationValue(v)
return nil
}