-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
353 lines (326 loc) · 7.3 KB
/
node.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Tideland Go Generic JSON Processing - Value
//
// Copyright (C) 2019-2023 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package dynaj // import "tideland.dev/go/dynaj"
//--------------------
// IMPORTS
//--------------------
import (
"fmt"
"reflect"
"strconv"
"strings"
"tideland.dev/go/matcher"
)
//--------------------
// NODE
//--------------------
// Processor defines the signature of function for processing
// a path value. This may be the iterating over the whole
// document or one object or array.
type Processor func(n *Node) error
// Node is the combination of path and its value.
type Node struct {
path Path
element Element
err error
}
// IsUndefined returns true if this value is undefined.
func (node *Node) IsUndefined() bool {
return node.element == nil && node.err == nil
}
// IsValue returns true if this node is a simple value.
func (node *Node) IsValue() bool {
switch node.element.(type) {
case Object, Array:
return false
default:
return true
}
}
// IsObject returns true if this node is an object.
func (node *Node) IsObject() bool {
_, ok := node.element.(Object)
return ok
}
// IsArray returns true if this node is an array.
func (node *Node) IsArray() bool {
_, ok := node.element.(Array)
return ok
}
// IsError returns true if this value is an error.
func (node *Node) IsError() bool {
return node.err != nil
}
// Err returns the error if there is one.
func (node *Node) Err() error {
return node.err
}
// AsString returns the value as string.
func (node *Node) AsString(dv string) string {
if node.IsUndefined() {
return dv
}
switch tv := node.element.(type) {
case string:
return tv
case int:
return strconv.Itoa(tv)
case float64:
return strconv.FormatFloat(tv, 'f', -1, 64)
case bool:
return strconv.FormatBool(tv)
}
return dv
}
// AsInt returns the value as int.
func (node *Node) AsInt(dv int) int {
if node.IsUndefined() {
return dv
}
switch tv := node.element.(type) {
case string:
i, err := strconv.Atoi(tv)
if err != nil {
return dv
}
return i
case int:
return tv
case float64:
return int(tv)
case bool:
if tv {
return 1
}
return 0
}
return dv
}
// AsFloat64 returns the value as float64.
func (node *Node) AsFloat64(dv float64) float64 {
if node.IsUndefined() {
return dv
}
switch tv := node.element.(type) {
case string:
f, err := strconv.ParseFloat(tv, 64)
if err != nil {
return dv
}
return f
case int:
return float64(tv)
case float64:
return tv
case bool:
if tv {
return 1.0
}
return 0.0
}
return dv
}
// AsBool returns the value as bool.
func (node *Node) AsBool(dv bool) bool {
if node.IsUndefined() {
return dv
}
switch tv := node.element.(type) {
case string:
b, err := strconv.ParseBool(tv)
if err != nil {
return dv
}
return b
case int:
return tv == 1
case float64:
return tv == 1.0
case bool:
return tv
}
return dv
}
// Equals compares a value with the passed one.
func (node *Node) Equals(other *Node) bool {
switch {
case node.IsUndefined() && other.IsUndefined():
return true
case node.IsUndefined() || other.IsUndefined():
return false
default:
return reflect.DeepEqual(node.element, other.element)
}
}
// Path returns the path of the value.
func (node *Node) Path() Path {
return node.path
}
// SplitPath splits the path into its keys.
func (node *Node) SplitPath() Keys {
return splitPath(node.path)
}
// NodeAt returns the node at the passed path.
func (node *Node) NodeAt(path Path) *Node {
if node.IsUndefined() {
return &Node{
path: path,
element: nil,
}
}
if node.IsValue() {
return &Node{
path: path,
element: node.element,
}
}
// Navigate downstream.
nodeAt := &Node{
path: joinPaths(node.path, path),
}
value, err := elementAt(node.element, splitPath(path))
if err != nil {
nodeAt.err = fmt.Errorf("invalid path %q: %v", path, err)
} else {
nodeAt.element = value
}
return nodeAt
}
// Process iterates over the node and all its subnodes and
// processes them with the passed processor function.
func (node *Node) Process(process Processor) error {
if node.err != nil {
return node.err
}
switch typed := node.element.(type) {
case Object:
// A JSON object.
if len(typed) == 0 {
return process(&Node{
path: node.path,
element: Object{},
})
}
for key, subvalue := range typed {
subpath := appendKey(node.path, key)
subnode := &Node{
path: subpath,
element: subvalue,
}
if err := subnode.Process(process); err != nil {
return fmt.Errorf("cannot process %q: %v", subpath, err)
}
}
case Array:
// A JSON array.
if len(typed) == 0 {
return process(&Node{
path: node.path,
element: Array{},
})
}
for idx, subvalue := range typed {
subpath := appendKey(node.path, strconv.Itoa(idx))
subnode := &Node{
path: subpath,
element: subvalue,
}
if err := subnode.Process(process); err != nil {
return fmt.Errorf("cannot process %q: %v", subpath, err)
}
}
default:
// A single value at the end.
err := process(&Node{
path: node.path,
element: typed,
})
if err != nil {
return fmt.Errorf("cannot process %q: %v", node.path, err)
}
}
return nil
}
// Range takes the node and processes it with the passed processor
// function. In case of an object all keys and in case of an array
// all indices will be processed. It is not working recursively.
func (node *Node) Range(process Processor) error {
if node.err != nil {
return node.err
}
switch typed := node.element.(type) {
case Object:
// A JSON object.
for key := range typed {
keypath := appendKey(node.path, key)
if isObjectOrArray(typed[key]) {
return fmt.Errorf("cannot process %q: is object or array", keypath)
}
err := process(&Node{
path: keypath,
element: typed[key],
})
if err != nil {
return fmt.Errorf("cannot process %q: %v", keypath, err)
}
}
case Array:
// A JSON array.
for idx := range typed {
idxpath := appendKey(node.path, strconv.Itoa(idx))
if isObjectOrArray(typed[idx]) {
return fmt.Errorf("cannot process %q: is object or array", idxpath)
}
err := process(&Node{
path: idxpath,
element: typed[idx],
})
if err != nil {
return fmt.Errorf("cannot process %q: %v", idxpath, err)
}
}
default:
// A single value at the end.
err := process(&Node{
path: node.path,
element: typed,
})
if err != nil {
return fmt.Errorf("cannot process %q: %v", node.path, err)
}
}
return nil
}
// Query iterates over the node and all its subnodes and returns
// all values with paths matching the passed pattern.
func (node *Node) Query(pattern string) (Nodes, error) {
nodes := Nodes{}
err := node.Process(func(pnode *Node) error {
trimmedPath := strings.TrimPrefix(pnode.path, node.path+Separator)
if matcher.Matches(pattern, trimmedPath, false) {
nodes = append(nodes, &Node{
path: pnode.path,
element: pnode.element,
})
}
return nil
})
return nodes, err
}
// String implements fmt.Stringer.
func (node *Node) String() string {
if node.IsUndefined() {
return "null"
}
if node.IsError() {
return fmt.Sprintf("error: %v", node.err)
}
return fmt.Sprintf("%v", node.element)
}
// Nodes contains a list of paths and their value.
type Nodes []*Node
// EOF