Debian Codegraph @

execution/func_to_bool.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 // FuncToBool is a function that converts the given value to a bool.
12 var FuncToBool = NewFunc(
13 "toBool",
14 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
15 switch args[0].Type() {
16 case model.TypeBool:
17 b, err := args[0].BoolValue()
18 if err != nil {
19 return nil, err
20 }
21 return model.NewBoolValue(b), nil
22 case model.TypeString:
23 s, err := args[0].StringValue()
24 if err != nil {
25 return nil, err
26 }
27 switch strings.ToLower(s) {
28 case "true", "1", "yes":
29 return model.NewBoolValue(true), nil
30 case "false", "0", "no", "":
31 return model.NewBoolValue(false), nil
32 default:
33 return nil, fmt.Errorf("cannot convert string %q to bool", s)
34 }
35 case model.TypeInt:
36 i, err := args[0].IntValue()
37 if err != nil {
38 return nil, err
39 }
40 return model.NewBoolValue(i != 0), nil
41 case model.TypeFloat:
42 f, err := args[0].FloatValue()
43 if err != nil {
44 return nil, err
45 }
46 return model.NewBoolValue(f != 0), nil
47 case model.TypeNull:
48 return model.NewBoolValue(false), nil
49 default:
50 return nil, fmt.Errorf("cannot convert %s to bool", args[0].Type())
51 }
52 },
53 ValidateArgsExactly(1),
54 )