github.com/wtfutil/wtf@v0.43.0/view/info_table.go (about) 1 package view 2 3 import ( 4 "bytes" 5 "sort" 6 7 "github.com/olekukonko/tablewriter" 8 ) 9 10 /* 11 An InfoTable is a two-column table of properties/values: 12 13 -------------------------- ------------------------------------------------- 14 PROPERTY VALUE 15 -------------------------- ------------------------------------------------- 16 CPUs 1 17 Created 2019-12-12T18:39:09Z 18 Disk 25 19 Features ipv6 20 Image 18.04.3 (LTS) x64 (Ubuntu) 21 Memory 1024 22 Region Toronto 1 (tor1) 23 -------------------------- ------------------------------------------------- 24 */ 25 26 // InfoTable contains the internal guts of an InfoTable 27 type InfoTable struct { 28 buf *bytes.Buffer 29 tblWriter *tablewriter.Table 30 } 31 32 // NewInfoTable creates and returns the stringified contents of a two-column table 33 func NewInfoTable(headers []string, dataMap map[string]string, colWidth0, colWidth1, tableHeight int) *InfoTable { 34 tbl := &InfoTable{ 35 buf: new(bytes.Buffer), 36 } 37 38 tbl.tblWriter = tablewriter.NewWriter(tbl.buf) 39 40 tbl.tblWriter.SetHeader(headers) 41 tbl.tblWriter.SetBorder(true) 42 tbl.tblWriter.SetCenterSeparator(" ") 43 tbl.tblWriter.SetColumnSeparator(" ") 44 tbl.tblWriter.SetRowSeparator("-") 45 tbl.tblWriter.SetAlignment(tablewriter.ALIGN_LEFT) 46 tbl.tblWriter.SetColMinWidth(0, colWidth0) 47 tbl.tblWriter.SetColMinWidth(1, colWidth1) 48 49 keys := []string{} 50 for key := range dataMap { 51 keys = append(keys, key) 52 } 53 54 sort.Strings(keys) 55 56 // Enumerate over the alphabetically-sorted keys to render the property values 57 for _, key := range keys { 58 tbl.tblWriter.Append([]string{key, dataMap[key]}) 59 } 60 61 // Pad the table with extra rows to push it to the bottom 62 paddingAmt := tableHeight - len(dataMap) - 1 63 if paddingAmt > 0 { 64 for i := 0; i < paddingAmt; i++ { 65 tbl.tblWriter.Append([]string{"", ""}) 66 } 67 } 68 69 return tbl 70 } 71 72 // Render returns the stringified version of the table 73 func (tbl *InfoTable) Render() string { 74 tbl.tblWriter.Render() 75 return tbl.buf.String() 76 }