Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | // +build freebsd openbsd netbsd dragonfly darwin linux solaris |
| 2 | |
| 3 | package remote |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "io/ioutil" |
| 8 | "os" |
| 9 | ) |
| 10 | |
| 11 | func NewOutputInterceptor() OutputInterceptor { |
| 12 | return &outputInterceptor{} |
| 13 | } |
| 14 | |
| 15 | type outputInterceptor struct { |
| 16 | redirectFile *os.File |
| 17 | intercepting bool |
| 18 | } |
| 19 | |
| 20 | func (interceptor *outputInterceptor) StartInterceptingOutput() error { |
| 21 | if interceptor.intercepting { |
| 22 | return errors.New("Already intercepting output!") |
| 23 | } |
| 24 | interceptor.intercepting = true |
| 25 | |
| 26 | var err error |
| 27 | |
| 28 | interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo-output") |
| 29 | if err != nil { |
| 30 | return err |
| 31 | } |
| 32 | |
| 33 | // Call a function in ./syscall_dup_*.go |
| 34 | // If building for everything other than linux_arm64, |
| 35 | // use a "normal" syscall.Dup2(oldfd, newfd) call. If building for linux_arm64 (which doesn't have syscall.Dup2) |
| 36 | // call syscall.Dup3(oldfd, newfd, 0). They are nearly identical, see: http://linux.die.net/man/2/dup3 |
| 37 | syscallDup(int(interceptor.redirectFile.Fd()), 1) |
| 38 | syscallDup(int(interceptor.redirectFile.Fd()), 2) |
| 39 | |
| 40 | return nil |
| 41 | } |
| 42 | |
| 43 | func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { |
| 44 | if !interceptor.intercepting { |
| 45 | return "", errors.New("Not intercepting output!") |
| 46 | } |
| 47 | |
| 48 | interceptor.redirectFile.Close() |
| 49 | output, err := ioutil.ReadFile(interceptor.redirectFile.Name()) |
| 50 | os.Remove(interceptor.redirectFile.Name()) |
| 51 | |
| 52 | interceptor.intercepting = false |
| 53 | |
| 54 | return string(output), err |
| 55 | } |