-
Notifications
You must be signed in to change notification settings - Fork 218
/
output.go
76 lines (63 loc) · 1.11 KB
/
output.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 main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"github.com/olekukonko/tablewriter"
)
func newOutput(w io.Writer, format string) output {
switch format {
case "csv":
return NewCSVOutput(w)
default:
return NewTableOutput(w)
}
}
type output interface {
SetHeader([]string)
Append([]string)
Flush() error
}
func NewTableOutput(w io.Writer) *tableOutput {
t := tablewriter.NewWriter(w)
t.SetBorder(false)
t.SetAutoWrapText(false)
return &tableOutput{
Table: t,
}
}
type tableOutput struct {
*tablewriter.Table
}
func (t *tableOutput) Flush() error {
t.Table.Render()
return nil
}
func NewCSVOutput(w io.Writer) *csvOutput {
return &csvOutput{
w: csv.NewWriter(w),
}
}
type csvOutput struct {
w *csv.Writer
}
func (t *csvOutput) SetHeader(header []string) {
t.Append(header)
}
func (t *csvOutput) Append(row []string) {
if err := t.w.Write(row); err != nil {
panic(err)
}
}
func (t *csvOutput) Flush() error {
t.w.Flush()
return t.w.Error()
}
func prettyPrintJSON(v any) {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
}