-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.go
107 lines (94 loc) · 2.08 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
107
package path
import (
"log"
"strings"
"github.com/cruffinoni/xml-generator/xml"
)
type pattern struct {
path string
matcher ComputedMatcher
}
type Elements []*xml.Element
// ResultType is the type of the result of a match.
//type ResultType interface {
// *xml.Element | []*xml.Element
//}
// Path is a path to a node in the XML tree.
type Path struct {
patterns []*pattern
tree *xml.Tree
}
type Matcher interface {
Build(pattern string) ComputedMatcher
RawMatch(pattern string) bool
}
type ComputedMatcher interface {
StrictMatch(node *xml.Element, input string) Elements
TrailingMatch() Elements
}
type DefaultMatcher = StringMatch
var matchers = []Matcher{
&WildcardMatch{},
&ArrayMatch{},
&ListMatch{},
&AttributeMatch{},
}
func NewPathing(rawPattern string) *Path {
split := strings.Split(rawPattern, ">")
p := &Path{
patterns: make([]*pattern, 0, len(split)),
}
for _, s := range split {
pm := &pattern{
path: s,
matcher: &DefaultMatcher{},
}
for _, m := range matchers {
if m.RawMatch(s) {
pm.matcher = m.Build(s)
if pm.matcher == nil {
log.Fatalf("failed to build matcher for %s", s)
}
break
}
}
p.patterns = append(p.patterns, pm)
}
return p
}
func FindWithPath(pattern string, root *xml.Element) Elements {
p := NewPathing(pattern)
return p.Find(root)
}
func (p *Path) Find(root *xml.Element) Elements {
var (
r Elements
n = root
patternIdx = 0
)
cpyPatterns := make([]*pattern, len(p.patterns))
copy(cpyPatterns, p.patterns)
for n != nil {
if r = p.patterns[patternIdx].matcher.StrictMatch(n, cpyPatterns[0].path); r == nil {
n = n.Next
continue
}
patternIdx++
cpyPatterns = cpyPatterns[1:]
if len(cpyPatterns) == 0 {
return r
} else {
n = n.Child
}
}
if r = p.patterns[patternIdx].matcher.TrailingMatch(); r != nil {
if len(r) == 0 {
log.Printf("Find: not found at %s (%T)", cpyPatterns[0].path, cpyPatterns[0].matcher)
}
return r
}
if len(r) == 0 {
log.Printf("Find: not found at %s (%T)", cpyPatterns[0].path, cpyPatterns[0].matcher)
}
return nil
}