Debian Codegraph @

pattern/pattern.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 // Package pattern allows working with shell pattern matching notation, also
5 // known as wildcards or globbing.
6 //
7 // For reference, see
8 // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13.
9 package pattern
10
11 import (
12 "fmt"
13 "io"
14 "regexp"
15 "strings"
16 "unicode/utf8"
17 )
18
19 // Mode can be used to supply a number of options to the package's functions.
20 // Not all functions change their behavior with all of the options below.
21 type Mode uint
22
23 type SyntaxError struct {
24 msg string
25 err error
26 }
27
28 func (e SyntaxError) Error() string { return e.msg }
29
30 func (e SyntaxError) Unwrap() error { return e.err }
31
32 // NegExtGlobGroup represents the byte offset range of a single !(expr) group
33 // within a pattern string. Start is the offset of '!', End is one past ')'.
34 type NegExtGlobGroup struct {
35 Start, End int
36 }
37
38 // NegExtGlobError is returned by [Regexp] when an extglob negation operator
39 // !(pattern-list) is encountered, as Go's [regexp] package does not support
40 // negative lookahead. Callers can handle this by negating the result of
41 // matching the inner pattern.
42 type NegExtGlobError struct {
43 Groups []NegExtGlobGroup
44 }
45
46 func (e *NegExtGlobError) Error() string {
47 return "extglob !(...) is not supported in this scenario"
48 }
49
50 // TODO(v4): flip NoGlobStar to be opt-in via GlobStar, matching bash
51 // TODO(v4): flip EntireString to be opt-out via PartialMatch, as EntireString causes subtle bugs when forgotten
52 // TODO(v4): rename NoGlobCase to CaseInsensitive for readability
53
54 const (
55 Shortest Mode = 1 << iota // prefer the shortest match.
56 Filenames // "*" and "?" don't match slashes; only "**" does; only makes sense with EntireString too
57 EntireString // match the entire string using ^$ delimiters
58 NoGlobCase // do case-insensitive match (that is, use (?i) in the regexp); shopt "nocaseglob"
59 NoGlobStar // do not support "**"; negated shopt "globstar"
60 GlobLeadingDot // let wildcards match leading dots in filenames; shopt "dotglob"
61 ExtendedOperators // support extended pattern matching operators; shopt "extglob" for pathname expansion
62 )
63
64 // Regexp turns a shell pattern into a regular expression that can be used with
65 // [regexp.Compile]. It will return an error if the input pattern was incorrect.
66 // Otherwise, the returned expression can be passed to [regexp.MustCompile].
67 //
68 // For example, Regexp(`foo*bar?`, true) returns `foo.*bar.`.
69 //
70 // Note that this function (and [QuoteMeta]) should not be directly used with file
71 // paths if Windows is supported, as the path separator on that platform is the
72 // same character as the escaping character for shell patterns.
73 func Regexp(pat string, mode Mode) (string, error) {
74 // If there are no special pattern matching or regular expression characters,
75 // and we don't need to insert extras for the modes affecting non-special characters,
76 // we can directly return the input string as a short-cut.
77 if mode&(EntireString|NoGlobCase) == 0 {
78 needsEscaping := false
79 noopLoop:
80 for _, r := range pat {
81 switch r {
82 // including those that need escaping since they are
83 // regular expression metacharacters
84 case '*', '?', '[', '\\', '.', '+', '(', ')', '|',
85 ']', '{', '}', '^', '$':
86 needsEscaping = true
87 break noopLoop
88 }
89 }
90 if !needsEscaping {
91 return pat, nil
92 }
93 }
94 var sb strings.Builder
95 // Enable matching `\n` with the `.` metacharacter as globs match `\n`
96 sb.WriteString(`(?s`)
97 if mode&NoGlobCase != 0 {
98 sb.WriteString(`i`)
99 }
100 if mode&Shortest != 0 {
101 sb.WriteString(`U`)
102 }
103 sb.WriteString(`)`)
104 if mode&EntireString != 0 {
105 sb.WriteString(`^`)
106 }
107 sl := stringLexer{s: pat}
108 var negGroups []NegExtGlobGroup
109 for {
110 if err := regexpNext(&sb, &sl, mode); err == io.EOF {
111 break
112 } else if err != nil {
113 negErr, ok := err.(*NegExtGlobError)
114 if !ok {
115 return "", err
116 }
117 negGroups = append(negGroups, negErr.Groups...)
118 }
119 }
120 if len(negGroups) > 0 {
121 return "", &NegExtGlobError{Groups: negGroups}
122 }
123 if mode&EntireString != 0 {
124 sb.WriteString(`$`)
125 }
126 return sb.String(), nil
127 }
128
129 // stringLexer helps us tokenize a pattern string.
130 // Note that we can use the null byte '\x00' to signal "no character" as shell strings cannot contain null bytes.
131 type stringLexer struct {
132 s string
133 i int
134 }
135
136 func (sl *stringLexer) next() rune {
137 if sl.i >= len(sl.s) {
138 return '\x00'
139 }
140 c, size := utf8.DecodeRuneInString(sl.s[sl.i:])
141 sl.i += size
142 return c
143 }
144
145 func (sl *stringLexer) last() rune {
146 if sl.i < 2 {
147 return '\x00'
148 }
149 c, _ := utf8.DecodeLastRuneInString(sl.s[:sl.i-1])
150 return c
151 }
152
153 func (sl *stringLexer) peekNext() rune {
154 if sl.i >= len(sl.s) {
155 return '\x00'
156 }
157 c, _ := utf8.DecodeRuneInString(sl.s[sl.i:])
158 return c
159 }
160
161 func (sl *stringLexer) peekRest() string {
162 return sl.s[sl.i:]
163 }
164
165 func regexpNext(sb *strings.Builder, sl *stringLexer, mode Mode) error {
166 c := sl.next()
167 if mode&ExtendedOperators != 0 {
168 // Handle extended pattern matching operators separately,
169 // given that they can be one of many two-character prefixes.
170 // Note that we recurse into the same function in a loop,
171 // as each of the patterns in the list separated by '|' is a regular pattern.
172 switch op := c; op {
173 case '!', '?', '*', '+', '@':
174 if sl.peekNext() != '(' {
175 break
176 }
177 start := sl.i - 1 // position of the operator
178 sb.WriteRune(sl.next()) // (
179 nestedLoop:
180 for {
181 switch sl.peekNext() {
182 case ')':
183 break nestedLoop
184 case '|':
185 // extended operators support a list of "or" separated expressions
186 sb.WriteRune(sl.next())
187 continue
188 }
189 if err := regexpNext(sb, sl, mode); err == io.EOF {
190 break
191 } else if err != nil {
192 return err
193 }
194 }
195 sb.WriteRune(sl.next()) // )
196 if op == '!' {
197 return &NegExtGlobError{Groups: []NegExtGlobGroup{{Start: start, End: sl.i}}}
198 }
199 if op != '@' {
200 // @( is [syntax.GlobOne] for matching once; no suffix needed
201 sb.WriteRune(op)
202 }
203 return nil
204 }
205 }
206 switch c {
207 case '\x00':
208 return io.EOF
209 case '*':
210 if mode&Filenames == 0 {
211 // * - matches anything when not in filename mode
212 sb.WriteString(`.*`)
213 break
214 }
215 // "**" only acts as globstar if it is alone as a path element.
216 singleBefore := sl.i == 1 || sl.last() == '/'
217 if sl.peekNext() == '*' {
218 sl.i++
219 singleAfter := sl.i == len(sl.s) || sl.peekNext() == '/'
220 if mode&NoGlobStar == 0 && singleBefore && singleAfter {
221 // ** - match any number of slashes or "*" path elements
222 slashSuffix := sl.peekNext() == '/'
223 if slashSuffix {
224 // **/ - like "**" but requiring a trailing slash when matching
225 sl.i++
226 // wrap the expression to ensure that any match has a slash suffix
227 sb.WriteString(`(`)
228 }
229 if mode&GlobLeadingDot == 0 {
230 sb.WriteString(`(/|[^/.][^/]*)*`)
231 } else {
232 // with GlobLeadingDot (dotglob), match anything at all
233 sb.WriteString(`.*`)
234 }
235 if slashSuffix {
236 sb.WriteString(`/)?`)
237 }
238 break
239 }
240 // foo**, **bar, or NoGlobStar - behaves like "*" below
241 }
242 // * - matches anything except slashes and leading dots
243 if singleBefore && mode&GlobLeadingDot == 0 {
244 sb.WriteString(`([^/.][^/]*)?`)
245 } else {
246 // with GlobLeadingDot (dotglob), match anything except slashes
247 sb.WriteString(`[^/]*`)
248 }
249 case '?':
250 if mode&Filenames != 0 {
251 sb.WriteString(`[^/]`)
252 } else {
253 sb.WriteByte('.')
254 }
255 case '\\':
256 c = sl.next()
257 if c == '\x00' {
258 return &SyntaxError{msg: `\ at end of pattern`}
259 }
260 sb.WriteString(regexp.QuoteMeta(string(c)))
261 case '[':
262 lit := sl.i // to reparse from, if the bracket turns out to be literal
263 filenames := mode&Filenames != 0
264 // Build the bracket expression separately; in Filenames mode, one
265 // which could match a slash must be emitted literally instead.
266 var bsb strings.Builder
267 bsb.WriteByte('[')
268 hasSlash := false
269 var deferredErr error // reported only if the bracket expression closes
270 var classErr error // reported even if the bracket is unmatched
271 // Like Bash, an unmatched "[" is a literal; emit it and reparse
272 // the rest of the pattern.
273 literalBracket := func() error {
274 sl.i = lit
275 sb.WriteString(`\[`)
276 return nil
277 }
278 if c = sl.next(); c == '\x00' {
279 return literalBracket()
280 }
281 switch c {
282 case '!', '^':
283 bsb.WriteByte('^')
284 if c = sl.next(); c == '\x00' {
285 return literalBracket()
286 }
287 }
288 if c == ']' {
289 bsb.WriteByte(']')
290 if c = sl.next(); c == '\x00' {
291 return literalBracket()
292 }
293 }
294 for {
295 switch c {
296 case '\x00':
297 // Bash is inconsistent about invalid character classes
298 // in an unmatched bracket: `case` treats the whole
299 // bracket as literal, but ${a//[[:} refuses to match.
300 // We follow the latter, keeping the error.
301 if classErr != nil {
302 return classErr
303 }
304 return literalBracket()
305 case '\\':
306 // An escaped character matches itself; quote it so that
307 // the regexp doesn't give it a special meaning, such as
308 // \0 being an octal escape or \d a character class.
309 switch c = sl.next(); {
310 case c == '\x00':
311 continue // handled by the case above
312 case c == '-':
313 // regexp.QuoteMeta does not escape '-', which would
314 // form a range inside a bracket expression.
315 bsb.WriteString(`\-`)
316 case c > utf8.RuneSelf:
317 bsb.WriteRune(c)
318 default:
319 if filenames && c == '/' {
320 hasSlash = true
321 }
322 bsb.WriteString(regexp.QuoteMeta(string(c)))
323 }
324 case '-':
325 bsb.WriteByte('-')
326 start := sl.last()
327 end := sl.peekNext()
328 // TODO: what about overlapping ranges, like: [a--z]
329 if end != ']' && start > end && deferredErr == nil {
330 deferredErr = &SyntaxError{msg: fmt.Sprintf("invalid range: %c-%c", start, end)}
331 }
332 case ']':
333 if hasSlash {
334 // Bracket expressions can't match slashes in filename
335 // patterns; emit the whole expression literally.
336 sb.WriteString(regexp.QuoteMeta(sl.s[lit-1 : sl.i]))
337 return nil
338 }
339 if deferredErr != nil {
340 return deferredErr
341 }
342 bsb.WriteByte(']')
343 sb.WriteString(bsb.String())
344 return nil
345 case '[':
346 rest := sl.peekRest()
347 n, err := charClass(rest)
348 if err != nil {
349 if classErr == nil {
350 classErr = &SyntaxError{msg: "charClass invalid", err: err}
351 }
352 if deferredErr == nil {
353 deferredErr = classErr
354 }
355 }
356 bsb.WriteByte('[')
357 if n > 0 {
358 if filenames && strings.Contains(rest[:n], "/") {
359 hasSlash = true
360 }
361 bsb.WriteString(rest[:n])
362 sl.i += n
363 }
364 default:
365 if filenames && c == '/' {
366 hasSlash = true
367 }
368 bsb.WriteRune(c)
369 }
370 c = sl.next()
371 }
372 default:
373 if c > utf8.RuneSelf {
374 sb.WriteRune(c)
375 } else {
376 sb.WriteString(regexp.QuoteMeta(string(c)))
377 }
378 }
379 return nil
380 }
381
382 // charClass returns the length in bytes of the bracket expression element
383 // starting just after an opening "[" in s, such as ":alpha:]" for the
384 // character class [:alpha:]. Elements which are well formed but invalid or
385 // unsupported, such as collating symbols, return their length with an error.
386 func charClass(s string) (int, error) {
387 if len(s) > 0 && (s[0] == '.' || s[0] == '=') {
388 sep := ".]"
389 if s[0] == '=' {
390 sep = "=]"
391 }
392 name, _, ok := strings.Cut(s[1:], sep)
393 if !ok {
394 return 0, fmt.Errorf("collating features not available")
395 }
396 return len(name) + 3, fmt.Errorf("collating features not available")
397 }
398 name, ok := strings.CutPrefix(s, ":")
399 if !ok {
400 return 0, nil
401 }
402 name, _, ok = strings.Cut(name, ":]")
403 if !ok {
404 return 0, fmt.Errorf("[[: was not matched with a closing :]")
405 }
406 switch name {
407 case "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph",
408 "lower", "print", "punct", "space", "upper", "word", "xdigit":
409 default:
410 return len(name) + 3, fmt.Errorf("invalid character class: %q", name)
411 }
412 return len(name) + 3, nil
413 }
414
415 // HasMeta returns whether a string contains any unescaped pattern
416 // metacharacters: '*', '?', or '[' followed by a matching ']'. When the
417 // function returns false, the given pattern can only match at most one string.
418 //
419 // For example, HasMeta(`foo\*bar`) returns false, but HasMeta(`foo*bar`)
420 // returns true.
421 //
422 // This can be useful to avoid extra work, like [Regexp]. Note that this
423 // function cannot be used to avoid [QuoteMeta], as backslashes are quoted by
424 // that function but ignored here.
425 //
426 // The [Mode] parameter is unused, and will be removed in v4.
427 func HasMeta(pat string, mode Mode) bool {
428 openBracket := false
429 for i := 0; i < len(pat); i++ {
430 switch pat[i] {
431 case '\\':
432 i++
433 case '*', '?':
434 return true
435 case '[':
436 openBracket = true
437 case ']':
438 // Like Bash, an unmatched '[' is a literal,
439 // so it can only match one string.
440 if openBracket {
441 return true
442 }
443 }
444 }
445 return false
446 }
447
448 // QuoteMeta returns a string that quotes all pattern metacharacters in the
449 // given text. The returned string is a pattern that matches the literal text.
450 //
451 // For example, QuoteMeta(`foo*bar?`) returns `foo\*bar\?`.
452 //
453 // The [Mode] parameter is unused, and will be removed in v4.
454 func QuoteMeta(pat string, mode Mode) string {
455 needsEscaping := false
456 loop:
457 for _, r := range pat {
458 switch r {
459 case '*', '?', '[', '\\':
460 needsEscaping = true
461 break loop
462 }
463 }
464 if !needsEscaping { // short-cut without a string copy
465 return pat
466 }
467 var sb strings.Builder
468 for _, r := range pat {
469 switch r {
470 case '*', '?', '[', '\\':
471 sb.WriteByte('\\')
472 }
473 sb.WriteRune(r)
474 }
475 return sb.String()
476 }