-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
390 lines (330 loc) · 8.98 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
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
package gommander
import (
"errors"
"fmt"
"strconv"
"strings"
)
type Parser struct {
cursor int
rootCmd *Command
currentCmd *Command
matches ParserMatches
eaten []string
cmdIdx int
currentToken string
}
func NewParser(entry *Command) Parser {
return Parser{
cursor: 0,
rootCmd: entry,
currentCmd: entry,
matches: ParserMatches{
argCount: 0,
rootCmd: entry,
matchedCmd: entry,
},
}
}
// Parser utilties
func (p *Parser) isFlagLike(val string) bool {
if p.rootCmd.settings[AllowNegativeNumbers] {
if _, e := strconv.Atoi(val); e == nil {
return false
}
}
return strings.HasPrefix(val, "-")
}
func (p *Parser) isLongOptSyntax(val string) bool {
return strings.HasPrefix(val, "--") && strings.ContainsAny(val, "=")
}
func (p *Parser) isSpecialValue(val string) bool {
return val == "-h" || val == "--help"
}
func (p *Parser) isPosixFlagSyntax(vals []string) bool {
return len(vals) > 2 && vals[0] == "-" && vals[1] != "-"
}
func (p *Parser) getFlag(val string) (*Flag, error) {
for _, f := range p.currentCmd.flags {
if f.ShortVal == val || f.LongVal == val {
return f, nil
}
}
return NewFlag(""), errors.New("flag not found")
}
func (p *Parser) getOption(val string) (*Option, error) {
for _, o := range p.currentCmd.options {
if o.ShortVal == val || o.LongVal == val {
return o, nil
}
}
return NewOption(""), errors.New("no option found")
}
func (p *Parser) getSubCommand(val string) (*Command, error) {
for _, s := range p.currentCmd.subCommands {
includes := func(val string) bool {
for _, v := range s.aliases {
if v == val {
return true
}
}
return false
}
if s.name == val || includes(val) {
return s, nil
}
}
return NewCommand(""), errors.New("no subcmd found")
}
func (p *Parser) _eat(val string) {
p.eaten = append(p.eaten, val)
}
func (p *Parser) _isEaten(val string) bool {
for _, v := range p.eaten {
if v == val {
return true
}
}
return false
}
func (p *Parser) reset() {
p.eaten = []string{}
p.cursor = 0
p.cmdIdx = -1
}
func (p *Parser) parse(rawArgs []string) (*ParserMatches, *Error) {
defer p.reset()
p.matches.rawArgs = rawArgs
p.matches.argCount = len(rawArgs)
p.cmdIdx = -1
allowPositionalArgs := false
for index, arg := range rawArgs {
p.cursor = index
p.currentToken = arg
if p.isFlagLike(arg) {
if flag, err := p.getFlag(arg); err == nil {
// handle is flag
p._eat(arg)
if !allowPositionalArgs {
flagCfg := flagMatches{
matchedFlag: *flag,
}
if !p.matches.ContainsFlag(flag.LongVal) {
p.matches.flagMatches = append(p.matches.flagMatches, flagCfg)
}
}
} else if opt, err := p.getOption(arg); err == nil {
// Handle is option
p._eat(arg)
err := p.parseOption(opt, rawArgs[(index+1):])
if err != nil {
return &p.matches, err
}
} else if arg == "--" {
p._eat(arg)
allowPositionalArgs = true
} else if p.isLongOptSyntax(arg) && !allowPositionalArgs {
// parse special option
p._eat(arg)
parts := strings.Split(arg, "=")
opt, err := p.getOption(parts[0])
if err != nil {
err := generateError(p.currentCmd, UnknownOption, []string{parts[0], arg})
return &p.matches, &err
}
temp := []string{parts[1]}
temp = append(temp, rawArgs[(index+1):]...)
e := p.parseOption(opt, temp)
if e != nil {
return &p.matches, e
}
} else if allowPositionalArgs {
p._eat(arg)
p.matches.positionalArgs = append(p.matches.positionalArgs, arg)
} else if strings.ContainsRune(arg, '=') {
err := generateError(p.currentCmd, UnknownOption, []string{})
return &p.matches, &err
} else if !p._isEaten(arg) && !allowPositionalArgs {
values := strings.Split(arg, "")
// TODO: More validation
if p.isPosixFlagSyntax(values) {
p._eat(arg)
for _, v := range values[1:] {
flag, err := p.getFlag(fmt.Sprintf("-%v", v))
if err != nil {
err := generateError(p.currentCmd, UnknownOption, []string{v, p.currentToken, ""})
return &p.matches, &err
}
flagCfg := flagMatches{
matchedFlag: *flag,
}
if !p.matches.ContainsFlag(flag.LongVal) {
p.matches.flagMatches = append(p.matches.flagMatches, flagCfg)
}
}
continue
}
err := generateError(p.currentCmd, UnknownOption, []string{p.currentToken})
return &p.matches, &err
}
} else if sc, err := p.getSubCommand(arg); err == nil {
// handle subcmd
p._eat(arg)
p.currentCmd = sc
p.cmdIdx = index
continue
} else if allowPositionalArgs {
// TODO: More conditionals
p._eat(arg)
p.matches.positionalArgs = append(p.matches.positionalArgs, arg)
}
}
p.matches.matchedCmd = p.currentCmd
p.matches.matchedCmdIdx = p.cmdIdx
cmdArgs := []string{}
if p.cmdIdx == -1 {
// No subcommands matched
cmdArgs = rawArgs
} else if len(rawArgs) > p.cmdIdx+1 {
cmdArgs = append(cmdArgs, rawArgs[p.cmdIdx+1:]...)
}
err := p.parseCmd(cmdArgs)
if err != nil {
return &p.matches, err
}
if !p.matches.ContainsFlag("help") {
for _, o := range p.currentCmd.options {
if o.IsRequired && !p.matches.ContainsOption(o.LongVal) {
var argVals []string
if o.Arg != nil {
a := o.Arg
if len(a.DefaultValue) == 0 {
// No default value and value is required
err := generateError(p.currentCmd, MissingRequiredOption, []string{o.LongVal})
return &p.matches, &err
}
// Generate opt match with default value
argVals = append(argVals, a.DefaultValue)
}
err := p.parseOption(o, argVals)
if err != nil {
return &p.matches, err
}
}
}
}
return &p.matches, nil
}
func (p *Parser) parseOption(opt *Option, rawArgs []string) *Error {
argList := []*Argument{}
if opt.Arg != nil {
argList = append(argList, opt.Arg)
}
args, err := p.getArgMatches(argList, rawArgs)
if err != nil {
return err
}
if p.matches.ContainsOption(opt.LongVal) {
for i, cfg := range p.matches.optionMatches {
if cfg.matchedOpt.LongVal == opt.LongVal {
cfg.passedArgs = append(cfg.passedArgs, args...)
cfg.instanceCount++
p.matches.optionMatches[i] = cfg
}
}
} else {
optCfg := optionMatches{
matchedOpt: *opt,
instanceCount: 1,
passedArgs: args,
}
p.matches.optionMatches = append(p.matches.optionMatches, optCfg)
}
return nil
}
func (p *Parser) parseCmd(rawArgs []string) *Error {
argCfgVals, err := p.getArgMatches(p.currentCmd.arguments, rawArgs)
if err != nil {
return err
}
// expected no args, probably a subcommand
if len(rawArgs) > 0 && len(argCfgVals) == 0 {
if p.currentCmd.hasSubcommands() && !p._isEaten(rawArgs[0]) {
err := generateError(p.currentCmd, UnknownCommand, []string{rawArgs[0]})
return &err
}
}
// any unresolved arguments
for _, a := range rawArgs {
if !p._isEaten(a) {
err := generateError(p.currentCmd, UnresolvedArgument, []string{a})
return &err
}
}
p.matches.argMatches = append(p.matches.argMatches, argCfgVals...)
return nil
}
func (p *Parser) getArgMatches(list []*Argument, args []string) ([]argMatches, *Error) {
// maxLen := len(list)
matches := []argMatches{}
for argIdx, argVal := range list {
var builder strings.Builder
if argVal.IsVariadic {
for _, v := range args {
if !p.isFlagLike(v) && !p._isEaten(v) {
p._eat(v)
builder.WriteString(v)
builder.WriteRune(' ')
}
}
} else if argIdx < len(args) {
v := args[argIdx]
if p.isSpecialValue(v) {
break
} else if !p.isFlagLike(v) && !p._isEaten(v) {
p._eat(v)
builder.WriteString(v)
} else if argVal.hasDefaultValue() {
builder.WriteString(argVal.DefaultValue)
} else if argVal.IsRequired {
args := []string{argVal.getRawValue(), v}
err := generateError(p.currentCmd, MissingRequiredArgument, args)
return matches, &err
} else {
continue
}
} else if argVal.IsRequired {
args := []string{argVal.getRawValue()}
err := generateError(p.currentCmd, MissingRequiredArgument, args)
return matches, &err
}
// test the value against default values if any
input := builder.String()
if len(input) > 0 && len(argVal.ValidValues) > 0 && !argVal.testValue(input) {
args := []string{input}
args = append(args, argVal.ValidValues...)
err := generateError(p.currentCmd, InvalidArgumentValue, args)
return matches, &err
}
// test the value against the validator func if any
for _, fn := range argVal.ValidatorFns {
if err := fn(input); err != nil {
args := []string{input, err.Error()}
err := generateError(p.currentCmd, InvalidArgumentValue, args)
return matches, &err
}
}
// test against validator regex if any
if argVal.ValidatorRe != nil && !argVal.ValidatorRe.MatchString(input) {
args := []string{input, "failed to match value against validator regex"}
err := generateError(p.currentCmd, InvalidArgumentValue, args)
return matches, &err
}
argCfg := argMatches{
rawValue: input,
instanceOf: *argVal,
}
matches = append(matches, argCfg)
}
return matches, nil
}