/
ui.go
234 lines (197 loc) · 6.54 KB
/
ui.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package ortfodb
import (
"fmt"
"io"
"os"
"regexp"
"strings"
"time"
"github.com/mattn/go-isatty"
"github.com/mitchellh/colorstring"
"github.com/xeipuuv/gojsonschema"
)
var LogFilePath string
var PrependDateToLogs = false
func logWriter(original io.Writer) io.Writer {
writer := original
if LogFilePath != "" {
logfile, err := os.OpenFile(LogFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err == nil {
writer = io.MultiWriter(writer, logfile)
}
}
if PrependDateToLogs {
writer = prependDateWriter{out: writer}
}
if progressBars != nil {
writer = progressBars.Bypass()
}
if !ShowingColors() {
writer = noAnsiCodesWriter{out: writer}
}
return writer
}
type prependDateWriter struct {
out io.Writer
}
func (w prependDateWriter) Write(p []byte) (n int, err error) {
return w.out.Write([]byte(
fmt.Sprintf("[%s] %s",
time.Now(),
strings.TrimLeft(string(p), " "),
)))
}
// noAnsiCodesWriter is an io.Writer that writes to the underlying writer, but strips ANSI color codes beforehand
type noAnsiCodesWriter struct {
out io.Writer
}
func (w noAnsiCodesWriter) Write(p []byte) (n int, err error) {
return w.out.Write(stripansicolors(p))
}
// Println is like fmt.Println but automatically strips ANSI color codes if colors are disabled
func Println(a ...interface{}) {
var writer io.Writer
writer = os.Stdout
if !ShowingColors() {
writer = noAnsiCodesWriter{out: writer}
}
fmt.Fprintln(writer, a...)
}
// Printf is like fmt.Printf but automatically strips ANSI color codes if colors are disabled
func Printf(format string, a ...interface{}) {
writer := logWriter(os.Stdout)
fmt.Fprintf(writer, format, a...)
}
// Print is like fmt.Print but automatically strips ANSI color codes if colors are disabled
func Print(a ...interface{}) {
writer := logWriter(os.Stdout)
fmt.Fprint(writer, a...)
}
func indentSubsequent(size int, text string) string {
indentation := strings.Repeat(" ", size)
return strings.ReplaceAll(text, "\n", "\n"+indentation)
}
func ExporterLogCustom(exporter Exporter, verb string, color string, message string, fmtArgs ...interface{}) {
if debugging() {
LogCustom(verb, color, fmt.Sprintf("[dim][bold](from exporter %s)[reset] %s", exporter.Name(), message), fmtArgs...)
} else {
LogCustom(verb, color, message, fmtArgs...)
}
}
func ExporterLogCustomNoFormatting(exporter Exporter, verb string, color string, message string) {
if debugging() {
LogCustomNoFormatting(verb, color, colorstring.Color("[dim][bold](from exporter "+exporter.Name()+")[reset] ")+message)
} else {
LogCustomNoFormatting(verb, color, message)
}
}
func LogCustom(verb string, color string, message string, fmtArgs ...interface{}) {
LogCustomNoFormatting(verb, color, colorstring.Color(fmt.Sprintf(message, fmtArgs...)))
}
// LogCustomNoColor logs a message without applying colorstring syntax to message.
func LogCustomNoColor(verb string, color string, message string, fmtArgs ...interface{}) {
LogCustomNoFormatting(verb, color, fmt.Sprintf(message, fmtArgs...))
}
func LogCustomNoFormatting(verb string, color string, message string) {
fmt.Fprintln(
logWriter(os.Stderr),
colorstring.Color(fmt.Sprintf("[bold][%s]%15s[reset]", color, verb))+
" "+
indentSubsequent(15+1, message),
)
}
// DisplayValidationErrors takes in a slice of json schema validation errors and displays them nicely to in the terminal.
func DisplayValidationErrors(errors []gojsonschema.ResultError, filename string, rootPath ...string) {
println("Your " + filename + " file is invalid. Here are the validation errors:\n")
for _, err := range errors {
/* FIXME: having a "." in the field name fucks up the display: eg:
- 0/media/fr-FR/2/online
Invalid type. Expected: boolean, given: string
if I replace fr-FR with fr.FR in the JSON:
↓
- 0/media/fr/FR/2/online
Invalid type. Expected: boolean, given: string
*/
colorstring.Println("- " + strings.ReplaceAll(displayValidationErrorFieldPath(err.Field(), rootPath...), ".", "[blue][bold]/[reset]"))
colorstring.Println(" [red]" + err.Description())
}
}
func displayValidationErrorFieldPath(field string, rootPath ...string) string {
if field == "(root)" {
field = ""
}
for i, fragment := range rootPath {
if strings.Contains(fragment, "/") {
rootPath[i] = fmt.Sprintf("%q", fragment)
}
}
return strings.Join(append(rootPath, field), "/")
}
// LogError logs non-fatal errors.
func LogError(message string, fmtArgs ...interface{}) {
LogCustom("Error", "red", message, fmtArgs...)
}
func DisplayError(msg string, err error, fmtArgs ...interface{}) {
LogError(formatErrors(fmt.Errorf(msg+": %w", append(fmtArgs, err)...)))
}
func DisplayWarning(msg string, err error, fmtArgs ...interface{}) {
LogWarning(formatErrors(fmt.Errorf(msg+": %w", append(fmtArgs, err)...)))
}
// LogInfo logs infos.
func LogInfo(message string, fmtArgs ...interface{}) {
LogCustom("Info", "blue", message, fmtArgs...)
}
// LogDebug logs debug information.
func LogDebug(message string, fmtArgs ...interface{}) {
if os.Getenv("DEBUG") == "" {
return
}
LogCustom("Debug", "magenta", message, fmtArgs...)
}
// LogDebugNoColor logs debug information without applying colorstring syntax to message.
func LogDebugNoColor(message string, fmtArgs ...interface{}) {
if os.Getenv("DEBUG") == "" {
return
}
LogCustomNoColor("Debug", "magenta", message, fmtArgs...)
}
// LogWarning logs warnings.
func LogWarning(message string, fmtArgs ...interface{}) {
LogCustom("Warning", "yellow", message, fmtArgs...)
}
func formatList(list []string, format string, separator string) string {
result := ""
for i, tag := range list {
sep := separator
if i == len(list)-1 {
sep = ""
}
result += fmt.Sprintf(format, tag) + sep
}
return result
}
// formatErrors returns a string where the error message was split on ': ', and each item is on a new line, indented once more than the previous line.
func formatErrors(err error) string {
causes := strings.Split(err.Error(), ": ")
output := ""
for i, cause := range causes {
output += strings.Repeat(" ", i) + cause
if i < len(causes)-1 {
output += "\n"
}
}
return output
}
func isInteractiveTerminal() bool {
return isatty.IsTerminal(os.Stdout.Fd()) && isatty.IsTerminal(os.Stderr.Fd())
}
func stripansicolors(b []byte) []byte {
// TODO find a way to do this without converting to string
s := string(b)
s = regexp.MustCompile(`\x1b\[[0-9;]*m`).ReplaceAllString(s, "")
return []byte(s)
}
// neutralizeColorstring strips colorstring syntax from s
func neutralizeColostring(s string) string {
return string(stripansicolors([]byte(colorstring.Color(s))))
}