File: doublestar.go

package info (click to toggle)
golang-github-bmatcuk-doublestar 2.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 116 kB
  • sloc: makefile: 6
file content (630 lines) | stat: -rw-r--r-- 17,143 bytes parent folder | download | duplicates (2)
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package doublestar

import (
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"
	"unicode/utf8"
)

// File defines a subset of file operations
type File interface {
	io.Closer
	Readdir(count int) ([]os.FileInfo, error)
}

// An OS abstracts functions in the standard library's os package.
type OS interface {
	Lstat(name string) (os.FileInfo, error)
	Open(name string) (File, error)
	PathSeparator() rune
	Stat(name string) (os.FileInfo, error)
}

// A standardOS implements OS by calling functions in the standard library's os
// package.
type standardOS struct{}

func (standardOS) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) }
func (standardOS) Open(name string) (File, error)         { return os.Open(name) }
func (standardOS) PathSeparator() rune                    { return os.PathSeparator }
func (standardOS) Stat(name string) (os.FileInfo, error)  { return os.Stat(name) }

// StandardOS is a value that implements the OS interface by calling functions
// in the standard libray's os package.
var StandardOS OS = standardOS{}

// ErrBadPattern indicates a pattern was malformed.
var ErrBadPattern = path.ErrBadPattern

// Find the first index of a rune in a string,
// ignoring any times the rune is escaped using "\".
func indexRuneWithEscaping(s string, r rune) int {
	end := strings.IndexRune(s, r)
	if end == -1 || r == '\\' {
		return end
	}
	if end > 0 && s[end-1] == '\\' {
		start := end + utf8.RuneLen(r)
		end = indexRuneWithEscaping(s[start:], r)
		if end != -1 {
			end += start
		}
	}
	return end
}

// Find the last index of a rune in a string,
// ignoring any times the rune is escaped using "\".
func lastIndexRuneWithEscaping(s string, r rune) int {
	end := strings.LastIndex(s, string(r))
	if end == -1 {
		return -1
	}
	if end > 0 && s[end-1] == '\\' {
		end = lastIndexRuneWithEscaping(s[:end-1], r)
	}
	return end
}

// Find the index of the first instance of one of the unicode characters in
// chars, ignoring any times those characters are escaped using "\".
func indexAnyWithEscaping(s, chars string) int {
	end := strings.IndexAny(s, chars)
	if end == -1 {
		return -1
	}
	if end > 0 && s[end-1] == '\\' {
		_, adj := utf8.DecodeRuneInString(s[end:])
		start := end + adj
		end = indexAnyWithEscaping(s[start:], chars)
		if end != -1 {
			end += start
		}
	}
	return end
}

// Split a set of alternatives such as {alt1,alt2,...} and returns the index of
// the rune after the closing curly brace. Respects nested alternatives and
// escaped runes.
func splitAlternatives(s string) (ret []string, idx int) {
	ret = make([]string, 0, 2)
	idx = 0
	slen := len(s)
	braceCnt := 1
	esc := false
	start := 0
	for braceCnt > 0 {
		if idx >= slen {
			return nil, -1
		}

		sRune, adj := utf8.DecodeRuneInString(s[idx:])
		if esc {
			esc = false
		} else if sRune == '\\' {
			esc = true
		} else if sRune == '{' {
			braceCnt++
		} else if sRune == '}' {
			braceCnt--
		} else if sRune == ',' && braceCnt == 1 {
			ret = append(ret, s[start:idx])
			start = idx + adj
		}

		idx += adj
	}
	ret = append(ret, s[start:idx-1])
	return
}

// Returns true if the pattern is "zero length", meaning
// it could match zero or more characters.
func isZeroLengthPattern(pattern string) (ret bool, err error) {
	// * can match zero
	if pattern == "" || pattern == "*" || pattern == "**" {
		return true, nil
	}

	// an alternative with zero length can match zero, for example {,x} - the
	// first alternative has zero length
	r, adj := utf8.DecodeRuneInString(pattern)
	if r == '{' {
		options, endOptions := splitAlternatives(pattern[adj:])
		if endOptions == -1 {
			return false, ErrBadPattern
		}
		if ret, err = isZeroLengthPattern(pattern[adj+endOptions:]); !ret || err != nil {
			return
		}
		for _, o := range options {
			if ret, err = isZeroLengthPattern(o); ret || err != nil {
				return
			}
		}
	}

	return false, nil
}

