Skip to content

Commit 72a7917

Browse files
committed
Add WithWorkingDir option
1 parent 8828639 commit 72a7917

File tree

4 files changed

+15
-14
lines changed

4 files changed

+15
-14
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Default option functions:
3535
- `cmd.WithStandardStreams`
3636
- `cmd.WithTimeout(time.Duration)`
3737
- `cmd.WithoutTimeout`
38+
- `cmd.WithWorkingDir(string)`
3839

3940
#### Example
4041

command.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"io"
77
"os"
88
"os/exec"
9-
"regexp"
109
"syscall"
1110
"time"
1211
)
@@ -89,21 +88,20 @@ func WithoutTimeout(c *Command) {
8988
c.Timeout = 0
9089
}
9190

91+
// WithWorkingDir sets the current working directory
92+
func WithWorkingDir(dir string) func(c *Command) {
93+
return func(c *Command) {
94+
c.WorkingDir = dir
95+
}
96+
}
97+
9298
// AddEnv adds an environment variable to the command
9399
// If a variable gets passed like ${VAR_NAME} the env variable will be read out by the current shell
94100
func (c *Command) AddEnv(key string, value string) {
95101
value = os.ExpandEnv(value)
96102
c.Env = append(c.Env, fmt.Sprintf("%s=%s", key, value))
97103
}
98104

99-
//Read all environment variables from the given value
100-
//with the syntax ${VAR_NAME}
101-
func parseEnvVariableFromShell(val string) []string {
102-
reg := regexp.MustCompile(`\$\{.*?\}`)
103-
matches := reg.FindAllString(val, -1)
104-
return matches
105-
}
106-
107105
//Stdout returns the output to stdout
108106
func (c *Command) Stdout() string {
109107
c.isExecuted("Stdout")

command_linux.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,9 @@ package cmd
22

33
import (
44
"os/exec"
5-
"strings"
65
)
76

87
func createBaseCommand(c *Command) *exec.Cmd {
98
cmd := exec.Command("/bin/sh", "-c", c.Command)
109
return cmd
1110
}
12-
13-
func (c *Command) removeLineBreaks(text string) string {
14-
return strings.Trim(text, "\n")
15-
}

command_linux_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,10 @@ func TestCommand_WithoutTimeout(t *testing.T) {
7474
assert.Nil(t, err)
7575
assert.Equal(t, "hello\n", cmd.Stdout())
7676
}
77+
78+
func TestCommand_WithInvalidDir(t *testing.T) {
79+
cmd := NewCommand("echo hello", WithWorkingDir("/invalid"))
80+
err := cmd.Execute()
81+
assert.NotNil(t, err)
82+
assert.Equal(t, "chdir /invalid: no such file or directory", err.Error())
83+
}

0 commit comments

Comments
 (0)