-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain.go
73 lines (62 loc) · 1.32 KB
/
chain.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
package main
import (
"fmt"
"log"
"regexp"
"strings"
)
var (
policyRgx = regexp.MustCompile(`Chain (\w+) \(policy (\w+)\)`)
columnRgx = regexp.MustCompile(`\s+`)
commentRgx = regexp.MustCompile(`\/\*.+\*\/`)
errCouldNotParseCmdOut = "Unknown command output: %s"
)
type chainInfo struct {
ChainName string
PolicyName string
Rules []rule
}
func (ci chainInfo) CommentedRules() int {
count := 0
for _, rule := range ci.Rules {
if rule.HasComment() {
count++
}
}
return count
}
func (ci chainInfo) CountRules(target string) int {
count := 0
for _, rule := range ci.Rules {
if rule.Target == target {
count++
}
}
return count
}
func newChainInfo(stdout string) (*chainInfo, error) {
lines := strings.Split(stdout, "\n")
if len(lines) < 2 {
return nil, fmt.Errorf(errCouldNotParseCmdOut, stdout)
}
matches := policyRgx.FindAllStringSubmatch(stdout, -1)
if len(matches) != 1 {
return nil, fmt.Errorf(errCouldNotParseCmdOut, stdout)
}
info := &chainInfo{}
info.ChainName = matches[0][1]
info.PolicyName = matches[0][2]
info.Rules = make([]rule, 0)
for _, line := range lines[2:] {
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
r, err := newRuleFromLine(line)
if err != nil {
log.Println(err)
}
info.Rules = append(info.Rules, *r)
}
return info, nil
}