-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflagx.go
73 lines (63 loc) · 1.85 KB
/
flagx.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
package flagx
import (
"encoding"
"reflect"
)
// Value is like [flag.Getter] (which is a superset of [flag.Value]).
type Value interface {
String() string
Set(string) error
Get() interface{}
}
// Dummy is a [flag.Value] that does nothing.
type Dummy struct{}
func (Dummy) String() string { return "" }
func (Dummy) Set(s string) error { return nil }
func (Dummy) Get() interface{} { return nil }
// stringSetter is the subset of [flag.Value] for setting a value from a string
type stringSetter interface {
// See [flag.Value.Set].
Set(string) error
}
var (
textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem()
stringSetterType = reflect.TypeOf(new(stringSetter)).Elem()
)
func setterFor(typ reflect.Type) func(target reflect.Value, value string) error {
switch {
case reflect.PtrTo(typ).Implements(stringSetterType):
return func(target reflect.Value, value string) error {
return target.Addr().Interface().(stringSetter).Set(value)
}
case reflect.PtrTo(typ).Implements(textUnmarshalerType):
return func(target reflect.Value, value string) error {
return target.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value))
}
case typ.Implements(stringSetterType):
return func(target reflect.Value, value string) error {
return target.Interface().(stringSetter).Set(value)
}
case typ.Implements(textUnmarshalerType):
return func(target reflect.Value, value string) error {
return target.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value))
}
case typ.Kind() == reflect.String:
return func(target reflect.Value, value string) error {
target.SetString(value)
return nil
}
default:
return nil
}
}
func isBoolFlag(f interface {
String() string
Set(string) error
}) bool {
if bf, ok := f.(interface {
IsBoolFlag() bool
}); ok {
return bf.IsBoolFlag()
}
return false
}