forked from heroku/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
393 lines (343 loc) · 8.15 KB
/
io.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"github.com/ansel1/merry"
"github.com/lunixbochs/vtclean"
rollbarAPI "github.com/stvp/rollbar"
"golang.org/x/crypto/ssh/terminal"
)
// Stdout is used to mock stdout for testing
var Stdout io.Writer = os.Stdout
// Stderr is to mock stderr for testing
var Stderr io.Writer = os.Stderr
var errLogger = newLogger(ErrLogPath)
// ExitFn is used to mock os.Exit
var ExitFn = os.Exit
// Debugging is HEROKU_DEBUG
var Debugging = isDebugging()
// DebuggingHeaders is HEROKU_DEBUG_HEADERS
var DebuggingHeaders = isDebuggingHeaders()
var swallowSigint = false
func newLogger(path string) *log.Logger {
err := os.MkdirAll(filepath.Dir(path), 0777)
must(err)
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
must(err)
return log.New(file, "", log.LstdFlags)
}
// Exit just calls os.Exit, but can be mocked out for testing
func Exit(code int) {
TriggerBackgroundUpdate()
currentAnalyticsCommand.RecordEnd(code)
ShowCursor()
ExitFn(code)
}
// Err just calls `fmt.Fprint(Stderr, a...)` but can be mocked out for testing.
func Err(a ...interface{}) {
fmt.Fprint(Stderr, a...)
Log(a...)
}
// Errf just calls `fmt.Fprintf(Stderr, a...)` but can be mocked out for testing.
func Errf(format string, a ...interface{}) {
fmt.Fprintf(Stderr, format, a...)
Logf(format, a...)
}
// Errln just calls `fmt.Fprintln(Stderr, a...)` but can be mocked out for testing.
func Errln(a ...interface{}) {
fmt.Fprintln(Stderr, a...)
Logln(a...)
}
// Print is used to replace `fmt.Print()` but can be mocked out for testing.
func Print(a ...interface{}) {
fmt.Fprint(Stdout, a...)
}
// Printf is used to replace `fmt.Printf()` but can be mocked out for testing.
func Printf(format string, a ...interface{}) {
fmt.Fprintf(Stdout, format, a...)
}
// Println is used to replace `fmt.Println()` but can be mocked out for testing.
func Println(a ...interface{}) {
fmt.Fprintln(Stdout, a...)
}
// Log is used to print debugging information
// It will be added to the logfile in ~/.cache/heroku/error.log or printed out if HEROKU_DEBUG is set.
func Log(a ...interface{}) {
errLogger.Print(vtclean.Clean(fmt.Sprint(a...), false))
}
// Logln is used to print debugging information
// It will be added to the logfile in ~/.cache/heroku/error.log
func Logln(a ...interface{}) {
Log(fmt.Sprintln(a...))
}
// Logf is used to print debugging information
// It will be added to the logfile in ~/.cache/heroku/error.log
func Logf(format string, a ...interface{}) {
Log(fmt.Sprintf(format, a...))
}
// Debugln is used to print debugging information
// It will be added to the logfile in ~/.cache/heroku/error.log and stderr if HEROKU_DEBUG is set.
func Debugln(a ...interface{}) {
Logln(a...)
if Debugging {
fmt.Fprintln(Stderr, a...)
}
}
// Debugf is used to print debugging information
// It will be added to the logfile in ~/.cache/heroku/error.log and stderr if HEROKU_DEBUG is set.
func Debugf(format string, a ...interface{}) {
Logf(format, a...)
if Debugging {
fmt.Fprintf(Stderr, format, a...)
}
}
// WarnIfError is a helper that prints out formatted error messages
// it will emit to rollbar
// it does not exit
func WarnIfError(err error) {
if err == nil {
return
}
err = merry.Wrap(err)
Warn(err.Error())
Debugln(merry.Details(err))
rollbar(err, "warning")
}
// Warn shows a message with excalamation points prepended to stderr
func Warn(msg string) {
if actionMsg != "" {
Errln(yellow(" !"))
}
prefix := " " + yellow(ErrorArrow) + " "
msg = strings.TrimSpace(msg)
msg = strings.Join(strings.Split(msg, "\n"), "\n"+prefix)
Errln(prefix + msg)
if actionMsg != "" {
Err(actionMsg + "...")
}
}
// Error shows a message with excalamation points prepended to stderr
func Error(msg string) {
if actionMsg != "" {
Errln(red(" !"))
}
prefix := " " + red(ErrorArrow) + " "
msg = strings.TrimSpace(msg)
msg = strings.Join(strings.Split(msg, "\n"), "\n"+prefix)
Errln(prefix + msg)
}
// ExitWithMessage shows an error message then exits with status code 2
// It does not emit to rollbar
func ExitWithMessage(format string, a ...interface{}) {
currentAnalyticsCommand.Valid = false
Error(fmt.Sprintf(format, a...))
Exit(2)
}
// ErrorArrow is the triangle or bang that prefixes errors
var ErrorArrow = errorArrow()
func errorArrow() string {
if windows() {
return "!"
}
return "▸"
}
func must(err error) {
if err != nil {
panic(err)
}
}
// LogIfError logs out an error if one arises
func LogIfError(e error) {
if e != nil {
Debugln(e.Error())
Debugln(string(debug.Stack()))
rollbar(e, "info")
}
}
// ONE is the string 1
const ONE = "1"
func isDebugging() bool {
debug := strings.ToUpper(os.Getenv("HEROKU_DEBUG"))
if debug == "TRUE" || debug == ONE {
return true
}
return false
}
func isDebuggingHeaders() bool {
debug := strings.ToUpper(os.Getenv("HEROKU_DEBUG_HEADERS"))
if debug == "TRUE" || debug == ONE {
return true
}
return false
}
func yellow(s string) string {
if supportsColor() && !windows() {
return "\x1b[33m" + s + "\x1b[39m"
}
return s
}
func red(s string) string {
if supportsColor() && !windows() {
return "\x1b[31m" + s + "\x1b[39m"
}
return s
}
func green(s string) string {
if supportsColor() && !windows() {
return "\x1b[32m" + s + "\x1b[39m"
}
return s
}
func cyan(s string) string {
if supportsColor() && !windows() {
return "\x1b[36m" + s + "\x1b[39m"
}
return s
}
func windows() bool {
return runtime.GOOS == WINDOWS
}
func istty() bool {
return terminal.IsTerminal(int(os.Stdout.Fd()))
}
func supportsColor() bool {
if !istty() {
return false
}
for _, arg := range Args {
if arg == "--no-color" {
return false
}
}
if os.Getenv("COLOR") == "false" {
return false
}
if os.Getenv("TERM") == "dumb" {
return false
}
if config != nil && config.Color != nil && !*config.Color {
return false
}
return true
}
func plural(word string, count int) string {
if count == 1 {
return word
}
return word + "s"
}
// ShowCursor displays the cursor
func ShowCursor() {
if supportsColor() && !windows() {
Print("\u001b[?25h")
}
}
func hideCursor() {
if supportsColor() && !windows() {
Print("\u001b[?25l")
}
}
var actionMsg string
func action(msg, done string, fn func()) {
actionMsg = msg
Err(actionMsg + "...")
hideCursor()
fn()
actionMsg = ""
ShowCursor()
if done != "" {
Errln(" " + done)
}
}
func handleSignal(s os.Signal, fn func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, s)
go func() {
<-c
fn()
}()
}
func handlePanic() {
if crashing {
// if already crashing just let the error bubble
// or else potential fork-bomb
return
}
crashing = true
if rec := recover(); rec != nil {
err, ok := rec.(error)
if !ok {
err = merry.New(rec.(string))
}
err = merry.Wrap(err)
Error(err.Error())
Debugln(merry.Details(err))
rollbar(err, "error")
Exit(1)
}
}
func rollbar(err error, level string) {
if os.Getenv("TESTING") == ONE {
return
}
rollbarAPI.Platform = "client"
rollbarAPI.Token = "d40104ae6fa8477dbb6907370231d7d8"
rollbarAPI.Environment = Channel
rollbarAPI.ErrorWriter = nil
rollbarAPI.CodeVersion = GitSHA
var cmd string
if len(Args) > 1 {
cmd = Args[1]
}
fields := []*rollbarAPI.Field{
{"version", Version},
{"os", runtime.GOOS},
{"arch", runtime.GOARCH},
{"command", cmd},
}
rollbarAPI.Error(level, err, fields...)
rollbarAPI.Wait()
}
func readJSON(obj interface{}, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
return json.NewDecoder(f).Decode(&obj)
}
func saveJSON(obj interface{}, path string) error {
data, err := json.MarshalIndent(obj, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(path, data, 0644)
}
// truncates the beginning of a file
func truncate(path string, n int) {
f, err := os.Open(path)
if err != nil {
LogIfError(err)
return
}
scanner := bufio.NewScanner(f)
lines := make([]string, 0, n+1)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
lines = append(lines, scanner.Text())
if len(lines) > n {
lines = lines[1:]
}
}
lines = append(lines, "")
ioutil.WriteFile(path, []byte(strings.Join(lines, "\n")), 0644)
}