-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecutable.go
78 lines (62 loc) · 2 KB
/
executable.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package commandgo
import (
"io"
"os/exec"
"github.com/onsi/gomega/gexec"
"fmt"
"github.com/onsi/ginkgo"
)
type ExecutableContext struct {
HandlesErrors
Path string
Arguments []string
command *exec.Cmd
OutWriter io.Writer
ErrWriter io.Writer
}
func NewExecutableContext(path string, arguments ...string) *ExecutableContext {
return &ExecutableContext{
HandlesErrors: NewHandlesErrors(),
Path: path,
Arguments: arguments,
OutWriter: ginkgo.GinkgoWriter,
ErrWriter: ginkgo.GinkgoWriter,
}
}
func (executable *ExecutableContext) AddArguments(arguments ...string) {
executable.Arguments = append(executable.Arguments, arguments...)
}
func (executable *ExecutableContext) Command(additonalArguments ...string) *exec.Cmd {
arguments := append(executable.Arguments, additonalArguments...)
executable.command = exec.Command(executable.Path, arguments...)
return executable.command
}
func (executable *ExecutableContext) PipeCommand(additonalArguments ...string) (*exec.Cmd, io.WriteCloser) {
executable.Command(additonalArguments...)
stdin, err := executable.command.StdinPipe()
if err != nil {
executable.ErrorHandler(err)
}
return executable.command, stdin
}
func (executable *ExecutableContext) Execute() *gexec.Session {
command := executable.Command()
session, err := gexec.Start(command, executable.OutWriter, executable.ErrWriter)
if err != nil {
executable.ErrorHandler(err)
}
return session
}
// The ExecuteWithInput function is a utility function that runs a PipeCommand and passes
// the input string to the command. It closes stdin to ensure the command completes and returns
// a gexec.Session you can use to evaluate output.
func (executable *ExecutableContext) ExecuteWithInput(input string) *gexec.Session {
command, stdin := executable.PipeCommand()
session, err := gexec.Start(command, executable.OutWriter, executable.ErrWriter)
if err != nil {
executable.ErrorHandler(err)
}
fmt.Fprint(stdin, input)
stdin.Close()
return session
}