| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncKeys returns the keys of a map or the indices of a slice. |
| 11 | var FuncKeys = NewFunc( |
| 12 | "keys", |
| 13 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 14 | switch data.Type() { |
| 15 | case model.TypeMap: |
| 16 | keys, err := data.MapKeys() |
| 17 | if err != nil { |
| 18 | return nil, err |
| 19 | } |
| 20 | res := model.NewSliceValue() |
| 21 | for _, key := range keys { |
| 22 | if err := res.Append(model.NewStringValue(key)); err != nil { |
| 23 | return nil, err |
| 24 | } |
| 25 | } |
| 26 | return res, nil |
| 27 | case model.TypeSlice: |
| 28 | len, err := data.SliceLen() |
| 29 | if err != nil { |
| 30 | return nil, err |
| 31 | } |
| 32 | res := model.NewSliceValue() |
| 33 | for i := 0; i < len; i++ { |
| 34 | if err := res.Append(model.NewIntValue(int64(i))); err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | } |
| 38 | return res, nil |
| 39 | default: |
| 40 | return nil, fmt.Errorf("keys can only be used on maps and slices") |
| 41 | } |
| 42 | }, |
| 43 | ValidateArgsExactly(0), |
| 44 | ) |