|
| 1 | +package utils |
| 2 | + |
| 3 | +// this is code taken from the v2 branch of github.com/deis/deis/tests/utils |
| 4 | + |
| 5 | +import ( |
| 6 | + "bufio" |
| 7 | + "bytes" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "os" |
| 11 | + "os/exec" |
| 12 | +) |
| 13 | + |
| 14 | +// RunCommandWithStdoutStderr execs a command and returns its output. |
| 15 | +func RunCommandWithStdoutStderr(cmd *exec.Cmd) (bytes.Buffer, bytes.Buffer, error) { |
| 16 | + var stdout, stderr bytes.Buffer |
| 17 | + stderrPipe, err := cmd.StderrPipe() |
| 18 | + stdoutPipe, err := cmd.StdoutPipe() |
| 19 | + |
| 20 | + cmd.Env = os.Environ() |
| 21 | + if err != nil { |
| 22 | + fmt.Println("error at io pipes") |
| 23 | + } |
| 24 | + |
| 25 | + err = cmd.Start() |
| 26 | + if err != nil { |
| 27 | + fmt.Println("error at command start") |
| 28 | + } |
| 29 | + |
| 30 | + go func() { |
| 31 | + streamOutput(stdoutPipe, &stdout, os.Stdout) |
| 32 | + }() |
| 33 | + go func() { |
| 34 | + streamOutput(stderrPipe, &stderr, os.Stderr) |
| 35 | + }() |
| 36 | + err = cmd.Wait() |
| 37 | + if err != nil { |
| 38 | + fmt.Println("error at command wait") |
| 39 | + } |
| 40 | + return stdout, stderr, err |
| 41 | +} |
| 42 | + |
| 43 | +// streamOutput from a source to a destination buffer while also printing |
| 44 | +func streamOutput(src io.Reader, dst *bytes.Buffer, out io.Writer) error { |
| 45 | + |
| 46 | + s := bufio.NewReader(src) |
| 47 | + |
| 48 | + for { |
| 49 | + var line []byte |
| 50 | + line, err := s.ReadSlice('\n') |
| 51 | + if err == io.EOF && len(line) == 0 { |
| 52 | + break // done |
| 53 | + } |
| 54 | + if err == io.EOF { |
| 55 | + return fmt.Errorf("Improper termination: %v", line) |
| 56 | + } |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + // append to the buffer |
| 62 | + dst.Write(line) |
| 63 | + |
| 64 | + // write to stdout/stderr also |
| 65 | + out.Write(line) |
| 66 | + } |
| 67 | + |
| 68 | + return nil |
| 69 | +} |
0 commit comments