-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommon.go
More file actions
79 lines (63 loc) · 1.58 KB
/
common.go
File metadata and controls
79 lines (63 loc) · 1.58 KB
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
package ibk
import (
"bytes"
"context"
"math/rand"
"strings"
"sync"
"time"
)
// SyncedBuffer is a concurrent buffer writer. Can be used for combined
// stdout/stderr output and ensures that lines do not overlap.
type SyncedBuffer struct {
b bytes.Buffer
mu sync.Mutex
}
// Write writes to the buffer
func (w *SyncedBuffer) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.b.Write(p)
}
// String returns the buffer as a string
func (w *SyncedBuffer) String() string {
w.mu.Lock()
defer w.mu.Unlock()
return w.b.String()
}
// FirstLine returns the first line of the output trimmed of leading and trailing whitespace
func (w *SyncedBuffer) FirstLine() string {
w.mu.Lock()
defer w.mu.Unlock()
return strings.TrimSpace(strings.SplitN(w.b.String(), "\n", 1)[0])
}
// Reset clears the buffer
func (w *SyncedBuffer) Reset() {
w.mu.Lock()
defer w.mu.Unlock()
w.b.Reset()
}
const letterBytes = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var randSource = rand.New(rand.NewSource(time.Now().UnixNano()))
// RandomString generates a random string of length n that is not cryptographically safe
func RandomString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[randSource.Int63()%int64(len(letterBytes))]
}
return string(b)
}
// Wait waits for the context to be done or for the function to return
func Wait(ctx context.Context, f func() error) error {
done := make(chan error, 1)
go func() {
err := f()
done <- err
}()
select {
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
}
}