-
Notifications
You must be signed in to change notification settings - Fork 3
/
table.go
115 lines (97 loc) · 2.32 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
package table
import (
"fmt"
"io"
"math"
"github.com/mattn/go-runewidth"
"github.com/mgutz/ansi"
)
// Config is the
type Config struct {
ShowIndex bool // shows the index/row number as the first column
Color bool // use the color codes in the output
AlternateColors bool // alternate the colors when writing
TitleColorCode string // the ansi code for the title row
AltColorCodes []string // the ansi codes to alternate between
}
// DefaultConfig returns the default config for table, if its ever left null in a method this will be the one
// used to display the table
func DefaultConfig() *Config {
return &Config{
ShowIndex: true,
Color: true,
AlternateColors: true,
TitleColorCode: ansi.ColorCode("white+buf"),
AltColorCodes: []string{
"",
"\u001b[40m",
},
}
}
// Table is the struct used to define the structure, this can be used from a zero state, or inferred using the
// reflection based methods
type Table struct {
Headers []string
Rows [][]string
}
// WriteTable writes the defined table to the writer passed in
func (t Table) WriteTable(w io.Writer, c *Config) error {
if c == nil {
c = DefaultConfig()
}
spacing := t.spacing()
idLen := 2
if d := digits(len(t.Rows)); d > idLen {
idLen = d
}
if c.Color {
fmt.Fprint(w, c.TitleColorCode)
}
if c.ShowIndex {
fmt.Fprintf(w, " [%*v] ", idLen, "ID")
}
for i, header := range t.Headers {
fmt.Fprintf(w, " %s", runewidth.FillRight(header, spacing[i]))
}
if c.Color {
fmt.Fprint(w, ansi.Reset)
}
fmt.Fprintln(w)
color := c.Color && c.AlternateColors && len(c.AltColorCodes) > 1
for n, row := range t.Rows {
if color {
fmt.Fprint(w, c.AltColorCodes[n%len(c.AltColorCodes)])
}
if c.ShowIndex {
fmt.Fprintf(w, " [%*v] ", idLen, n)
}
for i, v := range row {
fmt.Fprintf(w, " %s", runewidth.FillRight(v, spacing[i]))
}
if color {
fmt.Fprint(w, ansi.Reset)
}
fmt.Fprintln(w)
}
return nil
}
func (t Table) spacing() []int {
s := make([]int, len(t.Headers))
for i, header := range t.Headers {
s[i] = runewidth.StringWidth(header)
}
for _, arr := range t.Rows {
for i, v := range arr {
if len(v) > s[i] {
s[i] = runewidth.StringWidth(v)
}
}
}
return s
}
func digits(n int) int {
if n == 0 {
return 1
}
return int(math.Log10(float64(n))) + 1
}