-
Notifications
You must be signed in to change notification settings - Fork 3
/
command_executor.go
59 lines (49 loc) · 1.2 KB
/
command_executor.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
59
package commandexecutor
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"code.cloudfoundry.org/lager"
)
type CommandExecutor struct {
command *exec.Cmd
stdoutWriter io.Writer
stderrWriter io.Writer
logger lager.Logger
}
func NewCommandExecutor(command *exec.Cmd, stdoutWriter io.Writer, stderrWriter io.Writer, logger lager.Logger) CommandExecutor {
return CommandExecutor{
command: command,
stdoutWriter: stdoutWriter,
stderrWriter: stderrWriter,
logger: logger,
}
}
func (c CommandExecutor) Run() error {
c.command.Stderr = c.stderrWriter
stdout, err := c.command.StdoutPipe()
if err != nil {
c.logger.Error("Cannot get a Stdout Pipe", err)
return err
}
startErr := c.command.Start()
if startErr != nil {
c.logger.Error("Cannot start command", startErr)
return startErr
}
_, stdoutIoErr := io.Copy(c.stdoutWriter, stdout)
if stdoutIoErr != nil {
// we don't care about errs from canceled commands
_ = c.command.Process.Signal(os.Interrupt)
_ = stdout.Close()
_ = c.command.Wait()
return stdoutIoErr
}
err = c.command.Wait()
if err != nil {
return errors.New(fmt.Sprintf("Command did not complete successfully: %s", err.Error()))
}
return nil
}