forked from wtfutil/wtf
/
pipelines_display_data.go
120 lines (97 loc) · 2.33 KB
/
pipelines_display_data.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
114
115
116
117
118
119
120
package buildkite
import (
"fmt"
"sort"
"strings"
)
type pipelinesDisplayData struct {
buildsForPipeline map[string][]Build
orderedPipelines []string
}
func (data *pipelinesDisplayData) Content() string {
maxPipelineLength := getLongestLength(data.orderedPipelines)
str := ""
for _, pipeline := range data.orderedPipelines {
str += fmt.Sprintf("[white]%s", padRight(pipeline, maxPipelineLength))
for _, build := range data.buildsForPipeline[pipeline] {
str += fmt.Sprintf(" [%s]%s[white]", buildColor(build.State), build.Branch)
}
str += "\n"
}
return str
}
func newPipelinesDisplayData(builds []Build) pipelinesDisplayData {
grouped := make(map[string][]Build)
for _, build := range builds {
if _, ok := grouped[build.Pipeline.Slug]; ok {
grouped[build.Pipeline.Slug] = append(grouped[build.Pipeline.Slug], build)
} else {
grouped[build.Pipeline.Slug] = []Build{}
grouped[build.Pipeline.Slug] = append(grouped[build.Pipeline.Slug], build)
}
}
orderedPipelines := make([]string, len(grouped))
i := 0
for pipeline := range grouped {
orderedPipelines[i] = pipeline
i++
}
sort.Strings(orderedPipelines)
name := func(b1, b2 *Build) bool {
return b1.Branch < b2.Branch
}
for _, builds := range grouped {
ByBuild(name).Sort(builds)
}
return pipelinesDisplayData{
buildsForPipeline: grouped,
orderedPipelines: orderedPipelines,
}
}
type ByBuild func(b1, b2 *Build) bool
func (by ByBuild) Sort(builds []Build) {
sorter := &buildSorter{
builds: builds,
by: by,
}
sort.Sort(sorter)
}
type buildSorter struct {
builds []Build
by func(b1, b2 *Build) bool
}
func (bs *buildSorter) Len() int {
return len(bs.builds)
}
func (bs *buildSorter) Swap(i, j int) {
bs.builds[i], bs.builds[j] = bs.builds[j], bs.builds[i]
}
func (bs *buildSorter) Less(i, j int) bool {
return bs.by(&bs.builds[i], &bs.builds[j])
}
func getLongestLength(strs []string) int {
longest := 0
for _, str := range strs {
if len(str) > longest {
longest = len(str)
}
}
return longest
}
func padRight(text string, length int) string {
padLength := length - len(text)
if padLength <= 0 {
return text[:length]
}
return text + strings.Repeat(" ", padLength)
}
func buildColor(state string) string {
switch state {
case "passed":
return "green"
case "failed":
return "red"
default:
return "yellow"
}
}