| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "slices" |
| 8 | |
| 9 | "github.com/tomwright/dasel/v3/model" |
| 10 | "github.com/tomwright/dasel/v3/selector/ast" |
| 11 | ) |
| 12 | |
| 13 | func prepareArgs(ctx context.Context, opts *Options, data *model.Value, argsE ast.Expressions) (model.Values, error) { |
| 14 | args := make(model.Values, 0) |
| 15 | for i, arg := range argsE { |
| 16 | res, err := ExecuteAST(ctx, arg, data, opts) |
| 17 | if err != nil { |
| 18 | return nil, fmt.Errorf("error evaluating argument %d: %w", i, err) |
| 19 | } |
| 20 | |
| 21 | argVals, err := prepareSpreadValues(res) |
| 22 | if err != nil { |
| 23 | return nil, fmt.Errorf("error handling spread values: %w", err) |
| 24 | } |
| 25 | |
| 26 | args = append(args, argVals...) |
| 27 | } |
| 28 | return args, nil |
| 29 | } |
| 30 | |
| 31 | func callFnExecutor(f FuncFn, argsE ast.Expressions) (expressionExecutor, error) { |
| 32 | return func(ctx context.Context, options *Options, data *model.Value) (*model.Value, error) { |
| 33 | ctx = WithExecutorID(ctx, "callFnExpr") |
| 34 | args, err := prepareArgs(ctx, options, data, argsE) |
| 35 | if err != nil { |
| 36 | return nil, fmt.Errorf("error preparing arguments: %w", err) |
| 37 | } |
| 38 | |
| 39 | res, err := f(ctx, data, args) |
| 40 | if err != nil { |
| 41 | return nil, fmt.Errorf("error executing function: %w", err) |
| 42 | } |
| 43 | |
| 44 | return res, nil |
| 45 | }, nil |
| 46 | } |
| 47 | |
| 48 | var unstableFuncs = []string{ |
| 49 | "ignore", |
| 50 | } |
| 51 | |
| 52 | func callExprExecutor(options *Options, e ast.CallExpr) (expressionExecutor, error) { |
| 53 | if !options.Unstable && (slices.Contains(unstableFuncs, e.Function)) { |
| 54 | return nil, errors.New("unstable function are not enabled. to enable them use --unstable") |
| 55 | } |
| 56 | if f, ok := options.Funcs.Get(e.Function); ok { |
| 57 | res, err := callFnExecutor(f, e.Args) |
| 58 | if err != nil { |
| 59 | return nil, fmt.Errorf("error executing function %q: %w", e.Function, err) |
| 60 | } |
| 61 | return res, nil |
| 62 | } |
| 63 | |
| 64 | return nil, fmt.Errorf("unknown function: %q", e.Function) |
| 65 | } |