-
Notifications
You must be signed in to change notification settings - Fork 1
/
table.go
65 lines (53 loc) · 1.44 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
package printer
import (
"fmt"
"io"
"strings"
"github.com/SignorMercurio/limner/color"
)
type TablePrinter struct {
ColorPicker func(index int, column string) (color.Color, bool)
firstLine bool
}
func (tp *TablePrinter) Print(buf string, w io.Writer) {
for _, line := range strings.Split(buf, "\n") {
if tp.isHeader(line) {
fmt.Fprintln(w, color.Apply(line, headerColor))
tp.firstLine = false
continue
}
tp.printTable(w, line, columnColors)
}
}
func NewTablePrinter(colorPicker func(int, string) (color.Color, bool)) *TablePrinter {
return &TablePrinter{
ColorPicker: colorPicker,
firstLine: true,
}
}
// isHeader returns if a line is a table header
func (tp *TablePrinter) isHeader(line string) bool {
// --- --- also counts as headers
allCapital := strings.ToUpper(line) == line
return tp.firstLine || allCapital
}
// printTable prints a line to writer w as a row in the table
func (tp *TablePrinter) printTable(w io.Writer, line string, colors []color.Color) {
columns := spaces.Split(line, -1)
spaceIndices := spaces.FindAllStringIndex(line, -1)
for i, column := range columns {
c := colors[i&1]
if tp.ColorPicker != nil {
if cc, ok := tp.ColorPicker(i, column); ok {
c = cc
}
}
fmt.Fprint(w, color.Apply(column, c))
// Write the spaces in between
if i <= len(spaceIndices)-1 {
spaceIndex := spaceIndices[i]
fmt.Fprint(w, toSpaces(spaceIndex[1]-spaceIndex[0]))
}
}
fmt.Fprintln(w)
}