forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
369 lines (318 loc) · 10.9 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package terminal
import (
"bytes"
"fmt"
"io"
"strings"
)
// PrintableTable is an implementation of the Table interface. It
// remembers the headers, the added rows, the column widths, and a
// number of other things.
type Table struct {
ui UI
headers []string
headerPrinted bool
columnWidth []int
rowHeight []int
rows [][]string
colSpacing string
transformer []Transformer
}
// Transformer is the type of functions used to modify the content of
// a table cell for actual display. For multi-line content of a cell
// the transformation is applied to each individual line.
type Transformer func(s string) string
// NewTable is the constructor function creating a new printable table
// from a list of headers. The table is also connected to a UI, which
// is where it will print itself to on demand.
func NewTable(headers []string) *Table {
pt := &Table{
headers: headers,
columnWidth: make([]int, len(headers)),
colSpacing: " ",
transformer: make([]Transformer, len(headers)),
}
// Standard colorization, column 0 is auto-highlighted as some
// name. Everything else has no transformation (== identity
// transform)
for i := range pt.transformer {
pt.transformer[i] = nop
}
if 0 < len(headers) {
pt.transformer[0] = TableContentHeaderColor
}
return pt
}
// NoHeaders disables the printing of the header row for the specified
// table.
func (t *Table) NoHeaders() {
// Fake the Print() code into the belief that the headers have
// been printed already.
t.headerPrinted = true
}
// SetTransformer specifies a string transformer to apply to the
// content of the given column in the specified table.
func (t *Table) SetTransformer(columnIndex int, tr Transformer) {
t.transformer[columnIndex] = tr
}
// Add extends the table by another row.
func (t *Table) Add(row ...string) {
t.rows = append(t.rows, row)
}
// PrintTo is the core functionality for printing the table, placing
// the formatted table into the writer given to it as argument. The
// exported Print() is just a wrapper around this which redirects the
// result into CF datastructures.
func (t *Table) PrintTo(result io.Writer) error {
t.rowHeight = make([]int, len(t.rows)+1)
rowIndex := 0
if !t.headerPrinted {
// row transformer header row
err := t.calculateMaxSize(transHeader, rowIndex, t.headers)
if err != nil {
return err
}
rowIndex++
}
for _, row := range t.rows {
// table is row transformer itself, for content rows
err := t.calculateMaxSize(t, rowIndex, row)
if err != nil {
return err
}
rowIndex++
}
rowIndex = 0
if !t.headerPrinted {
err := t.printRow(result, transHeader, rowIndex, t.headers)
if err != nil {
return err
}
t.headerPrinted = true
rowIndex++
}
for row := range t.rows {
err := t.printRow(result, t, rowIndex, t.rows[row])
if err != nil {
return err
}
rowIndex++
}
// Note, printing a table clears it.
t.rows = [][]string{}
return nil
}
// calculateMaxSize iterates over the collected rows of the specified
// table, and their strings, determining the height of each row (in
// lines), and the width of each column (in characters). The results
// are stored in the table for use by Print.
func (t *Table) calculateMaxSize(transformer rowTransformer, rowIndex int, row []string) error {
// Iterate columns
for columnIndex := range row {
// Truncate long row, ignore the additional fields.
if columnIndex >= len(t.headers) {
break
}
// Note that the length of the cell in characters is
// __not__ equivalent to its width. Because it may be
// a multi-line value. We have to split the cell into
// lines and check the width of each such fragment.
// The number of lines founds also goes into the row
// height.
lines := strings.Split(row[columnIndex], "\n")
height := len(lines)
if t.rowHeight[rowIndex] < height {
t.rowHeight[rowIndex] = height
}
for i := range lines {
// (**) See also 'printCellValue' (pCV). Here
// and there we have to apply identical
// transformations to the cell value to get
// matching cell width information. If they do
// not match then pCV may compute a cell width
// larger than the max width found here, a
// negative padding length from that, and
// subsequently return an error. What
// was further missing is trimming before
// entering the user-transform. Especially
// with color transforms any trailing space
// going in will not be removable for print.
//
// This happened for
// https://www.pivotaltracker.com/n/projects/892938/stories/117404629
value := trim(Decolorize(transformer.Transform(columnIndex, trim(lines[i]))))
width, err := visibleSize(value)
if err != nil {
return err
}
if t.columnWidth[columnIndex] < width {
t.columnWidth[columnIndex] = width
}
}
}
return nil
}
// printRow is responsible for the layouting, transforming and
// printing of the string in a single row
func (t *Table) printRow(result io.Writer, transformer rowTransformer, rowIndex int, row []string) error {
height := t.rowHeight[rowIndex]
// Compute the index of the last column as the min number of
// cells in the header and cells in the current row.
// Note: math.Min seems to be for float only :(
last := len(t.headers) - 1
lastr := len(row) - 1
if lastr < last {
last = lastr
}
// Note how we always print into a line buffer before placing
// the assembled line into the result. This allows us to trim
// superfluous trailing whitespace from the line before making
// it final.
if height <= 1 {
// Easy case, all cells in the row are single-line
line := &bytes.Buffer{}
for columnIndex := range row {
// Truncate long row, ignore the additional fields.
if columnIndex >= len(t.headers) {
break
}
err := t.printCellValue(line, transformer, columnIndex, last, row[columnIndex])
if err != nil {
return err
}
}
fmt.Fprintf(result, "%s\n", trim(string(line.Bytes())))
return nil
}
// We have at least one multi-line cell in this row.
// Treat it a bit like a mini-table.
// Step I. Fill the mini-table. Note how it is stored
// column-major, not row-major.
// [column][row]string
sub := make([][]string, len(t.headers))
for columnIndex := range row {
// Truncate long row, ignore the additional fields.
if columnIndex >= len(t.headers) {
break
}
sub[columnIndex] = strings.Split(row[columnIndex], "\n")
// (*) Extend the column to the full height.
for len(sub[columnIndex]) < height {
sub[columnIndex] = append(sub[columnIndex], "")
}
}
// Step II. Iterate over the rows, then columns to
// collect the output. This assumes that all
// the rows in sub are the same height. See
// (*) above where that is made true.
for rowIndex := range sub[0] {
line := &bytes.Buffer{}
for columnIndex := range sub {
err := t.printCellValue(line, transformer, columnIndex, last, sub[columnIndex][rowIndex])
if err != nil {
return err
}
}
fmt.Fprintf(result, "%s\n", trim(string(line.Bytes())))
}
return nil
}
// printCellValue pads the specified string to the width of the given
// column, adds the spacing bewtween columns, and returns the result.
func (t *Table) printCellValue(result io.Writer, transformer rowTransformer, col, last int, value string) error {
value = trim(transformer.Transform(col, trim(value)))
fmt.Fprint(result, value)
// Pad all columns, but the last in this row (with the size of
// the header row limiting this). This ensures that most of
// the irrelevant spacing is not printed. At the moment
// irrelevant spacing can only occur when printing a row with
// multi-line cells, introducing a physical short line for a
// long logical row. Getting rid of that requires fixing in
// printRow.
//
// Note how the inter-column spacing is also irrelevant for
// that last column.
if col < last {
// (**) See also 'calculateMaxSize' (cMS). Here and
// there we have to apply identical transformations to
// the cell value to get matching cell width
// information. If they do not match then we may here
// compute a cell width larger than the max width
// found by cMS, derive a negative padding length from
// that, and subsequently return an error. What was
// further missing is trimming before entering the
// user-transform. Especially with color transforms
// any trailing space going in will not be removable
// for print.
//
// This happened for
// https://www.pivotaltracker.com/n/projects/892938/stories/117404629
decolorizedLength, err := visibleSize(trim(Decolorize(value)))
if err != nil {
return err
}
padlen := t.columnWidth[col] - decolorizedLength
padding := strings.Repeat(" ", padlen)
fmt.Fprint(result, padding)
fmt.Fprint(result, t.colSpacing)
}
return nil
}
// rowTransformer is an interface behind which we can specify how to
// transform the strings of an entire row on a column-by-column basis.
type rowTransformer interface {
Transform(column int, s string) string
}
// transformHeader is an implementation of rowTransformer which
// highlights all columns as a Header.
type transformHeader struct{}
// transHeader holds a package-global transformHeader to prevent us
// from continuously allocating a literal of the type whenever we
// print a header row. Instead all tables use this value.
var transHeader = &transformHeader{}
// Transform performs the Header highlighting for transformHeader
func (th *transformHeader) Transform(column int, s string) string {
return HeaderColor(s)
}
// Transform makes a PrintableTable an implementation of
// rowTransformer. It performs the per-column transformation for table
// content, as specified during construction and/or overridden by the
// user of the table, see SetTransformer.
func (t *Table) Transform(column int, s string) string {
return t.transformer[column](s)
}
// nop is the identity transformation which does not transform the
// string at all.
func nop(s string) string {
return s
}
// trim is a helper to remove trailing whitespace from a string.
func trim(s string) string {
return strings.TrimRight(s, " \t")
}
// visibleSize returns the number of columns the string will cover
// when displayed in the terminal. This is the number of runes,
// i.e. characters, not the number of bytes it consists of.
func visibleSize(s string) (int, error) {
// This code re-implements the basic functionality of
// RuneCountInString to account for special cases. Namely
// UTF-8 characters taking up 3 bytes (**) appear as double-width.
//
// (**) I wonder if that is the set of characters outside of
// the BMP <=> the set of characters requiring surrogates (2
// slots) when encoded in UCS-2.
r := strings.NewReader(s)
var size int
for range s {
_, runeSize, err := r.ReadRune()
if err != nil {
return -1, fmt.Errorf("error when calculating visible size of: %s", s)
}
if runeSize == 3 {
size += 2 // Kanji and Katakana characters appear as double-width
} else {
size++
}
}
return size, nil
}