/
statistics.go
91 lines (73 loc) · 2.1 KB
/
statistics.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
package executor
import (
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"github.com/aquasecurity/defsec/pkg/scan"
"github.com/olekukonko/tablewriter"
)
type StatisticsItem struct {
RuleID string `json:"rule_id"`
RuleDescription string `json:"rule_description"`
Links []string `json:"links"`
Count int `json:"count"`
}
type Statistics []StatisticsItem
type StatisticsResult struct {
Result Statistics `json:"results"`
}
func SortStatistics(statistics Statistics) Statistics {
sort.Slice(statistics, func(i, j int) bool {
return statistics[i].Count > statistics[j].Count
})
return statistics
}
func (statistics Statistics) PrintStatisticsTable(format string, w io.Writer) error {
// lovely is the default so we keep it like that
if format != "lovely" && format != "markdown" && format != "json" {
return fmt.Errorf("you must specify only lovely, markdown or json format with --run-statistics")
}
sorted := SortStatistics(statistics)
if format == "json" {
result := StatisticsResult{Result: sorted}
val, err := json.MarshalIndent(result, "", " ")
if err != nil {
return err
}
_, _ = fmt.Fprintln(w, string(val))
return nil
}
table := tablewriter.NewWriter(w)
table.SetHeader([]string{"Rule ID", "Description", "Link", "Count"})
table.SetRowLine(true)
if format == "markdown" {
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
}
for _, item := range sorted {
table.Append([]string{item.RuleID,
item.RuleDescription,
strings.Join(item.Links, "\n"),
strconv.Itoa(item.Count)})
}
table.Render()
return nil
}
func AddStatisticsCount(statistics Statistics, result scan.Result) Statistics {
for i, statistic := range statistics {
if statistic.RuleID == result.Rule().LongID() {
statistics[i].Count += 1
return statistics
}
}
statistics = append(statistics, StatisticsItem{
RuleID: result.Rule().LongID(),
RuleDescription: result.Rule().Summary,
Links: result.Rule().Links,
Count: 1,
})
return statistics
}