github.com/wtfutil/wtf@v0.43.0/modules/buildkite/pipelines_display_data.go (about) 1 package buildkite 2 3 import ( 4 "fmt" 5 "sort" 6 "strings" 7 ) 8 9 type pipelinesDisplayData struct { 10 buildsForPipeline map[string][]Build 11 orderedPipelines []string 12 } 13 14 func (data *pipelinesDisplayData) Content() string { 15 maxPipelineLength := getLongestLength(data.orderedPipelines) 16 17 str := "" 18 for _, pipeline := range data.orderedPipelines { 19 str += fmt.Sprintf("[white]%s", padRight(pipeline, maxPipelineLength)) 20 for _, build := range data.buildsForPipeline[pipeline] { 21 str += fmt.Sprintf(" [%s]%s[white]", buildColor(build.State), build.Branch) 22 } 23 str += "\n" 24 } 25 26 return str 27 } 28 29 func newPipelinesDisplayData(builds []Build) pipelinesDisplayData { 30 grouped := make(map[string][]Build) 31 32 for _, build := range builds { 33 if _, ok := grouped[build.Pipeline.Slug]; ok { 34 grouped[build.Pipeline.Slug] = append(grouped[build.Pipeline.Slug], build) 35 } else { 36 grouped[build.Pipeline.Slug] = []Build{} 37 grouped[build.Pipeline.Slug] = append(grouped[build.Pipeline.Slug], build) 38 } 39 } 40 41 orderedPipelines := make([]string, len(grouped)) 42 i := 0 43 for pipeline := range grouped { 44 orderedPipelines[i] = pipeline 45 i++ 46 } 47 sort.Strings(orderedPipelines) 48 49 name := func(b1, b2 *Build) bool { 50 return b1.Branch < b2.Branch 51 } 52 for _, builds := range grouped { 53 ByBuild(name).Sort(builds) 54 } 55 56 return pipelinesDisplayData{ 57 buildsForPipeline: grouped, 58 orderedPipelines: orderedPipelines, 59 } 60 } 61 62 type ByBuild func(b1, b2 *Build) bool 63 64 func (by ByBuild) Sort(builds []Build) { 65 sorter := &buildSorter{ 66 builds: builds, 67 by: by, 68 } 69 sort.Sort(sorter) 70 } 71 72 type buildSorter struct { 73 builds []Build 74 by func(b1, b2 *Build) bool 75 } 76 77 func (bs *buildSorter) Len() int { 78 return len(bs.builds) 79 } 80 81 func (bs *buildSorter) Swap(i, j int) { 82 bs.builds[i], bs.builds[j] = bs.builds[j], bs.builds[i] 83 } 84 85 func (bs *buildSorter) Less(i, j int) bool { 86 return bs.by(&bs.builds[i], &bs.builds[j]) 87 } 88 89 func getLongestLength(strs []string) int { 90 longest := 0 91 92 for _, str := range strs { 93 if len(str) > longest { 94 longest = len(str) 95 } 96 } 97 98 return longest 99 } 100 101 func padRight(text string, length int) string { 102 padLength := length - len(text) 103 104 if padLength <= 0 { 105 return text[:length] 106 } 107 108 return text + strings.Repeat(" ", padLength) 109 } 110 111 func buildColor(state string) string { 112 switch state { 113 case "passed": 114 return "green" 115 case "failed": 116 return "red" 117 default: 118 return "yellow" 119 } 120 }