-
Notifications
You must be signed in to change notification settings - Fork 715
/
util.go
45 lines (42 loc) · 900 Bytes
/
util.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
package fixtures
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
func Exec(name string, args ...string) (string, error) {
cmd := exec.Command(name, args...)
cmd.Env = os.Environ()
println(cmd.String())
output, err := runWithTimeout(cmd)
// Command completed before timeout. Print output and error if it exists.
if err != nil {
_, _ = fmt.Fprint(os.Stderr, err)
}
for _, s := range strings.Split(output, "\n") {
println(s)
}
return output, err
}
func runWithTimeout(cmd *exec.Cmd) (string, error) {
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Start()
if err != nil {
return "", err
}
done := make(chan error)
go func() { done <- cmd.Wait() }()
timeout := time.After(60 * time.Second)
select {
case <-timeout:
_ = cmd.Process.Kill()
return buf.String(), fmt.Errorf("timeout")
case err := <-done:
return buf.String(), err
}
}