-
Notifications
You must be signed in to change notification settings - Fork 0
/
print.go
96 lines (81 loc) · 1.91 KB
/
print.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
92
93
94
95
96
package printer
import (
"fmt"
"io"
"strings"
"github.com/gosuri/uitable"
"github.com/mimuret/dpfctl/pkg/utils"
"github.com/mimuret/golang-iij-dpf/pkg/api"
)
type Printer interface {
Print(w io.Writer, obj api.Spec) error
}
func GetPrinter(cmdName, outType string) (Printer, error) {
var arg string
outputType := strings.SplitN(outType, "=", 2)
if len(outputType) == 2 {
arg = outputType[1]
}
switch outputType[0] {
case "yaml":
return &YAMLPrinter{}, nil
case "json":
return &JsonPrinter{}, nil
case "go-template":
return NewGoTemplatePrinter(arg)
}
return NewLinePrinter(cmdName)
}
type YAMLPrinter struct{}
func (p *YAMLPrinter) Print(w io.Writer, obj api.Spec) error {
bs, err := api.MarshalOutput(obj)
if err != nil {
return err
}
bs, err = utils.JsonToYaml(bs)
if err != nil {
return err
}
_, err = w.Write(bs)
return err
}
type JsonPrinter struct{}
func (p *JsonPrinter) Print(w io.Writer, obj api.Spec) error {
bs, err := api.MarshalOutput(obj)
if err != nil {
return err
}
_, err = w.Write(bs)
return err
}
func NewGoTemplatePrinter(templateStr string) (*LinePrinter, error) {
printer, err := NewGoTemplateBasePrinter(templateStr)
if err != nil {
return nil, err
}
return &LinePrinter{Printer: printer}, nil
}
type LinePrinter struct {
Printer HumanReadablePrinter
}
func NewLinePrinter(cmdName string) (*LinePrinter, error) {
printer := GetHumanReadablePrinter(cmdName)
if printer == nil {
return nil, fmt.Errorf("not support print %s", cmdName)
}
return &LinePrinter{Printer: printer}, nil
}
func (p *LinePrinter) Print(w io.Writer, obj api.Spec) error {
table := uitable.New()
table.AddRow(p.Printer.GetHeaders()...)
if l, ok := obj.(api.ListSpec); ok {
for i := 0; i < l.Len(); i++ {
table.AddRow(p.Printer.GetRow(l.Index(i))...)
}
} else {
table.AddRow(p.Printer.GetRow(obj)...)
}
_, err := w.Write(table.Bytes())
w.Write([]byte("\n"))
return err
}