Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(printer): add support for YAML output #1308

Merged
merged 5 commits into from
Aug 25, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion internal/core/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"github.com/scaleway/scaleway-cli/internal/human"
"gopkg.in/yaml.v2"
)

// Type defines an formatter format.
Expand All @@ -21,6 +22,9 @@ 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")

Expand Down Expand Up @@ -58,7 +62,8 @@ func NewPrinter(config *PrinterConfig) (*Printer, error) {
if err != nil {
return nil, err
}

case PrinterTypeYAML.String():
printer.printerType = PrinterTypeYAML
default:
return nil, fmt.Errorf("invalid output format: %s", printerName)
}
Expand Down Expand Up @@ -110,6 +115,8 @@ func (p *Printer) Print(data interface{}, opt *human.MarshalOpt) error {
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)
}
Expand Down Expand Up @@ -199,3 +206,28 @@ func (p *Printer) printJSON(data interface{}) error {

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)

// 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)
}