Debian Codegraph @

execution/func_split.go

raw symbols SCIP
1 package execution
2
3 import (
4 "context"
5 "fmt"
6 "strings"
7
8 "github.com/tomwright/dasel/v3/model"
9 )
10
11 // FuncSplit is a function that splits a string by a separator into an array.
12 var FuncSplit = NewFunc(
13 "split",
14 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
15 separator, err := args[0].StringValue()
16 if err != nil {
17 return nil, fmt.Errorf("split expects a string separator as the first argument: %w", err)
18 }
19
20 var input string
21 if len(args) == 2 {
22 input, err = args[1].StringValue()
23 if err != nil {
24 return nil, fmt.Errorf("split expects a string as the second argument: %w", err)
25 }
26 } else {
27 input, err = data.StringValue()
28 if err != nil {
29 return nil, fmt.Errorf("split expects data to be a string: %w", err)
30 }
31 }
32
33 parts := strings.Split(input, separator)
34
35 res := model.NewSliceValue()
36 for _, part := range parts {
37 if err := res.Append(model.NewStringValue(part)); err != nil {
38 return nil, fmt.Errorf("could not append split result: %w", err)
39 }
40 }
41
42 return res, nil
43 },
44 ValidateArgsMinMax(1, 2),
45 )