-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.go
100 lines (88 loc) · 1.7 KB
/
helpers.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
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"sync"
"time"
spin "github.com/tj/go-spin"
)
func outputMux(ctx context.Context, out *safeBuffer) (stdOut, stdErr *safeBuffer) {
stdOut = newSafeBuffer()
stdErr = newSafeBuffer()
logBuffer := func(buf io.Reader) {
t := time.NewTimer(time.Millisecond)
for {
select {
case <-ctx.Done():
return
case <-t.C:
s := bufio.NewScanner(buf)
for s.Scan() {
// optionally replace with reactive
// line-by-line logging or similar
fmt.Fprintln(out, s.Text())
}
t.Reset(defaultOutputPolling)
}
}
}
go logBuffer(stdOut)
go logBuffer(stdErr)
return
}
type safeBuffer struct {
buf *bytes.Buffer
mux *sync.Mutex
}
func newSafeBuffer() *safeBuffer {
return &safeBuffer{
buf: new(bytes.Buffer),
mux: new(sync.Mutex),
}
}
func (b *safeBuffer) Read(p []byte) (n int, err error) {
b.mux.Lock()
n, err = b.buf.Read(p)
b.mux.Unlock()
return
}
func (b *safeBuffer) Write(p []byte) (n int, err error) {
b.mux.Lock()
n, err = b.buf.Write(p)
b.mux.Unlock()
return
}
func (b *safeBuffer) String() (s string) {
b.mux.Lock()
s = b.buf.String()
b.mux.Unlock()
return
}
func (b *safeBuffer) Bytes() (s []byte) {
b.mux.Lock()
s = b.buf.Bytes()
b.mux.Unlock()
return
}
func spinWith(label string) (func(), <-chan struct{}) {
s := spin.New()
ctx, cancelFn := context.WithCancel(context.Background())
doneC := make(chan struct{})
go func() {
for {
select {
case <-ctx.Done():
fmt.Printf("\r \033[36m%s\033[m done.\n", label)
close(doneC)
return
default:
fmt.Printf("\r \033[36m%s\033[m %s ", label, s.Next())
time.Sleep(100 * time.Millisecond)
}
}
}()
return cancelFn, doneC
}