Debian Codegraph @

execution/func_has.go

raw symbols SCIP
1 package execution
2
3 import (
4 "context"
5 "fmt"
6 "github.com/tomwright/dasel/v3/model"
7 )
8
9 // FuncHas is a function that true or false if the input has the given key/index.
10 var FuncHas = NewFunc(
11 "has",
12 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
13
14 arg := args[0]
15
16 switch arg.Type() {
17 case model.TypeInt:
18 // Given key is int, expect a slice.
19 if data.Type() != model.TypeSlice {
20 return model.NewBoolValue(false), nil
21 }
22 index, err := arg.IntValue()
23 if err != nil {
24 return nil, err
25 }
26 sliceLen, err := data.SliceLen()
27 if err != nil {
28 return nil, err
29 }
30 return model.NewBoolValue(index >= 0 && index < int64(sliceLen)), nil
31 case model.TypeString:
32 // Given key is string, expect a map.
33 if data.Type() != model.TypeMap {
34 return model.NewBoolValue(false), nil
35 }
36 key, err := arg.StringValue()
37 if err != nil {
38 return nil, err
39 }
40 exists, err := data.MapKeyExists(key)
41 if err != nil {
42 return nil, err
43 }
44 return model.NewBoolValue(exists), nil
45 default:
46 return nil, fmt.Errorf("has expects string or int argument")
47 }
48 },
49 ValidateArgsMin(1),
50 )