/
table.go
109 lines (92 loc) · 2.1 KB
/
table.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
package terminal
import (
"fmt"
"io"
"strings"
"github.com/mattn/go-runewidth"
)
type Table interface {
Add(row ...string)
Print()
}
type PrintableTable struct {
writer io.Writer
headers []string
headerPrinted bool
maxSizes []int
rows [][]string //each row is single line
}
func NewTable(w io.Writer, headers []string) Table {
return &PrintableTable{
writer: w,
headers: headers,
maxSizes: make([]int, len(headers)),
}
}
func (t *PrintableTable) Add(row ...string) {
var maxLines int
var columns [][]string
for _, value := range row {
lines := strings.Split(value, "\n")
if len(lines) > maxLines {
maxLines = len(lines)
}
columns = append(columns, lines)
}
for i := 0; i < maxLines; i++ {
var row []string
for _, col := range columns {
if i >= len(col) {
row = append(row, "")
} else {
row = append(row, col[i])
}
}
t.rows = append(t.rows, row)
}
}
func (t *PrintableTable) Print() {
for _, row := range append(t.rows, t.headers) {
t.calculateMaxSize(row)
}
if t.headerPrinted == false {
t.printHeader()
t.headerPrinted = true
}
for _, line := range t.rows {
t.printRow(line)
}
t.rows = [][]string{}
}
func (t *PrintableTable) calculateMaxSize(row []string) {
for index, value := range row {
cellLength := runewidth.StringWidth(Decolorize(value))
if t.maxSizes[index] < cellLength {
t.maxSizes[index] = cellLength
}
}
}
func (t *PrintableTable) printHeader() {
output := ""
for col, value := range t.headers {
output = output + t.cellValue(col, HeaderColor(value))
}
fmt.Fprintln(t.writer, output)
}
func (t *PrintableTable) printRow(row []string) {
output := ""
for columnIndex, value := range row {
if columnIndex == 0 {
value = TableContentHeaderColor(value)
}
output = output + t.cellValue(columnIndex, value)
}
fmt.Fprintln(t.writer, output)
}
func (t *PrintableTable) cellValue(col int, value string) string {
padding := ""
if col < len(t.headers)-1 {
padding = strings.Repeat(" ", t.maxSizes[col]-runewidth.StringWidth(Decolorize(value)))
}
return fmt.Sprintf("%s%s ", value, padding)
}