diff --git a/glob.go b/glob.go index 47a4c47..58f45c9 100644 --- a/glob.go +++ b/glob.go @@ -55,12 +55,12 @@ func MustCompile(pattern string, separators ...rune) Glob { return g } -// QuoteMeta returns a string that quotes all glob pattern metacharacters +// QuoteMeta returns a string that quotes all glob pattern meta characters // inside the argument text; For example, QuoteMeta(`{foo*}`) returns `\[foo\*\]`. func QuoteMeta(s string) string { b := make([]byte, 2*len(s)) - // A byte loop is correct because all metacharacters are ASCII. + // a byte loop is correct because all meta characters are ASCII j := 0 for i := 0; i < len(s); i++ { if special(s[i]) { diff --git a/glob_test.go b/glob_test.go index 5e6c360..6fe73a6 100644 --- a/glob_test.go +++ b/glob_test.go @@ -151,6 +151,12 @@ func TestGlob(t *testing.T) { } func TestQuoteMeta(t *testing.T) { + specialsQuoted := make([]byte, len(specials)*2) + for i, j := 0, 0; i < len(specials); i, j = i+1, j+2 { + specialsQuoted[j] = '\\' + specialsQuoted[j+1] = specials[i] + } + for id, test := range []struct { in, out string }{ @@ -158,11 +164,22 @@ func TestQuoteMeta(t *testing.T) { in: `[foo*]`, out: `\[foo\*\]`, }, + { + in: string(specials), + out: string(specialsQuoted), + }, + { + in: string(append([]byte("some text and"), specials...)), + out: string(append([]byte("some text and"), specialsQuoted...)), + }, } { act := QuoteMeta(test.in) if act != test.out { t.Errorf("#%d QuoteMeta(%q) = %q; want %q", id, test.in, act, test.out) } + if _, err := Compile(act); err != nil { + t.Errorf("#%d _, err := Compile(QuoteMeta(%q) = %q); err = %q", id, test.in, act, err) + } } }