/
table.go
119 lines (95 loc) · 2.09 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
110
111
112
113
114
115
116
117
118
119
package ui
import (
"bufio"
"fmt"
"io"
"strings"
"github.com/fatih/color"
)
type Table struct {
Headers TableRow
Data Data
}
type Data []TableRow
type TableRow []TableCell
type TableCell struct {
Contents string
Color *color.Color
}
func (d Data) Len() int { return len(d) }
func (d Data) Swap(i int, j int) { d[i], d[j] = d[j], d[i] }
func (d Data) Less(i int, j int) bool {
return d[i][0].Contents < d[j][0].Contents
}
func (table Table) Render(dst io.Writer, isPrintHeader bool) error {
dst, isTTY := ForTTY(dst)
bdst := bufio.NewWriter(dst)
defer bdst.Flush()
columnWidths := map[int]int{}
if isPrintHeader || isTTY {
for i, column := range table.Headers {
columnWidth := len(column.Contents)
if columnWidth > columnWidths[i] {
columnWidths[i] = columnWidth
}
}
}
for _, row := range table.Data {
for i, column := range row {
columnWidth := len(column.Contents)
if columnWidth > columnWidths[i] {
columnWidths[i] = columnWidth
}
}
}
if (isPrintHeader || isTTY) && table.Headers != nil {
err := table.renderRow(bdst, table.Headers, columnWidths, isTTY)
if err != nil {
return err
}
bdst.Flush()
}
for _, row := range table.Data {
err := table.renderRow(bdst, row, columnWidths, isTTY)
if err != nil {
return err
}
bdst.Flush()
}
return nil
}
func (table Table) renderRow(dst io.Writer, row TableRow, widths map[int]int, isTTY bool) error {
for i, column := range row {
if column.Color != nil {
if isTTY {
column.Color.EnableColor()
} else {
column.Color.DisableColor()
}
}
contents := column.Contents
if column.Color != nil {
contents = column.Color.SprintFunc()(contents)
}
_, err := fmt.Fprintf(dst, "%s", contents)
if err != nil {
return err
}
paddingSize := widths[i] - len(column.Contents)
_, err = fmt.Fprintf(dst, strings.Repeat(" ", paddingSize))
if err != nil {
return err
}
if i+1 < len(widths) {
_, err := fmt.Fprintf(dst, " ")
if err != nil {
return err
}
}
}
_, err := fmt.Fprintln(dst)
if err != nil {
return err
}
return nil
}