-
-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathfunc_has.go
More file actions
50 lines (46 loc) · 1.14 KB
/
func_has.go
File metadata and controls
50 lines (46 loc) · 1.14 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
package execution
import (
"context"
"fmt"
"github.com/tomwright/dasel/v3/model"
)
// FuncHas is a function that true or false if the input has the given key/index.
var FuncHas = NewFunc(
"has",
func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
arg := args[0]
switch arg.Type() {
case model.TypeInt:
// Given key is int, expect a slice.
if data.Type() != model.TypeSlice {
return model.NewBoolValue(false), nil
}
index, err := arg.IntValue()
if err != nil {
return nil, err
}
sliceLen, err := data.SliceLen()
if err != nil {
return nil, err
}
return model.NewBoolValue(index >= 0 && index < int64(sliceLen)), nil
case model.TypeString:
// Given key is string, expect a map.
if data.Type() != model.TypeMap {
return model.NewBoolValue(false), nil
}
key, err := arg.StringValue()
if err != nil {
return nil, err
}
exists, err := data.MapKeyExists(key)
if err != nil {
return nil, err
}
return model.NewBoolValue(exists), nil
default:
return nil, fmt.Errorf("has expects string or int argument")
}
},
ValidateArgsMin(1),
)