| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncReplace is a function that replaces all occurrences of a substring with another string. |
| 11 | var FuncReplace = NewFunc( |
| 12 | "replace", |
| 13 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 14 | inputData := data |
| 15 | if len(args)%2 != 0 { |
| 16 | inputData = args[0] |
| 17 | args = args[1:] |
| 18 | } |
| 19 | |
| 20 | argStrings := make([]string, len(args)) |
| 21 | for i, arg := range args { |
| 22 | s, err := arg.StringValue() |
| 23 | if err != nil { |
| 24 | return nil, err |
| 25 | } |
| 26 | argStrings[i] = s |
| 27 | } |
| 28 | replacer := strings.NewReplacer(argStrings...) |
| 29 | |
| 30 | inputString, err := inputData.StringValue() |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | |
| 35 | outputString := replacer.Replace(inputString) |
| 36 | |
| 37 | return model.NewStringValue(outputString), nil |
| 38 | }, |
| 39 | ValidateArgsMin(2), |
| 40 | ) |