| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | "github.com/tomwright/dasel/v3/selector/ast" |
| 9 | ) |
| 10 | |
| 11 | func mapExprExecutor(e ast.MapExpr) (expressionExecutor, error) { |
| 12 | return func(ctx context.Context, options *Options, data *model.Value) (*model.Value, error) { |
| 13 | ctx = WithExecutorID(ctx, "mapExpr") |
| 14 | if !data.IsSlice() { |
| 15 | return nil, fmt.Errorf("cannot map over non-array") |
| 16 | } |
| 17 | res := model.NewSliceValue() |
| 18 | |
| 19 | if err := data.RangeSlice(func(i int, item *model.Value) error { |
| 20 | restore := withKeyVar(options, model.NewIntValue(int64(i))) |
| 21 | defer restore() |
| 22 | |
| 23 | item, err := ExecuteAST(ctx, e.Expr, item, options) |
| 24 | if err != nil { |
| 25 | return err |
| 26 | } |
| 27 | if err := res.Append(item); err != nil { |
| 28 | return fmt.Errorf("error appending item to result: %w", err) |
| 29 | } |
| 30 | return nil |
| 31 | }); err != nil { |
| 32 | return nil, fmt.Errorf("error ranging over slice: %w", err) |
| 33 | } |
| 34 | return res, nil |
| 35 | }, nil |
| 36 | } |