This repository has been archived by the owner on Mar 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
parse.go
317 lines (268 loc) · 6.31 KB
/
parse.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
package dcmd
import (
"strings"
)
var (
ErrNoComboFound = NewSimpleUserError("No matching combo found")
ErrNotEnoughArguments = NewSimpleUserError("Not enough arguments passed")
)
func ArgParserMW(inner RunFunc) RunFunc {
return func(data *Data) (interface{}, error) {
// Parse Args
err := ParseCmdArgs(data)
if err != nil {
if IsUserError(err) {
return "Invalid arguments provided: " + err.Error(), nil
}
return nil, err
}
return inner(data)
}
}
// ParseCmdArgs is the standard argument parser
// todo, more doc on the format
func ParseCmdArgs(data *Data) error {
argDefsCommand, argDefsOk := data.Cmd.Command.(CmdWithArgDefs)
switchesCmd, switchesOk := data.Cmd.Command.(CmdWithSwitches)
if !argDefsOk && !switchesOk {
// Command dosen't use the standard arg parsing
return nil
}
// Split up the args
split := SplitArgs(data.MsgStrippedPrefix)
var err error
if switchesOk {
switches := switchesCmd.Switches()
if len(switches) > 0 {
// Parse the switches first
split, err = ParseSwitches(switchesCmd.Switches(), data, split)
if err != nil {
return err
}
}
}
if argDefsOk {
defs, req, combos := argDefsCommand.ArgDefs(data)
if len(defs) > 0 {
err = ParseArgDefs(defs, req, combos, data, split)
if err != nil {
return err
}
}
}
return nil
}
// ParseArgDefs parses ordered argument definition for a CmdWithArgDefs
func ParseArgDefs(defs []*ArgDef, required int, combos [][]int, data *Data, split []*RawArg) error {
combo, ok := FindCombo(defs, combos, split)
if !ok {
return ErrNoComboFound
}
parsedArgs := NewParsedArgs(defs)
for i, v := range combo {
def := defs[v]
if i >= len(split) {
if i >= required && len(combos) < 1 {
break
}
return ErrNotEnoughArguments
}
combined := ""
if i == len(combo)-1 && len(split)-1 > i {
// Last arg, but still more after, combine and rebuilt them
for j := i; j < len(split); j++ {
if j != i {
combined += " "
}
temp := split[j]
if temp.Container != 0 {
combined += string(temp.Container) + temp.Str + string(temp.Container)
} else {
combined += temp.Str
}
}
} else {
combined = split[i].Str
}
val, err := def.Type.Parse(def, combined, data)
if err != nil {
return err
}
parsedArgs[v].Value = val
}
data.Args = parsedArgs
return nil
}
// ParseSwitches parses all switches for a CmdWithSwitches, and also takes them out of the raw args
func ParseSwitches(switches []*ArgDef, data *Data, split []*RawArg) ([]*RawArg, error) {
newRaws := make([]*RawArg, 0, len(split))
// Initialise the parsed switches
parsedSwitches := make(map[string]*ParsedArg)
for _, v := range switches {
parsedSwitches[v.Switch] = &ParsedArg{
Value: v.Default,
Def: v,
}
}
for i := 0; i < len(split); i++ {
raw := split[i]
if raw.Container != 0 {
newRaws = append(newRaws, raw)
continue
}
if !strings.HasPrefix(raw.Str, "-") {
newRaws = append(newRaws, raw)
continue
}
rest := raw.Str[1:]
var matchedArg *ArgDef
for _, v := range switches {
if v.Switch == rest {
matchedArg = v
break
}
}
if matchedArg == nil {
newRaws = append(newRaws, raw)
continue
}
if matchedArg.Type == nil {
parsedSwitches[matchedArg.Switch].Raw = raw
parsedSwitches[matchedArg.Switch].Value = true
continue
}
if i >= len(split)-1 {
// A switch with extra stuff requird, but no extra data provided
// Can't handle this case...
continue
}
// At this point, we have encountered a switch with data
// so we need to skip the next RawArg
i++
val, err := matchedArg.Type.Parse(matchedArg, split[i].Str, data)
if err != nil {
// TODO: Use custom error type for helpfull errror
return nil, err
}
parsedSwitches[matchedArg.Switch].Raw = raw
parsedSwitches[matchedArg.Switch].Value = val
}
data.Switches = parsedSwitches
return newRaws, nil
}
var (
ArgContainers = []rune{
'"',
'`',
}
)
type RawArg struct {
Str string
Container rune
}
// SplitArgs splits the string into fields
func SplitArgs(in string) []*RawArg {
rawArgs := make([]*RawArg, 0)
curBuf := ""
escape := false
var container rune
for _, r := range in {
// Apply or remove escape mode
if r == '\\' {
if escape {
escape = false
curBuf += "\\"
} else {
escape = true
}
continue
}
// Check for other special tokens
isSpecialToken := true
if r == ' ' {
// Maybe seperate by space
if curBuf != "" && container == 0 && !escape {
rawArgs = append(rawArgs, &RawArg{curBuf, 0})
curBuf = ""
} else if curBuf != "" {
curBuf += " "
}
} else if r == container && container != 0 {
// Split arg here
if escape {
curBuf += string(r)
} else {
rawArgs = append(rawArgs, &RawArg{curBuf, container})
curBuf = ""
container = 0
}
} else if container == 0 && curBuf == "" {
// Check if we should start containing a arg
foundMatch := false
for _, v := range ArgContainers {
if v == r {
if escape {
curBuf += string(r)
} else {
container = v
}
foundMatch = true
break
}
}
if !foundMatch {
isSpecialToken = false
}
} else {
isSpecialToken = false
}
if !isSpecialToken {
if escape {
curBuf += "\\"
}
curBuf += string(r)
}
// Reset escape mode
escape = false
}
// Something was left in the buffer just add it to the end
if curBuf != "" {
if container != 0 {
curBuf = string(container) + curBuf
}
rawArgs = append(rawArgs, &RawArg{curBuf, 0})
}
return rawArgs
}
// Finds a proper argument combo from the provided args
func FindCombo(defs []*ArgDef, combos [][]int, args []*RawArg) (combo []int, ok bool) {
if len(combos) < 1 {
out := make([]int, len(defs))
for k, _ := range out {
out[k] = k
}
return out, true
}
var selectedCombo []int
// Find a possible match
OUTER:
for _, combo := range combos {
if len(combo) > len(args) {
// No match
continue
}
// See if this combos arguments matches that of the parsed command
for i, comboArg := range combo {
def := defs[comboArg]
if !def.Type.Matches(def, args[i].Str) {
continue OUTER
}
}
// We got a match, if this match is stronger than the last one set it as selected
if len(combo) > len(selectedCombo) || !ok {
selectedCombo = combo
ok = true
}
}
return selectedCombo, ok
}