Skip to content

Commit

Permalink
New negate matcher "-"
Browse files Browse the repository at this point in the history
Negate matcher is used for negating existing pattern, simply prefix the
pattern with "-".
  • Loading branch information
iwat committed May 11, 2017
1 parent 5f3b46f commit 42a1fb2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
1 change: 0 additions & 1 deletion internal/finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ func newFinder(queries ...string) *_Finder {
for _, query := range queries {
matcher, err := newMatcher(query)
if err != nil {
println(err)
continue
}
matchers = append(matchers, matcher)
Expand Down
36 changes: 33 additions & 3 deletions internal/matcher.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package internal

import (
"errors"
"regexp"
"strings"
)
Expand All @@ -13,11 +14,28 @@ type _StringMatcher struct {
pattern string
}

func newMatcher(pattern string) (_Matcher, error) {
func newMatcher(pattern string) (matcher _Matcher, err error) {
negate := false

if strings.HasPrefix(pattern, "-") {
if len(pattern) == 1 {
return nil, errors.New("incomplete negate matcher")
}
negate = true
pattern = pattern[1:]
}

if len(pattern) > 2 && strings.HasPrefix(pattern, "/") && strings.HasSuffix(pattern, "/") {
return newRegexpMatcher(pattern)
matcher, err = newRegexpMatcher(pattern)
} else {
matcher = newStringMatcher(pattern)
}
return newStringMatcher(pattern), nil

if negate {
matcher = newNegateMatcher(matcher)
}

return matcher, err
}

func newStringMatcher(pattern string) _StringMatcher {
Expand Down Expand Up @@ -46,3 +64,15 @@ func newRegexpMatcher(pattern string) (*_RegexpMatcher, error) {
func (m _RegexpMatcher) Matches(input string) bool {
return m.pattern.FindStringSubmatch(input) != nil
}

type _NegateMatcher struct {
original _Matcher
}

func newNegateMatcher(matcher _Matcher) *_NegateMatcher {
return &_NegateMatcher{matcher}
}

func (m _NegateMatcher) Matches(input string) bool {
return !m.original.Matches(input)
}

0 comments on commit 42a1fb2

Please sign in to comment.