-
Notifications
You must be signed in to change notification settings - Fork 1
/
internal.go
93 lines (76 loc) · 1.91 KB
/
internal.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
package goexec
import (
"bytes"
"fmt"
"io"
"github.com/brad-jones/goprefix/v2/pkg/colorchooser"
"github.com/brad-jones/goprefix/v2/pkg/prefixer"
)
func prefixed(prefix string,
stdOut, stdErr io.Writer,
stdOutPipeR, stdErrPipeR io.Reader,
stdOutPipeW, stdErrPipeW io.WriteCloser,
fn func() error) error {
errorCh := make(chan error)
// Make the prefix colorful
p := prefixer.New(colorchooser.Sprint(prefix) + " | ")
// Run the function, pipeing all StdOut and StdErr to our scanners
go func() {
defer stdOutPipeW.Close()
defer stdErrPipeW.Close()
errorCh <- fn()
}()
// Prefix all StdOut
go func() {
if err := p.ReadFrom(stdOutPipeR).WriteTo(stdOut); err != nil {
errorCh <- fmt.Errorf("prefixing standard out: %s", err)
}
}()
// Prefix all StdErr
go func() {
if err := p.ReadFrom(stdErrPipeR).WriteTo(stdErr); err != nil {
errorCh <- fmt.Errorf("prefixing standard out: %s", err)
}
}()
// Catch any errors
if err := <-errorCh; err != nil {
return err
}
return nil
}
func buffered(stdOutPipeR, stdErrPipeR io.Reader,
stdOutPipeW, stdErrPipeW io.WriteCloser,
fn func() error) (out *StdBytes, err error) {
errorCh := make(chan error)
// Run the function, pipeing all StdOut and StdErr to our buffers
go func() {
defer stdOutPipeW.Close()
defer stdErrPipeW.Close()
errorCh <- fn()
}()
// Read all StdOut into our buffer
stdOutC := make(chan []byte)
go func() {
var buf bytes.Buffer
if _, err := io.Copy(&buf, stdOutPipeR); err != nil {
errorCh <- err
} else {
stdOutC <- buf.Bytes()
}
}()
// Read all StdErr into our buffer
stdErrC := make(chan []byte)
go func() {
var buf bytes.Buffer
if _, err := io.Copy(&buf, stdErrPipeR); err != nil {
errorCh <- err
} else {
stdErrC <- buf.Bytes()
}
}()
// Catch any errors
if err := <-errorCh; err != nil {
return &StdBytes{<-stdOutC, <-stdErrC}, err
}
return &StdBytes{<-stdOutC, <-stdErrC}, nil
}