forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.go
97 lines (82 loc) · 2.46 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
package ui
import (
"fmt"
"strings"
"github.com/fatih/color"
"github.com/lunixbochs/vtclean"
runewidth "github.com/mattn/go-runewidth"
)
// DefaultTableSpacePadding is the default space padding in tables.
const DefaultTableSpacePadding = 3
// DisplayKeyValueTable outputs a matrix of strings as a table to UI.Out.
// Prefix will be prepended to each row and padding adds the specified number
// of spaces between columns. The final columns may wrap to multiple lines but
// will still be confined to the last column. Wrapping will occur on word
// boundaries.
func (ui *UI) DisplayKeyValueTable(prefix string, table [][]string, padding int) {
rows := len(table)
if rows == 0 {
return
}
var displayTable [][]string
for _, row := range table {
if len(row) > 0 {
displayTable = append(displayTable, row)
}
}
columns := len(displayTable[0])
if columns < 2 || !ui.IsTTY {
ui.DisplayNonWrappingTable(prefix, displayTable, padding)
return
}
ui.displayWrappingTableWithWidth(prefix, displayTable, padding)
}
// DisplayNonWrappingTable outputs a matrix of strings as a table to UI.Out.
// Prefix will be prepended to each row and padding adds the specified number
// of spaces between columns.
func (ui *UI) DisplayNonWrappingTable(prefix string, table [][]string, padding int) {
ui.terminalLock.Lock()
defer ui.terminalLock.Unlock()
if len(table) == 0 {
return
}
var columnPadding []int
rows := len(table)
columns := len(table[0])
for col := 0; col < columns; col++ {
var max int
for row := 0; row < rows; row++ {
if strLen := wordSize(table[row][col]); max < strLen {
max = strLen
}
}
columnPadding = append(columnPadding, max+padding)
}
for row := 0; row < rows; row++ {
fmt.Fprint(ui.Out, prefix)
for col := 0; col < columns; col++ {
data := table[row][col]
var addedPadding int
if col+1 != columns {
addedPadding = columnPadding[col] - wordSize(data)
}
fmt.Fprintf(ui.Out, "%s%s", data, strings.Repeat(" ", addedPadding))
}
fmt.Fprintf(ui.Out, "\n")
}
}
// DisplayTableWithHeader outputs a simple non-wrapping table with bolded
// headers.
func (ui *UI) DisplayTableWithHeader(prefix string, table [][]string, padding int) {
if len(table) == 0 {
return
}
for i, str := range table[0] {
table[0][i] = ui.modifyColor(str, color.New(color.Bold))
}
ui.DisplayNonWrappingTable(prefix, table, padding)
}
func wordSize(str string) int {
cleanStr := vtclean.Clean(str, false)
return runewidth.StringWidth(cleanStr)
}