-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharg-spec.go
460 lines (390 loc) · 10.7 KB
/
arg-spec.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package cmdline
import (
"fmt"
"strings"
"github.com/jimsnab/go-simpleutils"
)
type argValueSpec struct {
ArgIndex int
OptionName string
Optional bool
Multi bool
DefaultValue any
}
type argSpec struct {
CmdLine *CommandLine
Key string
Unnamed bool
Optional bool
ValuesDelim rune // the delimiter between value name and list of values
ValueDelim rune // the delimiter between values in a list
ValueSpecs []*argValueSpec
MultiValue bool
HelpText string
}
func indexOf(str string, substr string, pos int) int {
index := strings.Index(str[pos:], substr)
if index >= 0 {
index += pos
}
return index
}
func parseError(expected string, orgSpec string, specRemaining string, parsePos int) error {
if len(specRemaining) <= parsePos || orgSpec == specRemaining[parsePos:] {
return fmt.Errorf("%s%s in \"%s\"", basePanic, expected, orgSpec)
} else {
return fmt.Errorf("%s%s at \"%s\" of \"%s\"", basePanic, expected, specRemaining[parsePos:], orgSpec)
}
}
func (cl *CommandLine) newArgSpec(spec string, primaryArg bool) *argSpec {
orgSpec := spec
//
// Syntaxes:
//
// -arg
// -arg:<value>
// -arg:<value>,<value> ...
// -arg[:<value>]
// -arg:<value>[,<value>] ...
// [-arg]
// [-arg:<value>]
// [-arg:<value>,<value>] ...
// [-arg[:<value>]]
// [-arg:<value>[,<value>]] ...
// -arg [<value>]
// -arg [<value>] [<value>] ...
// -arg <value>[,<value>] ...
// -arg <value> [<value>] ...
// [-arg <value>]
// [-arg <value>,<value>] ...
// [-arg <value> <value>] ...
// [-arg <value> [<value>]] ...
//
// And the entire spec can be prefixed with asterisk (*) for a value list.
// Example:
//
// *-arg:<value>
//
// A value that can potentially contain commas can only appear as the only value. Example:
//
// -a:<string-a> -b:<string-b> # values a and b can have a comma
// -ab:<string-a>,<string-b> # values a and b cannot have a comma
//
// Help text is added to the end with a question mark separator. Example:
//
// [-t:<string-text>]?Specifies the text to save
//
as := argSpec{}
as.CmdLine = cl
as.HelpText = ""
helpCutPoint := strings.LastIndex(spec, "?")
if helpCutPoint >= 0 {
as.HelpText = spec[helpCutPoint+1:]
spec = spec[:helpCutPoint]
}
as.ValueSpecs = []*argValueSpec{}
if strings.HasPrefix(spec, "*") {
spec = spec[1:]
as.MultiValue = true
}
if strings.HasPrefix(spec, "[") && strings.HasSuffix(spec, "]") {
spec = spec[1 : len(spec)-1]
as.Optional = true
}
argDelimiter := strings.IndexAny(spec, ": ")
if argDelimiter < 0 {
as.Key = strings.ReplaceAll(spec, "+", " ")
} else {
as.Key = strings.ReplaceAll(spec[:argDelimiter], "+", " ")
as.ValuesDelim = rune(spec[argDelimiter])
suffix := simpleutils.WhichSuffix(as.Key, " [", "[")
if suffix != nil {
as.Key = as.Key[:argDelimiter-1]
if *suffix == " [" {
*suffix = "[ "
}
spec = *suffix + spec[argDelimiter+1:]
} else {
spec = spec[argDelimiter+1:]
}
parsePos := 0
if len(spec) == 0 {
panic(parseError("value spec", orgSpec, spec, parsePos))
}
for parsePos < len(spec) {
avs := argValueSpec{}
avs.Optional = false
var optionType string
c := spec[parsePos]
if c == '[' {
avs.Optional = true
parsePos++
c = spec[parsePos]
} else if parsePos+1 < len(spec) && c == ' ' && spec[parsePos+1] == '[' {
avs.Optional = true
parsePos++
}
if (c == ',' || c == ' ') && len(as.ValueSpecs) > 0 {
if as.ValueDelim == 0 {
if c == ' ' && as.ValuesDelim == ':' {
panic(parseError("comma-separated value spec list", orgSpec, spec, parsePos))
}
as.ValueDelim = rune(c)
} else if as.ValueDelim != rune(c) {
panic(parseError("uniform value delimiter", orgSpec, spec, parsePos))
}
parsePos++
c = spec[parsePos]
}
if c == '*' {
avs.Multi = true
parsePos++
c = spec[parsePos]
}
if c != '<' {
panic(parseError("'<'", orgSpec, spec, parsePos))
}
parsePos++
dashPos := indexOf(spec, "-", parsePos)
if dashPos < 0 {
panic(parseError("'-'", orgSpec, spec, parsePos))
}
optionType = spec[parsePos:dashPos]
ot := cl.optionTypes.StringToAttributes(optionType, orgSpec)
// defensive
if ot == nil {
panic(parseError("valid option type", orgSpec, spec, parsePos))
}
parsePos = dashPos + 1
closeBracket := indexOf(spec, ">", parsePos)
if closeBracket < 0 {
panic(parseError("'>'", orgSpec, spec, parsePos))
}
avs.OptionName = spec[parsePos:closeBracket]
if !simpleutils.IsTokenName(avs.OptionName) {
panic(parseError("valid option name", orgSpec, spec, parsePos))
}
parsePos = closeBracket + 1
if avs.Optional {
if parsePos >= len(spec) || spec[parsePos] != ']' {
panic(parseError("']'", orgSpec, spec, parsePos))
}
parsePos++
}
attribs := cl.optionTypes.StringToAttributes(optionType, orgSpec)
avs.ArgIndex = attribs.Index
avs.DefaultValue = attribs.DefaultValue
// check for a dup
for _, arg := range as.ValueSpecs {
if avs.OptionName == arg.OptionName {
panic(fmt.Errorf("duplicate value spec \"%s\" in \"%s\"", arg.OptionName, orgSpec))
}
}
as.ValueSpecs = append(as.ValueSpecs, &avs)
} // for parsePos
}
if len(as.Key) == 0 {
panic(parseError("argument name", orgSpec, spec, 0))
}
if as.Key == "~" {
as.Unnamed = true
}
// remove leading dash or dash-dash
trimmedKey := strings.TrimPrefix(as.Key, "-")
trimmedKey = strings.TrimPrefix(trimmedKey, "-")
if !simpleutils.IsTokenNameWithMiddleChars(trimmedKey, "- ") && !as.Unnamed {
panic(parseError("a valid argument token", orgSpec, spec, 0))
}
if primaryArg {
if as.Optional {
panic(parseError("non-optional primary argument", orgSpec, spec, 0))
}
if as.MultiValue {
panic(parseError("single-value primary argument", orgSpec, spec, 0))
}
if as.Unnamed && as.ValuesDelim == ':' {
panic(parseError("unnamed argument without a value spec", orgSpec, spec, 0))
}
} else {
if as.Unnamed {
panic(parseError("named seconary argument", orgSpec, spec, 0))
}
}
return &as
}
func (as *argSpec) storeArg(effectiveArgs *map[string]any, spec *argValueSpec, input string) error {
if as.MultiValue || spec.Multi {
//
// The very first arg will exist in effectiveArgs map with nil; convert it to a list.
// Subsequent args of the same option will be added to the list.
//
var err error
var list any
optVal := (*effectiveArgs)[spec.OptionName]
if optVal == nil {
list, err = as.CmdLine.optionTypes.NewList(spec.ArgIndex)
// defensive
if err != nil {
return err
}
} else {
list = optVal
}
list, err = as.CmdLine.optionTypes.AppendList(spec.ArgIndex, list, input)
if err != nil {
return err
}
(*effectiveArgs)[spec.OptionName] = list
} else {
value, err := as.CmdLine.optionTypes.MakeValue(spec.ArgIndex, input)
if err != nil {
return err
}
(*effectiveArgs)[spec.OptionName] = value
}
return nil
}
func (as *argSpec) Parse(effectiveArgs *map[string]any, colonValue *string, subsequentArgs []string) (int, error) {
argsUsed := 0
input := colonValue
if input == nil && as.ValuesDelim == ' ' {
if len(subsequentArgs) > 0 && !strings.HasPrefix(subsequentArgs[0], "-") {
input = &subsequentArgs[0]
argsUsed = 1
}
}
if input == nil {
if len(as.ValueSpecs) > 0 && !as.ValueSpecs[0].Optional {
return 0, NewCommandLineError("Required value %s is missing", as.ValueSpecs[0].OptionName)
}
if len(as.ValueSpecs) > 0 {
for _, valueSpec := range as.ValueSpecs {
(*effectiveArgs)[valueSpec.OptionName] = valueSpec.DefaultValue
}
}
} else if len(as.ValueSpecs) == 0 {
return 0, NewCommandLineError("Unexpected command argument: %s", *input)
} else if len(as.ValueSpecs) == 1 {
err := as.storeArg(effectiveArgs, as.ValueSpecs[0], *input)
if err != nil {
return 0, err
}
if as.ValueSpecs[0].Multi && as.ValuesDelim == ' ' {
for {
if argsUsed >= len(subsequentArgs) || strings.HasPrefix(subsequentArgs[argsUsed], "-") {
break
}
err := as.storeArg(effectiveArgs, as.ValueSpecs[0], subsequentArgs[argsUsed])
if err != nil {
return 0, err
}
argsUsed++
}
}
} else {
var values []string
if as.ValueDelim == ',' {
values = strings.Split(*input, ",")
} else {
// Because of syntax enforcement, argsUsed == 1 and *input == subsequentArgs[0]
argsUsed = 0
for i := 0; i < len(as.ValueSpecs); i++ {
if argsUsed >= len(subsequentArgs) {
break
}
if strings.HasPrefix(subsequentArgs[argsUsed], "-") {
break
}
values = append(values, subsequentArgs[argsUsed])
argsUsed++
if as.ValueSpecs[i].Multi {
for argsUsed < len(subsequentArgs) && !strings.HasPrefix(subsequentArgs[argsUsed], "-") {
values = append(values, subsequentArgs[argsUsed])
argsUsed++
}
}
}
}
for i, valueSpec := range as.ValueSpecs {
if i >= len(values) {
if as.ValueDelim == ',' {
// For comma-separated list, use the last value as a default when too few args are provided
err := as.storeArg(effectiveArgs, as.ValueSpecs[i], values[len(values)-1])
// defensive
if err != nil {
return 0, err
}
} else if valueSpec.Optional {
break
} else {
return 0, NewCommandLineError("Required value %s is missing", valueSpec.OptionName)
}
} else {
err := as.storeArg(effectiveArgs, as.ValueSpecs[i], values[i])
if err != nil {
return 0, err
}
if valueSpec.Multi && as.ValuesDelim == ' ' {
for {
if i+1 >= len(values) {
break
}
value := values[i+1]
values = append(values[0:i], values[i+2:]...)
err := as.storeArg(effectiveArgs, as.ValueSpecs[i], value)
if err != nil {
return 0, err
}
}
}
}
}
}
(*effectiveArgs)[as.Key] = true
return argsUsed, nil
}
func (as *argSpec) String() string {
var sb strings.Builder
if as.MultiValue {
sb.WriteString("*")
}
if as.Optional {
sb.WriteString("[")
}
if !as.Unnamed {
sb.WriteString(as.Key)
}
first := true
optionalValues := 0
for _, valueSpec := range as.ValueSpecs {
chars := make([]rune, 0, 2)
if valueSpec.Optional {
chars = append(chars, '[')
optionalValues++
}
if first {
if !as.Unnamed {
chars = append(chars, as.ValuesDelim) // note the 's' on ValuesDelim
}
first = false
} else {
chars = append(chars, as.ValueDelim)
}
s := string(chars)
if s == "[ " {
s = " [" // flip for readability
}
sb.WriteString(s)
sb.WriteString("<")
sb.WriteString(valueSpec.OptionName)
sb.WriteString(">")
}
for optionalValues > 0 {
optionalValues--
sb.WriteString("]")
}
if as.Optional {
sb.WriteString("]")
}
return sb.String()
}