-
Notifications
You must be signed in to change notification settings - Fork 69
/
output.go
113 lines (86 loc) · 1.88 KB
/
output.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
package output
import (
"strings"
"github.com/hokaccha/go-prettyjson"
"github.com/newrelic/newrelic-cli/internal/utils"
)
// globalOutput is the package level config of Output
var globalOutput *Output
// Format provides the list of output formats supported
type Format uint
const DefaultFormat = FormatJSON
const DefaultPretty = true
const DefaultTerminalWidth = 80
const (
FormatJSON Format = iota
FormatText
FormatYAML
//FormatCSV
)
var formatKeys = []Format{
FormatJSON,
FormatText,
FormatYAML,
}
var formatStrings = map[Format]string{
FormatJSON: "JSON",
FormatText: "Text",
FormatYAML: "YAML",
}
// Output is the main ref for the output package
type Output struct {
format Format
prettyPrint bool
terminalWidth int
jsonFormatter *prettyjson.Formatter
}
// String returns the string value of the format name
func (f Format) String() string {
if name, ok := formatStrings[f]; ok {
return name
}
return ""
}
func FormatOptions() string {
ret := make([]string, 0, len(formatKeys))
for _, k := range formatKeys {
ret = append(ret, formatStrings[k])
}
return strings.Join(ret, ", ")
}
func ParseFormat(name string) Format {
for k, v := range formatStrings {
if strings.EqualFold(name, v) {
return k
}
}
return DefaultFormat
}
func SetFormat(format Format) (err error) {
if err = ensureGlobalOutput(); err != nil {
return err
}
globalOutput.format = format
return nil
}
func SetPrettyPrint(pretty bool) (err error) {
if err = ensureGlobalOutput(); err != nil {
return err
}
globalOutput.prettyPrint = pretty
return nil
}
// ensureGlobalOutput is a helper function to make sure that
// we have a global instance of the outputter at all times
func ensureGlobalOutput() (err error) {
if globalOutput == nil {
globalOutput, err = New()
if err != nil {
return err
}
}
return nil
}
func init() {
utils.LogIfFatal(ensureGlobalOutput())
}