Repository navigation
Expand file tree
/
Copy pathflag_impl.go
More file actions
434 lines (381 loc) · 14 KB
/
Copy pathflag_impl.go
File metadata and controls
434 lines (381 loc) · 14 KB
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
package cli
import (
"context"
"flag"
"fmt"
"reflect"
"strings"
"time"
)
// Value represents a value as used by cli.
// For now it implements the golang flag.Value interface
type Value interface {
flag.Value
flag.Getter
}
type boolFlag interface {
IsBoolFlag() bool
}
type multiValueParsingConfig struct {
// SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
SliceFlagSeparator string
// DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
DisableSliceFlagSeparator bool
// MapFlagKeyValueSeparator is used to customize the separator for MapFlag, the default is "="
MapFlagKeyValueSeparator string
}
type multiValueParsingConfigSetter interface {
// configuration of parsing
setMultiValueParsingConfig(c multiValueParsingConfig)
}
// ValueCreator is responsible for creating a flag.Value emulation
// as well as custom formatting
//
// T specifies the type
// C specifies the config for the type
type ValueCreator[T any, C any] interface {
Create(T, *T, C) Value
ToString(T) string
}
// NoConfig is for flags which dont need a custom configuration
type NoConfig struct{}
// FlagBase [T,C,VC] is a generic flag base which can be used
// as a boilerplate to implement the most common interfaces
// used by urfave/cli.
//
// T specifies the type
// C specifies the configuration required(if any for that flag type)
// VC specifies the value creator which creates the flag.Value emulation
type FlagBase[T any, C any, VC ValueCreator[T, C]] struct {
Name string `json:"name"` // name of the flag
Category string `json:"category"` // category of the flag, if any
DefaultText string `json:"defaultText"` // default text of the flag for usage purposes
HideDefault bool `json:"hideDefault"` // whether to hide the default value in output
Usage string `json:"usage"` // usage string for help output
Sources ValueSourceChain `json:"-"` // sources to load flag value from
Required bool `json:"required"` // whether the flag is required or not
Hidden bool `json:"hidden"` // whether to hide the flag in help output
Deprecated string `json:"deprecated"` // deprecation message, if set a warning is printed when the flag is set
Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well
Value T `json:"defaultValue"` // default value for this flag if not set by from any source
Destination *T `json:"-"` // destination pointer for value when set
Aliases []string `json:"aliases"` // Aliases that are allowed for this flag
TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes
Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set
Config C `json:"config"` // Additional/Custom configuration associated with this flag type
OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line
Validator func(T) error `json:"-"` // custom function to validate this flag value
ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not
// unexported fields for internal use
count int // number of times the flag has been set
hasBeenSet bool // whether the flag has been set from env or file
fromSource bool // whether the current value came from Sources
applied bool // whether the flag has been applied to a flag set already
creator VC // value creator for this flag type
value Value // value representing this flag's value
stringer FlagStringFunc // optional per-flag override of FlagStringer
multiValueConfig *multiValueParsingConfig // last parsing config passed to value
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *FlagBase[T, C, V]) GetValue() string {
var v V
return v.ToString(f.Value)
}
// TypeName returns the type of the flag.
func (f *FlagBase[T, C, V]) TypeName() string {
ty := reflect.TypeOf(f.Value)
if ty == nil {
return ""
}
// convert the typename to generic type
convertToGenericType := func(name string) string {
prefixMap := map[string]string{
"float": "float",
"int": "int",
"uint": "uint",
}
for prefix, genericType := range prefixMap {
if strings.HasPrefix(name, prefix) {
return genericType
}
}
return strings.ToLower(name)
}
switch ty.Kind() {
// if it is a Slice, then return the slice's inner type. Will nested slices be used in the future?
case reflect.Slice:
elemType := ty.Elem()
return convertToGenericType(elemType.Name())
// if it is a Map, then return the map's key and value types.
case reflect.Map:
keyType := ty.Key()
valueType := ty.Elem()
return fmt.Sprintf("%s=%s", convertToGenericType(keyType.Name()), convertToGenericType(valueType.Name()))
default:
return convertToGenericType(ty.Name())
}
}
// PostParse populates the flag given the flag set and environment
func (f *FlagBase[T, C, V]) PostParse() error {
tracef("postparse (flag=%[1]q)", f.Name)
if !f.hasBeenSet {
// reflect.TypeOf yields nil when T is an interface type (e.g.
// GenericFlag) and the value is nil, so the kind has to be
// derived defensively.
kind := reflect.Invalid
if ty := reflect.TypeOf(f.Value); ty != nil {
kind = ty.Kind()
}
// An empty value is a value only for a string, and reads as false
// for a bool. Any other kind has nothing to parse from it, so an
// empty source is skipped: it neither marks the flag as set nor
// hides a later source in the chain.
emptyIsValue := kind == reflect.String || kind == reflect.Bool
for _, source := range f.Sources.Chain {
val, found := source.Lookup()
if !found || (val == "" && !emptyIsValue) {
continue
}
if val == "" && kind == reflect.Bool {
val = "false"
}
if err := f.Set(f.Name, val); err != nil {
return fmt.Errorf(
"could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s",
val, f.Value, source, f.Name, err,
)
}
f.hasBeenSet = true
f.fromSource = true
break
}
}
return nil
}
// pass configuration of parsing to value
func (f *FlagBase[T, C, V]) setMultiValueParsingConfig(c multiValueParsingConfig) {
tracef("setMultiValueParsingConfig %T, %+v", f.value, f.value)
f.multiValueConfig = &c
if cf, ok := f.value.(multiValueParsingConfigSetter); ok {
cf.setMultiValueParsingConfig(c)
}
}
// newValue creates the flag's value holding the default Value.
func (f *FlagBase[T, C, V]) newValue() Value {
if f.Destination == nil {
return f.creator.Create(f.Value, new(T), f.Config)
}
return f.creator.Create(f.Value, f.Destination, f.Config)
}
func (f *FlagBase[T, C, V]) getTypedValue() T {
value := f.value.Get()
if typed, ok := value.(T); ok {
return typed
}
// A GenericFlag's Getter may expose a payload rather than a cli.Value.
if generic, ok := f.value.(*genericValue); ok {
var typed T
if generic.val != nil {
typed = any(generic.val).(T)
}
return typed
}
return value.(T)
}
func (f *FlagBase[T, C, V]) PreParse() error {
f.value = f.newValue()
// Validate the given default or values set from external sources as well
if f.Validator != nil && f.ValidateDefaults {
if err := f.Validator(f.getTypedValue()); err != nil {
return err
}
}
f.applied = true
return nil
}
// Set applies given value from string
func (f *FlagBase[T, C, V]) Set(_ string, val string) error {
tracef("apply (flag=%[1]q)", f.Name)
// TODO move this phase into a separate flag initialization function
// if flag has been applied previously then it would have already been set
// from env or file. So no need to apply the env set again. However
// lots of units tests prior to persistent flags assumed that the
// flag can be applied to different flag sets multiple times while still
// keeping the env set.
if !f.applied {
if err := f.PreParse(); err != nil {
return err
}
f.applied = true
}
// A value from Sources is only a fallback, so a value set afterwards
// replaces it rather than being added to it or counted as a duplicate.
// This happens for a persistent flag: its command reads the Sources
// before a subcommand parses the flag from the command line.
if f.fromSource {
f.fromSource = false
f.count = 0
f.value = f.newValue()
if f.multiValueConfig != nil {
f.setMultiValueParsingConfig(*f.multiValueConfig)
}
}
if f.count == 1 && f.OnlyOnce {
return fmt.Errorf("can't duplicate this flag")
}
f.count++
if err := f.value.Set(val); err != nil {
return err
}
f.hasBeenSet = true
if f.Validator != nil {
if err := f.Validator(f.getTypedValue()); err != nil {
return err
}
}
return nil
}
func (f *FlagBase[T, C, V]) Get() any {
if f.value != nil {
return f.value.Get()
}
return f.Value
}
// IsDefaultVisible returns true if the flag is not hidden, otherwise false
func (f *FlagBase[T, C, V]) IsDefaultVisible() bool {
return !f.HideDefault
}
// String returns a readable representation of this value (for usage defaults)
func (f *FlagBase[T, C, V]) String() string {
if f.stringer != nil {
return f.stringer(f)
}
return FlagStringer(f)
}
// SetStringer overrides the [FlagStringFunc] used by this flag's String
// method. Passing nil restores the default behavior of using the
// package-level [FlagStringer]. This is used e.g. by
// [MutuallyExclusiveFlags.Stringer].
func (f *FlagBase[T, C, V]) SetStringer(s FlagStringFunc) {
f.stringer = s
}
// IsSet returns whether or not the flag has been set through env or file
func (f *FlagBase[T, C, V]) IsSet() bool {
return f.hasBeenSet
}
// Names returns the names of the flag
func (f *FlagBase[T, C, V]) Names() []string {
return FlagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *FlagBase[T, C, V]) IsRequired() bool {
return f.Required
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *FlagBase[T, C, V]) IsVisible() bool {
return !f.Hidden
}
// GetDeprecated returns the deprecation message of the flag
func (f *FlagBase[T, C, V]) GetDeprecated() string {
return f.Deprecated
}
// GetCategory returns the category of the flag
func (f *FlagBase[T, C, V]) GetCategory() string {
return f.Category
}
func (f *FlagBase[T, C, V]) SetCategory(c string) {
f.Category = c
}
// GetUsage returns the usage string for the flag
func (f *FlagBase[T, C, V]) GetUsage() string {
return f.Usage
}
// GetEnvVars returns the env vars for this flag
func (f *FlagBase[T, C, V]) GetEnvVars() []string {
return f.Sources.EnvKeys()
}
// TakesValue returns true if the flag takes a value, otherwise false
func (f *FlagBase[T, C, V]) TakesValue() bool {
var t T
return reflect.TypeOf(t) == nil || reflect.TypeOf(t).Kind() != reflect.Bool
}
// GetDefaultText returns the default text for this flag
func (f *FlagBase[T, C, V]) GetDefaultText() string {
return f.DefaultText
}
// RunAction executes flag action if set
func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error {
if f.Action != nil {
return f.Action(ctx, cmd, f.getTypedValue())
}
return nil
}
// SchemaType returns the JSON Schema type for the flag's value type.
func (f *FlagBase[T, C, V]) SchemaType() string {
var zero T
switch any(zero).(type) {
case bool:
return "boolean"
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return "integer"
case float32, float64:
return "number"
case string:
return "string"
case time.Duration:
return "duration"
case time.Time:
return "date-time"
case []string, []int, []int8, []int16, []int32, []int64,
[]uint, []uint8, []uint16, []uint32, []uint64,
[]float32, []float64:
return "array"
case map[string]string:
return "object"
default:
return ""
}
}
// SchemaItemsType returns the JSON Schema element type for slice flags.
func (f *FlagBase[T, C, V]) SchemaItemsType() string {
var zero T
// reflect.TypeOf yields nil when T is an interface type (e.g. GenericFlag),
// in which case there are no slice elements to describe.
t := reflect.TypeOf(zero)
if t != nil && t.Kind() == reflect.Slice {
switch t.Elem().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "integer"
case reflect.Float32, reflect.Float64:
return "number"
case reflect.String:
return "string"
}
}
return ""
}
// IsMultiValueFlag returns true if the value type T can take multiple
// values from cmd line. This is true for slice and map type flags
func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool {
// TBD how to specify
if reflect.TypeOf(f.Value) == nil {
return false
}
kind := reflect.TypeOf(f.Value).Kind()
return kind == reflect.Slice || kind == reflect.Map
}
// IsLocal returns false if flag needs to be persistent across subcommands
func (f *FlagBase[T, C, VC]) IsLocal() bool {
return f.Local
}
// IsBoolFlag returns whether the flag doesn't need to accept args
func (f *FlagBase[T, C, VC]) IsBoolFlag() bool {
bf, ok := f.value.(boolFlag)
return ok && bf.IsBoolFlag()
}
// Count returns the number of times this flag has been invoked
func (f *FlagBase[T, C, VC]) Count() int {
return f.count
}