forked from scaleway/scaleway-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
227 lines (190 loc) · 5.17 KB
/
printer.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package core
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strings"
"github.com/scaleway/scaleway-cli/internal/human"
"gopkg.in/yaml.v2"
)
// Type defines an formatter format.
type PrinterType string
func (p PrinterType) String() string {
return string(p)
}
const (
// PrinterTypeJSON defines a JSON formatter.
PrinterTypeJSON = PrinterType("json")
// PrinterTypeYAML defines a YAML formatter.
PrinterTypeYAML = PrinterType("yaml")
// PrinterTypeHuman defines a human readable formatted formatter.
PrinterTypeHuman = PrinterType("human")
// Option to enable pretty output on json printer.
PrinterOptJSONPretty = "pretty"
)
type PrinterConfig struct {
OutputFlag string
Stdout io.Writer
Stderr io.Writer
}
// NewPrinter returns an initialized formatter corresponding to a given FormatterType.
func NewPrinter(config *PrinterConfig) (*Printer, error) {
printer := &Printer{
stdout: config.Stdout,
stderr: config.Stderr,
}
// First we parse OutputFlag to extract printerName and printerOpt (e.g json=pretty)
tmp := strings.SplitN(config.OutputFlag, "=", 2)
printerName := tmp[0]
printerOpt := ""
if len(tmp) > 1 {
printerOpt = tmp[1]
}
// We call the correct setup method depending on the printer type
switch printerName {
case PrinterTypeHuman.String():
setupHumanPrinter(printer, printerOpt)
case PrinterTypeJSON.String():
err := setupJSONPrinter(printer, printerOpt)
if err != nil {
return nil, err
}
case PrinterTypeYAML.String():
printer.printerType = PrinterTypeYAML
default:
return nil, fmt.Errorf("invalid output format: %s", printerName)
}
return printer, nil
}
func setupJSONPrinter(printer *Printer, opts string) error {
printer.printerType = PrinterTypeJSON
switch opts {
case PrinterOptJSONPretty:
printer.jsonPretty = true
case "":
default:
return fmt.Errorf("invalid option %s for json outout. Valid options are: %s", opts, PrinterOptJSONPretty)
}
return nil
}
func setupHumanPrinter(printer *Printer, opts string) {
printer.printerType = PrinterTypeHuman
if opts != "" {
printer.humanFields = strings.Split(opts, ",")
}
}
type Printer struct {
printerType PrinterType
stdout io.Writer
stderr io.Writer
// Enable pretty print on json output
jsonPretty bool
// Allow to select specifics column in a table with human printer
humanFields []string
}
func (p *Printer) Print(data interface{}, opt *human.MarshalOpt) error {
// No matter the printer type if data is a RawResult we should print it as is.
if rawResult, isRawResult := data.(RawResult); isRawResult {
_, err := p.stdout.Write(rawResult)
return err
}
var err error
switch p.printerType {
case PrinterTypeHuman:
err = p.printHuman(data, opt)
case PrinterTypeJSON:
err = p.printJSON(data)
case PrinterTypeYAML:
err = p.printYAML(data)
default:
err = fmt.Errorf("unknown format: %s", p.printerType)
}
if err != nil {
// Only try to print error using the printer if data is not already an error to avoid infinite recursion
if _, isError := data.(error); !isError {
return p.Print(err, nil)
}
return err
}
return nil
}
func (p *Printer) printHuman(data interface{}, opt *human.MarshalOpt) error {
_, isError := data.(error)
if !isError {
if opt == nil {
opt = &human.MarshalOpt{}
}
if len(p.humanFields) > 0 && reflect.TypeOf(data).Kind() != reflect.Slice {
return fmt.Errorf("list of fields for human output is only supported for commands that return a list")
}
if len(p.humanFields) > 0 {
opt.Fields = []*human.MarshalFieldOpt(nil)
for _, field := range p.humanFields {
opt.Fields = append(opt.Fields, &human.MarshalFieldOpt{
FieldName: field,
})
}
}
}
str, err := human.Marshal(data, opt)
switch e := err.(type) {
case *human.UnknownFieldError:
return &CliError{
Err: fmt.Errorf("unknown field '%s' in output options", e.FieldName),
Hint: fmt.Sprintf("Valid fields are: %s", strings.Join(e.ValidFields, ", ")),
}
case nil:
// Do nothing
default:
return err
}
// If human marshal return an empty string we avoid printing empty line
if str == "" {
return nil
}
if _, isError := data.(error); isError {
_, err = fmt.Fprintln(p.stderr, str)
} else {
_, err = fmt.Fprintln(p.stdout, str)
}
return err
}
func (p *Printer) printJSON(data interface{}) error {
_, implementMarshaler := data.(json.Marshaler)
err, isError := data.(error)
if isError && !implementMarshaler {
data = map[string]string{
"error": err.Error(),
}
}
writer := p.stdout
if isError {
writer = p.stderr
}
encoder := json.NewEncoder(writer)
if p.jsonPretty {
encoder.SetIndent("", " ")
}
// We handle special case to make sure that a nil slice is marshal as `[]`
if reflect.TypeOf(data).Kind() == reflect.Slice && reflect.ValueOf(data).IsNil() {
_, err := p.stdout.Write([]byte("[]\n"))
return err
}
return encoder.Encode(data)
}
func (p *Printer) printYAML(data interface{}) error {
_, implementMarshaler := data.(yaml.Marshaler)
err, isError := data.(error)
if isError && !implementMarshaler {
data = map[string]string{
"error": err.Error(),
}
}
writer := p.stdout
if isError {
writer = p.stderr
}
encoder := yaml.NewEncoder(writer)
return encoder.Encode(data)
}