-
Notifications
You must be signed in to change notification settings - Fork 0
/
enum.go
117 lines (102 loc) · 2.07 KB
/
enum.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
package cli
import (
"fmt"
"strconv"
"strings"
)
type Enum struct {
target *string
defval *string // default value
}
func (v *Enum) Default(value string) {
v.defval = &value
}
type enumValue struct {
inner *Enum
set bool
possibilities []string
}
func (v *enumValue) check(displayName, val string) error {
for _, p := range v.possibilities {
if p == val {
return nil
}
}
s := new(strings.Builder)
lp := len(v.possibilities)
for i, p := range v.possibilities {
if i == lp-1 {
s.WriteString(" or ")
} else if i > 0 {
s.WriteString(", ")
}
s.WriteString(strconv.Quote(p))
}
return fmt.Errorf("%s %q must be either %s", displayName, val, s.String())
}
func (v *enumValue) verify(displayName string) error {
if v.set {
if err := v.check(displayName, *v.inner.target); err != nil {
return err
}
return nil
} else if v.inner.defval != nil {
if err := v.check(displayName, *v.inner.defval); err != nil {
return err
}
*v.inner.target = *v.inner.defval
return nil
}
return fmt.Errorf("missing %s", displayName)
}
func (v *enumValue) Set(val string) error {
*v.inner.target = val
v.set = true
return nil
}
func (v *enumValue) String() string {
if v.inner == nil {
return ""
} else if v.set {
return *v.inner.target
} else if v.inner.defval != nil {
return *v.inner.defval
}
return ""
}
type EnumValue struct {
target **string
defval *string // default value
}
func (v *EnumValue) Default(value string) {
v.defval = &value
}
type optionalEnumValue struct {
inner *EnumValue
set bool
}
var _ value = (*optionalEnumValue)(nil)
func (v *optionalEnumValue) verify(displayName string) error {
if v.set {
return nil
} else if v.inner.defval != nil {
*v.inner.target = v.inner.defval
return nil
}
return nil
}
func (v *optionalEnumValue) Set(val string) error {
*v.inner.target = &val
v.set = true
return nil
}
func (v *optionalEnumValue) String() string {
if v.inner == nil {
return ""
} else if v.set {
return **v.inner.target
} else if v.inner.defval != nil {
return *v.inner.defval
}
return ""
}