forked from TomWright/dasel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_keys.go
117 lines (99 loc) · 2.31 KB
/
func_keys.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
package dasel
import (
"fmt"
"github.com/tomwright/dasel/v2/dencoding"
"reflect"
"sort"
"strings"
)
type ErrInvalidType struct {
ExpectedTypes []string
CurrentType string
}
func (e *ErrInvalidType) Error() string {
return fmt.Sprintf("unexpected types: expect %s, get %s", strings.Join(e.ExpectedTypes, " "), e.CurrentType)
}
func (e *ErrInvalidType) Is(other error) bool {
o, ok := other.(*ErrInvalidType)
if !ok {
return false
}
if len(e.ExpectedTypes) != len(o.ExpectedTypes) {
return false
}
if e.CurrentType != o.CurrentType {
return false
}
for i, t := range e.ExpectedTypes {
if t != o.ExpectedTypes[i] {
return false
}
}
return true
}
var KeysFunc = BasicFunction{
name: "keys",
runFn: func(c *Context, s *Step, args []string) (Values, error) {
if err := requireNoArgs("keys", args); err != nil {
return nil, err
}
input := s.inputs()
res := make(Values, len(input))
for i, val := range input {
switch val.Kind() {
case reflect.Slice, reflect.Array:
list := make([]any, 0, val.Len())
for i := 0; i < val.Len(); i++ {
list = append(list, i)
}
res[i] = ValueOf(list)
case reflect.Map:
keys := val.MapKeys()
// we expect map keys to be string first so that we can sort them
list, ok := getStringList(keys)
if !ok {
list = getAnyList(keys)
}
res[i] = ValueOf(list)
default:
if val.IsDencodingMap() {
dencodingMap := val.Interface().(*dencoding.Map)
mapKeys := dencodingMap.Keys()
list := make([]any, 0, len(mapKeys))
for _, k := range mapKeys {
list = append(list, k)
}
res[i] = ValueOf(list)
} else {
return nil, &ErrInvalidType{
ExpectedTypes: []string{"slice", "array", "map"},
CurrentType: val.Kind().String(),
}
}
}
}
return res, nil
},
}
func getStringList(values []Value) ([]any, bool) {
stringList := make([]string, len(values))
for i, v := range values {
if v.Kind() != reflect.String {
return nil, false
}
stringList[i] = v.String()
}
sort.Strings(stringList)
anyList := make([]any, len(stringList))
for i, v := range stringList {
anyList[i] = v
}
return anyList, true
}
func getAnyList(values []Value) []any {
anyList := make([]any, len(values))
for i, v := range values {
anyList[i] = v.Interface()
}
return anyList
}