// Match returns true if name matches the shell file name pattern.
// The pattern syntax is:
//
//  pattern:
//    { term }
//  term:
//    '*'         matches any sequence of non-path-separators
//    '**'        matches any sequence of characters, including
//                path separators.
//    '?'         matches any single non-path-separator character
//    '[' [ '^' ] { character-range } ']'
//          character class (must be non-empty)
//    '{' { term } [ ',' { term } ... ] '}'
//    c           matches character c (c != '*', '?', '\\', '[')
//    '\\' c      matches character c
//
//  character-range:
//    c           matches character c (c != '\\', '-', ']')
//    '\\' c      matches character c
//    lo '-' hi   matches character c for lo <= c <= hi
//
// Match requires pattern to match all of name, not just a substring.
// The path-separator defaults to the '/' character. The only possible
// returned error is ErrBadPattern, when pattern is malformed.
//
// Note: this is meant as a drop-in replacement for path.Match() which
// always uses '/' as the path separator. If you want to support systems
// which use a different path separator (such as Windows), what you want
// is the PathMatch() function below.
//
func Match(pattern, name string) (bool, error) {
	return doMatching(pattern, name, '/')
}

// PathMatch is like Match except that it uses your system's path separator.
// For most systems, this will be '/'. However, for Windows, it would be '\\'.
// Note that for systems where the path separator is '\\', escaping is
// disabled.
//
// Note: this is meant as a drop-in replacement for filepath.Match().
//
func PathMatch(pattern, name string) (bool, error) {
	return PathMatchOS(StandardOS, pattern, name)
}

// PathMatchOS is like PathMatch except that it uses vos's path separator.
func PathMatchOS(vos OS, pattern, name string) (bool, error) {
	pattern = filepath.ToSlash(pattern)
	return doMatching(pattern, name, vos.PathSeparator())
}

func doMatching(pattern, name string, separator rune) (matched bool, err error) {
	// check for some base-cases
	patternLen, nameLen := len(pattern), len(name)
	if patternLen == 0 {
		return nameLen == 0, nil
	} else if nameLen == 0 {
		return isZeroLengthPattern(pattern)
	}

	separatorAdj := utf8.RuneLen(separator)

	patIdx := indexRuneWithEscaping(pattern, '/')
	lastPat := patIdx == -1
	if lastPat {
		patIdx = len(pattern)
	}
	if pattern[:patIdx] == "**" {
		// if our last pattern component is a doublestar, we're done -
		// doublestar will match any remaining name components, if any.
		if lastPat {
			return true, nil
		}

		// otherwise, try matching remaining components
		nameIdx := 0
		patIdx += 1
		for {
			if m, _ := doMatching(pattern[patIdx:], name[nameIdx:], separator); m {
				return true, nil
			}

			nextNameIdx := 0
			if nextNameIdx = indexRuneWithEscaping(name[nameIdx:], separator); nextNameIdx == -1 {
				break
			}
			nameIdx += separatorAdj + nextNameIdx
		}
		return false, nil
	}

	nameIdx := indexRuneWithEscaping(name, separator)
	lastName := nameIdx == -1
	if lastName {
		nameIdx = nameLen
	}

	var matches []string
	matches, err = matchComponent(pattern, name[:nameIdx])
	if matches == nil || err != nil {
		return
	}
	if len(matches) == 0 && lastName {
		return true, nil
	}

	if !lastName {
		nameIdx += separatorAdj
		for _, alt := range matches {
			matched, err = doMatching(alt, name[nameIdx:], separator)
			if matched || err != nil {
				return
			}
		}
	}

	return false, nil
}

// 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 (assuming the Separator is '/').
//
// Glob ignores file system errors such as I/O errors reading directories.
// The only possible returned error is ErrBadPattern, when pattern
// is malformed.
//
// Your system path separator is automatically used. This means on
// systems where the separator is '\\' (Windows), escaping will be
// disabled.
//
// Note: this is meant as a drop-in replacement for filepath.Glob().
//
func Glob(pattern string) (matches []string, err error) {
	return GlobOS(StandardOS, pattern)
}

