-
-
Notifications
You must be signed in to change notification settings - Fork 140
/
func_parent.go
54 lines (46 loc) · 895 Bytes
/
func_parent.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
package dasel
import (
"strconv"
)
var ParentFunc = BasicFunction{
name: "parent",
runFn: func(c *Context, s *Step, args []string) (Values, error) {
if err := requireXOrLessArgs("parent", args, 1); err != nil {
return nil, err
}
levels := 1
if len(args) > 0 {
arg, err := strconv.Atoi(args[0])
if err != nil {
return nil, err
}
levels = arg
}
if levels < 1 {
levels = 1
}
input := s.inputs()
res := make(Values, 0)
getParent := func(v Value, levels int) (Value, bool) {
res := v
for i := 0; i < levels; i++ {
p := res.Metadata("parent")
if p == nil {
return res, false
}
if pv, ok := p.(Value); ok {
res = pv
} else {
return res, false
}
}
return res, true
}
for _, i := range input {
if pv, ok := getParent(i, levels); ok {
res = append(res, pv)
}
}
return res, nil
},
}