Skip to content

Commit ba62333

Browse files
committed
Refactor InitEnvironmentVariables to always use os.Getwd() for working directory and add test for stale PWD override
1 parent bc4dfab commit ba62333

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

core/environment/env.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,14 @@ func InitEnvironmentVariables(envStorage EnvStorage) {
2929

3030
initUid(envStorage)
3131

32-
if envStorage.Get("PWD") == "" {
33-
workDir, err = os.Getwd()
34-
if err != nil {
35-
log.Fatal("Could not evaluate working directory - ", err)
36-
}
37-
envStorage.Set("PWD", workDir)
32+
// Always use os.Getwd() to determine the working directory rather than
33+
// trusting the PWD environment variable. PWD may be stale if a parent
34+
// process spawned kool with a different cwd without updating PWD.
35+
workDir, err = os.Getwd()
36+
if err != nil {
37+
log.Fatal("Could not evaluate working directory - ", err)
3838
}
39+
envStorage.Set("PWD", workDir)
3940

4041
for _, envFile := range envFiles {
4142
if _, err = os.Stat(envFile); os.IsNotExist(err) {

core/environment/env_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,23 @@ func TestInitEnvironmentVariables(t *testing.T) {
6161
t.Errorf("expecting $KOOL_GLOBAL_NETWORK value 'kool_global', got '%s'", envKoolNet)
6262
}
6363
}
64+
65+
func TestInitEnvironmentVariablesOverridesStalePWD(t *testing.T) {
66+
f := NewFakeEnvStorage()
67+
68+
// Simulate a stale PWD value (as might happen when spawned with cwd option)
69+
f.Envs["PWD"] = "/some/stale/path"
70+
71+
originalEnvFiles := envFiles
72+
defer func() { envFiles = originalEnvFiles }()
73+
envFiles = []string{} // no env files needed for this test
74+
75+
InitEnvironmentVariables(f)
76+
77+
workDir, _ := os.Getwd()
78+
79+
// PWD should be overridden with the actual working directory
80+
if envWorkDir := f.Envs["PWD"]; envWorkDir != workDir {
81+
t.Errorf("expecting $PWD to be overridden to '%s', got '%s'", workDir, envWorkDir)
82+
}
83+
}

0 commit comments

Comments
 (0)