forked from wtfutil/wtf
/
info_table.go
76 lines (62 loc) · 2.06 KB
/
info_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
package view
import (
"bytes"
"sort"
"github.com/olekukonko/tablewriter"
)
/*
An InfoTable is a two-column table of properties/values:
-------------------------- -------------------------------------------------
PROPERTY VALUE
-------------------------- -------------------------------------------------
CPUs 1
Created 2019-12-12T18:39:09Z
Disk 25
Features ipv6
Image 18.04.3 (LTS) x64 (Ubuntu)
Memory 1024
Region Toronto 1 (tor1)
-------------------------- -------------------------------------------------
*/
// InfoTable contains the internal guts of an InfoTable
type InfoTable struct {
buf *bytes.Buffer
tblWriter *tablewriter.Table
}
// NewInfoTable creates and returns the stringified contents of a two-column table
func NewInfoTable(headers []string, dataMap map[string]string, colWidth0, colWidth1, tableHeight int) *InfoTable {
tbl := &InfoTable{
buf: new(bytes.Buffer),
}
tbl.tblWriter = tablewriter.NewWriter(tbl.buf)
tbl.tblWriter.SetHeader(headers)
tbl.tblWriter.SetBorder(true)
tbl.tblWriter.SetCenterSeparator(" ")
tbl.tblWriter.SetColumnSeparator(" ")
tbl.tblWriter.SetRowSeparator("-")
tbl.tblWriter.SetAlignment(tablewriter.ALIGN_LEFT)
tbl.tblWriter.SetColMinWidth(0, colWidth0)
tbl.tblWriter.SetColMinWidth(1, colWidth1)
keys := []string{}
for key := range dataMap {
keys = append(keys, key)
}
sort.Strings(keys)
// Enumerate over the alphabetically-sorted keys to render the property values
for _, key := range keys {
tbl.tblWriter.Append([]string{key, dataMap[key]})
}
// Pad the table with extra rows to push it to the bottom
paddingAmt := tableHeight - len(dataMap) - 1
if paddingAmt > 0 {
for i := 0; i < paddingAmt; i++ {
tbl.tblWriter.Append([]string{"", ""})
}
}
return tbl
}
// Render returns the stringified version of the table
func (tbl *InfoTable) Render() string {
tbl.tblWriter.Render()
return tbl.buf.String()
}