forked from BishopFox/jsluice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjects.go
110 lines (88 loc) · 1.94 KB
/
objects.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
108
109
110
package jsluice
import (
"strings"
)
type object struct {
node *Node
source []byte
}
func newObject(n *Node, source []byte) object {
return object{
node: n,
source: source,
}
}
func (o object) asMap() map[string]string {
out := make(map[string]string, 0)
if !o.hasValidNode() {
return out
}
for _, k := range o.getKeys() {
out[k] = o.getString(k, "")
}
return out
}
func (o object) hasValidNode() bool {
return o.node.IsValid() && o.node.Type() == "object"
}
func (o object) getNodeFunc(fn func(key string) bool) *Node {
if !o.hasValidNode() {
return &Node{}
}
count := int(o.node.NamedChildCount())
for i := 0; i < count; i++ {
pair := o.node.NamedChild(i)
if pair.Type() != "pair" {
continue
}
if !fn(pair.ChildByFieldName("key").RawString()) {
continue
}
return pair.ChildByFieldName("value")
}
return nil
}
func (o object) getNode(key string) *Node {
return o.getNodeFunc(func(candidate string) bool {
return key == candidate
})
}
func (o object) getNodeI(key string) *Node {
key = strings.ToLower(key)
return o.getNodeFunc(func(candidate string) bool {
return key == strings.ToLower(candidate)
})
}
func (o object) getKeys() []string {
out := make([]string, 0)
if !o.hasValidNode() {
return out
}
count := int(o.node.NamedChildCount())
for i := 0; i < count; i++ {
pair := o.node.NamedChild(i)
if pair.Type() != "pair" {
continue
}
key := pair.ChildByFieldName("key").RawString()
out = append(out, key)
}
return out
}
func (o object) getObject(key string) object {
return newObject(o.getNode(key), o.source)
}
func (o object) getString(key, defaultVal string) string {
value := o.getNode(key)
if value == nil || value.Type() != "string" {
return defaultVal
}
return value.RawString()
}
func (o object) getStringI(key, defaultVal string) string {
value := o.getNodeI(key)
if value == nil || value.Type() != "string" {
return defaultVal
}
return value.RawString()
}