-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtable.go
60 lines (44 loc) · 930 Bytes
/
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
package stdcli
import (
"fmt"
"strings"
)
type Table struct {
Columns []string
Context *Context
Rows [][]string
}
func (t *Table) AddRow(row ...string) {
t.Rows = append(t.Rows, row)
}
func (t *Table) Print() error {
f := t.formatString()
t.Context.Writef(fmt.Sprintf("<h1>%s</h1>\n", f), interfaceSlice(t.Columns)...)
for _, r := range t.Rows {
t.Context.Writef(fmt.Sprintf("<value>%s</value>\n", f), interfaceSlice(r)...)
}
return nil
}
func (t *Table) formatString() string {
f := []string{}
ws := t.widths()
for _, w := range ws {
f = append(f, fmt.Sprintf("%%-%ds", w))
}
return strings.Join(f, " ")
}
func (t *Table) widths() []int {
w := make([]int, len(t.Columns))
for i, c := range t.Columns {
w[i] = len(stripTag(c))
for _, r := range t.Rows {
if len(r) > i {
if lri := len(stripTag(r[i])); lri > w[i] {
w[i] = lri
}
}
}
}
w[len(w)-1] = 0
return w
}