/
stream.go
58 lines (51 loc) · 1.14 KB
/
stream.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
package testutil
import (
"bufio"
"fmt"
"io"
"os/exec"
"strings"
"time"
)
// Stream provides the ability of read the output of an executing process while
// it is still running
type Stream struct {
cmd *exec.Cmd
out io.ReadCloser
}
// Stop closes the stream and kills the process
func (s *Stream) Stop() {
s.out.Close()
s.cmd.Process.Kill()
}
// ReadUntil reads from the process output until specified number of lines has
// been reached, or until a timeout
func (s *Stream) ReadUntil(lineCount int, timeout time.Duration) ([]string, error) {
output := make([]string, 0)
lines := make(chan string)
timeoutAfter := time.After(timeout)
scanner := bufio.NewScanner(s.out)
stopSignal := false
go func() {
for scanner.Scan() {
lines <- scanner.Text()
if stopSignal {
close(lines)
return
}
}
}()
for {
select {
case <-timeoutAfter:
stopSignal = true
return output, fmt.Errorf("cmd [%s] Timed out trying to read %d lines", strings.Join(s.cmd.Args, " "), lineCount)
case line := <-lines:
output = append(output, line)
if len(output) >= lineCount {
stopSignal = true
return output, nil
}
}
}
}