summaryrefslogtreecommitdiffstats
path: root/src/go/pkg/matcher/simple_patterns.go
blob: 91a0a3bbd30d6e5f6159411a0b81bc8375f35b3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// SPDX-License-Identifier: GPL-3.0-or-later

package matcher

import (
	"strings"
)

type (
	simplePatternTerm struct {
		matcher  Matcher
		positive bool
	}

	// simplePatternsMatcher patterns.
	simplePatternsMatcher []simplePatternTerm
)

// NewSimplePatternsMatcher creates new simple patterns. It returns error in case one of patterns has bad syntax.
func NewSimplePatternsMatcher(expr string) (Matcher, error) {
	ps := simplePatternsMatcher{}

	for _, pattern := range strings.Fields(expr) {
		if err := ps.add(pattern); err != nil {
			return nil, err
		}
	}
	if len(ps) == 0 {
		return FALSE(), nil
	}
	return ps, nil
}

func (m *simplePatternsMatcher) add(term string) error {
	p := simplePatternTerm{}
	if term[0] == '!' {
		p.positive = false
		term = term[1:]
	} else {
		p.positive = true
	}
	matcher, err := NewGlobMatcher(term)
	if err != nil {
		return err
	}

	p.matcher = matcher
	*m = append(*m, p)

	return nil
}

func (m simplePatternsMatcher) Match(b []byte) bool {
	return m.MatchString(string(b))
}

// MatchString matches.
func (m simplePatternsMatcher) MatchString(line string) bool {
	for _, p := range m {
		if p.matcher.MatchString(line) {
			return p.positive
		}
	}
	return false
}