forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
combo_writer.go
57 lines (44 loc) · 907 Bytes
/
combo_writer.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
package ui
import (
"io"
"strings"
"sync"
)
type ComboWriter struct {
ui UI
uiLock sync.Mutex
onNewLine bool
}
type prefixedWriter struct {
w *ComboWriter
prefix string
}
func NewComboWriter(ui UI) *ComboWriter {
return &ComboWriter{ui: ui, onNewLine: true}
}
func (w *ComboWriter) Writer(prefix string) io.Writer {
return prefixedWriter{w: w, prefix: prefix}
}
func (s prefixedWriter) Write(bytes []byte) (int, error) {
if len(bytes) == 0 {
return 0, nil
}
s.w.uiLock.Lock()
defer s.w.uiLock.Unlock()
lines := strings.Split(string(bytes), "\n")
for i, line := range lines {
lastLine := i == len(lines)-1
if !lastLine || len(line) > 0 {
if s.w.onNewLine {
s.w.ui.PrintBlock(s.prefix)
}
s.w.ui.PrintBlock(line)
s.w.onNewLine = false
if !lastLine {
s.w.ui.PrintBlock("\n")
s.w.onNewLine = true
}
}
}
return len(bytes), nil
}