-
Notifications
You must be signed in to change notification settings - Fork 45
/
flag.go
467 lines (442 loc) · 12.8 KB
/
flag.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package utils
import (
"bytes"
"flag"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/pkg/errors"
)
// ParseFlags parses arguments derived from and into the given into struct.
func ParseFlags(args []string, into interface{}) error {
if len(args) == 0 || into == nil {
return nil
}
cmdLine := flag.NewFlagSet(args[0], flag.ContinueOnError)
var buf bytes.Buffer
cmdLine.SetOutput(&buf)
if err := extractFlags(cmdLine, into); err != nil {
return fmt.Errorf("error extracing flags: %w", err)
}
if err := cmdLine.Parse(args[1:]); err != nil {
if errors.Is(err, flag.ErrHelp) {
return errors.New(buf.String())
}
return errors.Errorf("%s\n%s", buf.String(), err)
}
if err := UnmarshalFlags(cmdLine, into); err != nil {
if errors.Is(err, errRequiredFlagUnspecified) {
cmdLine.Usage()
return errors.Errorf("%s\n%s", err, buf.String())
}
return err
}
return nil
}
var errRequiredFlagUnspecified = errors.New("flag required but not specified")
// UnmarshalFlags unmarshals parsed flags into the given value.
func UnmarshalFlags(flagSet *flag.FlagSet, into interface{}) error {
numPositionalsTotal := len(flagSet.Args())
numPositionalsLeft := make(map[int]struct{}, numPositionalsTotal)
for i := 0; i < numPositionalsTotal; i++ {
numPositionalsLeft[i] = struct{}{}
}
v := reflect.ValueOf(into)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Type().Kind() != reflect.Struct || !v.CanAddr() {
return errors.Errorf("expected %T to be an addressable struct", into)
}
var extraField reflect.Value
var extraFieldName string
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
flagStr, ok := field.Tag.Lookup("flag")
if !ok {
continue
}
info, err := parseFlagInfo(field, flagStr)
if err != nil {
return err
}
if info.Extra {
if extraField.IsValid() {
return errors.Errorf("found more than one extra field %q; first was %q", field.Name, extraFieldName)
}
extraField = v.Field(i)
extraFieldName = field.Name
continue
}
var val interface{}
var flagValIsSet bool
if info.Positional {
strVal := flagSet.Arg(info.Position)
if info.Position < numPositionalsTotal {
delete(numPositionalsLeft, info.Position)
}
if info.IsFlagVal {
if strVal == "" {
val = info.Default
} else {
val = strVal
}
} else {
if strVal == "" {
val = info.DefaultIfc
} else {
switch field.Type.Kind() {
case reflect.String:
val = strVal
case reflect.Int:
conv, err := strconv.ParseInt(strVal, 10, 64)
if err != nil {
return errors.Wrapf(err, "error parsing positional argument %d", info.Position)
}
val = int(conv)
case reflect.Bool:
conv, err := strconv.ParseBool(strVal)
if err != nil {
return errors.Wrapf(err, "error parsing positional argument %d", info.Position)
}
val = conv
case reflect.Array, reflect.Chan, reflect.Complex128, reflect.Complex64, reflect.Float32,
reflect.Float64, reflect.Func, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8,
reflect.Interface, reflect.Invalid, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8, reflect.Uintptr,
reflect.UnsafePointer:
fallthrough
default:
return errors.Errorf("error parsing positional argument %d for %s: do not know how to unmarshal a %q",
info.Position,
info.Name,
field.Type.Kind())
}
}
}
} else {
flagVal := flagSet.Lookup(info.Name)
if flagVal == nil {
if info.Required {
return errors.Wrapf(errRequiredFlagUnspecified, "error parsing flag %q", info.Name)
}
if info.IsFlagVal {
val = info.Default
} else {
val = info.DefaultIfc
}
} else {
if info.IsFlagVal {
flagValP, ok := flagVal.Value.(*flagValueProxy)
if !ok {
panic(errors.Errorf("expected *flagValueProxy but got %T", flagVal.Value))
}
if flagValP.IsSet {
flagValIsSet = true
if field.Type.Kind() != reflect.Ptr {
// no more work to do here
continue
}
val = flagVal.Value.(flag.Getter).Get()
} else {
val = info.Default
}
} else {
val = flagVal.Value.(flag.Getter).Get()
}
}
}
if info.Required && (val == nil || reflect.ValueOf(val).IsZero()) {
return errors.Wrapf(errRequiredFlagUnspecified, "error parsing flag %q", info.Name)
}
valV := reflect.ValueOf(val)
if !valV.IsValid() {
continue
}
if !info.DefaultSet && valV.IsZero() {
continue
}
fieldV := v.Field(i)
if info.IsFlagVal && !flagValIsSet {
if reflect.PointerTo(fieldV.Type()).Implements(flagValueT) {
fieldV = fieldV.Addr()
}
if err := fieldV.Interface().(flag.Value).Set(val.(string)); err != nil { // will always be string
return errors.Wrapf(err, "error parsing flag %q", info.Name)
}
continue
}
if field.Type.Kind() == reflect.Slice {
fieldSlice := v.Field(i)
for i := 0; i < valV.Len(); i++ {
fieldSlice = reflect.Append(fieldSlice, valV.Index(i).Elem())
}
fieldV.Set(fieldSlice)
} else {
vT := fieldV.Type()
if vT.Kind() == reflect.Ptr {
newFieldV := reflect.New(vT.Elem())
fieldV.Set(newFieldV)
if valV.Kind() != reflect.Ptr {
fieldV = fieldV.Elem()
vT = vT.Elem()
}
}
if valV.Type().AssignableTo(vT) {
fieldV.Set(valV)
} else {
fieldV.Set(valV.Convert(vT))
}
}
}
if len(numPositionalsLeft) != 0 {
remArgs := make([]string, 0, len(numPositionalsLeft))
for idx := range numPositionalsLeft {
remArgs = append(remArgs, flagSet.Arg(idx))
}
if !extraField.IsValid() {
return errors.Errorf("unspecified arguments provided: %v", remArgs)
}
extraField.Set(reflect.ValueOf(remArgs))
}
return nil
}
type flagInfo struct {
Name string
Default string
DefaultIfc interface{}
DefaultSet bool
Usage string
Required bool
Positional bool
Position int
IsFlagVal bool
Extra bool
}
func parseFlagInfo(field reflect.StructField, val string) (flagInfo, error) {
fieldName := field.Name
valParts := strings.Split(val, ",")
if len(valParts) == 0 {
return flagInfo{Name: fieldName}, nil
}
var info flagInfo
info.Name = valParts[0]
if info.Name == "" {
info.Name = fieldName
}
if posIdx, err := strconv.ParseInt(info.Name, 10, 64); err == nil {
info.Positional = true
info.Position = int(posIdx)
info.Name = fmt.Sprintf("positional_arg_%d", posIdx)
}
if field.Type.Implements(flagValueT) || reflect.PointerTo(field.Type).Implements(flagValueT) {
info.IsFlagVal = true
}
for _, part := range valParts[1:] {
parted := strings.SplitN(part, "=", 2)
switch parted[0] {
case "required":
info.Required = true
case "default":
info.DefaultSet = true
if len(parted) != 2 {
return flagInfo{}, errors.Errorf("error parsing flag info for %q: default must have value", fieldName)
}
info.Default = parted[1]
switch field.Type.Kind() {
case reflect.Bool:
conv, err := strconv.ParseBool(info.Default)
if err != nil {
return flagInfo{}, errors.Wrapf(err, "error parsing flag info default for %q", fieldName)
}
info.DefaultIfc = conv
case reflect.String:
info.DefaultIfc = info.Default
case reflect.Int:
conv, err := strconv.ParseInt(info.Default, 10, 64)
if err != nil {
return flagInfo{}, errors.Wrapf(err, "error parsing flag info default for %q", fieldName)
}
info.DefaultIfc = int(conv)
case reflect.Array, reflect.Chan, reflect.Complex128, reflect.Complex64, reflect.Float32,
reflect.Float64, reflect.Func, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8,
reflect.Interface, reflect.Invalid, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8, reflect.Uintptr,
reflect.UnsafePointer:
fallthrough
default:
return flagInfo{}, errors.Errorf("error parsing flag infofor %q: unsupported default for flag kind %q", info.Name, field.Type.Kind())
}
case "usage":
if len(parted) != 2 {
return flagInfo{}, errors.Errorf("error parsing flag info for %q: usage must have usage string", fieldName)
}
info.Usage = parted[1]
case "extra":
if field.Type != reflect.TypeOf([]string(nil)) {
return flagInfo{}, errors.Errorf("error parsing flag info for %q: extra field must be []string", fieldName)
}
info.Extra = true
}
}
return info, nil
}
var flagValueT = reflect.TypeOf((*flag.Value)(nil)).Elem()
type flagValueProxy struct {
flag.Value
IsSet bool
}
func (fvp *flagValueProxy) String() string {
if fvp.Value == nil {
return ""
}
return fvp.Value.String()
}
func (fvp *flagValueProxy) Set(val string) error {
fvp.IsSet = true
return fvp.Value.Set(val)
}
func (fvp *flagValueProxy) Get() interface{} {
if fvp.Value == nil {
return nil
}
return fvp.Value.(flag.Getter).Get()
}
func extractFlags(flagSet *flag.FlagSet, from interface{}) error {
v := reflect.ValueOf(from)
t := v.Type()
if t.Kind() == reflect.Ptr {
v = v.Elem()
t = t.Elem()
}
if t.Kind() != reflect.Struct || !v.CanAddr() {
return errors.Errorf("expected %T to be an addressable struct", from)
}
var extraField reflect.Value
var extraFieldName string
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" {
continue // unexported
}
flagStr, ok := field.Tag.Lookup("flag")
if !ok {
continue
}
info, err := parseFlagInfo(field, flagStr)
if err != nil {
return err
}
if info.Extra {
if extraField.IsValid() {
return errors.Errorf("found more than one extra field %q; first was %q", field.Name, extraFieldName)
}
extraField = v.Field(i)
extraFieldName = field.Name
continue
}
fieldT := field.Type
if fieldT.Kind() == reflect.Ptr {
fieldT = fieldT.Elem()
}
if info.IsFlagVal {
flagValue := v.Field(i)
if flagValue.Kind() == reflect.Ptr {
flagValue = reflect.New(fieldT).Elem()
}
if reflect.PointerTo(fieldT).Implements(flagValueT) {
flagValue = flagValue.Addr()
}
flagSet.Var(&flagValueProxy{Value: flagValue.Interface().(flag.Value)}, info.Name, info.Usage)
continue
}
switch fieldT.Kind() {
case reflect.Bool:
var defaultVal bool
if info.Default != "" {
defaultVal, ok = info.DefaultIfc.(bool)
if !ok {
panic(errors.Errorf("expected int but got %T", info.DefaultIfc))
}
}
flagSet.Bool(info.Name, defaultVal, info.Usage)
case reflect.String:
flagSet.String(info.Name, info.Default, info.Usage)
case reflect.Int:
var defaultVal int
if info.Default != "" {
defaultVal, ok = info.DefaultIfc.(int)
if !ok {
panic(errors.Errorf("expected int but got %T", info.DefaultIfc))
}
}
flagSet.Int(info.Name, defaultVal, info.Usage)
case reflect.Slice:
sliceElem := fieldT.Elem()
var ctor func(val string) (interface{}, error)
if sliceElem.Implements(flagValueT) || reflect.PointerTo(sliceElem).Implements(flagValueT) {
ctor = func(val string) (interface{}, error) {
newSliceElem := reflect.New(sliceElem)
if err := newSliceElem.Interface().(flag.Value).Set(val); err != nil {
return nil, errors.Wrapf(err, "error setting flag for %q", info.Name)
}
return newSliceElem.Elem().Interface(), nil
}
} else {
return errors.Errorf("error extracting flag for %q: unsupported slice element type %q", info.Name, sliceElem)
}
flagSet.Var(&sliceFlag{
ctor: ctor,
}, info.Name, info.Usage)
case reflect.Array, reflect.Chan, reflect.Complex128, reflect.Complex64, reflect.Float32,
reflect.Float64, reflect.Func, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8,
reflect.Interface, reflect.Invalid, reflect.Map, reflect.Ptr, reflect.Struct,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8, reflect.Uintptr,
reflect.UnsafePointer:
fallthrough
default:
return errors.Errorf("error extracting flag for %q: unsupported flag kind %q", info.Name, fieldT.Kind())
}
}
return nil
}
type sliceFlag struct {
values []interface{}
ctor func(val string) (interface{}, error)
}
func (sf *sliceFlag) String() string {
return fmt.Sprintf("%v", sf.values)
}
func (sf *sliceFlag) Set(val string) error {
newVal, err := sf.ctor(val)
if err != nil {
return err
}
sf.values = append(sf.values, newVal)
return nil
}
func (sf *sliceFlag) Get() interface{} {
return sf.values
}
// NetPortFlag is used to correctly set and validate a
// network port.
type NetPortFlag int
// String returns the set value.
func (npf *NetPortFlag) String() string {
return fmt.Sprintf("%v", int(*npf))
}
// Set attempts to set the value as a network port.
func (npf *NetPortFlag) Set(val string) error {
portParsed, err := strconv.ParseUint(val, 10, 16)
if err != nil {
return err
}
*npf = NetPortFlag(portParsed)
return nil
}
// Get returns the value as an integer.
func (npf *NetPortFlag) Get() interface{} {
return int(*npf)
}