@@ -24,24 +24,48 @@ import (
24
24
"github.com/sirupsen/logrus"
25
25
)
26
26
27
+ // OutputFormat is used to determine the output format
28
+ type OutputFormat int
29
+
30
+ const (
31
+ // Text means plain text format, suitable for ansi terminals
32
+ Text OutputFormat = iota
33
+ // JSON means JSON format
34
+ JSON
35
+ )
36
+
37
+ // Result is anything more complex than a sentence that needs to be printed
38
+ // for the user.
39
+ type Result interface {
40
+ fmt.Stringer
41
+ Data () interface {}
42
+ }
43
+
27
44
// Feedback wraps an io.Writer and provides an uniform API the CLI can use to
28
45
// provide feedback to the users.
29
46
type Feedback struct {
30
- out io.Writer
31
- err io.Writer
47
+ out io.Writer
48
+ err io.Writer
49
+ format OutputFormat
32
50
}
33
51
34
52
// New creates a Feedback instance
35
- func New (out , err io.Writer ) * Feedback {
53
+ func New (out , err io.Writer , format OutputFormat ) * Feedback {
36
54
return & Feedback {
37
- out : out ,
38
- err : err ,
55
+ out : out ,
56
+ err : err ,
57
+ format : format ,
39
58
}
40
59
}
41
60
42
61
// DefaultFeedback provides a basic feedback object to be used as default.
43
62
func DefaultFeedback () * Feedback {
44
- return New (os .Stdout , os .Stderr )
63
+ return New (os .Stdout , os .Stderr , Text )
64
+ }
65
+
66
+ // SetFormat can be used to change the output format at runtime
67
+ func (fb * Feedback ) SetFormat (f OutputFormat ) {
68
+ fb .format = f
45
69
}
46
70
47
71
// OutputWriter returns the underlying io.Writer to be used when the Print*
@@ -88,3 +112,16 @@ func (fb *Feedback) PrintJSON(v interface{}) {
88
112
fb .Print (string (d ))
89
113
}
90
114
}
115
+
116
+ // PrintResult is a convenient wrapper...
117
+ func (fb * Feedback ) PrintResult (res Result ) {
118
+ if fb .format == JSON {
119
+ if d , err := json .MarshalIndent (res .Data (), "" , " " ); err != nil {
120
+ fb .Errorf ("Error during JSON encoding of the output: %v" , err )
121
+ } else {
122
+ fb .Print (string (d ))
123
+ }
124
+ } else {
125
+ fb .Print (fmt .Sprintf ("%s" , res ))
126
+ }
127
+ }
0 commit comments