forked from mattn/lastpass-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
search.go
81 lines (69 loc) · 1.73 KB
/
search.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
package lastpass
import (
"regexp"
"strings"
)
type Field uint32
type SearchMethod uint32
const (
// Account fields
Id Field = iota
Name
Url
Username
// Match function types
CaseSensitive SearchMethod = iota
CaseInsensitive
Regex
SubstringSensitive
SubstringInsensitive
)
type matchFunc func(fieldValue string, value string) bool
var matchFuncs = map[SearchMethod]matchFunc{
CaseSensitive: exactMatch(true),
CaseInsensitive: exactMatch(false),
SubstringSensitive: substringMatch(true),
SubstringInsensitive: substringMatch(false),
Regex: regexMatch,
}
// regexMatch matches a fieldValue with a given pattern
func regexMatch(fieldValue, pattern string) bool {
match, _ := regexp.MatchString(pattern, fieldValue)
return match
}
// exactMatch matches a fieldValue with a given match
// value through string equality
func exactMatch(caseSensitive bool) func(fieldValue, matchValue string) bool {
return func(fieldValue, matchValue string) bool {
if !caseSensitive {
fieldValue = strings.ToLower(fieldValue)
matchValue = strings.ToLower(matchValue)
}
return fieldValue == matchValue
}
}
// substringMatch matches a fieldValue contains
// the given substring
func substringMatch(caseSensitive bool) func(fieldValue, matchValue string) bool {
return func(fieldValue, matchValue string) bool {
if !caseSensitive {
fieldValue = strings.ToLower(fieldValue)
matchValue = strings.ToLower(matchValue)
}
return strings.Contains(fieldValue, matchValue)
}
}
func getValue(account Account, field Field) string {
switch field {
case Id:
return account.Id
case Name:
return account.Name
case Url:
return account.Url
case Username:
return account.Username
default:
return account.Id
}
}