fix(glob): treat escaped characters as literals (#40516)

The glob compiler wrote a backslash followed by the escaped character
into the generated regexp, so `\d`, `\w`, `\s` and `\b` were parsed as
regexp constructs instead of the literal character. `a\d` compiled to
`^a\d$` and matched "a5" instead of "ad"; `a\b` became a zero-width word
boundary. Escaping a character Go does not recognise, e.g. `\C`, made
the pattern fail to compile, and protected branch rules then fell back
to matching the raw rule text literally.

Escape only ASCII punctuation, which Go always reads as a literal, and
write letters, digits and non-ASCII characters as-is. This matches
gobwas/glob and act. Rules that relied on `\d` matching a digit since
https://github.com/go-gitea/gitea/pull/35478 now match a literal `d`.

Assisted-by: OpenCode (DeepSeek V4.1 Flash)
Assisted-by: Claude Code:claude-opus-5-5

---------

Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
karnati praveenandsilverwind authored and GitHub committed 2026-11-27 06:35:30 +00:00
1 parent 372d4dc97a
commit 17ac892df5
2 files changed
+14 -4

No files matched your search

+11 -4
View File
@@ -9,6 +9,7 @@ import (
"regexp"
"slices"
"strings"
"unicode"
"gitea.dev/modules/util"
)
@@ -35,6 +36,14 @@ type globCompiler struct {
negativeFlip bool
}
// writeLiteral escapes only ASCII punctuation, an escaped letter like \d is a regexp class
func (g *globCompiler) writeLiteral(r rune) {
if r <= unicode.MaxASCII && !unicode.IsLetter(r) && !unicode.IsDigit(r) {
g.builder.WriteByte('\\')
}
g.builder.WriteRune(r)
}
// compileChars compiles character class patterns like [abc] or [!abc]
func (g *globCompiler) compileChars() error {
g.builder.WriteByte('[')
@@ -56,8 +65,7 @@ func (g *globCompiler) compileChars() error {
if g.pos >= len(g.globPattern) {
return errors.New("unterminated character class escape")
}
g.builder.WriteByte('\\')
g.builder.WriteRune(g.globPattern[g.pos])
g.writeLiteral(g.globPattern[g.pos])
g.pos++
} else {
g.builder.WriteRune(c)
@@ -135,8 +143,7 @@ func (g *globCompiler) compile(subPattern bool) error {
if g.pos >= len(g.globPattern) {
return errors.New("no character to escape")
}
g.builder.WriteByte('\\')
g.builder.WriteRune(g.globPattern[g.pos])
g.writeLiteral(g.globPattern[g.pos])
g.pos++
case '.', '^', '$', '(', ')', '|':
g.builder.WriteByte('\\')
+3
View File
@@ -90,6 +90,9 @@ func TestGlob(t *testing.T) {
glob(true, "?at", "fat"),
glob(true, "*", "abc"),
glob(true, `\*`, "*"),
glob(true, `a\d`, "ad"),
glob(true, `[\d]`, "d"),
glob(false, `[a\-z]`, "m"),
glob(true, "**", "a.b.c", '.'),
glob(false, "?at", "at"),