/
result.go
111 lines (95 loc) · 2.09 KB
/
result.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
package controllers
import (
"encoding/json"
"fmt"
)
type ControllerResult struct {
HumanOutput *HumanOutput
MarshalableOutput interface{}
Error error
}
func NewControllerResult() *ControllerResult {
return &ControllerResult{
HumanOutput: NewHumanOutput(""),
}
}
func (r ControllerResult) Print(jsonFlag bool) error {
if r.Error != nil {
return r.Error
}
if jsonFlag {
data, _ := json.Marshal(r.MarshalableOutput)
fmt.Println(string(data))
} else {
fmt.Println(r.HumanOutput.value)
}
return nil
}
type HumanOutput struct {
value string
}
func NewHumanOutput(format string, a ...interface{}) *HumanOutput {
return &HumanOutput{
value: fmt.Sprintf(format, a...),
}
}
func (h *HumanOutput) AddLine(a string, a1 ...interface{}) {
if h.addNewLine() {
if len(a1) == 0 {
h.value = fmt.Sprintf("%v\n%s", h.value, a)
} else {
a1 = append([]interface{}{h.value}, a1...)
h.value = fmt.Sprintf("%v\n"+a, a1...)
}
} else {
h.value = fmt.Sprintf(a, a1...)
}
}
func (h *HumanOutput) AddMap(mapToAdd map[string]interface{}) {
i := 0
for k, v := range mapToAdd {
if i == 0 {
if h.addNewLine() {
h.value = NewHumanOutput("%s\n\n%s: %v", h.value, k, v).value
} else {
h.value = NewHumanOutput("%s%s: %v", h.value, k, v).value
}
} else {
h.value = NewHumanOutput("%s\n%s: %v", h.value, k, v).value
}
i++
}
}
func (h *HumanOutput) AddStringList(listToAdd []string) {
i := 0
for _, k := range listToAdd {
if i == 0 {
if h.addNewLine() {
h.value = NewHumanOutput("%s\n\n%v", h.value, k).value
} else {
h.value = NewHumanOutput("%v", k).value
}
} else {
h.value = NewHumanOutput("%s\n%v", h.value, k).value
}
i++
}
}
func (h *HumanOutput) AddList(listToAdd []interface{}) {
i := 0
for _, k := range listToAdd {
if i == 0 {
if h.addNewLine() {
h.value = NewHumanOutput("%s\n\n%v", h.value, k).value
} else {
h.value = NewHumanOutput("%v", k).value
}
} else {
h.value = NewHumanOutput("%s\n%v", h.value, k).value
}
i++
}
}
func (h *HumanOutput) addNewLine() bool {
return len(h.value) > 0
}