forked from Versent/unicreds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
77 lines (63 loc) · 1.51 KB
/
cli.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
package unicreds
import (
"encoding/csv"
"io"
"github.com/olekukonko/tablewriter"
)
const (
// TableFormatTerm format the table for a terminal session
TableFormatTerm = iota // 0
// TableFormatCSV format the table as CSV
TableFormatCSV // 1
)
// TableWriter enables writing of tables in a variety of formats
type TableWriter struct {
tableFormat int
headers []string
rows [][]string
wr io.Writer
}
// NewTable create a new table writer
func NewTable(wr io.Writer) *TableWriter {
return &TableWriter{wr: wr}
}
// SetHeaders set the column headers
func (tw *TableWriter) SetHeaders(headers []string) {
tw.headers = headers
}
// SetFormat set the format
func (tw *TableWriter) SetFormat(tableFormat int) {
tw.tableFormat = tableFormat
}
func (tw *TableWriter) Write(row []string) {
tw.rows = append(tw.rows, row)
}
// BulkWrite append an array of rows to the buffer
func (tw *TableWriter) BulkWrite(rows [][]string) {
tw.rows = append(tw.rows, rows...)
}
// Render render the table out to the supplied writer
func (tw *TableWriter) Render() error {
switch tw.tableFormat {
case TableFormatTerm:
table := tablewriter.NewWriter(tw.wr)
table.SetHeader(tw.headers)
table.AppendBulk(tw.rows)
table.Render()
case TableFormatCSV:
w := csv.NewWriter(tw.wr)
if err := w.Write(tw.headers); err != nil {
return err
}
for _, r := range tw.rows {
if err := w.Write(r); err != nil {
return err
}
}
w.Flush()
if err := w.Error(); err != nil {
return err
}
}
return nil
}