Debian Codegraph @

execution/func_index_of.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 // FuncIndexOf is a function that returns the index of the first occurrence of a substring.
12 // Returns -1 if the substring is not found.
13 var FuncIndexOf = NewFunc(
14 "indexOf",
15 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
16 var input string
17 var substr string
18 var err error
19
20 if len(args) == 2 {
21 input, err = args[0].StringValue()
22 if err != nil {
23 return nil, fmt.Errorf("indexOf expects a string as the first argument: %w", err)
24 }
25 substr, err = args[1].StringValue()
26 if err != nil {
27 return nil, fmt.Errorf("indexOf expects a string substring as the second argument: %w", err)
28 }
29 } else {
30 input, err = data.StringValue()
31 if err != nil {
32 return nil, fmt.Errorf("indexOf expects data to be a string: %w", err)
33 }
34 substr, err = args[0].StringValue()
35 if err != nil {
36 return nil, fmt.Errorf("indexOf expects a string substring as the first argument: %w", err)
37 }
38 }
39
40 return model.NewIntValue(int64(strings.Index(input, substr))), nil
41 },
42 ValidateArgsMinMax(1, 2),
43 )