| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncFlatten is a function that flattens a nested array by one level. |
| 11 | var FuncFlatten = NewFunc( |
| 12 | "flatten", |
| 13 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 14 | var input *model.Value |
| 15 | if len(args) == 1 { |
| 16 | input = args[0] |
| 17 | } else { |
| 18 | input = data |
| 19 | } |
| 20 | |
| 21 | if !input.IsSlice() { |
| 22 | return nil, fmt.Errorf("flatten expects an array, got %s", input.Type().String()) |
| 23 | } |
| 24 | |
| 25 | res := model.NewSliceValue() |
| 26 | if err := input.RangeSlice(func(i int, value *model.Value) error { |
| 27 | if value.IsSlice() { |
| 28 | return value.RangeSlice(func(j int, inner *model.Value) error { |
| 29 | return res.Append(inner) |
| 30 | }) |
| 31 | } |
| 32 | return res.Append(value) |
| 33 | }); err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 | |
| 37 | return res, nil |
| 38 | }, |
| 39 | ValidateArgsMax(1), |
| 40 | ) |