Skip to content

Commit

Permalink
set working directory on Cmd if variable #CWD is set (magefile#213)
Browse files Browse the repository at this point in the history
  • Loading branch information
philipsahli committed Jun 7, 2019
1 parent 5bc3a8a commit 0d962b7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
11 changes: 9 additions & 2 deletions sh/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,10 @@ func OutputWith(env map[string]string, cmd string, args ...string) (string, erro
// an error that, if returned from a target or mg.Deps call, will cause mage to
// exit with the same code as the command failed with. Env is a list of
// environment variables to set when running the command, these override the
// current environment variables set (which are also passed to the command). cmd
// and args may include references to environment variables in $FOO format, in
// current environment variables set (which are also passed to the command).
// If the variable #CWD is set, the value will be used as working directory
// when running the command.
// cmd and args may include references to environment variables in $FOO format, in
// which case these will be expanded before the command is run.
//
// Ran reports if the command ran (rather than was not found or not executable).
Expand Down Expand Up @@ -121,6 +123,11 @@ func run(env map[string]string, stdout, stderr io.Writer, cmd string, args ...st
c := exec.Command(cmd, args...)
c.Env = os.Environ()
for k, v := range env {
// if environment variable #CWD is set, use the value as working directory by setting Cmd.Dir
if k == "#CWD" {
c.Dir = v
continue
}
c.Env = append(c.Env, k+"="+v)
}
c.Stderr = stderr
Expand Down
15 changes: 15 additions & 0 deletions sh/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,21 @@ func TestExitCode(t *testing.T) {
}

func TestEnv(t *testing.T) {
env := "SOME_REALLY_LONG_MAGEFILE_SPECIFIC_THING"
out := &bytes.Buffer{}
ran, err := Exec(map[string]string{"#CWD": "/tmp"}, out, nil, "pwd", env)
if err != nil {
t.Fatalf("unexpected error from runner: %#v", err)
}
if !ran {
t.Errorf("expected ran to be true but was false.")
}
if out.String() != "/tmp\n" {
t.Errorf("expected /tmp, got %q", out)
}
}

func TestCwd(t *testing.T) {
env := "SOME_REALLY_LONG_MAGEFILE_SPECIFIC_THING"
out := &bytes.Buffer{}
ran, err := Exec(map[string]string{env: "foobar"}, out, nil, os.Args[0], "-printVar", env)
Expand Down

0 comments on commit 0d962b7

Please sign in to comment.