-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.go
106 lines (96 loc) · 2.58 KB
/
path.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
package traveller
import (
"errors"
"strings"
)
var (
// The error that is returned when there is an invalid path.
ErrInvalidPath = errors.New("invalid path")
)
// Shorthand for MustPath(ps, false).
//
// Will panic if the given path string is invalid.
// Use Path if an invalid input is expected.
func P(ps string) []Matcher {
return MustPath(ps, false)
}
// Shorthand for MustPath(ps, true).
//
// Will panic if the given path string is invalid.
// Use Path if an invalid input is expected.
func PCI(ps string) []Matcher {
return MustPath(ps, true)
}
// Convert a string path to a series of matchers.
//
// Will panic if the given path string is invalid.
// Use Path if an invalid input is expected.
func MustPath(ps string, caseInsensitive bool) []Matcher {
mp, err := Path(ps, caseInsensitive)
if err != nil {
panic(err)
}
return mp
}
// Convert a string path to a series of matchers.
func Path(ps string, caseInsensitive bool) ([]Matcher, error) {
tokens := splitEscape(ps, '.', '\\')
matchers := make([]Matcher, 0, len(tokens))
for _, token := range tokens {
if isExactToken(token) {
if !caseInsensitive {
matchers = append(matchers, MatchExact{Value: token})
} else {
matchers = append(matchers, MatchPattern{
Pattern: token,
CaseInsensitive: caseInsensitive,
})
}
} else if isMultiMatchToken(token) {
matchers = append(matchers, MatchMulti{})
} else if !isInvalidToken(token) {
matchers = append(matchers, MatchPattern{
Pattern: token,
CaseInsensitive: caseInsensitive,
})
} else {
return nil, ErrInvalidPath
}
}
return matchers, nil
}
// Whether the token is an exact match value.
func isExactToken(token string) bool {
return !strings.Contains(token, "*")
}
// Whether the token is a multi match/recursive match value.
func isMultiMatchToken(token string) bool {
return token == "**"
}
// Whether a token is invalid and should not be parsed.
func isInvalidToken(token string) bool {
return strings.Contains(token, "**") && len(token) != 2
}
// Splits a string to a collection of token by the given separator.
//
// Will not attempt to split when a separator is preceded by
// the specified escape character.
func splitEscape(s string, separator, escape byte) []string {
var (
token []byte
tokens []string
)
for i := 0; i < len(s); i++ {
if s[i] == separator {
tokens = append(tokens, string(token))
token = token[:0]
} else if s[i] == escape && i+1 < len(s) {
i++
token = append(token, s[i])
} else {
token = append(token, s[i])
}
}
tokens = append(tokens, string(token))
return tokens
}