forked from TomWright/dasel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_or_default.go
58 lines (49 loc) · 1.24 KB
/
func_or_default.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
package dasel
import (
"errors"
"fmt"
)
var OrDefaultFunc = BasicFunction{
name: "orDefault",
runFn: func(c *Context, s *Step, args []string) (Values, error) {
if err := requireExactlyXArgs("orDefault", args, 2); err != nil {
return nil, err
}
input := s.inputs()
if c.CreateWhenMissing() {
input = input.initEmptydencodingMaps()
}
runSubselect := func(value Value, selector string, defaultSelector string) (Value, error) {
gotValues, err := c.subSelect(value, selector)
if err != nil {
notFound := false
if errors.Is(err, &ErrPropertyNotFound{}) {
notFound = true
} else if errors.Is(err, &ErrIndexNotFound{Index: -1}) {
notFound = true
}
if notFound {
gotValues, err = c.subSelect(value, defaultSelector)
} else {
return Value{}, err
}
}
if len(gotValues) == 1 && err == nil {
return gotValues[0], nil
}
if err != nil {
return Value{}, err
}
return Value{}, fmt.Errorf("orDefault expects selector to return exactly 1 value")
}
res := make(Values, 0)
for _, val := range input {
resolvedValue, err := runSubselect(val, args[0], args[1])
if err != nil {
return nil, err
}
res = append(res, resolvedValue)
}
return res, nil
},
}