mirror of https://github.com/gobwas/glob.git
add quote meta func
This commit is contained in:
parent
f3d7e5e3d7
commit
eccf734cd7
4
glob.go
4
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]) {
|
||||
|
|
17
glob_test.go
17
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue