Skip to content

Commit 6bf5543

Browse files
committed
remove use of regex
1 parent ce774d0 commit 6bf5543

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

internal/vfs/utilities.go

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package vfs
22

33
import (
44
"fmt"
5-
"regexp"
65
"sort"
76
"strings"
87
"sync"
@@ -75,18 +74,28 @@ func replaceWildcardCharacter(match string, singleAsteriskRegexFragment string)
7574
}
7675
}
7776

77+
func escapeRegexMetacharacters(s string, replaceWildcard func(string) string) string {
78+
var result strings.Builder
79+
result.Grow(len(s))
80+
for _, ch := range s {
81+
switch ch {
82+
case '\\', '.', '+', '*', '?', '(', ')', '[', ']', '{', '}', '^', '$', '|', '#':
83+
result.WriteString(replaceWildcard(string(ch)))
84+
default:
85+
result.WriteRune(ch)
86+
}
87+
}
88+
return result.String()
89+
}
90+
7891
// An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
7992
// and does not contain any glob characters itself.
8093
func IsImplicitGlob(lastPathComponent string) bool {
8194
return !strings.ContainsAny(lastPathComponent, ".*?")
8295
}
8396

84-
// Reserved characters - only escape actual regex metacharacters.
85-
// Go's regexp doesn't support \x escape sequences for arbitrary characters,
86-
// so we only escape characters that have special meaning in regex.
8797
var (
88-
reservedCharacterPattern *regexp.Regexp = regexp.MustCompile(`[\\.\+*?()\[\]{}^$|#]`)
89-
wildcardCharCodes = []rune{'*', '?'}
98+
wildcardCharCodes = []rune{'*', '?'}
9099
)
91100

92101
var (
@@ -206,7 +215,7 @@ func getSubPatternFromSpec(
206215
componentPattern.WriteString("[^./]")
207216
component = component[1:]
208217
}
209-
componentPattern.WriteString(reservedCharacterPattern.ReplaceAllStringFunc(component, replaceWildcardCharacter))
218+
componentPattern.WriteString(escapeRegexMetacharacters(component, replaceWildcardCharacter))
210219

211220
// Patterns should not include subfolders like node_modules unless they are
212221
// explicitly included as part of the path.
@@ -219,7 +228,7 @@ func getSubPatternFromSpec(
219228
}
220229
subpattern.WriteString(componentPattern.String())
221230
} else {
222-
subpattern.WriteString(reservedCharacterPattern.ReplaceAllStringFunc(component, replaceWildcardCharacter))
231+
subpattern.WriteString(escapeRegexMetacharacters(component, replaceWildcardCharacter))
223232
}
224233
}
225234
hasWrittenComponent = true

0 commit comments

Comments
 (0)