-
Notifications
You must be signed in to change notification settings - Fork 36
/
matcher.go
88 lines (80 loc) · 1.68 KB
/
matcher.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"regexp"
"strings"
)
// Matcher can be used as a cli argument.
type Matcher struct {
regexp *regexp.Regexp
invert bool
}
// NewMatcher compiles the regexp and returns a Matcher.
func NewMatcher(exp string) (Matcher, error) {
switch {
case strings.HasPrefix(exp, "!"):
re, err := regexp.Compile(exp[1:])
if err != nil {
return Matcher{}, err
}
return Matcher{regexp: re, invert: true}, nil
default:
re, err := regexp.Compile(exp)
if err != nil {
return Matcher{}, err
}
return Matcher{regexp: re, invert: false}, nil
}
}
// NewMatcher compiles the regexp and returns a Matcher, it will panic if an error is returned.
func MustMatcher(exp string) Matcher {
re, err := NewMatcher(exp)
if err != nil {
panic(err)
}
return re
}
// MarshalText implements the TextMarshaller interface.
func (m Matcher) MarshalText() ([]byte, error) {
switch {
case m.invert:
return []byte("!" + m.regexp.String()), nil
default:
return []byte(m.regexp.String()), nil
}
}
// UnmarshalText implements the TextUnmarshaller interface.
func (m *Matcher) UnmarshalText(data []byte) error {
switch s := string(data); {
case strings.HasPrefix(s, "!"):
re, err := regexp.Compile(s[1:])
if err != nil {
return err
}
m.regexp = re
m.invert = true
default:
re, err := regexp.Compile(s)
if err != nil {
return err
}
m.regexp = re
m.invert = false
}
return nil
}
func (m Matcher) Match(check []byte) bool {
switch ok := m.regexp.Match(check); {
case m.invert:
return !ok
default:
return ok
}
}
func (m Matcher) MatchString(check string) bool {
switch ok := m.regexp.MatchString(check); {
case m.invert:
return !ok
default:
return ok
}
}