-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.go
More file actions
65 lines (56 loc) · 1.3 KB
/
utils.go
File metadata and controls
65 lines (56 loc) · 1.3 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
package utils
// this is code taken from the v2 branch of github.com/deis/deis/tests/utils
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/exec"
)
// RunCommandWithStdoutStderr execs a command and returns its output.
func RunCommandWithStdoutStderr(cmd *exec.Cmd) (bytes.Buffer, bytes.Buffer, error) {
var stdout, stderr bytes.Buffer
stderrPipe, err := cmd.StderrPipe()
stdoutPipe, err := cmd.StdoutPipe()
cmd.Env = os.Environ()
if err != nil {
fmt.Println("error at io pipes")
}
err = cmd.Start()
if err != nil {
fmt.Println("error at command start")
}
go func() {
streamOutput(stdoutPipe, &stdout, os.Stdout)
}()
go func() {
streamOutput(stderrPipe, &stderr, os.Stderr)
}()
err = cmd.Wait()
if err != nil {
fmt.Println("error at command wait")
}
return stdout, stderr, err
}
// streamOutput from a source to a destination buffer while also printing
func streamOutput(src io.Reader, dst *bytes.Buffer, out io.Writer) error {
mw := io.MultiWriter(dst, out)
s := bufio.NewReader(src)
for {
var line []byte
line, err := s.ReadSlice('\n')
if err == io.EOF && len(line) == 0 {
break // done
}
if err == io.EOF {
return fmt.Errorf("Improper termination: %v", line)
}
if err != nil {
return err
}
// append to the buffer and out at once
mw.Write(line)
}
return nil
}