MCPcopy Create free account
hub / github.com/cli/cli / IsolateConfig

Function IsolateConfig

git/test.go:14–64  ·  view source on GitHub ↗

IsolateConfig prevents ambient Git configuration and repository routing from reaching tests that shell out to real Git. https://git-scm.com/docs/git-config#ENVIRONMENT

(t *testing.T)

Source from the content-addressed store, hash-verified

12//
13// https://git-scm.com/docs/git-config#ENVIRONMENT
14func IsolateConfig(t *testing.T) {
15 t.Helper()
16
17 // Isolating global/system config does not override Git's environment variables.
18 // These can redirect repository, config, index, object, or shallow-file access
19 // outside the test directory, or change discovery and initialization defaults
20 // (templates, index version, object hash, and ref format). Unset them so tests
21 // use their own repositories and Git's defaults, not the caller's environment.
22 // https://git-scm.com/docs/git#_environment_variables
23 for _, variable := range []string{
24 "GIT_DIR",
25 "GIT_WORK_TREE",
26 "GIT_COMMON_DIR",
27 "GIT_CONFIG",
28 "GIT_INDEX_FILE",
29 "GIT_INDEX_VERSION",
30 "GIT_OBJECT_DIRECTORY",
31 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
32 "GIT_NAMESPACE",
33 "GIT_SHALLOW_FILE",
34 "GIT_CEILING_DIRECTORIES",
35 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
36 "GIT_TEMPLATE_DIR",
37 "GIT_DEFAULT_HASH",
38 "GIT_DEFAULT_REF_FORMAT",
39 } {
40 unsetEnv(t, variable)
41 }
42
43 // Point the global config at a test-owned file that disables the caller's
44 // global ignore and attributes rules, and ignore the system config.
45 configDir := t.TempDir()
46 emptyRulesFile := filepath.Join(configDir, "empty-rules")
47 if err := os.WriteFile(emptyRulesFile, nil, 0600); err != nil {
48 t.Fatalf("failed to create empty Git rules file: %v", err)
49 }
50 globalConfig := filepath.Join(configDir, ".gitconfig")
51 config := fmt.Sprintf("[core]\n\texcludesFile = %[1]q\n\tattributesFile = %[1]q\n", filepath.ToSlash(emptyRulesFile))
52 if err := os.WriteFile(globalConfig, []byte(config), 0600); err != nil {
53 t.Fatalf("failed to create global Git config: %v", err)
54 }
55 t.Setenv("GIT_CONFIG_GLOBAL", globalConfig)
56 t.Setenv("GIT_CONFIG_NOSYSTEM", "true")
57
58 // Config from these vars is command line scope, which outranks the global and
59 // system files, so redirecting those files alone leaves it in place. Tools that
60 // wrap git inject config this way, and an inherited safe.bareRepository=explicit
61 // makes git refuse to open a bare repository at all.
62 t.Setenv("GIT_CONFIG_COUNT", "")
63 t.Setenv("GIT_CONFIG_PARAMETERS", "")
64}
65
66func unsetEnv(t *testing.T, name string) {
67 t.Helper()

Calls 4

unsetEnvFunction · 0.85
JoinMethod · 0.80
WriteFileMethod · 0.80
HelperMethod · 0.65