| 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 branchExprExecutor(e ast.BranchExpr) (expressionExecutor, error) { |
| 12 | return func(ctx context.Context, options *Options, data *model.Value) (*model.Value, error) { |
| 13 | ctx = WithExecutorID(ctx, "branchExpr") |
| 14 | res := model.NewSliceValue() |
| 15 | res.MarkAsBranch() |
| 16 | |
| 17 | if len(e.Exprs) == 0 { |
| 18 | // No expressions given. We'll branch on the input data. |
| 19 | if err := data.RangeSlice(func(_ int, value *model.Value) error { |
| 20 | if err := res.Append(value); err != nil { |
| 21 | return fmt.Errorf("failed to append branch result: %w", err) |
| 22 | } |
| 23 | return nil |
| 24 | }); err != nil { |
| 25 | return nil, fmt.Errorf("failed to range slice: %w", err) |
| 26 | } |
| 27 | } else { |
| 28 | for _, expr := range e.Exprs { |
| 29 | r, err := ExecuteAST(ctx, expr, data, options) |
| 30 | if err != nil { |
| 31 | return nil, fmt.Errorf("failed to execute branch expr: %w", err) |
| 32 | } |
| 33 | |
| 34 | // This deals with the spread operator in the branch expression. |
| 35 | valsToAppend, err := prepareSpreadValues(r) |
| 36 | if err != nil { |
| 37 | return nil, fmt.Errorf("error handling spread values: %w", err) |
| 38 | } |
| 39 | for _, v := range valsToAppend { |
| 40 | if err := res.Append(v); err != nil { |
| 41 | return nil, fmt.Errorf("failed to append branch result: %w", err) |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | return res, nil |
| 48 | }, nil |
| 49 | } |