Skip to content

Commit

Permalink
Let grepper use matcher module
Browse files Browse the repository at this point in the history
  • Loading branch information
iwat committed May 11, 2017
1 parent 42a1fb2 commit 9538e80
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions internal/grepper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package internal

import (
"bufio"
"bytes"
"os"
)

Expand All @@ -14,7 +13,14 @@ func newGrepper() *_Grepper {
}

func (g *_Grepper) grep(file string, keywords ...string) (bool, error) {
keywordMap := mapKeywords(keywords)
matchers := make(map[string]_Matcher, len(keywords))
for _, keyword := range keywords {
matcher, err := newMatcher(keyword)
if err != nil {
continue
}
matchers[keyword] = matcher
}

f, err := os.Open(file)
if err != nil {
Expand All @@ -29,12 +35,12 @@ func (g *_Grepper) grep(file string, keywords ...string) (bool, error) {

scanner := bufio.NewScanner(f)
for scanner.Scan() {
for keyword := range keywordMap {
if bytes.Contains(scanner.Bytes(), []byte(keyword)) {
delete(keywordMap, keyword)
for keyword, matcher := range matchers {
if matcher.Matches(scanner.Text()) {
delete(matchers, keyword)
}
}
if len(keywordMap) == 0 {
if len(matchers) == 0 {
break
}
}
Expand All @@ -43,16 +49,5 @@ func (g *_Grepper) grep(file string, keywords ...string) (bool, error) {
return false, err
}

return len(keywordMap) == 0, nil
}

func mapKeywords(keywords []string) map[string]bool {
keywordMap := map[string]bool{}

// Create a map of all unique elements.
for _, keyword := range keywords {
keywordMap[keyword] = false
}

return keywordMap
return len(matchers) == 0, nil
}

0 comments on commit 9538e80

Please sign in to comment.