This repository has been archived by the owner on May 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathtableprinter.go
467 lines (385 loc) · 13.7 KB
/
tableprinter.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package tableprinter
import (
"fmt"
"io"
"os"
"reflect"
"strings"
"github.com/kataras/tablewriter"
)
// Alignment is the alignment type (int).
//
// See `Printer#DefaultColumnAlignment` and `Printer#DefaultColumnAlignment` too.
type Alignment int
const (
// AlignDefault is the default alignment (0).
AlignDefault Alignment = iota
// AlignCenter is the center aligment (1).
AlignCenter
// AlignRight is the right aligment (2).
AlignRight
// AlignLeft is the left aligment (3).
AlignLeft
)
// Printer contains some information about the final table presentation.
// Look its `Print` function for more.
type Printer struct {
// out can not change during its work because the `acquire/release table` must work with only one output target,
// a new printer should be declared for a different output.
out io.Writer
AutoFormatHeaders bool
AutoWrapText bool
BorderTop, BorderLeft, BorderRight, BorderBottom bool
HeaderLine bool
HeaderAlignment Alignment
HeaderColors []tablewriter.Colors
HeaderBgColor int
HeaderFgColor int
RowLine bool
ColumnSeparator string
NewLine string
CenterSeparator string
RowSeparator string
RowCharLimit int
RowTextWrap bool // if RowCharLimit > 0 && RowTextWrap == true then wrap the line otherwise replace the trailing with "...".
DefaultAlignment Alignment // see `NumbersAlignment` too.
NumbersAlignment Alignment
RowLengthTitle func(int) bool
AllowRowsOnly bool // if true then `Print/Render` will print the headers even if parsed rows where no found. Useful for putting rows to a table manually.
table *tablewriter.Table
}
// Default is the default Table Printer.
var Default = Printer{
out: os.Stdout,
AutoFormatHeaders: true,
AutoWrapText: false,
BorderTop: false,
BorderLeft: false,
BorderRight: false,
BorderBottom: false,
HeaderLine: true,
HeaderAlignment: AlignLeft,
RowLine: false, /* it could be true as well */
ColumnSeparator: " ",
NewLine: "\n",
CenterSeparator: " ", /* it could be empty as well */
RowSeparator: tablewriter.ROW,
RowCharLimit: 60,
RowTextWrap: true,
DefaultAlignment: AlignLeft,
NumbersAlignment: AlignRight,
RowLengthTitle: func(rowsLength int) bool {
// if more than 3 then show the length of rows.
return rowsLength > 3
},
AllowRowsOnly: true,
}
// New creates and initializes a Printer with the default values based on the "w" target writer.
//
// See its `Print`, `PrintHeadList` too.
func New(w io.Writer) *Printer {
return &Printer{
out: w,
AutoFormatHeaders: Default.AutoFormatHeaders,
AutoWrapText: Default.AutoWrapText,
BorderTop: Default.BorderTop,
BorderLeft: Default.BorderLeft,
BorderRight: Default.BorderRight,
BorderBottom: Default.BorderBottom,
HeaderLine: Default.HeaderLine,
HeaderAlignment: Default.HeaderAlignment,
RowLine: Default.RowLine,
ColumnSeparator: Default.ColumnSeparator,
NewLine: Default.NewLine,
CenterSeparator: Default.CenterSeparator,
RowSeparator: Default.RowSeparator,
RowCharLimit: Default.RowCharLimit,
RowTextWrap: Default.RowTextWrap,
DefaultAlignment: Default.DefaultAlignment,
NumbersAlignment: Default.NumbersAlignment,
RowLengthTitle: Default.RowLengthTitle,
AllowRowsOnly: Default.AllowRowsOnly,
}
}
func (p *Printer) acquireTable() *tablewriter.Table {
table := p.table
if table == nil {
table = tablewriter.NewWriter(p.out)
// these properties can change until first `Print/Render` call.
table.SetAlignment(int(p.DefaultAlignment))
table.SetAutoFormatHeaders(p.AutoFormatHeaders)
table.SetAutoWrapText(p.AutoWrapText)
table.SetBorders(tablewriter.Border{Top: p.BorderTop, Left: p.BorderLeft, Right: p.BorderRight, Bottom: p.BorderBottom})
table.SetHeaderLine(p.HeaderLine)
table.SetHeaderAlignment(int(p.HeaderAlignment))
table.SetRowLine(p.RowLine)
table.SetColumnSeparator(p.ColumnSeparator)
table.SetNewLine(p.NewLine)
table.SetCenterSeparator(p.CenterSeparator)
table.SetRowSeparator(p.RowSeparator)
p.table = table
}
return table
}
func (p *Printer) calculateColumnAlignment(numbersColsPosition []int, size int) []int {
columnAlignment := make([]int, size)
for i := range columnAlignment {
columnAlignment[i] = int(p.DefaultAlignment)
for _, j := range numbersColsPosition {
if i == j {
columnAlignment[i] = int(p.NumbersAlignment)
break
}
}
}
return columnAlignment
}
// Render prints a table based on the rules of this "p" Printer.
//
// It's used to customize manually the parts of a table like the headers.
// If need to append a row after its creation you should create a new `Printer` instance by calling the `New` function
// and use its `RenderRow` instead, because the "w" writer is different on each package-level printer function.
//
// Returns the total amount of rows written to the table.
func Render(w io.Writer, headers []string, rows [][]string, numbersColsPosition []int, reset bool) int {
return New(w).Render(headers, rows, numbersColsPosition, reset)
}
// TODO: auto-remove headers and columns based on the user's terminal width (static),
// if `getTerminalWidth() == maxWidth` then don't bother, show the expected based on the `PrintXXX` func.
//
// Note that the font size of the terminal is customizable, so don't expect it to work precisely everywhere.
const maxWidth = 7680
func (p *Printer) calcWidth(k []string) (rowWidth int) {
for _, r := range k {
w := tablewriter.DisplayWidth(r) + len(p.ColumnSeparator) + len(p.CenterSeparator) + len(p.RowSeparator)
rowWidth += w
}
return
}
// it "works" but not always, need more research or just let the new `RowCharLimit` and `RowTextWrap` do their job to avoid big table on small terminal.
func (p *Printer) formatTableBasedOnWidth(headers []string, rows [][]string, fontSize int) ([]string, [][]string) {
totalWidthPreCalculated := p.calcWidth(headers)
var rowsWidth int
for _, rs := range rows {
w := p.calcWidth(rs)
if w > rowsWidth {
rowsWidth = w
}
}
if rowsWidth > totalWidthPreCalculated {
totalWidthPreCalculated = rowsWidth
}
pd := float64(fontSize/9) * 1.2
pdTrail := fontSize + fontSize/3
totalWidthPreCalculated = int(float64(totalWidthPreCalculated)*pd + float64(pdTrail))
termWidth := int(getTerminalWidth())
if totalWidthPreCalculated > termWidth {
dif := totalWidthPreCalculated - termWidth
difSpace := int(float64(fontSize) * 0.6)
// remove the last element of the rows and the last header.
if dif >= difSpace {
for idx, r := range rows {
rLastIdx := len(r) - 1
r = append(r[:rLastIdx], r[rLastIdx+1:]...)
rows[idx] = r
}
if len(headers) > 0 {
hLastIdx := len(headers) - 1
headers = append(headers[:hLastIdx], headers[hLastIdx+1:]...)
}
return p.formatTableBasedOnWidth(headers, rows, fontSize)
}
}
return headers, rows
}
// Render prints a table based on the rules of this "p" Printer.
//
// It's used to customize manually the parts of a table like the headers.
// It can be used side by side with the `RenderRow`, first and once `Render`, after and maybe many `RenderRow`.
//
// Returns the total amount of rows written to the table.
func (p *Printer) Render(headers []string, rows [][]string, numbersColsPosition []int, reset bool) int {
table := p.acquireTable()
if reset {
// ClearHeaders added on kataras/tablewriter version, Changes from the original repository:
// https://github.com/olekukonko/tablewriter/compare/master...kataras:master
table.ClearHeaders()
table.ClearRows()
p.HeaderColors = nil
}
// headers, rows = p.formatTableBasedOnWidth(headers, rows, 11)
if len(headers) > 0 {
if p.RowLengthTitle != nil && p.RowLengthTitle(len(rows)) {
headers[0] = fmt.Sprintf("%s (%d) ", headers[0], len(rows))
}
table.SetHeader(headers)
// colors must set after headers, depends on the number of headers.
if l := len(p.HeaderColors); l > 0 {
// dev set header color for each header, can panic if not match
table.SetHeaderColor(p.HeaderColors...)
} else if bg, fg := p.HeaderBgColor, p.HeaderFgColor; bg > 0 || fg > 0 {
colors := make([]tablewriter.Colors, len(headers))
for i := range headers {
colors[i] = tablewriter.Color(bg, fg)
}
p.HeaderColors = colors
table.SetHeaderColor(colors...)
}
} else if !p.AllowRowsOnly {
return 0 // if not allow to print anything without headers, then exit.
}
if p.RowCharLimit > 0 {
for i, rs := range rows {
rows[i] = p.rowText(rs)
}
}
table.AppendBulk(rows)
table.SetColumnAlignment(p.calculateColumnAlignment(numbersColsPosition, len(headers)))
table.Render()
return table.NumLines()
}
func cellText(cell string, charLimit int) string {
if strings.Contains(cell, "\n") {
if strings.HasSuffix(cell, "\n") {
cell = cell[0 : len(cell)-2]
if len(cell) > charLimit {
return cellText(cell, charLimit)
}
}
return cell
}
words := strings.Fields(strings.TrimSpace(cell))
if len(words) == 0 {
return cell
}
cell = words[0]
rem := charLimit - len(cell)
for _, w := range words[1:] {
if c := len(w) + 1; c <= rem {
cell += " " + w
rem -= c + 1 // including space.
continue
}
cell += "\n" + w
rem = charLimit - len(w)
}
return cell
}
func (p *Printer) rowText(row []string) []string {
if p.RowCharLimit <= 0 {
return row
}
for j, r := range row {
if len(r) <= p.RowCharLimit {
continue
}
row[j] = cellText(r, p.RowCharLimit)
}
return row
}
// RenderRow prints a row based on the same alignment rules to the last `Print` or `Render`.
// It can be used to live update the table.
//
// Returns the total amount of rows written to the table.
func (p *Printer) RenderRow(row []string, numbersColsPosition []int) int {
table := p.acquireTable()
row = p.rowText(row)
table.SetColumnAlignment(p.calculateColumnAlignment(numbersColsPosition, len(row)))
// RenderRowOnce added on kataras/tablewriter version, Changes from the original repository:
// https://github.com/olekukonko/tablewriter/compare/master...kataras:master
return table.RenderRowOnce(row)
}
// Print outputs whatever "in" value passed as a table to the "w",
// filters cna be used to control what rows can be visible or hidden.
// Usage:
// Print(os.Stdout, values, func(t MyStruct) bool { /* or any type, depends on the type(s) of the "t" */
// return t.Visibility != "hidden"
// })
//
// Returns the total amount of rows written to the table or
// -1 if printer was unable to find a matching parser or if headers AND rows were empty.
func Print(w io.Writer, in interface{}, filters ...interface{}) int {
return New(w).Print(in, filters...)
}
// Print outputs whatever "in" value passed as a table, filters can be used to control what rows can be visible and which not.
// Usage:
// Print(values, func(t MyStruct) bool { /* or any type, depends on the type(s) of the "t" */
// return t.Visibility != "hidden"
// })
//
// Returns the total amount of rows written to the table or
// -1 if printer was unable to find a matching parser or if headers AND rows were empty.
func (p *Printer) Print(in interface{}, filters ...interface{}) int {
v := indirectValue(reflect.ValueOf(in))
f := MakeFilters(v, filters...)
parser := WhichParser(v.Type())
if parser == nil {
return -1
}
headers, rows, nums := parser.Parse(v, f)
if len(headers) == 0 && len(rows) == 0 {
return -1
}
return p.Render(headers, rows, nums, true)
}
// PrintJSON prints the json-bytes as a table to the "w",
// filters cna be used to control what rows can be visible or hidden.
//
// Returns the total amount of rows written to the table or
// -1 if headers AND rows were empty.
func PrintJSON(w io.Writer, in []byte, filters ...interface{}) int {
return New(w).PrintJSON(in, filters...)
}
// PrintJSON prints the json-bytes as a table,
// filters cna be used to control what rows can be visible or hidden.
//
// Returns the total amount of rows written to the table or
// -1 if headers AND rows were empty.
func (p *Printer) PrintJSON(in interface{}, filters ...interface{}) int {
v := indirectValue(reflect.ValueOf(in))
f := MakeFilters(v, filters...)
if !v.IsValid() {
return -1
}
headers, rows, nums := JSONParser.Parse(v, f)
if len(headers) == 0 && len(rows) == 0 {
return -1
}
return p.Render(headers, rows, nums, true)
}
// PrintHeadList prints whatever "list" as a table to the "w" with a single header.
// The "list" should be a slice of something, however
// that list can also contain different type of values, even interface{}, the function will parse each of its elements differently if needed.
//
// It can be used when want to print a simple list of string, i.e names []string, a single column each time.
//
// Returns the total amount of rows written to the table.
func PrintHeadList(w io.Writer, list interface{}, header string, filters ...interface{}) int {
return New(w).PrintHeadList(list, header, filters...)
}
var emptyHeader StructHeader
// PrintHeadList prints whatever "list" as a table with a single header.
// The "list" should be a slice of something, however
// that list can also contain different type of values, even interface{}, the function will parse each of its elements differently if needed.
//
// It can be used when want to print a simple list of string, i.e names []string, a single column each time.
//
// Returns the total amount of rows written to the table.
func (p *Printer) PrintHeadList(list interface{}, header string, filters ...interface{}) int {
items := indirectValue(reflect.ValueOf(list))
if items.Kind() != reflect.Slice {
return 0
}
var (
rows [][]string
numbersColsPosition []int
)
for i, n := 0, items.Len(); i < n; i++ {
item := items.Index(i)
c, r := extractCells(i, emptyHeader, indirectValue(item), true)
rows = append(rows, r)
numbersColsPosition = append(numbersColsPosition, c...)
}
headers := []string{header}
return p.Render(headers, rows, numbersColsPosition, true)
}