-
Notifications
You must be signed in to change notification settings - Fork 0
/
matcher.go
128 lines (107 loc) · 2.46 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"regexp"
"strings"
)
type matcherFunc func([]string, string, []string) []string
func (mf matcherFunc) Match(args []string, pat string, list []string) []string {
return mf(args, pat, list)
}
func init() {
registerMatcher("string", matcherFunc(matchString))
registerMatcher("substring", matcherFunc(matchSubstring))
registerMatcher("token", matcherFunc(matchToken))
registerMatcher("subtoken", matcherFunc(matchSubtoken))
registerMatcher("alias_regexp", matcherFunc(matchAliasRegexp))
}
// string match, pattern is exactly the same as target.
func matchString(args []string, pat string, list []string) []string {
var result []string
for _, v := range list {
if pat == v {
result = append(result, v)
}
}
return result
}
// pattern is a substring of target.
func matchSubstring(args []string, pat string, list []string) []string {
var result []string
for _, v := range list {
if strings.Contains(v, pat) {
result = append(result, v)
}
}
return result
}
// match token separated by option
func matchToken(args []string, pat string, list []string) []string {
keys := strings.Split(pat, options.Sep)
var result []string
re := regexp.MustCompile("[^.-]+")
for _, v := range list {
parts := re.FindAllString(v, -1)
findMatch := true
for _, key := range keys {
match := false
for _, part := range parts {
if key == part {
match = true
break
}
}
if !match {
findMatch = false
break
}
}
if findMatch {
result = append(result, v)
}
}
return result
}
// match token by substring
func matchSubtoken(args []string, pat string, list []string) []string {
keys := strings.Split(pat, options.Sep)
var result []string
re := regexp.MustCompile("[^.-]+")
for _, v := range list {
parts := re.FindAllString(v, -1)
findMatch := true
for _, key := range keys {
match := false
for _, part := range parts {
if strings.Contains(part, key) {
match = true
break
}
}
if !match {
findMatch = false
break
}
}
if findMatch {
result = append(result, v)
}
}
return result
}
func matchAliasRegexp(args []string, pat string, list []string) []string {
if len(args) < 2 {
return nil
}
hostPattern := args[0]
template := args[1]
re, err := regexp.Compile(hostPattern)
if err != nil {
return nil
}
match := re.FindStringSubmatchIndex(pat)
if match == nil {
return nil
}
exp := re.ExpandString(nil, template, pat, match)
return []string{string(exp)}
}