forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
144 lines (116 loc) · 2.26 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package table
import (
"fmt"
"io"
"sort"
)
func (t Table) AsRows() [][]Value {
rows := [][]Value{}
totalRows := 0
if len(t.Sections) > 0 {
for _, s := range t.Sections {
if s.FirstColumn != nil && len(s.FirstColumn.String()) > 0 {
if len(s.Rows) > 0 && len(s.Rows[0]) > 0 {
for i, _ := range s.Rows {
s.Rows[i][0] = s.FirstColumn
}
}
}
totalRows += len(s.Rows)
for _, r := range s.Rows {
rows = append(rows, r)
}
}
}
if len(t.Rows) > 0 {
totalRows += len(t.Rows)
for _, r := range t.Rows {
rows = append(rows, r)
}
}
// Fill in nils
for i, r := range rows {
for j, c := range r {
if c == nil {
rows[i][j] = ValueNone{}
}
}
}
// Sort all rows
sort.Sort(Sorting{t.SortBy, rows})
// Dedup first column
if !t.FillFirstColumn {
var lastVal Value
for _, r := range rows {
if lastVal == nil {
lastVal = r[0]
} else if lastVal.String() == r[0].String() {
r[0] = ValueString{"~"}
} else {
lastVal = r[0]
}
}
}
return rows
}
func (t Table) Print(w io.Writer) error {
err := t.printHeader(w)
if err != nil {
return err
}
if len(t.BackgroundStr) == 0 {
t.BackgroundStr = " "
}
if len(t.BorderStr) == 0 {
t.BorderStr = " "
}
writer := NewWriter(w, "-", t.BackgroundStr, t.BorderStr)
if len(t.HeaderVals) > 0 {
writer.Write(t.HeaderVals)
} else if len(t.Header) > 0 {
var headerVals []Value
for _, h := range t.Header {
headerVals = append(headerVals, ValueString{h})
}
writer.Write(headerVals)
}
rows := t.AsRows()
for _, row := range rows {
writer.Write(row)
}
err = writer.Flush()
if err != nil {
return err
}
return t.printFooter(w, len(rows))
}
func (t Table) printHeader(w io.Writer) error {
if len(t.Title) > 0 {
_, err := fmt.Fprintf(w, "%s\n\n", t.Title)
if err != nil {
return err
}
}
return nil
}
func (t Table) printFooter(w io.Writer, num int) error {
if len(t.Notes) > 0 {
_, err := fmt.Fprintf(w, "\n")
if err != nil {
return err
}
for _, n := range t.Notes {
_, err := fmt.Fprintf(w, "%s\n", n)
if err != nil {
return err
}
}
}
if len(t.Header) > 0 || len(t.HeaderVals) > 0 {
_, err := fmt.Fprintf(w, "\n%d %s\n", num, t.Content)
if err != nil {
return err
}
}
return nil
}