| 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 reduceExprExecutor(e ast.ReduceExpr) (expressionExecutor, error) { |
| 12 | return func(ctx context.Context, options *Options, data *model.Value) (*model.Value, error) { |
| 13 | ctx = WithExecutorID(ctx, "reduceExpr") |
| 14 | if !data.IsSlice() { |
| 15 | return nil, fmt.Errorf("cannot reduce over non-array") |
| 16 | } |
| 17 | |
| 18 | // Evaluate init expression to get the initial accumulator value. |
| 19 | acc, err := ExecuteAST(ctx, e.Init, data, options) |
| 20 | if err != nil { |
| 21 | return nil, fmt.Errorf("error evaluating reduce init: %w", err) |
| 22 | } |
| 23 | |
| 24 | // Save and restore the acc variable to avoid polluting the caller's scope. |
| 25 | prevAcc, hadAcc := options.Vars["acc"] |
| 26 | defer func() { |
| 27 | if hadAcc { |
| 28 | options.Vars["acc"] = prevAcc |
| 29 | } else { |
| 30 | delete(options.Vars, "acc") |
| 31 | } |
| 32 | }() |
| 33 | |
| 34 | if err := data.RangeSlice(func(i int, item *model.Value) error { |
| 35 | restore := withKeyVar(options, model.NewIntValue(int64(i))) |
| 36 | defer restore() |
| 37 | |
| 38 | // Evaluate the per-element expression against the item. |
| 39 | elemVal, err := ExecuteAST(ctx, e.Expr, item, options) |
| 40 | if err != nil { |
| 41 | return fmt.Errorf("error evaluating reduce expr for element %d: %w", i, err) |
| 42 | } |
| 43 | |
| 44 | // Set $acc to the current accumulator and $this to the element value. |
| 45 | options.Vars["acc"] = acc |
| 46 | options.Vars["this"] = elemVal |
| 47 | |
| 48 | // Evaluate the update expression. |
| 49 | newAcc, err := ExecuteAST(ctx, e.Update, elemVal, options) |
| 50 | if err != nil { |
| 51 | return fmt.Errorf("error evaluating reduce update for element %d: %w", i, err) |
| 52 | } |
| 53 | acc = newAcc |
| 54 | return nil |
| 55 | }); err != nil { |
| 56 | return nil, fmt.Errorf("error ranging over slice: %w", err) |
| 57 | } |
| 58 | |
| 59 | return acc, nil |
| 60 | }, nil |
| 61 | } |