forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
87 lines (75 loc) · 1.82 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
package table
import (
"fmt"
"io"
"github.com/jenkins-x/jx/pkg/util"
)
type Table struct {
Out io.Writer
Rows [][]string
ColumnWidths []int
ColumnAlign []int
}
func CreateTable(out io.Writer) Table {
return Table{
Out: out,
}
}
// Clear removes all rows while preserving the layout
func (t *Table) Clear() {
t.Rows = [][]string{}
}
// AddRow adds a new row to the table
func (t *Table) AddRow(col ...string) {
t.Rows = append(t.Rows, col)
}
func (t *Table) Render() {
// lets figure out the max widths of each column
for _, row := range t.Rows {
for ci, col := range row {
l := len(col)
t.ColumnWidths = ensureArrayCanContain(t.ColumnWidths, ci)
if l > t.ColumnWidths[ci] {
t.ColumnWidths[ci] = l
}
}
}
out := t.Out
for _, row := range t.Rows {
lastColumn := len(row) - 1
for ci, col := range row {
if ci > 0 {
fmt.Fprint(out, " ")
}
l := t.ColumnWidths[ci]
align := t.GetColumnAlign(ci)
if ci >= lastColumn && align != util.ALIGN_CENTER && align != util.ALIGN_RIGHT {
fmt.Fprint(out, col)
} else {
fmt.Fprint(out, util.Pad(col, " ", l, align))
}
}
fmt.Fprint(out, "\n")
}
}
// SetColumnsAligns sets the alignment of the columns
func (t *Table) SetColumnsAligns(colAligns []int) {
t.ColumnAlign = colAligns
}
// GetColumnAlign return the column alignment
func (t *Table) GetColumnAlign(i int) int {
t.ColumnAlign = ensureArrayCanContain(t.ColumnAlign, i)
return t.ColumnAlign[i]
}
// SetColumnAlign sets the column alignment for the given column index
func (t *Table) SetColumnAlign(i int, align int) {
t.ColumnAlign = ensureArrayCanContain(t.ColumnAlign, i)
t.ColumnAlign[i] = align
}
func ensureArrayCanContain(array []int, idx int) []int {
diff := idx + 1 - len(array)
for i := 0; i < diff; i++ {
array = append(array, 0)
}
return array
}