/
tableviewer.go
285 lines (248 loc) · 6.91 KB
/
tableviewer.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
package tableviewer
import (
"io"
"log"
"os"
"strings"
"unicode"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/ts"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/gjsonpath"
"github.com/tidwall/gjson"
)
var Logger *log.Logger
var TextEllipsis = "…"
func init() {
Logger = log.New(io.Discard, "tableviewer", 0)
}
const (
RowModeTruncate = "truncate"
RowModeWrap = "wrap"
RowModeOverflow = "overflow" // default
)
// TableView renders a table in the terminal
type TableView struct {
Out io.Writer
Columns []string
ColumnWidths []int
MinColumnWidth int
MinEmptyValueColumnWidth int
MaxColumnWidth int
ColumnPadding int
Data gjson.Result
TableData [][]string
EnableColor bool
RowMode string
}
func (v *TableView) getValue(value gjson.Result) []string {
row := []string{}
for i, col := range v.Columns {
columnValue := strings.Trim(value.Get(gjsonpath.EscapePath(col)).Raw, "\"")
columnWidth := v.MaxColumnWidth
if i < len(v.ColumnWidths) {
columnWidth = v.ColumnWidths[i]
}
if columnWidth != 0 && len(columnValue) > columnWidth {
if v.RowMode == RowModeTruncate {
columnValue = columnValue[0:columnWidth-1] + TextEllipsis
} else if v.RowMode == RowModeWrap {
columnValue = WrapLine(columnValue, columnWidth, "")
}
}
row = append(row, columnValue)
}
return row
}
func (v *TableView) getWidth(defaultWidth int) int {
termSize, err := ts.GetSize()
if err != nil {
return defaultWidth
}
return termSize.Col() - 1
}
var TABLE_MAX_WIDTH = 120
func minmax(values []int) (min int, max int) {
for _, val := range values {
if val > max {
max = val
}
if val < min {
min = val
}
}
return
}
func (v *TableView) calculateColumnWidths(minWidth int, row []string) {
if len(v.ColumnWidths) == 0 {
maxTableWidth := v.getWidth(TABLE_MAX_WIDTH)
v.ColumnWidths = make([]int, 0)
columnSeparatorWidth := 3
tableEndBuffer := 3
usedWith := 0
curMinWidth := 0
columns := []string{}
// only include columns if they fit in the view
for i, columnValue := range row {
curMinWidth = minWidth
if columnValue == "" && v.MinEmptyValueColumnWidth > 0 {
curMinWidth = v.MinEmptyValueColumnWidth
}
Logger.Printf("iColumn: name=%s, cellWidth=%d, min=%d, col=%d",
v.Columns[i],
tablewriter.DisplayWidth(columnValue)+v.ColumnPadding,
curMinWidth+v.ColumnPadding,
tablewriter.DisplayWidth(v.Columns[i]),
)
_, colWidth := minmax([]int{
// only pad value (not column widths)
tablewriter.DisplayWidth(columnValue) + v.ColumnPadding,
curMinWidth + v.ColumnPadding,
tablewriter.DisplayWidth(v.Columns[i]),
})
// TODO: When the column value is empty, then use a dedicate empty width value instead
// of the minimum width value
if usedWith+colWidth+columnSeparatorWidth > maxTableWidth {
leftOver := maxTableWidth - usedWith - columnSeparatorWidth - tableEndBuffer
Logger.Printf("Left over: %d", leftOver)
if leftOver > curMinWidth {
v.ColumnWidths = append(v.ColumnWidths, leftOver)
columns = append(columns, v.Columns[i])
}
break
}
v.ColumnWidths = append(v.ColumnWidths, colWidth)
usedWith += colWidth + columnSeparatorWidth // overhead
if i < len(v.ColumnWidths) {
columns = append(columns, v.Columns[i])
}
}
v.Columns = columns
Logger.Printf("columns: %v\n", v.Columns)
Logger.Printf("column widths: %v\n", v.ColumnWidths)
Logger.Printf("Column summary: max=%d, used=%d", maxTableWidth, usedWith)
}
}
func (v *TableView) getHeaderRow() []string {
header := []string{}
for i, name := range v.Columns {
width := v.MinColumnWidth
if i < len(v.ColumnWidths) {
width = len(name)
}
header = append(header, strings.Repeat("-", width))
}
return header
}
// TransformData tranform the data so that is presentable in the terminal
func (v *TableView) TransformData(j []byte, property string) [][]string {
r := gjson.ParseBytes(j)
data := [][]string{}
if property != "" {
if v := r.Get(property); v.Exists() {
r = v
}
}
if r.IsArray() {
if len(r.Array()) > 0 {
v.calculateColumnWidths(v.MinColumnWidth, v.getValue(r.Array()[0]))
}
r.ForEach(func(key, value gjson.Result) bool {
Logger.Printf("parsing row: columns: %v", v.Columns)
data = append(data, v.getValue(value))
return true
})
} else if r.IsObject() {
v.calculateColumnWidths(v.MinColumnWidth, v.getValue(r))
Logger.Printf("parsing row: columns: %v", v.Columns)
data = append(data, v.getValue(r))
}
return data
}
func WrapLine(line string, width int, wrapPrefix string) string {
if len(line) <= width {
return line
}
name := strings.Builder{}
lineWidth := 0
for _, c := range line {
if unicode.IsSpace(c) {
// table writer will split on whitespace
lineWidth = -1
}
if lineWidth >= width {
name.WriteRune('\n')
if wrapPrefix != "" {
name.WriteString(wrapPrefix)
lineWidth = 1
} else {
lineWidth = 0
}
}
name.WriteRune(c)
lineWidth++
}
return name.String()
}
func (v *TableView) GetHeaders() (headers []string) {
for i, col := range v.Columns {
if i < len(v.ColumnWidths) {
headers = append(headers, WrapLine(col, v.ColumnWidths[i], ""))
}
}
return headers
}
// Render writes the json data to console in the form of a table
func (v *TableView) Render(jsonData []byte, withHeader bool) {
data := v.TransformData(jsonData, "")
if v.Out == nil {
v.Out = os.Stdout
}
table := tablewriter.NewWriter(v.Out)
isMarkdown := true
if withHeader {
table.SetHeader(v.GetHeaders())
if !isMarkdown {
table.Append(v.getHeaderRow())
}
}
maxWidth := 0
headerColors := []tablewriter.Colors{}
for i, width := range v.ColumnWidths {
headerColors = append(headerColors, tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor})
table.SetColMinWidth(i, width)
if width >= maxWidth {
maxWidth = width
}
}
table.SetColWidth(maxWidth)
if withHeader && v.EnableColor {
table.SetHeaderColor(headerColors...)
}
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
wrapEnabled := v.RowMode == RowModeWrap
if isMarkdown {
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
table.SetAutoFormatHeaders(false)
table.SetAutoWrapText(true)
} else {
table.SetAutoWrapText(wrapEnabled)
table.SetReflowDuringAutoWrap(wrapEnabled)
table.SetAutoFormatHeaders(false)
table.SetHeaderLine(false)
table.SetBorder(false)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowLine(false)
table.SetRowSeparator("-")
table.SetTablePadding(" ")
table.SetNoWhiteSpace(true)
}
// Enable row separator when wrapping cells to make it easier to read
table.SetRowSeparator("-")
table.SetAutoWrapText(wrapEnabled)
table.SetRowLine(wrapEnabled)
table.AppendBulk(data)
table.Render()
}