forked from scaleway/scaleway-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprinter.go
More file actions
298 lines (253 loc) · 7.01 KB
/
printer.go
File metadata and controls
298 lines (253 loc) · 7.01 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package core
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strings"
"text/template"
"github.com/scaleway/scaleway-cli/internal/gofields"
"github.com/scaleway/scaleway-cli/internal/human"
"gopkg.in/yaml.v3"
)
// 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")
// PrinterTypeTemplate defines a go template to use to format output.
PrinterTypeTemplate = PrinterType("template")
// 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
case PrinterTypeTemplate.String():
err := setupTemplatePrinter(printer, printerOpt)
if err != nil {
return nil, err
}
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 setupTemplatePrinter(printer *Printer, opts string) error {
printer.printerType = PrinterTypeTemplate
if opts == "" {
return &CliError{
Err: fmt.Errorf("cannot use a template output with an empty template"),
Hint: `Try using golang template string: scw instance server list -o template="{{ .ID }} ☜(˚▽˚)☞ {{ .Name }}"`,
Details: `https://golang.org/pkg/text/template`,
}
}
t, err := template.New("OutputFormat").Parse(opts)
if err != nil {
return err
}
printer.template = t
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
// go template to use on template output
template *template.Template
// 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)
case PrinterTypeTemplate:
err = p.printTemplate(data)
default:
err = fmt.Errorf("unknown format: %s", p.printerType)
}
if err != nil {
// if the printer itself returns an error, don't try to format it just print it
_, err := fmt.Fprintln(p.stderr, err.Error())
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 p.printHuman(fmt.Errorf("list of fields for human output is only supported for commands that return a list"), nil)
}
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 p.printHuman(&CliError{
Err: fmt.Errorf("unknown field '%s' in output options", e.FieldName),
Hint: fmt.Sprintf("Valid fields are: %s", strings.Join(e.ValidFields, ", ")),
}, nil)
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 {
_, 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)
}
func (p *Printer) printTemplate(data interface{}) error {
writer := p.stdout
if _, isError := data.(error); isError {
return p.printHuman(data, nil)
}
dataValue := reflect.ValueOf(data)
switch dataValue.Type().Kind() {
// If we have a slice of value, we apply the template for each item
case reflect.Slice:
for i := 0; i < dataValue.Len(); i++ {
elemValue := dataValue.Index(i)
err := p.template.Execute(writer, elemValue)
if err != nil {
return p.printHuman(&CliError{
Err: err,
Message: "templating error",
Hint: fmt.Sprintf("Acceptable values are:\n - %s", strings.Join(gofields.ListFields(elemValue.Type()), "\n - ")),
}, nil)
}
_, err = writer.Write([]byte{'\n'})
if err != nil {
return err
}
}
default:
err := p.template.Execute(writer, data)
if err != nil {
return err
}
_, err = writer.Write([]byte{'\n'})
if err != nil {
return err
}
}
return nil
}