-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.go
70 lines (61 loc) · 1.34 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
package hush
import (
"fmt"
"strings"
)
type table struct {
rows [][]string
align []columnAlign
}
type columnAlign int
const (
leftAlign columnAlign = iota
rightAlign
)
func (t *table) Align(alignment ...columnAlign) {
t.align = alignment
}
func (t *table) Add(columns ...interface{}) {
stringColumns := make([]string, len(columns))
for i := range columns {
stringColumns[i] = strings.TrimSpace(fmt.Sprint(columns[i]))
}
t.rows = append(t.rows, stringColumns)
}
func (t table) String() string {
var columnWidths []int
for _, row := range t.rows {
if len(columnWidths) < len(row) {
columnWidths = append(columnWidths, make([]int, len(row)-len(columnWidths))...)
}
for ix, col := range row {
if len(col) > columnWidths[ix] {
columnWidths[ix] = len(col)
}
}
}
const colSeparator = ' '
var s strings.Builder
for _, row := range t.rows {
for ix, col := range row {
align := leftAlign
if len(t.align) > ix {
align = t.align[ix]
}
switch align {
case rightAlign:
s.WriteString(padString(columnWidths[ix] - len(col)))
s.WriteString(col)
default:
s.WriteString(col)
s.WriteString(padString(columnWidths[ix] - len(col)))
}
s.WriteRune(colSeparator)
}
s.WriteRune('\n')
}
return s.String()
}
func padString(length int) string {
return fmt.Sprintf(fmt.Sprintf("%%%ds", length), "")
}