Skip to content

Commit 9511861

Browse files
committed
Add not func
1 parent f2b3685 commit 9511861

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed

func.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ func standardFunctions() *FunctionCollection {
5858
LessThanFunc,
5959
AndFunc,
6060
OrFunc,
61+
NotFunc,
6162

6263
// Metadata
6364
MetadataFunc,

func_not.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package dasel
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
)
7+
8+
var NotFunc = BasicFunction{
9+
name: "not",
10+
runFn: func(c *Context, s *Step, args []string) (Values, error) {
11+
if err := requireXOrMoreArgs("filter", args, 1); err != nil {
12+
return nil, err
13+
}
14+
15+
input := c.inputValue(s)
16+
17+
runComparison := func(value Value, selector string) (bool, error) {
18+
gotValues, err := performSubQuery(c, value, selector)
19+
if err != nil {
20+
return false, err
21+
}
22+
23+
if len(gotValues) > 1 {
24+
return false, fmt.Errorf("not expects selector to return a single value")
25+
}
26+
27+
if len(gotValues) == 0 {
28+
return false, nil
29+
}
30+
31+
return IsTruthy(gotValues[0].Interface()), nil
32+
}
33+
34+
res := make(Values, 0)
35+
36+
for _, val := range input {
37+
for _, selector := range args {
38+
truthy, err := runComparison(val, selector)
39+
if err != nil {
40+
return nil, err
41+
}
42+
res = append(res, Value{Value: reflect.ValueOf(!truthy)})
43+
}
44+
}
45+
46+
return res, nil
47+
},
48+
}

func_not_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package dasel
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestNotFunc(t *testing.T) {
8+
9+
t.Run(
10+
"Single Equal",
11+
selectTest(
12+
"name.all().not(equal(key(),first))",
13+
map[string]interface{}{
14+
"name": map[string]interface{}{
15+
"first": "Tom",
16+
"last": "Wright",
17+
},
18+
},
19+
[]interface{}{
20+
false,
21+
true,
22+
},
23+
),
24+
)
25+
26+
t.Run(
27+
"Not Banned",
28+
selectTest(
29+
"all().filter(not(equal(banned,true))).name",
30+
[]map[string]interface{}{
31+
{
32+
"name": "Tom",
33+
"banned": true,
34+
},
35+
{
36+
"name": "Jess",
37+
"banned": false,
38+
},
39+
},
40+
[]interface{}{
41+
"Jess",
42+
},
43+
),
44+
)
45+
}

0 commit comments

Comments
 (0)