forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matcher.go
80 lines (72 loc) · 2 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
package completion
import (
"errors"
"strings"
"github.com/u-root/u-root/cmds/elvish/eval"
"github.com/u-root/u-root/cmds/elvish/eval/vals"
"github.com/u-root/u-root/cmds/elvish/util"
"github.com/u-root/u-root/cmds/elvish/hashmap"
)
var (
errIncorrectNumOfResults = errors.New("matcher must return a bool for each candidate")
errMatcherMustBeFn = errors.New("matcher must be a function")
errMatcherInputMustBeString = errors.New("matcher input must be string")
)
var (
matchPrefix = eval.NewBuiltinFn(
"edit:match-prefix", wrapMatcher(strings.HasPrefix))
matchSubstr = eval.NewBuiltinFn(
"edit:match-substr", wrapMatcher(strings.Contains))
matchSubseq = eval.NewBuiltinFn(
"edit:match-subseq", wrapMatcher(util.HasSubseq))
)
func lookupMatcher(m hashmap.Map, name string) (eval.Callable, bool) {
key := name
if !hashmap.HasKey(m, key) {
// Use fallback matcher
if !hashmap.HasKey(m, "") {
return nil, false
}
key = ""
}
value, _ := m.Index(key)
matcher, ok := value.(eval.Callable)
return matcher, ok
}
func wrapMatcher(matcher func(s, p string) bool) interface{} {
return func(fm *eval.Frame,
opts eval.RawOptions, pattern string, inputs eval.Inputs) {
var options struct {
IgnoreCase bool
SmartCase bool
}
opts.Scan(&options)
switch {
case options.IgnoreCase && options.SmartCase:
throwf("-ignore-case and -smart-case cannot be used together")
case options.IgnoreCase:
innerMatcher := matcher
matcher = func(s, p string) bool {
return innerMatcher(strings.ToLower(s), strings.ToLower(p))
}
case options.SmartCase:
innerMatcher := matcher
matcher = func(s, p string) bool {
if p == strings.ToLower(p) {
// Ignore case is pattern is all lower case.
return innerMatcher(strings.ToLower(s), p)
} else {
return innerMatcher(s, p)
}
}
}
out := fm.OutputChan()
inputs(func(v interface{}) {
s, ok := v.(string)
if !ok {
throw(errMatcherInputMustBeString)
}
out <- vals.Bool(matcher(s, pattern))
})
}
}