| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncEntries converts a map into an array of {key, value} objects. |
| 11 | var FuncEntries = NewFunc( |
| 12 | "entries", |
| 13 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 14 | if !data.IsMap() { |
| 15 | return nil, fmt.Errorf("entries can only be used on maps, got %s", data.Type().String()) |
| 16 | } |
| 17 | |
| 18 | res := model.NewSliceValue() |
| 19 | if err := data.RangeMap(func(key string, value *model.Value) error { |
| 20 | entry := model.NewMapValue() |
| 21 | if err := entry.SetMapKey("key", model.NewStringValue(key)); err != nil { |
| 22 | return err |
| 23 | } |
| 24 | if err := entry.SetMapKey("value", value); err != nil { |
| 25 | return err |
| 26 | } |
| 27 | return res.Append(entry) |
| 28 | }); err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | |
| 32 | return res, nil |
| 33 | }, |
| 34 | ValidateArgsExactly(0), |
| 35 | ) |
| 36 | |
| 37 | // FuncFromEntries converts an array of {key, value} objects into a map. |
| 38 | var FuncFromEntries = NewFunc( |
| 39 | "fromEntries", |
| 40 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 41 | var input *model.Value |
| 42 | if len(args) == 1 { |
| 43 | input = args[0] |
| 44 | } else { |
| 45 | input = data |
| 46 | } |
| 47 | |
| 48 | if !input.IsSlice() { |
| 49 | return nil, fmt.Errorf("fromEntries expects an array, got %s", input.Type().String()) |
| 50 | } |
| 51 | |
| 52 | res := model.NewMapValue() |
| 53 | if err := input.RangeSlice(func(i int, entry *model.Value) error { |
| 54 | if !entry.IsMap() { |
| 55 | return fmt.Errorf("fromEntries expects each element to be an object, got %s at index %d", entry.Type().String(), i) |
| 56 | } |
| 57 | |
| 58 | keyVal, err := entry.GetMapKey("key") |
| 59 | if err != nil { |
| 60 | return fmt.Errorf("fromEntries expects each element to have a \"key\" field: %w", err) |
| 61 | } |
| 62 | key, err := keyVal.StringValue() |
| 63 | if err != nil { |
| 64 | return fmt.Errorf("fromEntries expects \"key\" to be a string: %w", err) |
| 65 | } |
| 66 | |
| 67 | value, err := entry.GetMapKey("value") |
| 68 | if err != nil { |
| 69 | return fmt.Errorf("fromEntries expects each element to have a \"value\" field: %w", err) |
| 70 | } |
| 71 | |
| 72 | return res.SetMapKey(key, value) |
| 73 | }); err != nil { |
| 74 | return nil, err |
| 75 | } |
| 76 | |
| 77 | return res, nil |
| 78 | }, |
| 79 | ValidateArgsMax(1), |
| 80 | ) |