-
Notifications
You must be signed in to change notification settings - Fork 46
/
table.go
91 lines (74 loc) · 1.8 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package terminal
import (
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
)
// Passed to UI.Table to provide a nicely formatted table.
type Table struct {
Headers []string
Rows [][]TableEntry
}
// Table creates a new Table structure that can be used with UI.Table.
func NewTable(headers ...string) *Table {
return &Table{
Headers: headers,
}
}
// TableEntry is a single entry for a table.
type TableEntry struct {
Value string
Color string
}
// Rich adds a row to the table.
func (t *Table) Rich(cols []string, colors []string) {
var row []TableEntry
for i, col := range cols {
if i < len(colors) {
row = append(row, TableEntry{Value: col, Color: colors[i]})
} else {
row = append(row, TableEntry{Value: col})
}
}
t.Rows = append(t.Rows, row)
}
// Table implements UI
func (u *basicUI) Table(tbl *Table, opts ...Option) {
// Build our config and set our options
cfg := &config{Writer: color.Output}
for _, opt := range opts {
opt(cfg)
}
table := tablewriter.NewWriter(cfg.Writer)
table.SetHeader(tbl.Headers)
table.SetBorder(false)
table.SetAutoWrapText(false)
for _, row := range tbl.Rows {
colors := make([]tablewriter.Colors, len(row))
entries := make([]string, len(row))
for i, ent := range row {
entries[i] = ent.Value
color, ok := colorMapping[ent.Color]
if ok {
colors[i] = tablewriter.Colors{color}
}
}
table.Rich(entries, colors)
}
table.Render()
}
const (
Yellow = YellowStyle
Green = GreenStyle
Red = RedStyle
Bold = BoldStyle
Default = DefaultStyle
)
var colorMapping = map[string]int{
Green: tablewriter.FgGreenColor,
Yellow: tablewriter.FgYellowColor,
Red: tablewriter.FgRedColor,
Bold: tablewriter.Bold,
Default: tablewriter.Normal,
}