Skip to content

Commit

Permalink
feat: #1 Allow setting working directory via env:PWD=something
Browse files Browse the repository at this point in the history
  • Loading branch information
blackandred committed Jan 20, 2022
1 parent 187833b commit b480436
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions process.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
)

Expand All @@ -15,9 +16,23 @@ func getProcessName(args []string) string {

func StartProcess(processName string, processArgs []string, extraEnv []string) *exec.Cmd {
cmd := exec.Command(processName, processArgs...)

if extraEnv != nil {
cmd.Env = append(os.Environ(), extraEnv...)

// #2: Support for setting workdir (PWD)
for _, envAsStr := range extraEnv {
if strings.Contains(envAsStr, "PWD=") {
name, value := parseEnvironmentVariable(envAsStr)

_ = os.Setenv(name, value)
cmd.Dir = os.Getenv("PWD")

break
}
}
}

cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
Expand Down
15 changes: 15 additions & 0 deletions process_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package main

import (
"fmt"
"github.com/stretchr/testify/assert"
"os"
"strings"
"testing"
)

Expand Down Expand Up @@ -32,3 +34,16 @@ func TestProcessExitCodeSaving_WhenProcessFails(t *testing.T) {
actual, _ := os.ReadFile(".build/TestProcessExitCodeSaving")
assert.Equal(t, "1", string(actual))
}

func TestExtraPWDSetting(t *testing.T) {
_ = os.Mkdir(".build", 0755)
currentDir, _ := os.Getwd()

process := StartProcess("/bin/bash",
[]string{"-c", fmt.Sprintf("pwd > %v/.build/TestExtraPWDSetting", currentDir)},
[]string{"PWD=/tmp"})
_ = waitAndRetrieveStatusCode(process)

actual, _ := os.ReadFile(".build/TestExtraPWDSetting")
assert.Equal(t, "/tmp", strings.Trim(string(actual), "\n "))
}

0 comments on commit b480436

Please sign in to comment.