Skip to content

Commit 1b5d75a

Browse files
committed
add cache for regexp compilation
1 parent c1df6ef commit 1b5d75a

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

hound.go

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ import (
88
"regexp"
99
)
1010

11+
var (
12+
regexes = make(map[string]*regexp.Regexp)
13+
)
14+
1115
// A Hound contains the local configuration filename and all regexp patterns
1216
// used for sniffing git-diffs.
1317
type Hound struct {
@@ -38,13 +42,13 @@ func (h *Hound) New() bool {
3842
func (h *Hound) Sniff(fileName string, hunk *diff.Hunk, smells chan<- smell, done chan<- bool) {
3943
defer func() { done <- true }()
4044

41-
rxFileName, _ := regexp.Compile(`^\w+\/`)
45+
rxFileName, _ := h.regexp(`^\w+\/`)
4246
fileName = rxFileName.ReplaceAllString(fileName, "")
4347
if _, ok := h.matchPatterns(h.Skips, []byte(fileName)); ok {
4448
return
4549
}
4650

47-
rxModLines, _ := regexp.Compile(`(?m)^\+\s*(.+)$`)
51+
rxModLines, _ := h.regexp(`(?m)^\+\s*(.+)$`)
4852
matches := rxModLines.FindAllSubmatch(hunk.Body, -1)
4953

5054
for _, match := range matches {
@@ -84,9 +88,26 @@ func (h *Hound) parse(config []byte) error {
8488
return yaml.Unmarshal(config, h)
8589
}
8690

91+
// getRegexp looks for the specified pattern in Hound's regexes cache, and if
92+
// it is available, it will fetch from it. If it is not available, it
93+
// will compile the pattern and store it in the cache. Returns a Regexp
94+
// and an error.
95+
func (h *Hound) regexp(pattern string) (*regexp.Regexp, error) {
96+
if regexes[pattern] != nil {
97+
return regexes[pattern], nil
98+
}
99+
100+
r, err := regexp.Compile(pattern)
101+
if err == nil {
102+
regexes[pattern] = r
103+
}
104+
105+
return r, err
106+
}
107+
87108
// match matches a byte array against a regexp pattern and returns a bool.
88109
func (h *Hound) match(pattern string, subject []byte) bool {
89-
r, err := regexp.Compile(pattern)
110+
r, err := h.regexp(pattern)
90111
if err != nil {
91112
panic(err)
92113
}

0 commit comments

Comments
 (0)