// GlobOS is like Glob except that it operates on vos.
func GlobOS(vos OS, pattern string) (matches []string, err error) {
	if len(pattern) == 0 {
		return nil, nil
	}

	// if the pattern starts with alternatives, we need to handle that here - the
	// alternatives may be a mix of relative and absolute
	if pattern[0] == '{' {
		options, endOptions := splitAlternatives(pattern[1:])
		if endOptions == -1 {
			return nil, ErrBadPattern
		}
		for _, o := range options {
			m, e := GlobOS(vos, o+pattern[endOptions+1:])
			if e != nil {
				return nil, e
			}
			matches = append(matches, m...)
		}
		return matches, nil
	}

	// If the pattern is relative or absolute and we're on a non-Windows machine,
	// volumeName will be an empty string. If it is absolute and we're on a
	// Windows machine, volumeName will be a drive letter ("C:") for filesystem
	// paths or \\<server>\<share> for UNC paths.
	isAbs := filepath.IsAbs(pattern) || pattern[0] == '\\' || pattern[0] == '/'
	volumeName := filepath.VolumeName(pattern)
	isWindowsUNC := strings.HasPrefix(volumeName, `\\`)
	if isWindowsUNC || isAbs {
		startIdx := len(volumeName) + 1
		return doGlob(vos, fmt.Sprintf("%s%s", volumeName, string(vos.PathSeparator())), filepath.ToSlash(pattern[startIdx:]), matches)
	}

	// otherwise, it's a relative pattern
	return doGlob(vos, ".", filepath.ToSlash(pattern), matches)
}

// Perform a glob
func doGlob(vos OS, basedir, pattern string, matches []string) (m []string, e error) {
	m = matches
	e = nil

	// if the pattern starts with any path components that aren't globbed (ie,
	// `path/to/glob*`), we can skip over the un-globbed components (`path/to` in
	// our example).
	globIdx := indexAnyWithEscaping(pattern, "*?[{\\")
	if globIdx > 0 {
		globIdx = lastIndexRuneWithEscaping(pattern[:globIdx], '/')
	} else if globIdx == -1 {
		globIdx = lastIndexRuneWithEscaping(pattern, '/')
	}
	if globIdx > 0 {
		basedir = filepath.Join(basedir, pattern[:globIdx])
		pattern = pattern[globIdx+1:]
	}

	// Lstat will return an error if the file/directory doesn't exist
	fi, err := vos.Lstat(basedir)
	if err != nil {
		return
	}

	// if the pattern is empty, we've found a match
	if len(pattern) == 0 {
		m = append(m, basedir)
		return
	}

	// otherwise, we need to check each item in the directory...

	// first, if basedir is a symlink, follow it...
	if (fi.Mode() & os.ModeSymlink) != 0 {
		fi, err = vos.Stat(basedir)
		if err != nil {
			return
		}
	}

	// confirm it's a directory...
	if !fi.IsDir() {
		return
	}

	files, err := filesInDir(vos, basedir)
	if err != nil {
		return
	}

	sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() })

	slashIdx := indexRuneWithEscaping(pattern, '/')
	lastComponent := slashIdx == -1
	if lastComponent {
		slashIdx = len(pattern)
	}
	if pattern[:slashIdx] == "**" {
		// if the current component is a doublestar, we'll try depth-first
		for _, file := range files {
			// if symlink, we may want to follow
			if (file.Mode() & os.ModeSymlink) != 0 {
				file, err = vos.Stat(filepath.Join(basedir, file.Name()))
				if err != nil {
					continue
				}
			}

			if file.IsDir() {
				// recurse into directories
				if lastComponent {
					m = append(m, filepath.Join(basedir, file.Name()))
				}
				m, e = doGlob(vos, filepath.Join(basedir, file.Name()), pattern, m)
			} else if lastComponent {
				// if the pattern's last component is a doublestar, we match filenames, too
				m = append(m, filepath.Join(basedir, file.Name()))
			}
		}
		if lastComponent {
			return // we're done
		}

		pattern = pattern[slashIdx+1:]
	}

	// check items in current directory and recurse
	var match []string
	for _, file := range files {
		match, e = matchComponent(pattern, file.Name())
		if e != nil {
			return
		}
		if match != nil {
			if len(match) == 0 {
				m = append(m, filepath.Join(basedir, file.Name()))
			} else {
				for _, alt := range match {
					m, e = doGlob(vos, filepath.Join(basedir, file.Name()), alt, m)
				}
			}
		}
	}
	return
}

func filesInDir(vos OS, dirPath string) (files []os.FileInfo, e error) {
	dir, err := vos.Open(dirPath)
	if err != nil {
		return nil, nil
	}
	defer func() {
		if err := dir.Close(); e == nil {
			e = err
		}
	}()

	files, err = dir.Readdir(-1)
	if err != nil {
		return nil, nil
	}

	return
}

