-
Notifications
You must be signed in to change notification settings - Fork 7
/
render.go
115 lines (99 loc) · 2.3 KB
/
render.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
package output
import (
"bytes"
"encoding/json"
"fmt"
"io"
"github.com/UpCloudLtd/upcloud-cli/v3/internal/clierrors"
)
const (
formatHuman string = "human"
formatJSON string = "json"
formatYAML string = "yaml"
)
func formats() []string {
return []string{
formatHuman,
formatJSON,
formatYAML,
}
}
// Render renders commandOutput to writer using cfg to configure the output.
func Render(writer io.Writer, outputFormat string, commandOutputs ...Output) (err error) {
var b []byte
switch outputFormat {
case formatHuman:
b, err = withNewline(toHuman(commandOutputs...))
case formatJSON:
b, err = withNewline(toJSON(commandOutputs...))
case formatYAML:
b, err = toYAML(commandOutputs...)
default:
err = fmt.Errorf("output format not valid: %s, valid formats: %v", outputFormat, formats())
}
if err != nil {
return err
}
_, err = writer.Write(b)
if err != nil {
return err
}
// Count failed outputs
failedCount := 0
for _, commandOutput := range commandOutputs {
if _, ok := commandOutput.(Error); ok {
failedCount++
}
}
if failedCount > 0 {
return &clierrors.CommandFailedError{
FailedCount: failedCount,
}
}
return nil
}
func toHuman(commandOutputs ...Output) ([]byte, error) {
buffer := new(bytes.Buffer)
for _, commandOutput := range commandOutputs {
outBytes, err := commandOutput.MarshalHuman()
if err != nil {
return nil, err
}
buffer.Write(outBytes)
}
return buffer.Bytes(), nil
}
func toJSON(commandOutputs ...Output) ([]byte, error) {
var output []byte
var jsonOutput []json.RawMessage
for _, commandOutput := range commandOutputs {
if _, ok := commandOutput.(None); !ok {
// don't marshal none outputs
outBytes, err := commandOutput.MarshalJSON()
if err != nil {
return nil, err
}
jsonOutput = append(jsonOutput, outBytes)
}
}
var err error
if len(jsonOutput) == 1 {
output, err = json.MarshalIndent(jsonOutput[0], "", " ")
} else if len(jsonOutput) > 0 {
output, err = json.MarshalIndent(jsonOutput, "", " ")
}
if err != nil {
return nil, err
}
return output, nil
}
func toYAML(commandOutputs ...Output) ([]byte, error) {
b, err := toJSON(commandOutputs...)
if err != nil {
return nil, err
}
return JSONToYAML(b)
}
func withNewline(b []byte, err error) ([]byte, error) {
return append(b, "\n"...), err
}