-
Notifications
You must be signed in to change notification settings - Fork 2
/
rules.go
93 lines (77 loc) · 1.8 KB
/
rules.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package scam_backoffice_rules
import (
_ "embed"
"encoding/json"
"fmt"
"regexp"
"github.com/labstack/gommon/log"
"gopkg.in/yaml.v3"
)
//go:embed default_rules.yaml
var defaultRules []byte
type TypeOfAction string
const (
Accept TypeOfAction = "accept"
Drop TypeOfAction = "drop"
MarkScam TypeOfAction = "mark_scam"
UnKnown TypeOfAction = "unknown"
)
type ConvertedRules struct {
Rules []struct {
Pattern string `yaml:"pattern" json:"pattern"`
Action TypeOfAction `yaml:"action" json:"action"`
} `yaml:"rules" json:"rules"`
}
type Rule struct {
Evaluate func(comment string) TypeOfAction
}
type Rules []Rule
func LoadRules(bytesOfRules []byte, yamlConverted bool) Rules {
var rules Rules
var convertedRules ConvertedRules
var err error
if yamlConverted {
err = yaml.Unmarshal(bytesOfRules, &convertedRules)
} else {
err = json.Unmarshal(bytesOfRules, &convertedRules)
}
if err != nil {
log.Panicf("Failed to parse rules: %v", err)
}
for _, inputRule := range convertedRules.Rules {
compiledRegexp, err := regexp.Compile(inputRule.Pattern)
if err != nil {
fmt.Printf("Failed to compile regexp for pattern %s: %v", inputRule.Pattern, err)
continue
}
var rule Rule
action := inputRule.Action
rule.Evaluate = func(comment string) TypeOfAction {
match := compiledRegexp.MatchString(comment)
if !match {
return UnKnown
}
return action
}
rules = append(rules, rule)
}
return rules
}
func CheckAction(rules Rules, comment string) TypeOfAction {
var err error
comment, err = NormalizeComment(comment)
if err != nil {
return Drop
}
action := UnKnown
for _, rule := range rules {
action = rule.Evaluate(comment)
if action != UnKnown {
break
}
}
return action
}
func GetDefaultRules() Rules {
return LoadRules(defaultRules, true)
}