Skip to content

Commit

Permalink
feat(perf): Replace regexp replace with strings replace
Browse files Browse the repository at this point in the history
These functions are faster than the regexp ones.
  • Loading branch information
inkel authored and hairyhenderson committed Sep 27, 2024
1 parent 36a9095 commit 4d84dbb
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions codeowners.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,21 +225,14 @@ func (c *Codeowners) Owners(path string) []string {

// precompile all regular expressions
var (
reCommentIgnore = regexp.MustCompile(`^(\\#|\\!)`)
rePrependSlash = regexp.MustCompile(`([^\/+])/.*\*\.`)
reEscapeDot = regexp.MustCompile(`\.`)
reDoubleStar1 = regexp.MustCompile(`/\*\*/`)
reDoubleStar2 = regexp.MustCompile(`\*\*/`)
reDoubleStar3 = regexp.MustCompile(`/\*\*`)
reEscapeStar1 = regexp.MustCompile(`\\\*`)
reEscapeStar2 = regexp.MustCompile(`\*`)
rePrependSlash = regexp.MustCompile(`([^\/+])/.*\*\.`)
)

// based on github.com/sabhiram/go-gitignore
// but modified so that 'dir/*' only matches files in 'dir/'
func getPattern(line string) (*regexp.Regexp, error) {
// when # or ! is escaped with a \
if reCommentIgnore.MatchString(line) {
if strings.HasPrefix(line, `\#`) || strings.HasPrefix(line, `\!`) {
line = line[1:]
}

Expand All @@ -249,21 +242,21 @@ func getPattern(line string) (*regexp.Regexp, error) {
}

// Handle escaping the "." char
line = reEscapeDot.ReplaceAllString(line, `\.`)
line = strings.ReplaceAll(line, ".", `\.`)

magicStar := "#$~"

// Handle "/**/" usage
if strings.HasPrefix(line, "/**/") {
line = line[1:]
}
line = reDoubleStar1.ReplaceAllString(line, `(/|/.+/)`)
line = reDoubleStar2.ReplaceAllString(line, `(|.`+magicStar+`/)`)
line = reDoubleStar3.ReplaceAllString(line, `(|/.`+magicStar+`)`)
line = strings.ReplaceAll(line, `/**/`, `(/|/.+/)`)
line = strings.ReplaceAll(line, `**/`, `(|.`+magicStar+`/)`)
line = strings.ReplaceAll(line, `/**`, `(|/.`+magicStar+`)`)

// Handle escaping the "*" char
line = reEscapeStar1.ReplaceAllString(line, `\`+magicStar)
line = reEscapeStar2.ReplaceAllString(line, `([^/]*)`)
line = strings.ReplaceAll(line, `\*`, `\`+magicStar)
line = strings.ReplaceAll(line, `*`, `([^/]*)`)

// Handle escaping the "?" char
line = strings.ReplaceAll(line, "?", `\?`)
Expand Down

0 comments on commit 4d84dbb

Please sign in to comment.