Repository navigation
Expand file tree
/
Copy pathtabularize.go
More file actions
98 lines (91 loc) · 2.16 KB
/
Copy pathtabularize.go
File metadata and controls
98 lines (91 loc) · 2.16 KB
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
package tabularize
import (
"strings"
)
type Table struct {
useColumnSeparators bool
useHeaderSeparator bool
usePadding bool
useRowSeparators bool
useTableBorders bool
}
func NewTable() *Table {
return &Table{
useColumnSeparators: true,
useHeaderSeparator: true,
usePadding: true,
useTableBorders: false,
useRowSeparators: false,
}
}
// find the max length of each column
func maxLengths(data [][]string) []int {
maxLengths := make([]int, len(data[0]))
for _, row := range data {
for i, col := range row {
if len(col) > maxLengths[i] {
maxLengths[i] = len(col)
}
}
}
return maxLengths
}
func (t *Table) horizontalSeparator(sb *strings.Builder, maxLengths []int) {
if t.useTableBorders {
sb.WriteString("+")
}
for col, length := range maxLengths {
if t.usePadding {
length += 2
}
sb.WriteString(strings.Repeat("-", length))
if !(col == len(maxLengths)-1) || t.useTableBorders {
sb.WriteString("+")
}
}
sb.WriteString("\n")
}
func (t *Table) padCell(cell string, maxLength int) string {
pad := ""
if t.usePadding {
pad = " "
}
return pad + cell + strings.Repeat(" ", maxLength-len(cell)) + pad
}
// Tabluarize takes a 2D slice of strings and returns a string
// representation of the data in a table format.
func (t *Table) Render(data [][]string) string {
if len(data) == 0 {
return ""
}
var sb strings.Builder
maxLengths := maxLengths(data)
if t.useTableBorders {
t.horizontalSeparator(&sb, maxLengths)
}
for row, rowdata := range data {
if t.useTableBorders {
sb.WriteString("|")
}
for col, cell := range rowdata {
paddedCell := t.padCell(cell, maxLengths[col])
if col == len(maxLengths)-1 && !t.useTableBorders {
paddedCell = strings.TrimRight(paddedCell, " ")
}
sb.WriteString(paddedCell)
if t.useColumnSeparators && (col < len(maxLengths)-1 || t.useTableBorders) {
sb.WriteString("|")
} else if col < len(maxLengths)-1 {
sb.WriteString(" ")
}
}
sb.WriteString("\n")
if row == 0 && t.useHeaderSeparator {
t.horizontalSeparator(&sb, maxLengths)
}
}
if t.useTableBorders {
t.horizontalSeparator(&sb, maxLengths)
}
return sb.String()
}