/
table.go
57 lines (50 loc) · 1.1 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
package text
import (
"fmt"
"io"
"strings"
"text/tabwriter"
)
var (
lineStyle = Reset
headerStyle = Bold
)
// Table wraps an instance of a tabwriter and provides helper methods to easily
// create a table, add a header, add rows and print to the writer.
type Table struct {
writer *tabwriter.Writer
}
// NewTable contructs a new Table.
func NewTable(w io.Writer) *Table {
return &Table{
writer: tabwriter.NewWriter(w, 0, 2, 2, ' ', 0),
}
}
// AddLine writes a new row to the table.
func (t *Table) AddLine(args ...interface{}) {
var b strings.Builder
for i := range args {
b.WriteString(lineStyle(`%v`))
if i+1 != len(args) {
b.WriteString("\t")
}
}
b.WriteString("\n")
fmt.Fprintf(t.writer, b.String(), args...)
}
// AddHeader writes a table header line.
func (t *Table) AddHeader(args ...interface{}) {
var b strings.Builder
for i := range args {
b.WriteString(headerStyle(`%s`))
if i+1 != len(args) {
b.WriteString("\t")
}
}
b.WriteString("\n")
fmt.Fprintf(t.writer, b.String(), args...)
}
// Print writes the table to the writer.
func (t *Table) Print() {
t.writer.Flush()
}