-
Notifications
You must be signed in to change notification settings - Fork 4
/
rule.go
53 lines (45 loc) · 919 Bytes
/
rule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package ruler
import (
"bytes"
"fmt"
"github.com/thedevsaddam/gojsonq/v2"
)
type NotSupportedError struct {
Kind string
}
func (e *NotSupportedError) Error() string {
return fmt.Sprintf("rule does not apply to kind %s", e.Kind)
}
type Rule struct {
Selector string
ID string
Title string
Reason string
Link string
Kinds []string
Points int
Weight int
Advise int
Predicate func([]byte) int
}
// Eval executes the predicate if the kind matches the rule
func (r *Rule) Eval(json []byte) (int, error) {
jq := gojsonq.New().Reader(bytes.NewReader(json)).From("kind")
if jq.Error() != nil {
return 0, jq.Error()
}
kind := fmt.Sprintf("%s", jq.Get())
var match bool
for _, k := range r.Kinds {
if k == kind {
match = true
break
}
}
if match {
count := r.Predicate(json)
return count, nil
} else {
return 0, &NotSupportedError{Kind: kind}
}
}