/
presenter.go
113 lines (92 loc) · 2.47 KB
/
presenter.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package table
import (
"fmt"
"io"
"sort"
"strconv"
"time"
"github.com/olekukonko/tablewriter"
"github.com/xeol-io/xeol/xeol/match"
"github.com/xeol-io/xeol/xeol/pkg"
"github.com/xeol-io/xeol/xeol/presenter/models"
)
var now = time.Now
// Presenter is a generic struct for holding fields needed for reporting
type Presenter struct {
matches match.Matches
packages []pkg.Package
}
// NewPresenter is a *Presenter constructor
func NewPresenter(pb models.PresenterConfig) *Presenter {
return &Presenter{
matches: pb.Matches,
packages: pb.Packages,
}
}
// Present creates a JSON-based reporting
func (pres *Presenter) Present(output io.Writer) error {
rows := make([][]string, 0)
columns := []string{"NAME", "VERSION", "EOL", "DAYS EOL", "TYPE"}
// Generate rows for matches
for m := range pres.matches.Enumerate() {
if m.Package.Name == "" {
continue
}
row, err := createRow(m)
if err != nil {
return err
}
rows = append(rows, row)
}
if len(rows) == 0 {
_, err := io.WriteString(output, "✅ no EOL software has been found\n")
return err
}
// sort by name, version, then type
sort.SliceStable(rows, func(i, j int) bool {
for col := 0; col < len(columns); col++ {
if rows[i][0] != rows[j][0] {
return rows[i][col] < rows[j][col]
}
}
return false
})
table := tablewriter.NewWriter(output)
table.SetHeader(columns)
table.SetAutoWrapText(false)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeaderLine(false)
table.SetBorder(false)
table.SetAutoFormatHeaders(true)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetTablePadding(" ")
table.SetNoWhiteSpace(true)
table.AppendBulk(rows)
table.Render()
return nil
}
func createRow(m match.Match) ([]string, error) {
daysEol, err := calculateDaysEol(m)
if err != nil {
return nil, err
}
if m.Cycle.EolBool {
return []string{m.Package.Name, m.Package.Version, "YES", "-", string(m.Package.Type)}, nil
}
return []string{m.Package.Name, m.Package.Version, m.Cycle.Eol, daysEol, string(m.Package.Type)}, nil
}
func calculateDaysEol(m match.Match) (string, error) {
today := now()
cycleEolDate, err := time.Parse("2006-01-02", m.Cycle.Eol)
if err != nil {
return "", fmt.Errorf("unable to parse EOL date for package %s: %w", m.Package.PURL, err)
}
daysEol := int((today.Sub(cycleEolDate).Hours() / 24))
if daysEol < 0 {
return "-", nil
}
return strconv.Itoa(daysEol), nil
}