forked from rancher/cli
/
writer.go
88 lines (75 loc) · 1.53 KB
/
writer.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
package cmd
import (
"encoding/json"
"os"
"text/tabwriter"
"github.com/urfave/cli"
)
type TableWriter struct {
quite bool
HeaderFormat string
ValueFormat string
err error
headerPrinted bool
Writer *tabwriter.Writer
}
func NewTableWriter(values [][]string, ctx *cli.Context) *TableWriter {
t := &TableWriter{
Writer: tabwriter.NewWriter(os.Stdout, 10, 1, 3, ' ', 0),
}
t.HeaderFormat, t.ValueFormat = SimpleFormat(values)
if ctx.Bool("quiet") {
t.HeaderFormat = ""
t.ValueFormat = "{{.ID}}\n"
}
customFormat := ctx.String("format")
if customFormat == "json" {
t.HeaderFormat = ""
t.ValueFormat = "json"
} else if customFormat != "" {
t.ValueFormat = customFormat + "\n"
t.HeaderFormat = ""
}
return t
}
func (t *TableWriter) Err() error {
return t.err
}
func (t *TableWriter) writeHeader() {
if t.HeaderFormat != "" && !t.headerPrinted {
t.headerPrinted = true
t.err = printTemplate(t.Writer, t.HeaderFormat, struct{}{})
if t.err != nil {
return
}
}
}
func (t *TableWriter) Write(obj interface{}) {
if t.err != nil {
return
}
t.writeHeader()
if t.err != nil {
return
}
if t.ValueFormat == "json" {
content, err := json.Marshal(obj)
t.err = err
if t.err != nil {
return
}
_, t.err = t.Writer.Write(append(content, byte('\n')))
} else {
t.err = printTemplate(t.Writer, t.ValueFormat, obj)
}
}
func (t *TableWriter) Close() error {
if t.err != nil {
return t.err
}
t.writeHeader()
if t.err != nil {
return t.err
}
return t.Writer.Flush()
}