Debian Codegraph @

execution/func_to_int.go

raw symbols SCIP
1 package execution
2
3 import (
4 "context"
5 "fmt"
6 "strconv"
7
8 "github.com/tomwright/dasel/v3/model"
9 )
10
11 // FuncToInt is a function that converts the given value to a string.
12 var FuncToInt = NewFunc(
13 "toInt",
14 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
15 switch args[0].Type() {
16 case model.TypeString:
17 stringValue, err := args[0].StringValue()
18 if err != nil {
19 return nil, err
20 }
21
22 i, err := strconv.ParseInt(stringValue, 0, 64)
23 if err != nil {
24 return nil, err
25 }
26
27 return model.NewIntValue(i), nil
28 case model.TypeInt:
29 return args[0], nil
30 case model.TypeFloat:
31 i, err := args[0].FloatValue()
32 if err != nil {
33 return nil, err
34 }
35 return model.NewIntValue(int64(i)), nil
36 case model.TypeBool:
37 i, err := args[0].BoolValue()
38 if err != nil {
39 return nil, err
40 }
41 if i {
42 return model.NewIntValue(1), nil
43 }
44 return model.NewIntValue(0), nil
45 default:
46 return nil, fmt.Errorf("cannot convert %s to int", args[0].Type())
47 }
48 },
49 ValidateArgsExactly(1),
50 )