-
Notifications
You must be signed in to change notification settings - Fork 37
/
parser.go
295 lines (259 loc) · 7.72 KB
/
parser.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
package sflags
import (
"errors"
"reflect"
"strings"
)
const (
defaultDescTag = "desc"
defaultFlagTag = "flag"
defaultEnvTag = "env"
defaultFlagDivider = "-"
defaultEnvDivider = "_"
defaultFlatten = true
)
// ValidateFunc describes a validation func,
// that takes string val for flag from command line,
// field that's associated with this flag in structure cfg.
// Should return error if validation fails.
type ValidateFunc func(val string, field reflect.StructField, cfg interface{}) error
type opts struct {
descTag string
flagTag string
prefix string
envPrefix string
flagDivider string
envDivider string
flatten bool
validator ValidateFunc
}
func (o opts) apply(optFuncs ...OptFunc) opts {
for _, optFunc := range optFuncs {
optFunc(&o)
}
return o
}
// OptFunc sets values in opts structure.
type OptFunc func(opt *opts)
// DescTag sets custom description tag. It is "desc" by default.
func DescTag(val string) OptFunc { return func(opt *opts) { opt.descTag = val } }
// FlagTag sets custom flag tag. It is "flag" be default.
func FlagTag(val string) OptFunc { return func(opt *opts) { opt.flagTag = val } }
// Prefix sets prefix that will be applied for all flags (if they are not marked as ~).
func Prefix(val string) OptFunc { return func(opt *opts) { opt.prefix = val } }
// EnvPrefix sets prefix that will be applied for all environment variables (if they are not marked as ~).
func EnvPrefix(val string) OptFunc { return func(opt *opts) { opt.envPrefix = val } }
// FlagDivider sets custom divider for flags. It is dash by default. e.g. "flag-name".
func FlagDivider(val string) OptFunc { return func(opt *opts) { opt.flagDivider = val } }
// EnvDivider sets custom divider for environment variables.
// It is underscore by default. e.g. "ENV_NAME".
func EnvDivider(val string) OptFunc { return func(opt *opts) { opt.envDivider = val } }
// Validator sets validator function for flags.
// Check existed validators in sflags/validator package.
func Validator(val ValidateFunc) OptFunc { return func(opt *opts) { opt.validator = val } }
// Flatten set flatten option.
// Set to false if you don't want anonymous structure fields to be flatten.
func Flatten(val bool) OptFunc { return func(opt *opts) { opt.flatten = val } }
func copyOpts(val opts) OptFunc { return func(opt *opts) { *opt = val } }
func hasOption(options []string, option string) bool {
for _, opt := range options {
if opt == option {
return true
}
}
return false
}
func defOpts() opts {
return opts{
descTag: defaultDescTag,
flagTag: defaultFlagTag,
flagDivider: defaultFlagDivider,
envDivider: defaultEnvDivider,
flatten: defaultFlatten,
}
}
func parseFlagTag(field reflect.StructField, opt opts) *Flag {
flag := Flag{}
ignoreFlagPrefix := false
flag.Name = camelToFlag(field.Name, opt.flagDivider)
if flagTags := strings.Split(field.Tag.Get(opt.flagTag), ","); len(flagTags) > 0 {
switch fName := flagTags[0]; fName {
case "-":
return nil
case "":
default:
fNameSplitted := strings.Split(fName, " ")
if len(fNameSplitted) > 1 {
fName = fNameSplitted[0]
flag.Short = fNameSplitted[1]
}
if strings.HasPrefix(fName, "~") {
flag.Name = fName[1:]
ignoreFlagPrefix = true
} else {
flag.Name = fName
}
}
flag.Hidden = hasOption(flagTags[1:], "hidden")
flag.Deprecated = hasOption(flagTags[1:], "deprecated")
flag.Required = hasOption(flagTags[1:], "required")
}
if opt.prefix != "" && !ignoreFlagPrefix {
flag.Name = opt.prefix + flag.Name
}
return &flag
}
func parseEnv(flagName string, field reflect.StructField, opt opts) string {
ignoreEnvPrefix := false
envVar := flagToEnv(flagName, opt.flagDivider, opt.envDivider)
if envTags := strings.Split(field.Tag.Get(defaultEnvTag), ","); len(envTags) > 0 {
switch envName := envTags[0]; envName {
case "-":
// if tag is `env:"-"` then won't fill flag from environment
envVar = ""
case "":
// if tag is `env:""` then env var will be taken from flag name
default:
// if tag is `env:"NAME"` then env var is envPrefix_flagPrefix_NAME
// if tag is `env:"~NAME"` then env var is NAME
if strings.HasPrefix(envName, "~") {
envVar = envName[1:]
ignoreEnvPrefix = true
} else {
envVar = envName
if opt.prefix != "" {
envVar = flagToEnv(
opt.prefix,
opt.flagDivider,
opt.envDivider) + envVar
}
}
}
}
if envVar != "" && opt.envPrefix != "" && !ignoreEnvPrefix {
envVar = opt.envPrefix + envVar
}
return envVar
}
// ParseStruct parses structure and returns list of flags based on this structure.
// This list of flags can be used by generators for flag, kingpin, cobra, pflag, urfave/cli.
func ParseStruct(cfg interface{}, optFuncs ...OptFunc) ([]*Flag, error) {
// what we want is Ptr to Structure
if cfg == nil {
return nil, errors.New("object cannot be nil")
}
v := reflect.ValueOf(cfg)
if v.Kind() != reflect.Ptr {
return nil, errors.New("object must be a pointer to struct or interface")
}
if v.IsNil() {
return nil, errors.New("object cannot be nil")
}
switch e := v.Elem(); e.Kind() {
case reflect.Struct:
return parseStruct(e, optFuncs...), nil
default:
return nil, errors.New("object must be a pointer to struct or interface")
}
}
func parseVal(value reflect.Value, optFuncs ...OptFunc) ([]*Flag, Value) {
// value is addressable, let's check if we can parse it
if value.CanAddr() && value.Addr().CanInterface() {
valueInterface := value.Addr().Interface()
val := parseGenerated(valueInterface)
if val != nil {
return nil, val
}
// check if field implements Value interface
if val, casted := valueInterface.(Value); casted {
return nil, val
}
}
switch value.Kind() {
case reflect.Ptr:
if value.IsNil() {
value.Set(reflect.New(value.Type().Elem()))
}
val := parseGeneratedPtrs(value.Addr().Interface())
if val != nil {
return nil, val
}
return parseVal(value.Elem(), optFuncs...)
case reflect.Struct:
flags := parseStruct(value, optFuncs...)
return flags, nil
case reflect.Map:
mapType := value.Type()
keyKind := value.Type().Key().Kind()
// check that map key is string or integer
if !anyOf(MapAllowedKinds, keyKind) {
break
}
if value.IsNil() {
value.Set(reflect.MakeMap(mapType))
}
valueInterface := value.Addr().Interface()
val := parseGeneratedMap(valueInterface)
if val != nil {
return nil, val
}
}
return nil, nil
}
func parseStruct(value reflect.Value, optFuncs ...OptFunc) []*Flag {
opt := defOpts().apply(optFuncs...)
flags := []*Flag{}
valueType := value.Type()
fields:
for i := 0; i < value.NumField(); i++ {
field := valueType.Field(i)
fieldValue := value.Field(i)
// skip unexported and non anonymous fields
if field.PkgPath != "" && !field.Anonymous {
continue fields
}
flag := parseFlagTag(field, opt)
if flag == nil {
continue fields
}
flag.EnvName = parseEnv(flag.Name, field, opt)
flag.Usage = field.Tag.Get(opt.descTag)
prefix := flag.Name + opt.flagDivider
if field.Anonymous && opt.flatten {
prefix = opt.prefix
}
nestedFlags, val := parseVal(fieldValue,
copyOpts(opt),
Prefix(prefix),
)
// field contains a simple value.
if val != nil {
if opt.validator != nil {
val = &validateValue{
Value: val,
validateFunc: func(val string) error {
return opt.validator(val, field, value.Interface())
},
}
}
flag.Value = val
flag.DefValue = val.String()
flags = append(flags, flag)
continue fields
}
// field is a structure
if len(nestedFlags) > 0 {
flags = append(flags, nestedFlags...)
continue fields
}
}
return flags
}
func anyOf(kinds []reflect.Kind, needle reflect.Kind) bool {
for _, kind := range kinds {
if kind == needle {
return true
}
}
return false
}