-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathwalk.go
More file actions
66 lines (58 loc) · 1.74 KB
/
Copy pathwalk.go
File metadata and controls
66 lines (58 loc) · 1.74 KB
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
package dyn
import "errors"
// WalkValueFunc is the type of the function called by Walk to traverse the configuration tree.
type WalkValueFunc func(p Path, v Value) (Value, error)
// ErrDrop may be returned by WalkValueFunc to remove a value from the subtree.
var ErrDrop = errors.New("drop value from subtree")
// ErrSkip may be returned by WalkValueFunc to skip traversal of a subtree.
var ErrSkip = errors.New("skip traversal of subtree")
// Walk walks the configuration tree and calls the given function on each node.
// The callback may return ErrDrop to remove a value from the subtree.
// The callback may return ErrSkip to skip traversal of a subtree.
// If the callback returns another error, the walk is aborted, and the error is returned.
func Walk(v Value, fn func(p Path, v Value) (Value, error)) (Value, error) {
return walk(v, EmptyPath, fn)
}
// Unexported counterpart to Walk.
// It carries the path leading up to the current node,
// such that it can be passed to the WalkValueFunc.
func walk(v Value, p Path, fn func(p Path, v Value) (Value, error)) (Value, error) {
v, err := fn(p, v)
if err != nil {
if err == ErrSkip {
return v, nil
}
return NilValue, err
}
switch v.Kind() {
case KindMap:
m := v.MustMap()
out := make(map[string]Value, len(m))
for k := range m {
nv, err := walk(m[k], append(p, Key(k)), fn)
if err == ErrDrop {
continue
}
if err != nil {
return NilValue, err
}
out[k] = nv
}
v.v = out
case KindSequence:
s := v.MustSequence()
out := make([]Value, 0, len(s))
for i := range s {
nv, err := walk(s[i], append(p, Index(i)), fn)
if err == ErrDrop {
continue
}
if err != nil {
return NilValue, err
}
out = append(out, nv)
}
v.v = out
}
return v, nil
}