forked from alicebob/miniredis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys.go
83 lines (78 loc) · 1.74 KB
/
keys.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
package miniredis
// Translate the 'KEYS' or 'PSUBSCRIBE' argument ('foo*', 'f??', &c.) into a regexp.
import (
"bytes"
"regexp"
)
// patternRE compiles a glob to a regexp. Returns nil if the given
// pattern will never match anything.
// The general strategy is to sandwich all non-meta characters between \Q...\E.
func patternRE(k string) *regexp.Regexp {
re := bytes.Buffer{}
re.WriteString(`(?s)^\Q`)
for i := 0; i < len(k); i++ {
p := k[i]
switch p {
case '*':
re.WriteString(`\E.*\Q`)
case '?':
re.WriteString(`\E.\Q`)
case '[':
charClass := bytes.Buffer{}
i++
for ; i < len(k); i++ {
if k[i] == ']' {
break
}
if k[i] == '\\' {
if i == len(k)-1 {
// Ends with a '\'. U-huh.
return nil
}
charClass.WriteByte(k[i])
i++
charClass.WriteByte(k[i])
continue
}
charClass.WriteByte(k[i])
}
if charClass.Len() == 0 {
// '[]' is valid in Redis, but matches nothing.
return nil
}
re.WriteString(`\E[`)
re.Write(charClass.Bytes())
re.WriteString(`]\Q`)
case '\\':
if i == len(k)-1 {
// Ends with a '\'. U-huh.
return nil
}
// Forget the \, keep the next char.
i++
re.WriteByte(k[i])
continue
default:
re.WriteByte(p)
}
}
re.WriteString(`\E$`)
return regexp.MustCompile(re.String())
}
// matchKeys filters only matching keys.
// The returned boolean is whether the match pattern was valid
func matchKeys(keys []string, match string) ([]string, bool) {
re := patternRE(match)
if re == nil {
// Special case: the given pattern won't match anything or is invalid.
return nil, false
}
var res []string
for _, k := range keys {
if !re.MatchString(k) {
continue
}
res = append(res, k)
}
return res, true
}