Skip to content

Commit c756bf2

Browse files
committed
Add option WithCustomBaseCommand to provide the ability for clients to bring their own os/exec.Cmd
1 parent bdd1038 commit c756bf2

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

command.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ type Command struct {
2020
StderrWriter io.Writer
2121
StdoutWriter io.Writer
2222
WorkingDir string
23+
baseCommand *exec.Cmd
2324
executed bool
2425
exitCode int
2526
// stderr and stdout retrieve the output after the command was executed
@@ -60,6 +61,7 @@ func NewCommand(cmd string, options ...func(*Command)) *Command {
6061
Env: []string{},
6162
}
6263

64+
c.baseCommand = createBaseCommand(c)
6365
c.StdoutWriter = io.MultiWriter(&c.stdout, &c.combined)
6466
c.StderrWriter = io.MultiWriter(&c.stderr, &c.combined)
6567

@@ -70,6 +72,13 @@ func NewCommand(cmd string, options ...func(*Command)) *Command {
7072
return c
7173
}
7274

75+
func WithCustomBaseCommand(baseCommand *exec.Cmd) func(c *Command) {
76+
return func(c *Command) {
77+
baseCommand.Args = append(baseCommand.Args, c.Command)
78+
c.baseCommand = baseCommand
79+
}
80+
}
81+
7382
// WithStandardStreams is used as an option by the NewCommand constructor function and writes the output streams
7483
// to stderr and stdout of the operating system
7584
//
@@ -187,7 +196,7 @@ func (c *Command) isExecuted(property string) {
187196

188197
// ExecuteContext runs Execute but with Context
189198
func (c *Command) ExecuteContext(ctx context.Context) error {
190-
cmd := createBaseCommand(c)
199+
cmd := c.baseCommand
191200
cmd.Env = c.Env
192201
cmd.Dir = c.Dir
193202
cmd.Stdout = c.StdoutWriter

command_darwin_test.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,26 @@
11
package cmd
22

33
import (
4-
"github.com/stretchr/testify/assert"
4+
"os/exec"
55
"testing"
66
"time"
7+
8+
"github.com/stretchr/testify/assert"
79
)
810

11+
func TestCommand_WithCustomBaseCommand(t *testing.T) {
12+
cmd := NewCommand(
13+
"echo $0",
14+
WithCustomBaseCommand(exec.Command("/bin/bash", "-c")),
15+
)
16+
17+
err := cmd.Execute()
18+
assert.Nil(t, err)
19+
// on darwin we use /bin/sh by default test if we're using bash
20+
assert.NotEqual(t, "/bin/sh\n", cmd.Stdout())
21+
assert.Equal(t, "/bin/bash\n", cmd.Stdout())
22+
}
23+
924
func TestCommand_ExecuteStderr(t *testing.T) {
1025
cmd := NewCommand(">&2 echo hello")
1126

0 commit comments

Comments
 (0)