-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpattern_bundle.go
337 lines (324 loc) · 8.61 KB
/
pattern_bundle.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
// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT.
//go:generate bundle -o pattern_bundle.go -prefix pattern mvdan.cc/sh/v3/pattern
// Package pattern allows working with shell pattern matching notation, also
// known as wildcards or globbing.
//
// For reference, see
// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13.
//
package editorconfig
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
)
// Mode can be used to supply a number of options to the package's functions.
// Not all functions change their behavior with all of the options below.
type patternMode uint
type patternSyntaxError struct {
msg string
err error
}
func (e patternSyntaxError) Error() string { return e.msg }
func (e patternSyntaxError) Unwrap() error { return e.err }
const (
patternShortest patternMode = 1 << iota // prefer the shortest match.
patternFilenames // "*" and "?" don't match slashes; only "**" does
patternBraces // support "{a,b}" and "{1..4}"
patternEntireString // match the entire string using ^$ delimiters
)
var patternnumRange = regexp.MustCompile(`^([+-]?\d+)\.\.([+-]?\d+)}`)
// Regexp turns a shell pattern into a regular expression that can be used with
// [regexp.Compile]. It will return an error if the input pattern was incorrect.
// Otherwise, the returned expression can be passed to [regexp.MustCompile].
//
// For example, Regexp(`foo*bar?`, true) returns `foo.*bar.`.
//
// Note that this function (and [QuoteMeta]) should not be directly used with file
// paths if Windows is supported, as the path separator on that platform is the
// same character as the escaping character for shell patterns.
func patternRegexp(pat string, mode patternMode) (string, error) {
needsEscaping := false
noopLoop:
for _, r := range pat {
switch r {
// including those that need escaping since they are
// regular expression metacharacters
case '*', '?', '[', '\\', '.', '+', '(', ')', '|',
']', '{', '}', '^', '$':
needsEscaping = true
break noopLoop
}
}
if !needsEscaping && mode&patternEntireString == 0 { // short-cut without a string copy
return pat, nil
}
closingBraces := []int{}
var buf bytes.Buffer
// Enable matching `\n` with the `.` metacharacter as globs match `\n`
buf.WriteString("(?s)")
dotMeta := false
if mode&patternEntireString != 0 {
buf.WriteString("^")
}
writeLoop:
for i := 0; i < len(pat); i++ {
switch c := pat[i]; c {
case '*':
if mode&patternFilenames != 0 {
if i++; i < len(pat) && pat[i] == '*' {
if i++; i < len(pat) && pat[i] == '/' {
buf.WriteString("(.*/|)")
dotMeta = true
} else {
buf.WriteString(".*")
dotMeta = true
i--
}
} else {
buf.WriteString("[^/]*")
i--
}
} else {
buf.WriteString(".*")
dotMeta = true
}
if mode&patternShortest != 0 {
buf.WriteByte('?')
}
case '?':
if mode&patternFilenames != 0 {
buf.WriteString("[^/]")
} else {
buf.WriteByte('.')
dotMeta = true
}
case '\\':
if i++; i >= len(pat) {
return "", &patternSyntaxError{msg: `\ at end of pattern`}
}
buf.WriteString(regexp.QuoteMeta(string(pat[i])))
case '[':
name, err := patterncharClass(pat[i:])
if err != nil {
return "", &patternSyntaxError{msg: "charClass invalid", err: err}
}
if name != "" {
buf.WriteString(name)
i += len(name) - 1
break
}
if mode&patternFilenames != 0 {
for _, c := range pat[i:] {
if c == ']' {
break
} else if c == '/' {
buf.WriteString("\\[")
continue writeLoop
}
}
}
buf.WriteByte(c)
if i++; i >= len(pat) {
return "", &patternSyntaxError{msg: "[ was not matched with a closing ]"}
}
switch c = pat[i]; c {
case '!', '^':
buf.WriteByte('^')
if i++; i >= len(pat) {
return "", &patternSyntaxError{msg: "[ was not matched with a closing ]"}
}
}
if c = pat[i]; c == ']' {
buf.WriteByte(']')
if i++; i >= len(pat) {
return "", &patternSyntaxError{msg: "[ was not matched with a closing ]"}
}
}
rangeStart := byte(0)
loopBracket:
for ; i < len(pat); i++ {
c = pat[i]
buf.WriteByte(c)
switch c {
case '\\':
if i++; i < len(pat) {
buf.WriteByte(pat[i])
}
continue
case ']':
break loopBracket
}
if rangeStart != 0 && rangeStart > c {
return "", &patternSyntaxError{msg: fmt.Sprintf("invalid range: %c-%c", rangeStart, c)}
}
if c == '-' {
rangeStart = pat[i-1]
} else {
rangeStart = 0
}
}
if i >= len(pat) {
return "", &patternSyntaxError{msg: "[ was not matched with a closing ]"}
}
case '{':
if mode&patternBraces == 0 {
buf.WriteString(regexp.QuoteMeta(string(c)))
break
}
innerLevel := 1
commas := false
peekBrace:
for j := i + 1; j < len(pat); j++ {
switch c := pat[j]; c {
case '{':
innerLevel++
case ',':
commas = true
case '\\':
j++
case '}':
if innerLevel--; innerLevel > 0 {
continue
}
if !commas {
break peekBrace
}
closingBraces = append(closingBraces, j)
buf.WriteString("(?:")
continue writeLoop
}
}
if match := patternnumRange.FindStringSubmatch(pat[i+1:]); len(match) == 3 {
start, err1 := strconv.Atoi(match[1])
end, err2 := strconv.Atoi(match[2])
if err1 != nil || err2 != nil || start > end {
return "", &patternSyntaxError{msg: fmt.Sprintf("invalid range: %q", match[0])}
}
// TODO: can we do better here?
buf.WriteString("(?:")
for n := start; n <= end; n++ {
if n > start {
buf.WriteByte('|')
}
fmt.Fprintf(&buf, "%d", n)
}
buf.WriteByte(')')
i += len(match[0])
break
}
buf.WriteString(regexp.QuoteMeta(string(c)))
case ',':
if len(closingBraces) == 0 {
buf.WriteString(regexp.QuoteMeta(string(c)))
} else {
buf.WriteByte('|')
}
case '}':
if len(closingBraces) > 0 && closingBraces[len(closingBraces)-1] == i {
buf.WriteByte(')')
closingBraces = closingBraces[:len(closingBraces)-1]
} else {
buf.WriteString(regexp.QuoteMeta(string(c)))
}
default:
if c > 128 {
buf.WriteByte(c)
} else {
buf.WriteString(regexp.QuoteMeta(string(c)))
}
}
}
if mode&patternEntireString != 0 {
buf.WriteString("$")
}
// No `.` metacharacters were used, so don't return the flag.
if !dotMeta {
return string(buf.Bytes()[4:]), nil
}
return buf.String(), nil
}
func patterncharClass(s string) (string, error) {
if strings.HasPrefix(s, "[[.") || strings.HasPrefix(s, "[[=") {
return "", fmt.Errorf("collating features not available")
}
if !strings.HasPrefix(s, "[[:") {
return "", nil
}
name := s[3:]
end := strings.Index(name, ":]]")
if end < 0 {
return "", fmt.Errorf("[[: was not matched with a closing :]]")
}
name = name[:end]
switch name {
case "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph",
"lower", "print", "punct", "space", "upper", "word", "xdigit":
default:
return "", fmt.Errorf("invalid character class: %q", name)
}
return s[:len(name)+6], nil
}
// HasMeta returns whether a string contains any unescaped pattern
// metacharacters: '*', '?', or '['. When the function returns false, the given
// pattern can only match at most one string.
//
// For example, HasMeta(`foo\*bar`) returns false, but HasMeta(`foo*bar`)
// returns true.
//
// This can be useful to avoid extra work, like TranslatePattern. Note that this
// function cannot be used to avoid QuotePattern, as backslashes are quoted by
// that function but ignored here.
func patternHasMeta(pat string, mode patternMode) bool {
for i := 0; i < len(pat); i++ {
switch pat[i] {
case '\\':
i++
case '*', '?', '[':
return true
case '{':
if mode&patternBraces != 0 {
return true
}
}
}
return false
}
// QuoteMeta returns a string that quotes all pattern metacharacters in the
// given text. The returned string is a pattern that matches the literal text.
//
// For example, QuoteMeta(`foo*bar?`) returns `foo\*bar\?`.
func patternQuoteMeta(pat string, mode patternMode) string {
needsEscaping := false
loop:
for _, r := range pat {
switch r {
case '{':
if mode&patternBraces == 0 {
continue
}
fallthrough
case '*', '?', '[', '\\':
needsEscaping = true
break loop
}
}
if !needsEscaping { // short-cut without a string copy
return pat
}
var buf bytes.Buffer
for _, r := range pat {
switch r {
case '*', '?', '[', '\\':
buf.WriteByte('\\')
case '{':
if mode&patternBraces != 0 {
buf.WriteByte('\\')
}
}
buf.WriteRune(r)
}
return buf.String()
}