-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcombined_output.go
More file actions
58 lines (54 loc) · 948 Bytes
/
combined_output.go
File metadata and controls
58 lines (54 loc) · 948 Bytes
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
package main
import (
"io"
"os/exec"
"sync"
"github.com/pkg/errors"
)
func mergeReaders(rs ...io.Reader) io.Reader {
pr, pw := io.Pipe()
go func() {
defer pw.Close()
wg := sync.WaitGroup{}
wg.Add(len(rs))
for _, r := range rs {
go func(r io.Reader) {
defer wg.Done()
_, err := io.Copy(pw, r)
if err != nil {
pw.CloseWithError(err)
}
}(r)
}
wg.Wait()
}()
return pr
}
func combinedOutput(cmd *exec.Cmd, out io.Writer) error {
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
pr := mergeReaders(stdout, stderr)
err = cmd.Start()
if err != nil {
return err
}
_, err = io.Copy(out, pr)
if err != nil {
return err
}
err = cmd.Wait()
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
// ignore exit status != 0
} else {
return errors.Wrap(err, "error executing command")
}
}
return nil
}