-
Notifications
You must be signed in to change notification settings - Fork 45
/
glob_parser.go
371 lines (317 loc) · 9.25 KB
/
glob_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
package filetree
import (
"regexp"
"strings"
)
const (
// searchByGlob is the default, unparsed/processed glob value searched directly against the filetree.
searchByGlob searchBasis = iota
// searchByFullPath indicates that the given glob value is not a glob, thus a (simpler) path lookup against the filetree should be performed as the search.
searchByFullPath
// searchByExtension indicates cases like "**/*.py" where the only specific glob element indicates the file or directory extension.
searchByExtension
// searchByBasename indicates cases like "**/bin/python" where the only specific glob element indicates the file or directory basename (e.g. "python").
searchByBasename
// searchByBasenameGlob indicates cases like "**/bin/python*" where the search space is limited to the full set of all basenames that match the given glob.
searchByBasenameGlob
// searchBySubDirectory indicates cases like "**/var/lib/dpkg/status.d/*" where we're interested in selecting all files within a directory (but not the directory itself).
searchBySubDirectory
)
type searchBasis int
func (s searchBasis) String() string {
switch s {
case searchByGlob:
return "glob"
case searchByFullPath:
return "full-path"
case searchByExtension:
return "extension"
case searchByBasename:
return "basename"
case searchByBasenameGlob:
return "basename-glob"
case searchBySubDirectory:
return "subdirectory"
}
return "unknown search basis"
}
type searchRequest struct {
searchBasis
value string
requirement string
}
func (s searchRequest) String() string {
value := s.searchBasis.String() + ": " + s.value
if s.requirement != "" {
value += " (requirement: " + s.requirement + ")"
}
return value
}
func parseGlob(glob string) []searchRequest {
glob = cleanGlob(glob)
if !strings.ContainsAny(glob, "*?[]{}") {
return []searchRequest{
{
searchBasis: searchByFullPath,
value: glob,
},
}
}
beforeBasename, basename := splitAtBasename(glob)
if basename == "*" {
_, nestedBasename := splitAtBasename(beforeBasename)
if !strings.ContainsAny(nestedBasename, "*?[]{}") {
// special case: glob is a parent glob
requests := []searchRequest{
{
searchBasis: searchBySubDirectory,
value: nestedBasename,
requirement: beforeBasename,
},
}
return requests
}
}
requests := parseGlobBasename(basename)
for i := range requests {
applyRequirement(&requests[i], beforeBasename, glob)
}
return requests
}
func splitAtBasename(glob string) (string, string) {
// TODO: need to correctly avoid indexes within [] and {} groups
basenameSplitAt := strings.LastIndex(glob, "/")
var basename string
var beforeBasename string
if basenameSplitAt == -1 {
// note: this has no glob path prefix, thus no requirement...
// this can only be a basename, basename glob, or extension
basename = glob
beforeBasename = ""
} else if basenameSplitAt < len(glob)-1 {
basename = glob[basenameSplitAt+1:]
}
if basenameSplitAt >= 0 && basenameSplitAt < len(glob)-1 {
beforeBasename = glob[:basenameSplitAt]
}
return beforeBasename, basename
}
func applyRequirement(request *searchRequest, beforeBasename, glob string) {
var requirement string
if beforeBasename != "" {
requirement = glob
switch beforeBasename {
case "**", request.requirement:
if request.searchBasis != searchByExtension {
requirement = ""
}
}
} else {
requirement = ""
}
request.requirement = requirement
if request.searchBasis == searchByGlob {
request.value = glob
if glob == request.requirement {
request.requirement = ""
}
}
}
func parseGlobBasename(basenameInput string) []searchRequest {
if strings.ContainsAny(basenameInput, "[]{}") {
return parseBasenameAltAndClassGlobSections(basenameInput)
}
extensionFields := strings.Split(basenameInput, "*.")
if len(extensionFields) == 2 && extensionFields[0] == "" {
possibleExtension := extensionFields[1]
if !strings.ContainsAny(possibleExtension, "*?") {
// special case, this is plain extension
return []searchRequest{
{
searchBasis: searchByExtension,
value: "." + possibleExtension,
},
}
}
}
if !strings.ContainsAny(basenameInput, "*?") {
// special case, this is plain basename
return []searchRequest{
{
searchBasis: searchByBasename,
value: basenameInput,
},
}
}
if strings.ReplaceAll(strings.ReplaceAll(basenameInput, "?", ""), "*", "") == "" {
// special case, this is a glob that is only asterisks... do not process!
return []searchRequest{
{
searchBasis: searchByGlob,
// note: we let the parent caller attach the full glob value
},
}
}
return []searchRequest{
{
searchBasis: searchByBasenameGlob,
value: basenameInput,
},
}
}
func parseBasenameAltAndClassGlobSections(basenameInput string) []searchRequest {
// TODO: process escape sequences
altStartCount := strings.Count(basenameInput, "{")
altEndCount := strings.Count(basenameInput, "}")
classStartCount := strings.Count(basenameInput, "[")
classEndCount := strings.Count(basenameInput, "]")
if altStartCount != altEndCount || classStartCount != classEndCount {
// imbalanced braces, this is not a valid glob relative to just the basename
return []searchRequest{
{
searchBasis: searchByGlob,
// note: we let the parent caller attach the full glob value
},
}
}
if classStartCount > 0 {
// parsing this is not supported at this time
return []searchRequest{
{
searchBasis: searchByBasenameGlob,
value: basenameInput,
},
}
}
// if the glob is the simplest list form, them allow for breaking into sub-searches
if altStartCount == 1 {
indexStartIsPrefix := strings.Index(basenameInput, "{") == 0
indexEndIsSuffix := strings.Index(basenameInput, "}") == len(basenameInput)-1
if indexStartIsPrefix && indexEndIsSuffix {
// this is a simple list, split it up
// e.g. {a,b,c} -> a, b, c
altSections := strings.Split(basenameInput[1:len(basenameInput)-1], ",")
if len(altSections) > 1 {
var requests []searchRequest
for _, altSection := range altSections {
basis := searchByBasename
if strings.ContainsAny(altSection, "*?") {
basis = searchByBasenameGlob
}
requests = append(requests, searchRequest{
searchBasis: basis,
value: altSection,
})
}
return requests
}
}
}
// there is some sort of alt usage, but it is not a simple list... just treat it as a glob
return []searchRequest{
{
searchBasis: searchByBasenameGlob,
value: basenameInput,
},
}
}
func cleanGlob(glob string) string {
glob = strings.TrimSpace(glob)
glob = removeRedundantCountGlob(glob, '/', 1)
glob = removeRedundantCountGlob(glob, '*', 2)
if len(glob) > 1 {
// input case: /
// then preserve the slash
glob = strings.TrimRight(glob, "/")
}
// e.g. replace "/bar**/" with "/bar*/"
glob = simplifyMultipleGlobAsterisks(glob)
glob = simplifyGlobRecursion(glob)
return glob
}
func simplifyMultipleGlobAsterisks(glob string) string {
// this will replace any recursive globs (**) that are not clearly indicating recursive tree searches with a single *
var sb strings.Builder
var asteriskBuff strings.Builder
var withinRecursiveStreak bool
for idx, c := range glob {
isAsterisk := c == '*'
isSlash := c == '/'
// special case, this is the first character in the glob and it is an asterisk...
// treat this like a recursive streak
if idx == 0 && isAsterisk {
withinRecursiveStreak = true
asteriskBuff.WriteRune(c)
continue
}
if isAsterisk {
asteriskBuff.WriteRune(c)
continue
}
if isSlash {
if withinRecursiveStreak {
// this is a confirmed recursive streak
// keep all asterisks!
sb.WriteString(asteriskBuff.String())
asteriskBuff.Reset()
}
if asteriskBuff.Len() > 0 {
// this is NOT a recursive streak, but there are asterisks
// keep only one asterisk
sb.WriteRune('*')
asteriskBuff.Reset()
}
// this is potentially a new streak...
withinRecursiveStreak = true
} else {
// ... and this is NOT a recursive streak
if asteriskBuff.Len() > 0 {
// ... keep only one asterisk, since it's not recursive
sb.WriteRune('*')
}
asteriskBuff.Reset()
withinRecursiveStreak = false
}
sb.WriteRune(c)
}
if asteriskBuff.Len() > 0 {
if withinRecursiveStreak {
sb.WriteString(asteriskBuff.String())
} else {
sb.WriteRune('*')
}
}
return sb.String()
}
var globRecursionRightPattern = regexp.MustCompile(`(\*\*/?)+`)
func simplifyGlobRecursion(glob string) string {
// this function assumes that all redundant asterisks have been removed (e.g. /****/ -> /**/)
// and that all seemingly recursive globs have been replaced with a single asterisk (e.g. /bar**/ -> /bar*/)
glob = globRecursionRightPattern.ReplaceAllString(glob, "**/")
glob = strings.ReplaceAll(glob, "//", "/")
if strings.HasPrefix(glob, "/**/") {
glob = strings.TrimPrefix(glob, "/")
}
if len(glob) > 1 {
// input case: /**
// then preserve the slash
glob = strings.TrimRight(glob, "/")
}
return glob
}
func removeRedundantCountGlob(glob string, val rune, count int) string {
var sb strings.Builder
var streak int
for _, c := range glob {
if c == val {
streak++
if streak > count {
continue
}
} else {
streak = 0
}
sb.WriteRune(c)
}
return sb.String()
}