Skip to content

Commit

Permalink
internal/vcs: use limited environment when executing git in tests
Browse files Browse the repository at this point in the history
We don't want git environment variables like `$GIT_DIR`
to cause the test to fail. This change was prompted
by the fact that running `git rebase --exec` causes
the test to fail because it sets `$DIR_DIR` which
overrides the current directory, causing `git init`
to use the wrong directory to create the `.git` directory in.

Signed-off-by: Roger Peppe <rogpeppe@gmail.com>
Change-Id: Ia17380a313a88fb525933c7ae6ef389f1042d67a
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1193380
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
Unity-Result: CUE porcuepine <cue.porcuepine@gmail.com>
  • Loading branch information
rogpeppe committed Apr 19, 2024
1 parent f0f56f8 commit dc78c66
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions internal/vcs/vcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ package vcs

import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"

Expand All @@ -44,6 +47,7 @@ func TestGit(t *testing.T) {
_, err = New("git", filepath.Join(dir, "subdir"))
qt.Assert(t, qt.ErrorMatches(err, `git VCS not found in any parent of ".+"`))

initTestEnv(t)
mustRunCmd(t, dir, "git", "init")
v, err := New("git", filepath.Join(dir, "subdir"))
qt.Assert(t, qt.IsNil(err))
Expand Down Expand Up @@ -81,6 +85,26 @@ func TestGit(t *testing.T) {
}))
}

// initTestEnv sets up the environment so that
// any executed VCS command won't be affected
// by the outer level environment.
func initTestEnv(t *testing.T) {
path := os.Getenv("PATH")
systemRoot := os.Getenv("SYSTEMROOT")
// First unset all environment variables to make a pristine environment.
for _, kv := range os.Environ() {
key, _, _ := strings.Cut(kv, "=")
t.Setenv(key, "")
os.Unsetenv(key)
}
os.Setenv("PATH", path)
os.Setenv(homeEnvName(), "/no-home")
// Must preserve SYSTEMROOT on Windows: https://github.com/golang/go/issues/25513 et al
if runtime.GOOS == "windows" {
os.Setenv("SYSTEMROOT", systemRoot)
}
}

func mustRunCmd(t *testing.T, dir string, exe string, args ...string) {
c := exec.Command(exe, args...)
c.Dir = dir
Expand All @@ -93,3 +117,14 @@ func skipIfNoExecutable(t *testing.T, exeName string) {
t.Skipf("cannot find %q executable: %v", exeName, err)
}
}

func homeEnvName() string {
switch runtime.GOOS {
case "windows":
return "USERPROFILE"
case "plan9":
return "home"
default:
return "HOME"
}
}

0 comments on commit dc78c66

Please sign in to comment.