Debian Codegraph @

pushrules/glob/glob.go

raw
1 // Package glob provides objects for matching strings with globs
2 package glob
3
4 import "regexp"
5
6 // Glob is a wrapper of *regexp.Regexp.
7 // It should contain a glob expression compiled into a regular expression.
8 type Glob struct {
9 *regexp.Regexp
10 }
11
12 // Compile a takes a glob expression as a string and transforms it
13 // into a *Glob object (which is really just a regular expression)
14 // Compile also returns a possible error.
15 func Compile(pattern string) (*Glob, error) {
16 r, err := globToRegex(pattern)
17 return &Glob{r}, err
18 }
19
20 func globToRegex(glob string) (*regexp.Regexp, error) {
21 regex := ""
22 inGroup := 0
23 inClass := 0
24 firstIndexInClass := -1
25 arr := []byte(glob)
26
27 hasGlobCharacters := false
28
29 for i := 0; i < len(arr); i++ {
30 ch := arr[i]
31
32 switch ch {
33 case '\\':
34 i++
35 if i >= len(arr) {
36 regex += "\\"
37 } else {
38 next := arr[i]
39 switch next {
40 case ',':
41 // Nothing
42 case 'Q', 'E':
43 regex += "\\\\"
44 default:
45 regex += "\\"
46 }
47 regex += string(next)
48 }
49 case '*':
50 if inClass == 0 {
51 regex += ".*"
52 } else {
53 regex += "*"
54 }
55 hasGlobCharacters = true
56 case '?':
57 if inClass == 0 {
58 regex += "."
59 } else {
60 regex += "?"
61 }
62 hasGlobCharacters = true
63 case '[':
64 inClass++
65 firstIndexInClass = i + 1
66 regex += "["
67 hasGlobCharacters = true
68 case ']':
69 inClass--
70 regex += "]"
71 case '.', '(', ')', '+', '|', '^', '$', '@', '%':
72 if inClass == 0 || (firstIndexInClass == i && ch == '^') {
73 regex += "\\"
74 }
75 regex += string(ch)
76 hasGlobCharacters = true
77 case '!':
78 if firstIndexInClass == i {
79 regex += "^"
80 } else {
81 regex += "!"
82 }
83 hasGlobCharacters = true
84 case '{':
85 inGroup++
86 regex += "("
87 hasGlobCharacters = true
88 case '}':
89 inGroup--
90 regex += ")"
91 case ',':
92 if inGroup > 0 {
93 regex += "|"
94 hasGlobCharacters = true
95 } else {
96 regex += ","
97 }
98 default:
99 regex += string(ch)
100 }
101 }
102
103 if hasGlobCharacters {
104 return regexp.Compile("^" + regex + "$")
105 } else {
106 return regexp.Compile(regex)
107 }
108 }