Skip to content

Commit 6613d58

Browse files
committed
feat(printer): add support for YAML output
1 parent 2d4a8a2 commit 6613d58

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

internal/core/printer.go

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"strings"
99

1010
"github.com/scaleway/scaleway-cli/internal/human"
11+
"gopkg.in/yaml.v2"
1112
)
1213

1314
// Type defines an formatter format.
@@ -21,6 +22,9 @@ const (
2122
// PrinterTypeJSON defines a JSON formatter.
2223
PrinterTypeJSON = PrinterType("json")
2324

25+
// PrinterTypeYAML defines a YAML formatter.
26+
PrinterTypeYAML = PrinterType("yaml")
27+
2428
// PrinterTypeHuman defines a human readable formatted formatter.
2529
PrinterTypeHuman = PrinterType("human")
2630

@@ -58,7 +62,8 @@ func NewPrinter(config *PrinterConfig) (*Printer, error) {
5862
if err != nil {
5963
return nil, err
6064
}
61-
65+
case PrinterTypeYAML.String():
66+
printer.printerType = PrinterTypeYAML
6267
default:
6368
return nil, fmt.Errorf("invalid output format: %s", printerName)
6469
}
@@ -110,6 +115,8 @@ func (p *Printer) Print(data interface{}, opt *human.MarshalOpt) error {
110115
err = p.printHuman(data, opt)
111116
case PrinterTypeJSON:
112117
err = p.printJSON(data)
118+
case PrinterTypeYAML:
119+
err = p.printYAML(data)
113120
default:
114121
err = fmt.Errorf("unknown format: %s", p.printerType)
115122
}
@@ -199,3 +206,28 @@ func (p *Printer) printJSON(data interface{}) error {
199206

200207
return encoder.Encode(data)
201208
}
209+
210+
func (p *Printer) printYAML(data interface{}) error {
211+
_, implementMarshaler := data.(yaml.Marshaler)
212+
err, isError := data.(error)
213+
214+
if isError && !implementMarshaler {
215+
data = map[string]string{
216+
"error": err.Error(),
217+
}
218+
}
219+
220+
writer := p.stdout
221+
if isError {
222+
writer = p.stderr
223+
}
224+
encoder := yaml.NewEncoder(writer)
225+
226+
// We handle special case to make sure that a nil slice is marshal as `[]`
227+
if reflect.TypeOf(data).Kind() == reflect.Slice && reflect.ValueOf(data).IsNil() {
228+
_, err := p.stdout.Write([]byte("[]\n"))
229+
return err
230+
}
231+
232+
return encoder.Encode(data)
233+
}

0 commit comments

Comments
 (0)