|
8 | 8 | "os"
|
9 | 9 | "os/exec"
|
10 | 10 | "path/filepath"
|
| 11 | + "strings" |
11 | 12 | "testing"
|
12 | 13 | "time"
|
13 | 14 |
|
@@ -51,6 +52,7 @@ func (repo *TestRepo) Init(t *testing.T, bare bool) {
|
51 | 52 | } else {
|
52 | 53 | cmd = exec.Command("git", "init", repo.Path)
|
53 | 54 | }
|
| 55 | + cmd.Env = CleanGitEnv() |
54 | 56 | err := cmd.Run()
|
55 | 57 | require.NoError(t, err)
|
56 | 58 | }
|
@@ -90,14 +92,59 @@ func (repo *TestRepo) Repository(t *testing.T) *git.Repository {
|
90 | 92 | return r
|
91 | 93 | }
|
92 | 94 |
|
| 95 | +// localEnvVars is a list of the variable names that should be cleared |
| 96 | +// to give Git a clean environment. |
| 97 | +var localEnvVars = func() map[string]bool { |
| 98 | + m := map[string]bool{ |
| 99 | + "HOME": true, |
| 100 | + "XDG_CONFIG_HOME": true, |
| 101 | + } |
| 102 | + out, err := exec.Command("git", "rev-parse", "--local-env-vars").Output() |
| 103 | + if err != nil { |
| 104 | + return m |
| 105 | + } |
| 106 | + for _, k := range strings.Fields(string(out)) { |
| 107 | + m[k] = true |
| 108 | + } |
| 109 | + return m |
| 110 | +}() |
| 111 | + |
| 112 | +// GitEnv returns an appropriate environment for running `git` |
| 113 | +// commands without being confused by any existing environment or |
| 114 | +// gitconfig. |
| 115 | +func CleanGitEnv() []string { |
| 116 | + var env []string |
| 117 | + for _, e := range os.Environ() { |
| 118 | + i := strings.IndexByte(e, '=') |
| 119 | + if i == -1 { |
| 120 | + // This shouldn't happen, but if it does, |
| 121 | + // ignore it. |
| 122 | + continue |
| 123 | + } |
| 124 | + k := e[:i] |
| 125 | + if localEnvVars[k] { |
| 126 | + continue |
| 127 | + } |
| 128 | + env = append(env, e) |
| 129 | + } |
| 130 | + return append( |
| 131 | + env, |
| 132 | + fmt.Sprintf("HOME=%s", os.DevNull), |
| 133 | + fmt.Sprintf("XDG_CONFIG_HOME=%s", os.DevNull), |
| 134 | + "GIT_CONFIG_NOSYSTEM=1", |
| 135 | + ) |
| 136 | +} |
| 137 | + |
93 | 138 | // GitCommand creates an `*exec.Cmd` for running `git` in `repo` with
|
94 | 139 | // the specified arguments.
|
95 | 140 | func (repo *TestRepo) GitCommand(t *testing.T, args ...string) *exec.Cmd {
|
96 | 141 | t.Helper()
|
97 | 142 |
|
98 | 143 | gitArgs := []string{"-C", repo.Path}
|
99 | 144 | gitArgs = append(gitArgs, args...)
|
100 |
| - return exec.Command("git", gitArgs...) |
| 145 | + cmd := exec.Command("git", gitArgs...) |
| 146 | + cmd.Env = CleanGitEnv() |
| 147 | + return cmd |
101 | 148 | }
|
102 | 149 |
|
103 | 150 | func (repo *TestRepo) UpdateRef(t *testing.T, refname string, oid git.OID) {
|
|
0 commit comments