forked from bmatcuk/doublestar
-
Notifications
You must be signed in to change notification settings - Fork 1
/
glob.go
491 lines (448 loc) · 14.5 KB
/
glob.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package doublestar
import (
"errors"
"io/fs"
"path"
)
// Glob returns the names of all files matching pattern or nil if there is no
// matching file. The syntax of pattern is the same as in Match(). The pattern
// may describe hierarchical names such as usr/*/bin/ed.
//
// Glob ignores file system errors such as I/O errors reading directories by
// default. The only possible returned error is ErrBadPattern, reporting that
// the pattern is malformed.
//
// To enable aborting on I/O errors, the WithFailOnIOErrors option can be
// passed.
//
// Note: this is meant as a drop-in replacement for io/fs.Glob(). Like
// io/fs.Glob(), this function assumes that your pattern uses `/` as the path
// separator even if that's not correct for your OS (like Windows). If you
// aren't sure if that's the case, you can use filepath.ToSlash() on your
// pattern before calling Glob().
//
// Like `io/fs.Glob()`, patterns containing `/./`, `/../`, or starting with `/`
// will return no results and no errors. You can use SplitPattern to divide a
// pattern into a base path (to initialize an `FS` object) and pattern.
//
// Note: users should _not_ count on the returned error,
// doublestar.ErrBadPattern, being equal to path.ErrBadPattern.
func Glob(fsys fs.FS, pattern string, opts ...GlobOption) ([]string, error) {
if !ValidatePattern(pattern) {
return nil, ErrBadPattern
}
g := newGlob(opts...)
if hasMidDoubleStar(pattern) {
// If the pattern has a `**` anywhere but the very end, GlobWalk is more
// performant because it can get away with less allocations. If the pattern
// ends in a `**`, both methods are pretty much the same, but Glob has a
// _very_ slight advantage because of lower function call overhead.
var matches []string
err := g.doGlobWalk(fsys, pattern, true, true, func(p string, d fs.DirEntry) error {
if !d.IsDir() {
if fi, err := d.Info(); err == nil {
if !isOlder(fi.ModTime(), g.maxAge) {
matches = append(matches, p)
}
} else {
matches = append(matches, p)
}
return nil
}
matches = append(matches, p)
return nil
})
return matches, err
}
return g.doGlob(fsys, pattern, nil, true, true)
}
// Does the actual globbin'
// - firstSegment is true if we're in the first segment of the pattern, ie,
// the right-most part where we can match files. If it's false, we're
// somewhere in the middle (or at the beginning) and can only match
// directories since there are path segments above us.
// - beforeMeta is true if we're exploring segments before any meta
// characters, ie, in a pattern such as `path/to/file*.txt`, the `path/to/`
// bit does not contain any meta characters.
func (g *glob) doGlob(fsys fs.FS, pattern string, m []string, firstSegment, beforeMeta bool) (matches []string, err error) {
matches = m
patternStart := indexMeta(pattern)
if patternStart == -1 {
// pattern doesn't contain any meta characters - does a file matching the
// pattern exist?
// The pattern may contain escaped wildcard characters for an exact path match.
path := unescapeMeta(pattern)
pathInfo, pathExists, pathErr := g.exists(fsys, path, beforeMeta)
if pathErr != nil {
return nil, pathErr
}
if pathExists && (!firstSegment || !g.filesOnly || !pathInfo.IsDir()) {
if !isOlder(pathInfo.ModTime(), g.maxAge) {
matches = append(matches, path)
}
}
return
}
dir := "."
splitIdx := lastIndexSlashOrAlt(pattern)
if splitIdx != -1 {
if pattern[splitIdx] == '}' {
openingIdx := indexMatchedOpeningAlt(pattern[:splitIdx])
if openingIdx == -1 {
// if there's no matching opening index, technically Match() will treat
// an unmatched `}` as nothing special, so... we will, too!
splitIdx = lastIndexSlash(pattern[:splitIdx])
if splitIdx != -1 {
dir = pattern[:splitIdx]
pattern = pattern[splitIdx+1:]
}
} else {
// otherwise, we have to handle the alts:
return g.globAlts(fsys, pattern, openingIdx, splitIdx, matches, firstSegment, beforeMeta)
}
} else {
dir = pattern[:splitIdx]
pattern = pattern[splitIdx+1:]
}
}
// if `splitIdx` is less than `patternStart`, we know `dir` has no meta
// characters. They would be equal if they are both -1, which means `dir`
// will be ".", and we know that doesn't have meta characters either.
if splitIdx <= patternStart {
return g.globDir(fsys, dir, pattern, matches, firstSegment, beforeMeta)
}
var dirs []string
dirs, err = g.doGlob(fsys, dir, matches, false, beforeMeta)
if err != nil {
return
}
for _, d := range dirs {
matches, err = g.globDir(fsys, d, pattern, matches, firstSegment, false)
if err != nil {
return
}
}
return
}
// handle alts in the glob pattern - `openingIdx` and `closingIdx` are the
// indexes of `{` and `}`, respectively
func (g *glob) globAlts(fsys fs.FS, pattern string, openingIdx, closingIdx int, m []string, firstSegment, beforeMeta bool) (matches []string, err error) {
matches = m
var dirs []string
startIdx := 0
afterIdx := closingIdx + 1
splitIdx := lastIndexSlashOrAlt(pattern[:openingIdx])
if splitIdx == -1 || pattern[splitIdx] == '}' {
// no common prefix
dirs = []string{""}
} else {
// our alts have a common prefix that we can process first
dirs, err = g.doGlob(fsys, pattern[:splitIdx], matches, false, beforeMeta)
if err != nil {
return
}
startIdx = splitIdx + 1
}
for _, d := range dirs {
patIdx := openingIdx + 1
altResultsStartIdx := len(matches)
thisResultStartIdx := altResultsStartIdx
for patIdx < closingIdx {
nextIdx := indexNextAlt(pattern[patIdx:closingIdx], true)
if nextIdx == -1 {
nextIdx = closingIdx
} else {
nextIdx += patIdx
}
alt := buildAlt(d, pattern, startIdx, openingIdx, patIdx, nextIdx, afterIdx)
matches, err = g.doGlob(fsys, alt, matches, firstSegment, beforeMeta)
if err != nil {
return
}
matchesLen := len(matches)
if altResultsStartIdx != thisResultStartIdx && thisResultStartIdx != matchesLen {
// Alts can result in matches that aren't sorted, or, worse, duplicates
// (consider the trivial pattern `path/to/{a,*}`). Since doGlob returns
// sorted results, we can do a sort of in-place merge and remove
// duplicates. But, we only need to do this if this isn't the first alt
// (ie, `altResultsStartIdx != thisResultsStartIdx`) and if the latest
// alt actually added some matches (`thisResultStartIdx !=
// len(matches)`)
matches = sortAndRemoveDups(matches, altResultsStartIdx, thisResultStartIdx, matchesLen)
// length of matches may have changed
thisResultStartIdx = len(matches)
} else {
thisResultStartIdx = matchesLen
}
patIdx = nextIdx + 1
}
}
return
}
// find files/subdirectories in the given `dir` that match `pattern`
func (g *glob) globDir(fsys fs.FS, dir, pattern string, matches []string, canMatchFiles, beforeMeta bool) (m []string, e error) {
m = matches
if pattern == "" {
if !canMatchFiles || !g.filesOnly {
// pattern can be an empty string if the original pattern ended in a
// slash, in which case, we should just return dir, but only if it
// actually exists and it's a directory (or a symlink to a directory)
_, isDir, err := g.isPathDir(fsys, dir, beforeMeta)
if err != nil {
return nil, err
}
if isDir {
m = append(m, dir)
}
}
return
}
if pattern == "**" {
return g.globDoubleStar(fsys, dir, m, canMatchFiles, beforeMeta)
}
dirs, err := fs.ReadDir(fsys, dir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
e = g.handlePatternNotExist(beforeMeta)
} else {
e = g.forwardErrIfFailOnIOErrors(err)
}
return
}
var matched bool
for _, info := range dirs {
name := info.Name()
matched, e = matchWithSeparator(pattern, name, '/', false)
if e != nil {
return
}
if matched {
matched = canMatchFiles
if !matched || g.filesOnly {
matched, e = g.isDir(fsys, dir, name, info)
if e != nil {
return
}
if canMatchFiles {
// if we're here, it's because g.filesOnly
// is set and we don't want directories
if fi, err := info.Info(); err == nil {
if !isOlder(fi.ModTime(), g.maxAge) {
matched = !matched
}
} else {
matched = !matched
}
}
}
if matched {
m = append(m, path.Join(dir, name))
}
}
}
return
}
func (g *glob) globDoubleStar(fsys fs.FS, dir string, matches []string, canMatchFiles, beforeMeta bool) ([]string, error) {
dirs, err := fs.ReadDir(fsys, dir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return matches, g.handlePatternNotExist(beforeMeta)
} else {
return matches, g.forwardErrIfFailOnIOErrors(err)
}
}
if !g.filesOnly {
// `**` can match *this* dir, so add it
matches = append(matches, dir)
}
for _, info := range dirs {
name := info.Name()
isDir, err := g.isDir(fsys, dir, name, info)
if err != nil {
return nil, err
}
if isDir {
matches, err = g.globDoubleStar(fsys, path.Join(dir, name), matches, canMatchFiles, false)
if err != nil {
return nil, err
}
} else if canMatchFiles {
matches = append(matches, path.Join(dir, name))
}
}
return matches, nil
}
// Returns true if the pattern has a doublestar in the middle of the pattern.
// In this case, GlobWalk is faster because it can get away with less
// allocations. However, Glob has a _very_ slight edge if the pattern ends in
// `**`.
func hasMidDoubleStar(p string) bool {
// subtract 3: 2 because we want to return false if the pattern ends in `**`
// (Glob is _very_ slightly faster in that case), and the extra 1 because our
// loop checks p[i] and p[i+1].
l := len(p) - 3
for i := 0; i < l; i++ {
if p[i] == '\\' {
// escape next byte
i++
} else if p[i] == '*' && p[i+1] == '*' {
return true
}
}
return false
}
// Returns the index of the first unescaped meta character, or negative 1.
func indexMeta(s string) int {
var c byte
l := len(s)
for i := 0; i < l; i++ {
c = s[i]
if c == '*' || c == '?' || c == '[' || c == '{' {
return i
} else if c == '\\' {
// skip next byte
i++
}
}
return -1
}
// Returns the index of the last unescaped slash or closing alt (`}`) in the
// string, or negative 1.
func lastIndexSlashOrAlt(s string) int {
for i := len(s) - 1; i >= 0; i-- {
if (s[i] == '/' || s[i] == '}') && (i == 0 || s[i-1] != '\\') {
return i
}
}
return -1
}
// Returns the index of the last unescaped slash in the string, or negative 1.
func lastIndexSlash(s string) int {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '/' && (i == 0 || s[i-1] != '\\') {
return i
}
}
return -1
}
// Assuming the byte after the end of `s` is a closing `}`, this function will
// find the index of the matching `{`. That is, it'll skip over any nested `{}`
// and account for escaping.
func indexMatchedOpeningAlt(s string) int {
alts := 1
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '}' && (i == 0 || s[i-1] != '\\') {
alts++
} else if s[i] == '{' && (i == 0 || s[i-1] != '\\') {
if alts--; alts == 0 {
return i
}
}
}
return -1
}
// Returns true if the path exists
func (g *glob) exists(fsys fs.FS, name string, beforeMeta bool) (fs.FileInfo, bool, error) {
// name might end in a slash, but Stat doesn't like that
namelen := len(name)
if namelen > 1 && name[namelen-1] == '/' {
name = name[:namelen-1]
}
info, err := fs.Stat(fsys, name)
if errors.Is(err, fs.ErrNotExist) {
return nil, false, g.handlePatternNotExist(beforeMeta)
}
return info, err == nil, g.forwardErrIfFailOnIOErrors(err)
}
// Returns true if the path exists and is a directory or a symlink to a
// directory
func (g *glob) isPathDir(fsys fs.FS, name string, beforeMeta bool) (fs.FileInfo, bool, error) {
info, err := fs.Stat(fsys, name)
if errors.Is(err, fs.ErrNotExist) {
return nil, false, g.handlePatternNotExist(beforeMeta)
}
return info, err == nil && info.IsDir(), g.forwardErrIfFailOnIOErrors(err)
}
// Returns whether or not the given DirEntry is a directory. If the DirEntry
// represents a symbolic link, the link is followed by running fs.Stat() on
// `path.Join(dir, name)` (if dir is "", name will be used without joining)
func (g *glob) isDir(fsys fs.FS, dir, name string, info fs.DirEntry) (bool, error) {
if !g.noFollow && (info.Type()&fs.ModeSymlink) > 0 {
p := name
if dir != "" {
p = path.Join(dir, name)
}
finfo, err := fs.Stat(fsys, p)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// this function is only ever called while expanding a glob, so it can
// never return ErrPatternNotExist
return false, nil
}
return false, g.forwardErrIfFailOnIOErrors(err)
}
return finfo.IsDir(), nil
}
return info.IsDir(), nil
}
// Builds a string from an alt
func buildAlt(prefix, pattern string, startIdx, openingIdx, currentIdx, nextIdx, afterIdx int) string {
// pattern:
// ignored/start{alts,go,here}remaining - len = 36
// | | | | ^--- afterIdx = 27
// | | | \--------- nextIdx = 21
// | | \----------- currentIdx = 19
// | \----------------- openingIdx = 13
// \---------------------- startIdx = 8
//
// result:
// prefix/startgoremaining - len = 7 + 5 + 2 + 9 = 23
var buf []byte
patLen := len(pattern)
size := (openingIdx - startIdx) + (nextIdx - currentIdx) + (patLen - afterIdx)
if prefix != "" && prefix != "." {
buf = make([]byte, 0, size+len(prefix)+1)
buf = append(buf, prefix...)
buf = append(buf, '/')
} else {
buf = make([]byte, 0, size)
}
buf = append(buf, pattern[startIdx:openingIdx]...)
buf = append(buf, pattern[currentIdx:nextIdx]...)
if afterIdx < patLen {
buf = append(buf, pattern[afterIdx:]...)
}
return string(buf)
}
// Running alts can produce results that are not sorted, and, worse, can cause
// duplicates (consider the trivial pattern `path/to/{a,*}`). Since we know
// each run of doGlob is sorted, we can basically do the "merge" step of a
// merge sort in-place.
func sortAndRemoveDups(matches []string, idx1, idx2, l int) []string {
var tmp string
for ; idx1 < idx2; idx1++ {
if matches[idx1] < matches[idx2] {
// order is correct
continue
} else if matches[idx1] > matches[idx2] {
// need to swap and then re-sort matches above idx2
tmp = matches[idx1]
matches[idx1] = matches[idx2]
shft := idx2 + 1
for ; shft < l && matches[shft] < tmp; shft++ {
matches[shft-1] = matches[shft]
}
matches[shft-1] = tmp
} else {
// duplicate - shift matches above idx2 down one and decrement l
for shft := idx2 + 1; shft < l; shft++ {
matches[shft-1] = matches[shft]
}
if l--; idx2 == l {
// nothing left to do... matches[idx2:] must have been full of dups
break
}
}
}
return matches[:l]
}