// Attempt to match a single path component with a pattern. Note that the
// pattern may include multiple components but that the "name" is just a single
// path component. The return value is a slice of patterns that should be
// checked against subsequent path components or nil, indicating that the
// pattern does not match this path. It is assumed that pattern components are
// separated by '/'
func matchComponent(pattern, name string) ([]string, error) {
	// check for matches one rune at a time
	patternLen, nameLen := len(pattern), len(name)
	patIdx, nameIdx := 0, 0
	for patIdx < patternLen && nameIdx < nameLen {
		patRune, patAdj := utf8.DecodeRuneInString(pattern[patIdx:])
		nameRune, nameAdj := utf8.DecodeRuneInString(name[nameIdx:])
		if patRune == '/' {
			patIdx++
			break
		} else if patRune == '\\' {
			// handle escaped runes, only if separator isn't '\\'
			patIdx += patAdj
			patRune, patAdj = utf8.DecodeRuneInString(pattern[patIdx:])
			if patRune == utf8.RuneError {
				return nil, ErrBadPattern
			} else if patRune == nameRune {
				patIdx += patAdj
				nameIdx += nameAdj
			} else {
				return nil, nil
			}
		} else if patRune == '*' {
			// handle stars - a star at the end of the pattern or before a separator
			// will always match the rest of the path component
			if patIdx += patAdj; patIdx >= patternLen {
				return []string{}, nil
			}
			if patRune, patAdj = utf8.DecodeRuneInString(pattern[patIdx:]); patRune == '/' {
				return []string{pattern[patIdx+patAdj:]}, nil
			}

			// check if we can make any matches
			for ; nameIdx < nameLen; nameIdx += nameAdj {
				if m, e := matchComponent(pattern[patIdx:], name[nameIdx:]); m != nil || e != nil {
					return m, e
				}
				_, nameAdj = utf8.DecodeRuneInString(name[nameIdx:])
			}
			return nil, nil
		} else if patRune == '[' {
			// handle character sets
			patIdx += patAdj
			endClass := indexRuneWithEscaping(pattern[patIdx:], ']')
			if endClass == -1 {
				return nil, ErrBadPattern
			}
			endClass += patIdx
			classRunes := []rune(pattern[patIdx:endClass])
			classRunesLen := len(classRunes)
			if classRunesLen > 0 {
				classIdx := 0
				matchClass := false
				if classRunes[0] == '^' {
					classIdx++
				}
				for classIdx < classRunesLen {
					low := classRunes[classIdx]
					if low == '-' {
						return nil, ErrBadPattern
					}
					classIdx++
					if low == '\\' {
						if classIdx < classRunesLen {
							low = classRunes[classIdx]
							classIdx++
						} else {
							return nil, ErrBadPattern
						}
					}
					high := low
					if classIdx < classRunesLen && classRunes[classIdx] == '-' {
						// we have a range of runes
						if classIdx++; classIdx >= classRunesLen {
							return nil, ErrBadPattern
						}
						high = classRunes[classIdx]
						if high == '-' {
							return nil, ErrBadPattern
						}
						classIdx++
						if high == '\\' {
							if classIdx < classRunesLen {
								high = classRunes[classIdx]
								classIdx++
							} else {
								return nil, ErrBadPattern
							}
						}
					}
					if low <= nameRune && nameRune <= high {
						matchClass = true
					}
				}
				if matchClass == (classRunes[0] == '^') {
					return nil, nil
				}
			} else {
				return nil, ErrBadPattern
			}
			patIdx = endClass + 1
			nameIdx += nameAdj
		} else if patRune == '{' {
			// handle alternatives such as {alt1,alt2,...}
			patIdx += patAdj
			options, endOptions := splitAlternatives(pattern[patIdx:])
			if endOptions == -1 {
				return nil, ErrBadPattern
			}
			patIdx += endOptions

			results := make([][]string, 0, len(options))
			totalResults := 0
			for _, o := range options {
				m, e := matchComponent(o+pattern[patIdx:], name[nameIdx:])
				if e != nil {
					return nil, e
				}
				if m != nil {
					results = append(results, m)
					totalResults += len(m)
				}
			}
			if len(results) > 0 {
				lst := make([]string, 0, totalResults)
				for _, m := range results {
					lst = append(lst, m...)
				}
				return lst, nil
			}

			return nil, nil
		} else if patRune == '?' || patRune == nameRune {
			// handle single-rune wildcard
			patIdx += patAdj
			nameIdx += nameAdj
		} else {
			return nil, nil
		}
	}
	if nameIdx >= nameLen {
		if patIdx >= patternLen {
			return []string{}, nil
		}

		pattern = pattern[patIdx:]
		slashIdx := indexRuneWithEscaping(pattern, '/')
		testPattern := pattern
		if slashIdx >= 0 {
			testPattern = pattern[:slashIdx]
		}

		zeroLength, err := isZeroLengthPattern(testPattern)
		if err != nil {
			return nil, err
		}
		if zeroLength {
			if slashIdx == -1 {
				return []string{}, nil
			} else {
				return []string{pattern[slashIdx+1:]}, nil
			}
		}
	}
	return nil, nil
}