| 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 |
extended: |
| 173 |
switch op := c; op { |
| 174 |
case '!', '?', '*', '+', '@': |
| 175 |
if sl.peekNext() != '(' { |
| 176 |
break |
| 177 |
} |
| 178 |
start := sl.i - 1 // position of the operator |
| 179 |
// Build the group separately; like Bash, an unclosed group |
| 180 |
// is not an extended operator, so we reparse the operator |
| 181 |
// as a regular character below and the rest as a pattern. |
| 182 |
var gsb strings.Builder |
| 183 |
gsb.WriteRune(sl.next()) // ( |
| 184 |
nestedLoop: |
| 185 |
for { |
| 186 |
switch sl.peekNext() { |
| 187 |
case ')': |
| 188 |
break nestedLoop |
| 189 |
case '|': |
| 190 |
// extended operators support a list of "or" separated expressions |
| 191 |
gsb.WriteRune(sl.next()) |
| 192 |
continue |
| 193 |
case '\x00': |
| 194 |
sl.i = start + 1 |
| 195 |
break extended |
| 196 |
} |
| 197 |
if err := regexpNext(&gsb, sl, mode); err != nil { |
| 198 |
return err |
| 199 |
} |
| 200 |
} |
| 201 |
gsb.WriteRune(sl.next()) // ) |
| 202 |
sb.WriteString(gsb.String()) |
| 203 |
if op == '!' { |
| 204 |
return &NegExtGlobError{Groups: []NegExtGlobGroup{{Start: start, End: sl.i}}} |
| 205 |
} |
| 206 |
if op != '@' { |
| 207 |
// @( is [syntax.GlobOne] for matching once; no suffix needed |
| 208 |
sb.WriteRune(op) |
| 209 |
} |
| 210 |
return nil |
| 211 |
} |
| 212 |
} |
| 213 |
switch c { |
| 214 |
case '\x00': |
| 215 |
return io.EOF |
| 216 |
case '*': |
| 217 |
if mode&Filenames == 0 { |
| 218 |
// * - matches anything when not in filename mode |
| 219 |
sb.WriteString(`.*`) |
| 220 |
break |
| 221 |
} |
| 222 |
// "**" only acts as globstar if it is alone as a path element. |
| 223 |
singleBefore := sl.i == 1 || sl.last() == '/' |
| 224 |
if sl.peekNext() == '*' { |
| 225 |
sl.i++ |
| 226 |
singleAfter := sl.i == len(sl.s) || sl.peekNext() == '/' |
| 227 |
if mode&NoGlobStar == 0 && singleBefore && singleAfter { |
| 228 |
// ** - match any number of slashes or "*" path elements |
| 229 |
slashSuffix := sl.peekNext() == '/' |
| 230 |
if slashSuffix { |
| 231 |
// **/ - like "**" but requiring a trailing slash when matching |
| 232 |
sl.i++ |
| 233 |
// wrap the expression to ensure that any match has a slash suffix |
| 234 |
sb.WriteString(`(`) |
| 235 |
} |
| 236 |
if mode&GlobLeadingDot == 0 { |
| 237 |
sb.WriteString(`(/|[^/.][^/]*)*`) |
| 238 |
} else { |
| 239 |
// with GlobLeadingDot (dotglob), match anything at all |
| 240 |
sb.WriteString(`.*`) |
| 241 |
} |
| 242 |
if slashSuffix { |
| 243 |
sb.WriteString(`/)?`) |
| 244 |
} |
| 245 |
break |
| 246 |
} |
| 247 |
// foo**, **bar, or NoGlobStar - behaves like "*" below |
| 248 |
} |
| 249 |
// * - matches anything except slashes and leading dots |
| 250 |
if singleBefore && mode&GlobLeadingDot == 0 { |
| 251 |
sb.WriteString(`([^/.][^/]*)?`) |
| 252 |
} else { |
| 253 |
// with GlobLeadingDot (dotglob), match anything except slashes |
| 254 |
sb.WriteString(`[^/]*`) |
| 255 |
} |
| 256 |
case '?': |
| 257 |
if mode&Filenames != 0 { |
| 258 |
sb.WriteString(`[^/]`) |
| 259 |
} else { |
| 260 |
sb.WriteByte('.') |
| 261 |
} |
| 262 |
case '\\': |
| 263 |
c = sl.next() |
| 264 |
if c == '\x00' { |
| 265 |
return &SyntaxError{msg: `\ at end of pattern`} |
| 266 |
} |
| 267 |
sb.WriteString(regexp.QuoteMeta(string(c))) |
| 268 |
case '[': |
| 269 |
lit := sl.i // to reparse from, if the bracket turns out to be literal |
| 270 |
filenames := mode&Filenames != 0 |
| 271 |
// Build the bracket expression separately; in Filenames mode, one |
| 272 |
// which could match a slash must be emitted literally instead. |
| 273 |
var bsb strings.Builder |
| 274 |
bsb.WriteByte('[') |
| 275 |
hasSlash := false |
| 276 |
var deferredErr error // reported only if the bracket expression closes |
| 277 |
var classErr error // reported even if the bracket is unmatched |
| 278 |
// Like Bash, an unmatched "[" is a literal; emit it and reparse |
| 279 |
// the rest of the pattern. |
| 280 |
literalBracket := func() error { |
| 281 |
sl.i = lit |
| 282 |
sb.WriteString(`\[`) |
| 283 |
return nil |
| 284 |
} |
| 285 |
if c = sl.next(); c == '\x00' { |
| 286 |
return literalBracket() |
| 287 |
} |
| 288 |
switch c { |
| 289 |
case '!', '^': |
| 290 |
bsb.WriteByte('^') |
| 291 |
if c = sl.next(); c == '\x00' { |
| 292 |
return literalBracket() |
| 293 |
} |
| 294 |
} |
| 295 |
if c == ']' { |
| 296 |
bsb.WriteByte(']') |
| 297 |
if c = sl.next(); c == '\x00' { |
| 298 |
return literalBracket() |
| 299 |
} |
| 300 |
} |
| 301 |
for { |
| 302 |
switch c { |
| 303 |
case '\x00': |
| 304 |
// Bash is inconsistent about invalid character classes |
| 305 |
// in an unmatched bracket: `case` treats the whole |
| 306 |
// bracket as literal, but ${a//[[:} refuses to match. |
| 307 |
// We follow the latter, keeping the error. |
| 308 |
if classErr != nil { |
| 309 |
return classErr |
| 310 |
} |
| 311 |
return literalBracket() |
| 312 |
case '\\': |
| 313 |
// An escaped character matches itself; quote it so that |
| 314 |
// the regexp doesn't give it a special meaning, such as |
| 315 |
// \0 being an octal escape or \d a character class. |
| 316 |
switch c = sl.next(); { |
| 317 |
case c == '\x00': |
| 318 |
continue // handled by the case above |
| 319 |
case c == '-': |
| 320 |
// regexp.QuoteMeta does not escape '-', which would |
| 321 |
// form a range inside a bracket expression. |
| 322 |
bsb.WriteString(`\-`) |
| 323 |
case c > utf8.RuneSelf: |
| 324 |
bsb.WriteRune(c) |
| 325 |
default: |
| 326 |
if filenames && c == '/' { |
| 327 |
hasSlash = true |
| 328 |
} |
| 329 |
bsb.WriteString(regexp.QuoteMeta(string(c))) |
| 330 |
} |
| 331 |
case '-': |
| 332 |
bsb.WriteByte('-') |
| 333 |
start := sl.last() |
| 334 |
end := sl.peekNext() |
| 335 |
// TODO: what about overlapping ranges, like: [a--z] |
| 336 |
if end != ']' && start > end && deferredErr == nil { |
| 337 |
deferredErr = &SyntaxError{msg: fmt.Sprintf("invalid range: %c-%c", start, end)} |
| 338 |
} |
| 339 |
case ']': |
| 340 |
if hasSlash { |
| 341 |
// Bracket expressions can't match slashes in filename |
| 342 |
// patterns; emit the whole expression literally. |
| 343 |
sb.WriteString(regexp.QuoteMeta(sl.s[lit-1 : sl.i])) |
| 344 |
return nil |
| 345 |
} |
| 346 |
if deferredErr != nil { |
| 347 |
return deferredErr |
| 348 |
} |
| 349 |
bsb.WriteByte(']') |
| 350 |
sb.WriteString(bsb.String()) |
| 351 |
return nil |
| 352 |
case '[': |
| 353 |
rest := sl.peekRest() |
| 354 |
n, err := charClass(rest) |
| 355 |
if err != nil { |
| 356 |
if classErr == nil { |
| 357 |
classErr = &SyntaxError{msg: "charClass invalid", err: err} |
| 358 |
} |
| 359 |
if deferredErr == nil { |
| 360 |
deferredErr = classErr |
| 361 |
} |
| 362 |
} |
| 363 |
bsb.WriteByte('[') |
| 364 |
if n > 0 { |
| 365 |
if filenames && strings.Contains(rest[:n], "/") { |
| 366 |
hasSlash = true |
| 367 |
} |
| 368 |
bsb.WriteString(rest[:n]) |
| 369 |
sl.i += n |
| 370 |
} |
| 371 |
default: |
| 372 |
if filenames && c == '/' { |
| 373 |
hasSlash = true |
| 374 |
} |
| 375 |
bsb.WriteRune(c) |
| 376 |
} |
| 377 |
c = sl.next() |
| 378 |
} |
| 379 |
default: |
| 380 |
if c > utf8.RuneSelf { |
| 381 |
sb.WriteRune(c) |
| 382 |
} else { |
| 383 |
sb.WriteString(regexp.QuoteMeta(string(c))) |
| 384 |
} |
| 385 |
} |
| 386 |
return nil |
| 387 |
} |
| 388 |
|
| 389 |
// charClass returns the length in bytes of the bracket expression element |
| 390 |
// starting just after an opening "[" in s, such as ":alpha:]" for the |
| 391 |
// character class [:alpha:]. Elements which are well formed but invalid or |
| 392 |
// unsupported, such as collating symbols, return their length with an error. |
| 393 |
func charClass(s string) (int, error) { |
| 394 |
if len(s) > 0 && (s[0] == '.' || s[0] == '=') { |
| 395 |
sep := ".]" |
| 396 |
if s[0] == '=' { |
| 397 |
sep = "=]" |
| 398 |
} |
| 399 |
name, _, ok := strings.Cut(s[1:], sep) |
| 400 |
if !ok { |
| 401 |
return 0, fmt.Errorf("collating features not available") |
| 402 |
} |
| 403 |
return len(name) + 3, fmt.Errorf("collating features not available") |
| 404 |
} |
| 405 |
name, ok := strings.CutPrefix(s, ":") |
| 406 |
if !ok { |
| 407 |
return 0, nil |
| 408 |
} |
| 409 |
name, _, ok = strings.Cut(name, ":]") |
| 410 |
if !ok { |
| 411 |
return 0, fmt.Errorf("[[: was not matched with a closing :]") |
| 412 |
} |
| 413 |
switch name { |
| 414 |
case "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph", |
| 415 |
"lower", "print", "punct", "space", "upper", "word", "xdigit": |
| 416 |
default: |
| 417 |
return len(name) + 3, fmt.Errorf("invalid character class: %q", name) |
| 418 |
} |
| 419 |
return len(name) + 3, nil |
| 420 |
} |
| 421 |
|
| 422 |
// HasMeta returns whether a string contains any unescaped pattern |
| 423 |
// metacharacters: '*', '?', or '[' followed by a matching ']'. When the |
| 424 |
// function returns false, the given pattern can only match at most one string. |
| 425 |
// |
| 426 |
// For example, HasMeta(`foo\*bar`) returns false, but HasMeta(`foo*bar`) |
| 427 |
// returns true. |
| 428 |
// |
| 429 |
// This can be useful to avoid extra work, like [Regexp]. Note that this |
| 430 |
// function cannot be used to avoid [QuoteMeta], as backslashes are quoted by |
| 431 |
// that function but ignored here. |
| 432 |
// |
| 433 |
// The [Mode] parameter is unused, and will be removed in v4. |
| 434 |
func HasMeta(pat string, mode Mode) bool { |
| 435 |
openBracket := false |
| 436 |
for i := 0; i < len(pat); i++ { |
| 437 |
switch pat[i] { |
| 438 |
case '\\': |
| 439 |
i++ |
| 440 |
case '*', '?': |
| 441 |
return true |
| 442 |
case '[': |
| 443 |
openBracket = true |
| 444 |
case ']': |
| 445 |
// Like Bash, an unmatched '[' is a literal, |
| 446 |
// so it can only match one string. |
| 447 |
if openBracket { |
| 448 |
return true |
| 449 |
} |
| 450 |
} |
| 451 |
} |
| 452 |
return false |
| 453 |
} |
| 454 |
|
| 455 |
// QuoteMeta returns a string that quotes all pattern metacharacters in the |
| 456 |
// given text. The returned string is a pattern that matches the literal text. |
| 457 |
// |
| 458 |
// For example, QuoteMeta(`foo*bar?`) returns `foo\*bar\?`. |
| 459 |
// |
| 460 |
// The [Mode] parameter is unused, and will be removed in v4. |
| 461 |
func QuoteMeta(pat string, mode Mode) string { |
| 462 |
needsEscaping := false |
| 463 |
loop: |
| 464 |
for _, r := range pat { |
| 465 |
switch r { |
| 466 |
case '*', '?', '[', '\\': |
| 467 |
needsEscaping = true |
| 468 |
break loop |
| 469 |
} |
| 470 |
} |
| 471 |
if !needsEscaping { // short-cut without a string copy |
| 472 |
return pat |
| 473 |
} |
| 474 |
var sb strings.Builder |
| 475 |
for _, r := range pat { |
| 476 |
switch r { |
| 477 |
case '*', '?', '[', '\\': |
| 478 |
sb.WriteByte('\\') |
| 479 |
} |
| 480 |
sb.WriteRune(r) |
| 481 |
} |
| 482 |
return sb.String() |
| 483 |
} |