forked from hmarr/codeowners
-
Notifications
You must be signed in to change notification settings - Fork 0
/
match.go
177 lines (151 loc) · 4.42 KB
/
match.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
package codeowners
import (
"fmt"
"path/filepath"
"regexp"
"strings"
)
type pattern struct {
pattern string
regex *regexp.Regexp
leftAnchoredLiteral bool
}
// newPattern creates a new pattern struct from a gitignore-style pattern string
func newPattern(patternStr string) (pattern, error) {
pat := pattern{pattern: patternStr}
if !strings.ContainsAny(patternStr, "*?\\") && patternStr[0] == '/' {
pat.leftAnchoredLiteral = true
} else {
patternRegex, err := buildPatternRegex(patternStr)
if err != nil {
return pattern{}, err
}
pat.regex = patternRegex
}
return pat, nil
}
// match tests if the path provided matches the pattern
func (p pattern) match(testPath string) (bool, error) {
// Normalize Windows-style path separators to forward slashes
testPath = filepath.ToSlash(testPath)
if p.leftAnchoredLiteral {
prefix := p.pattern
// Strip the leading slash as we're anchored to the root already
if prefix[0] == '/' {
prefix = prefix[1:]
}
// If the pattern ends with a slash we can do a simple prefix match
if prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(testPath, prefix), nil
}
// If the strings are the same length, check for an exact match
if len(testPath) == len(prefix) {
return testPath == prefix, nil
}
// Otherwise check if the test path is a subdirectory of the pattern
if len(testPath) > len(prefix) && testPath[len(prefix)] == '/' {
return testPath[:len(prefix)] == prefix, nil
}
// Otherwise the test path must be shorter than the pattern, so it can't match
return false, nil
}
return p.regex.MatchString(testPath), nil
}
// buildPatternRegex compiles a new regexp object from a gitignore-style pattern string
func buildPatternRegex(pattern string) (*regexp.Regexp, error) {
// Handle specific edge cases first
switch {
case strings.Contains(pattern, "***"):
return nil, fmt.Errorf("pattern cannot contain three consecutive asterisks")
case pattern == "":
return nil, fmt.Errorf("empty pattern")
case pattern == "/":
// "/" doesn't match anything
return regexp.Compile(`\A\z`)
}
segs := strings.Split(pattern, "/")
if segs[0] == "" {
// Leading slash: match is relative to root
segs = segs[1:]
} else {
// No leading slash - check for a single segment pattern, which matches
// relative to any descendent path (equivalent to a leading **/)
if len(segs) == 1 || (len(segs) == 2 && segs[1] == "") {
if segs[0] != "**" {
segs = append([]string{"**"}, segs...)
}
}
}
if len(segs) > 1 && segs[len(segs)-1] == "" {
// Trailing slash is equivalent to "/**"
segs[len(segs)-1] = "**"
}
sep := "/"
lastSegIndex := len(segs) - 1
needSlash := false
var re strings.Builder
re.WriteString(`\A`)
for i, seg := range segs {
switch seg {
case "**":
switch {
case i == 0 && i == lastSegIndex:
// If the pattern is just "**" we match everything
re.WriteString(`.+`)
case i == 0:
// If the pattern starts with "**" we match any leading path segment
re.WriteString(`(?:.+` + sep + `)?`)
needSlash = false
case i == lastSegIndex:
// If the pattern ends with "**" we match any trailing path segment
re.WriteString(sep + `.*`)
default:
// If the pattern contains "**" we match zero or more path segments
re.WriteString(`(?:` + sep + `.+)?`)
needSlash = true
}
case "*":
if needSlash {
re.WriteString(sep)
}
// Regular wildcard - match any characters except the separator
re.WriteString(`[^` + sep + `]+`)
needSlash = true
default:
if needSlash {
re.WriteString(sep)
}
escape := false
for _, ch := range seg {
if escape {
escape = false
re.WriteString(regexp.QuoteMeta(string(ch)))
continue
}
// Other pathspec implementations handle character classes here (e.g.
// [AaBb]), but CODEOWNERS doesn't support that so we don't need to
switch ch {
case '\\':
escape = true
case '*':
// Multi-character wildcard
re.WriteString(`[^` + sep + `]*`)
case '?':
// Single-character wildcard
re.WriteString(`[^` + sep + `]`)
default:
// Regular character
re.WriteString(regexp.QuoteMeta(string(ch)))
}
}
if i == lastSegIndex {
// As there's no trailing slash (that'd hit the '**' case), we
// need to match descendent paths
re.WriteString(`(?:` + sep + `.*)?`)
}
needSlash = true
}
}
re.WriteString(`\z`)
return regexp.Compile(re.String())
}