-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
glob.go
58 lines (50 loc) · 1.37 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
package helpers
import "strings"
type GlobWildcard uint8
const (
GlobNone GlobWildcard = iota
GlobAllExceptSlash
GlobAllIncludingSlash
)
type GlobPart struct {
Prefix string
Wildcard GlobWildcard
}
// The returned array will always be at least one element. If there are no
// wildcards then it will be exactly one element, and if there are wildcards
// then it will be more than one element.
func ParseGlobPattern(text string) (pattern []GlobPart) {
for {
star := strings.IndexByte(text, '*')
if star < 0 {
pattern = append(pattern, GlobPart{Prefix: text})
break
}
count := 1
for star+count < len(text) && text[star+count] == '*' {
count++
}
wildcard := GlobAllExceptSlash
// Allow both "/" and "\" as slashes
if count > 1 && (star == 0 || text[star-1] == '/' || text[star-1] == '\\') &&
(star+count == len(text) || text[star+count] == '/' || text[star+count] == '\\') {
wildcard = GlobAllIncludingSlash // A "globstar" path segment
}
pattern = append(pattern, GlobPart{Prefix: text[:star], Wildcard: wildcard})
text = text[star+count:]
}
return
}
func GlobPatternToString(pattern []GlobPart) string {
sb := strings.Builder{}
for _, part := range pattern {
sb.WriteString(part.Prefix)
switch part.Wildcard {
case GlobAllExceptSlash:
sb.WriteByte('*')
case GlobAllIncludingSlash:
sb.WriteString("**")
}
}
return sb.String()
}