-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathoutput.go
92 lines (73 loc) · 1.33 KB
/
output.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
package shell
import (
"strings"
"sync"
)
// output contains the output after runnig a command.
type output struct {
stdout *outputStream
stderr *outputStream
// merged contains stdout and stderr merged into one stream.
merged *merged
}
func newOutput() *output {
m := new(merged)
return &output{
merged: m,
stdout: &outputStream{
merged: m,
},
stderr: &outputStream{
merged: m,
},
}
}
func (o *output) Stdout() string {
if o == nil {
return ""
}
return o.stdout.String()
}
func (o *output) Stderr() string {
if o == nil {
return ""
}
return o.stderr.String()
}
func (o *output) Combined() string {
if o == nil {
return ""
}
return o.merged.String()
}
type outputStream struct {
Lines []string
*merged
}
func (st *outputStream) WriteString(s string) (n int, err error) {
st.Lines = append(st.Lines, string(s))
return st.merged.WriteString(s)
}
func (st *outputStream) String() string {
if st == nil {
return ""
}
return strings.Join(st.Lines, "\n")
}
type merged struct {
// ensure that there are no parallel writes
sync.Mutex
Lines []string
}
func (m *merged) String() string {
if m == nil {
return ""
}
return strings.Join(m.Lines, "\n")
}
func (m *merged) WriteString(s string) (n int, err error) {
m.Lock()
defer m.Unlock()
m.Lines = append(m.Lines, string(s))
return len(s), nil
}