forked from alecthomas/kingpin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flags.go
394 lines (346 loc) · 9.83 KB
/
flags.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
package kingpin
import (
"fmt"
)
type flagGroup struct {
short map[string]*FlagClause
long map[string]*FlagClause
aliases map[string]flagAlias
flagOrder []*FlagClause
autoShortcut bool
}
func newFlagGroup() *flagGroup {
return &flagGroup{
short: map[string]*FlagClause{},
long: map[string]*FlagClause{},
}
}
// GetFlag gets a flag definition.
//
// This allows existing flags to be modified after definition but before parsing. Useful for
// modular applications.
func (f *flagGroup) GetFlag(name string) *FlagClause {
return f.long[name]
}
// Flag defines a new flag with the given long name and help.
func (f *flagGroup) Flag(name, help string) *FlagClause {
flag := newFlag(name, help)
f.long[name] = flag
f.flagOrder = append(f.flagOrder, flag)
return flag
}
// GetNames returns the list of flag names in declared order.
func (f *flagGroup) GetNames() (result []string) {
for i := range f.flagOrder {
result = append(result, f.flagOrder[i].name)
}
return
}
// DeleteFlag removes a flag from a flag group.
func (f *flagGroup) DeleteFlag(name string) error {
flag := f.GetFlag(name)
if flag == nil {
return fmt.Errorf("Flag %s does not exist", name)
}
delete(f.long, name)
// We find all the matches in the flagOrder list (a flag could have been defined more that once)
var matches []int
for i := range f.flagOrder {
if f.flagOrder[i].name == name {
matches = append(matches, i)
}
}
// We delete all found occurrences (starting with the last one)
for i := len(matches) - 1; i >= 0; i-- {
f.flagOrder = append(f.flagOrder[:matches[i]], f.flagOrder[matches[i]+1:]...)
}
return nil
}
func (f *flagGroup) init(defaultEnvarPrefix string) error {
if err := f.checkDuplicates(); err != nil {
return err
}
for _, flag := range f.long {
if defaultEnvarPrefix != "" && !flag.noEnvar && flag.envar == "" {
flag.envar = envarTransform(defaultEnvarPrefix + "_" + flag.name)
}
if err := flag.init(); err != nil {
return err
}
if flag.shorthand != 0 {
f.short[string(flag.shorthand)] = flag
}
}
return nil
}
func (f *flagGroup) checkDuplicates() error {
seenShort := map[rune]bool{}
seenLong := map[string]bool{}
for _, flag := range f.flagOrder {
if flag.shorthand != 0 {
if _, ok := seenShort[flag.shorthand]; ok {
return fmt.Errorf("duplicate short flag -%c", flag.shorthand)
}
seenShort[flag.shorthand] = true
}
if _, ok := seenLong[flag.name]; ok {
return fmt.Errorf("duplicate long flag --%s", flag.name)
}
seenLong[flag.name] = true
}
return nil
}
func (f *flagGroup) parse(context *ParseContext) (*FlagClause, error) {
token := context.Peek()
switch token.Type {
case TokenEOL:
return nil, nil
case TokenLong, TokenShort:
flagToken := token
defaultValue := ""
var flag *FlagClause
var ok bool
var err error
invert := false
name := token.Value
if token.Type == TokenLong {
if flag, invert, err = f.getFlagAlias(name); err != nil {
return nil, err
} else if flag == nil {
err = fmt.Errorf("unknown long flag '%s'", flagToken)
}
} else if flag, ok = f.short[name]; !ok {
err = fmt.Errorf("unknown short flag '%s'", flagToken)
}
if err != nil {
if context.appUnmanagedArgs == nil {
return nil, err
}
// The current flag is not managed by the application, but we gather it anyway in the unmanaged args
current := context.current()
if token.Type == TokenLong {
context.Next()
} else {
remainingArgs := "-"
if len(context.args) > 0 && context.rawArgs[len(context.rawArgs)-len(context.args)] == current {
// There are more short flags in the current element
remainingArgs = context.args[0]
}
// We remove all previous elements from the same short flags group
previousElementsCount := len(current) - len(remainingArgs) - 1
context.Elements = context.Elements[:len(context.Elements)-previousElementsCount]
// We consume the remaining short flags of the current group
for i := 0; i < len(remainingArgs); i++ {
// We consume the remaining short flags of the current group
if consumed := context.Next(); consumed.Type != TokenShort {
break
}
}
}
context.appUnmanagedArgs.Unmanaged = append(context.appUnmanagedArgs.Unmanaged, current)
return nil, nil
}
context.Next()
flag.isSetByUser()
if fb, ok := flag.value.(boolFlag); ok && fb.IsBoolFlag() {
if invert {
defaultValue = "false"
} else {
defaultValue = "true"
}
} else {
token = context.Peek()
if token.Type != TokenArg {
context.Push(token)
return nil, fmt.Errorf("expected argument for flag '%s'", flagToken)
}
context.Next()
defaultValue = token.Value
}
context.matchedFlag(flag, defaultValue)
return flag, nil
default:
return nil, nil
}
}
// FlagClause is a fluid interface used to build flags.
type FlagClause struct {
parserMixin
actionMixin
completionsMixin
envarMixin
aliasMixin
name string
shorthand rune
help string
defaultValues []string
placeholder string
hidden bool
setByUser *bool
}
func newFlag(name, help string) *FlagClause {
f := &FlagClause{
name: name,
help: help,
}
return f
}
func (f *FlagClause) setDefault() error {
if f.HasEnvarValue() {
if v, ok := f.value.(repeatableFlag); !ok || !v.IsCumulative() {
// Use the value as-is
return f.value.Set(f.GetEnvarValue())
}
for _, value := range f.GetSplitEnvarValue() {
if err := f.value.Set(value); err != nil {
return err
}
}
return nil
}
if len(f.defaultValues) > 0 {
for _, defaultValue := range f.defaultValues {
if err := f.value.Set(defaultValue); err != nil {
return err
}
}
return nil
}
return nil
}
func (f *FlagClause) isSetByUser() {
if f.setByUser != nil {
*f.setByUser = true
}
}
func (f *FlagClause) needsValue() bool {
haveDefault := len(f.defaultValues) > 0
return f.required && !(haveDefault || f.HasEnvarValue())
}
func (f *FlagClause) init() error {
if f.required && len(f.defaultValues) > 0 {
return fmt.Errorf("required flag '--%s' with default value that will never be used", f.name)
}
if f.value == nil {
return fmt.Errorf("no type defined for --%s (eg. .String())", f.name)
}
if v, ok := f.value.(repeatableFlag); (!ok || !v.IsCumulative()) && len(f.defaultValues) > 1 {
return fmt.Errorf("invalid default for '--%s', expecting single value", f.name)
}
return nil
}
// Action dispatches to the given function after the flag is parsed and validated.
func (f *FlagClause) Action(action Action) *FlagClause {
if action == nil {
f.actions = nil
}
f.addAction(action)
return f
}
// PreAction called after parsing completes but before validation and execution.
func (f *FlagClause) PreAction(action Action) *FlagClause {
if action == nil {
f.preActions = nil
}
f.addPreAction(action)
return f
}
// HintAction registers a HintAction (function) for the flag to provide completions.
func (f *FlagClause) HintAction(action HintAction) *FlagClause {
if action == nil {
f.hintActions = nil
}
f.addHintAction(action)
return f
}
// HintOptions registers any number of options for the flag to provide completions.
func (f *FlagClause) HintOptions(options ...string) *FlagClause {
f.addHintAction(func() []string {
return options
})
return f
}
// EnumVar associates this flag a string variable (with valid options).
func (f *FlagClause) EnumVar(target *string, options ...string) {
f.parserMixin.EnumVar(target, options...)
f.addHintActionBuiltin(func() []string {
return options
})
}
// Enum makes this flag a string variable (with valid options).
func (f *FlagClause) Enum(options ...string) (target *string) {
f.addHintActionBuiltin(func() []string {
return options
})
return f.parserMixin.Enum(options...)
}
// IsSetByUser let to know if the flag was set by the user
func (f *FlagClause) IsSetByUser(setByUser *bool) *FlagClause {
if setByUser != nil {
*setByUser = false
}
f.setByUser = setByUser
return f
}
// Default values for this flag. They *must* be parseable by the value of the flag.
func (f *FlagClause) Default(values ...interface{}) *FlagClause {
valuesStr := make([]string, len(values))
for i := range values {
valuesStr[i] = fmt.Sprint(values[i])
}
f.defaultValues = valuesStr
return f
}
// OverrideDefaultFromEnvar acts exactly as Envar.
// DEPRECATED: Use Envar(name) instead.
func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause {
return f.Envar(envar)
}
// Envar overrides the default value(s) for a flag from an environment variable,
// if it is set. Several default values can be provided by using new lines to
// separate them.
func (f *FlagClause) Envar(name string) *FlagClause {
f.envar = name
f.noEnvar = false
return f
}
// NoEnvar forces environment variable defaults to be disabled for this flag.
// Most useful in conjunction with app.DefaultEnvars().
func (f *FlagClause) NoEnvar() *FlagClause {
f.envar = ""
f.noEnvar = true
return f
}
// PlaceHolder sets the place-holder string used for flag values in the help. The
// default behaviour is to use the value provided by Default() if provided,
// then fall back on the capitalized flag name.
func (f *FlagClause) PlaceHolder(placeholder string) *FlagClause {
f.placeholder = placeholder
return f
}
// Hidden hides a flag from usage but still allows it to be used.
func (f *FlagClause) Hidden() *FlagClause {
f.hidden = true
return f
}
// Required makes the flag required. You can not provide a Default() value to a Required() flag.
func (f *FlagClause) Required() *FlagClause {
f.required = true
return f
}
// Short sets the short flag name.
func (f *FlagClause) Short(name rune) *FlagClause {
f.shorthand = name
return f
}
// Help sets the help message.
func (f *FlagClause) Help(help string) *FlagClause {
f.help = help
return f
}
// Bool makes this flag a boolean flag.
func (f *FlagClause) Bool() (target *bool) {
target = new(bool)
f.SetValue(newBoolValue(target))
return
}