/
stringtable.go
107 lines (84 loc) · 1.97 KB
/
stringtable.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
package common
import (
"fmt"
"reflect"
"strings"
)
type StringTable struct {
cols [][]interface{}
NoHeader bool
Markdown bool
}
func NewStringTable() *StringTable {
return &StringTable{}
}
func (st *StringTable) Clear() {
st.cols = nil
}
func (st *StringTable) AddRow() {
st.cols = append(st.cols, make([]interface{}, 0))
}
func (st *StringTable) AddCol(txt interface{}) {
y := len(st.cols) - 1
st.cols[y] = append(st.cols[y], fmt.Sprintf("%v", txt))
}
func (st *StringTable) AddCols(txts ...interface{}) {
st.AddRow()
for _, txt := range txts {
val := reflect.ValueOf(txt)
if val.Type().Kind() == reflect.Slice || val.Type().Kind() == reflect.Array {
for i := 0; i < val.Len(); i++ {
st.AddCol(val.Index(i))
}
continue
}
st.AddCol(txt)
}
}
func (st *StringTable) rower(cols []interface{}, colLengths []int, cross bool) string {
line := strings.Builder{}
for x := 0; x < len(cols); x++ {
format := fmt.Sprintf("%%-%dv", colLengths[x])
if line.Len() > 0 {
if cross {
if st.Markdown {
line.WriteString(" | ")
} else {
line.WriteString("-+-")
}
} else {
line.WriteString(" | ")
}
}
line.WriteString(fmt.Sprintf(format, cols[x]))
}
txt := line.String()
if st.Markdown {
txt = "| " + txt + " |"
}
txt += "\n"
return txt
}
func (st *StringTable) String() string {
colLengths := make([]int, 0)
for y := 0; y < len(st.cols); y++ {
for len(colLengths) < len(st.cols[y]) {
colLengths = append(colLengths, 0)
}
for x := 0; x < len(st.cols[y]); x++ {
colLengths[x] = Max(colLengths[x], len(fmt.Sprintf("%v", st.cols[y][x])))
}
}
sb := strings.Builder{}
for y := 0; y < len(st.cols); y++ {
sb.WriteString(st.rower(st.cols[y], colLengths, false))
if y == 0 && !st.NoHeader {
sep := make([]interface{}, len(st.cols[0]))
for x := 0; x < len(sep); x++ {
sep[x] = strings.Repeat("-", colLengths[x])
}
sb.WriteString(st.rower(sep, colLengths, true))
}
}
return sb.String()
}