test(cmd/bd): stop tests from mutating the host checkout's .git; guard it in TestMain (wy-qlvlmf) (#7650)
* wy-qlvlmf: test(cmd/bd): stop tests from mutating the host checkout's .git; guard it in TestMain On 2026-10-16 a 'go test ./cmd/bd' run from a linked worktree rewrote the host rig's shared .git/config (core.bare=true, extensions.worktreeConfig, remote.origin.url replaced by metadata_test's fixture URL, user identity, core.hooksPath) and its hooks dir, leaving every worktree of that clone answering 'fatal: this operation must be run in a work tree' (r880). Root causes, all one class — fixture git commands routed at the repository the test process itself lives in instead of a fixture the test owns: - TestRunApplyAllOK ran runApply(false) (a LIVE apply: hook reinstall, hooksPath mkdir) with no fixture, against the package cwd's repo. - runGitForBootstrapTest treated dir=="" as 'inherit package cwd'. - doctor/fix setupGitRepoInDir swallowed git config failures non-fatally and ran with whatever git routing env (GIT_DIR, GIT_WORK_TREE) leaked in. Fixes: - TestRunApplyAllOK / TestRunApplyDryRun now chdir into an isolated git+.beads fixture (isolatedApplyFixture + runInDir). - runGitForBootstrapTest: empty dir gets a neutral t.TempDir() cwd, never the package cwd; env scrubbed of git routing vars. - initGitRepoAt / doctor setupGitRepoInDir / doctor-fix setupGitRepoInDir: refuse an empty dir, fail on ANY git error, scrub routing env. - testMainInner scrubs git routing env process-wide at startup. - TestMain's repo guard now also snapshots the checkout's own git state (common .git/config, config.worktree, common hooks dir) and reddens the run on any diff, naming the mutated file. Guard vacuity check: a probe test writing one key into the checkout's .git/config passes individually and reddens the suite via the guard. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * build(bazel): auto-sync BUILD files Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/39013861275 (`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy). Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see scripts/bazel-autofix-push.sh. * test(cmd/bd): scrub doctor suites, keep git fences, key-level config guard (wy-qlvlmf) Maintainer fixup on top of #7650 by cat, for the first review's three majors, minor and nit, and three of the second review's minors. - Doctor suites: the leaked-GIT_DIR vector was still open in cmd/bd/doctor and cmd/bd/doctor/fix. Their four TestMains now unset the repository-location env first (testutil.UnsetGitRepoLocationEnv), and the three initGitTemplate copies plus testutil.ForceRepoLocalHooksPath run git with a filtered env. With GIT_DIR/GIT_WORK_TREE leaked at a decoy repo, the PR head wrote core.hooksPath into the decoy and failed 120 doctor tests; with this commit all three packages pass and the decoy stays byte-identical. - Narrower scrub: the process-wide scrub also removed GIT_CEILING_DIRECTORIES and the GIT_CONFIG_* fences that tools/bazel/test_env.sh and scripts/ci/lib/test-env.sh set on purpose. testutil.WithoutGitRepoLocationEnv removes only GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES, GIT_NAMESPACE and the legacy GIT_CONFIG (which sends `git config` reads and writes to the file it names, even under -C). Keys match exactly, so GIT_CEILING_DIRECTORIES, GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM stay. Every helper that built its own scrubbed env now uses it. - Guard false reds: the TestMain guard compared the shared common config byte for byte, so a sibling worktree's routine branch write failed a passing run. It now diffs `git config --list -z` key by key. branch.<name>.* keys, and a remote other than origin added or removed whole, print a NOTE and leave the exit code alone. Any other key (including origin appearing or disappearing, and a changed key of a remote that exists before and after), any config.worktree change, any hook file change or an unparseable config still fails the run. - config.worktree: the guard also snapshots a main checkout's own config.worktree, which sits in the common dir. With extensions.worktreeConfig set its keys override the shared config, and before this an escaped `git config --worktree` write there went unreported. - Report: changed keys are named with values redacted, deleted and new files are reported as such, pre-run copies of the changed files are saved (0700 dir, 0600 files) and their path printed, and a failure to locate the checkout's git dirs prints a warning instead of disarming the guard silently. - doctor setupGitRepoInDir stat-checks its dir like the doctor/fix copy. New tests: internal/testutil/git_env_test.go, and cmd/bd/test_repo_git_guard_test.go (real-git fixtures for locating the git dirs, classifying writes, config parsing and the report). Validation: ./scripts/test.sh ./cmd/bd in a scratch clone with GIT_DIR leaked at a decoy (ok; decoy and the clone's .git unchanged; guard quiet); bazel test --config=ci for testutil, doctor, doctor/fix, fmt_test and the new bd_test guard tests; make ci-pr-lint; tools/bazel/go_srcs.py --check. Second review: leaving GIT_CONFIG out of the scrub fails TestWithoutGitRepoLocationEnvKeepsWrapperGitControls and TestForceRepoLocalHooksPathIgnoresLeakedGitDir; the old main-checkout config.worktree path fails TestLocateRepoGitDirs/main_checkout and the new config.worktree case; treating origin like any other remote fails the new origin added and removed cases. In a scratch main-checkout clone with extensions.worktreeConfig set, a test that wrote `git config --worktree user.email` into the checkout now fails the suite (exit 1, an ERROR naming .git/config.worktree). bazel test --config=ci passes for testutil, fmt_test and the bd_test guard tests. Not in this commit: the same scrub in beads_test_env_enter (scripts/ci/lib/test-env.sh) and tools/bazel/test_env.sh, which would cover the packages outside cmd/bd that still write to the clone under a hook-leaked GIT_DIR. That predates this PR and is left to a follow-up. Co-authored-by: cat <cino@ghosttrack.com> Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: cat <cino@ghosttrack.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
This commit is contained in:
parent
4450fe99bb
commit
46aa59cc65
18 changed files with 1212 additions and 31 deletions
|
|
@ -1243,6 +1243,7 @@ go_test(
|
|||
"test_helpers_test.go",
|
||||
"test_repo_beads_guard_darwin_test.go",
|
||||
"test_repo_beads_guard_test.go",
|
||||
"test_repo_git_guard_test.go",
|
||||
"test_wait_helper_test.go",
|
||||
"thread_test.go",
|
||||
"tips_example_test.go",
|
||||
|
|
|
|||
|
|
@ -193,32 +193,52 @@ func TestApplyServerSkipsWhenAutoStartDisabled(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// isolatedApplyFixture builds a throwaway git repo with a .beads dir for the
|
||||
// runApply tests. runApply(false) is a live apply: it inspects AND MUTATES the
|
||||
// repository that owns the process cwd (hook reinstalls, hooksPath mkdirs).
|
||||
// Run bare from the package dir, that repository is this checkout — the r880
|
||||
// host .git clobber (wy-qlvlmf) — so these tests must always chdir into a
|
||||
// fixture they own first.
|
||||
func isolatedApplyFixture(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
initGitRepoAt(t, dir)
|
||||
if err := os.MkdirAll(filepath.Join(dir, ".beads"), 0o755); err != nil {
|
||||
t.Fatalf("create fixture .beads: %v", err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestRunApplyAllOK(t *testing.T) {
|
||||
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
|
||||
// In a test environment with no drift, all results should be ok or skipped
|
||||
results := runApply(false)
|
||||
if len(results) != 3 {
|
||||
t.Errorf("expected 3 results, got %d", len(results))
|
||||
}
|
||||
for _, r := range results {
|
||||
if r.Status == applyStatusError {
|
||||
t.Errorf("unexpected error for check %q: %s", r.Check, r.Error)
|
||||
runInDir(t, isolatedApplyFixture(t), func() {
|
||||
// In a test environment with no drift, all results should be ok or skipped
|
||||
results := runApply(false)
|
||||
if len(results) != 3 {
|
||||
t.Errorf("expected 3 results, got %d", len(results))
|
||||
}
|
||||
}
|
||||
for _, r := range results {
|
||||
if r.Status == applyStatusError {
|
||||
t.Errorf("unexpected error for check %q: %s", r.Check, r.Error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunApplyDryRun(t *testing.T) {
|
||||
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
|
||||
results := runApply(true)
|
||||
if len(results) != 3 {
|
||||
t.Errorf("expected 3 results, got %d", len(results))
|
||||
}
|
||||
// In dry-run, no actions should be "applied"
|
||||
for _, r := range results {
|
||||
if r.Status == applyStatusApplied {
|
||||
t.Errorf("dry-run should not apply actions, but check %q was applied", r.Check)
|
||||
runInDir(t, isolatedApplyFixture(t), func() {
|
||||
results := runApply(true)
|
||||
if len(results) != 3 {
|
||||
t.Errorf("expected 3 results, got %d", len(results))
|
||||
}
|
||||
}
|
||||
// In dry-run, no actions should be "applied"
|
||||
for _, r := range results {
|
||||
if r.Status == applyStatusApplied {
|
||||
t.Errorf("dry-run should not apply actions, but check %q was applied", r.Check)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDriftDomainsGroupsDottedChecks(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -57,6 +57,14 @@ func TestMain(m *testing.M) {
|
|||
}
|
||||
|
||||
func testMainInner(m *testing.M) int {
|
||||
// A GIT_DIR/GIT_WORK_TREE leaked in from the invoking shell or a git hook
|
||||
// would route the fixture `git init`/`git config` writes in this suite
|
||||
// into that repository: the host checkout in the r880 clobber (wy-qlvlmf).
|
||||
if err := testutil.UnsetGitRepoLocationEnv(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "FATAL: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
os.Setenv("BEADS_TEST_MODE", "1")
|
||||
// AD-01 (be-c5p): doctor e2e tests connect to a per-package test server.
|
||||
// The dolt.New database-name firewall requires this opt-in to allow
|
||||
|
|
|
|||
|
|
@ -30,8 +30,13 @@ func initGitTemplate() {
|
|||
}
|
||||
gitTemplateDir = dir
|
||||
|
||||
// The template is built once, inside whichever test asks first. Its
|
||||
// writes must land in dir even if that test set GIT_DIR/GIT_WORK_TREE,
|
||||
// or they hit that repository (the r880 clobber class, wy-qlvlmf).
|
||||
env := testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
cmd := gitCommand("init", "--initial-branch=main")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
if err := cmd.Run(); err != nil {
|
||||
gitTemplateErr = fmt.Errorf("git init failed: %w", err)
|
||||
return
|
||||
|
|
@ -43,6 +48,7 @@ func initGitTemplate() {
|
|||
} {
|
||||
cmd = gitCommand(args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
if err := cmd.Run(); err != nil {
|
||||
gitTemplateErr = fmt.Errorf("git %v failed: %w", args, err)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import (
|
|||
|
||||
mysql "github.com/go-sql-driver/mysql"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/testutil"
|
||||
)
|
||||
|
||||
// TestFixMissingMetadata_NotBeadsWorkspace verifies that FixMissingMetadata
|
||||
|
|
@ -199,8 +200,21 @@ func TestFixMissingMetadataJSON_NotBeadsWorkspace(t *testing.T) {
|
|||
}
|
||||
|
||||
// setupGitRepoInDir initializes a git repo in the given directory with a remote.
|
||||
//
|
||||
// Every step is fatal on failure, the dir must exist, and the child env is
|
||||
// scrubbed of the git vars that name a repository (GIT_DIR, GIT_WORK_TREE,
|
||||
// ...). An empty dir, a swallowed config failure, or a leaked GIT_DIR each make
|
||||
// these writes land in whatever repository git resolves from the process
|
||||
// environment — the host checkout's own .git/config in the r880 clobber
|
||||
// (wy-qlvlmf), where this helper's remote.origin.url overwrote the real origin.
|
||||
func setupGitRepoInDir(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if dir == "" {
|
||||
t.Fatal("setupGitRepoInDir: empty dir would run git against the host checkout")
|
||||
}
|
||||
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
|
||||
t.Fatalf("setupGitRepoInDir: %q is not an existing directory (err=%v)", dir, err)
|
||||
}
|
||||
cmds := [][]string{
|
||||
{"git", "init"},
|
||||
{"git", "config", "user.email", "test@test.com"},
|
||||
|
|
@ -211,11 +225,9 @@ func setupGitRepoInDir(t *testing.T, dir string) {
|
|||
for _, args := range cmds {
|
||||
cmd := exec.Command(args[0], args[1:]...)
|
||||
cmd.Dir = dir
|
||||
if err := cmd.Run(); err != nil {
|
||||
// git init must succeed; config failures are non-fatal
|
||||
if args[1] == "init" {
|
||||
t.Fatalf("git init failed: %v", err)
|
||||
}
|
||||
cmd.Env = testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("%v failed: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,14 @@ func TestMain(m *testing.M) {
|
|||
// exits — os.Exit skips deferred calls, so TestMain itself must never defer
|
||||
// anything (be-5kkk6).
|
||||
func testMainInner(m *testing.M) int {
|
||||
// A GIT_DIR/GIT_WORK_TREE leaked in from the invoking shell or a git hook
|
||||
// would route the fixture `git init`/`git config` writes in this suite
|
||||
// into that repository: the host checkout in the r880 clobber (wy-qlvlmf).
|
||||
if err := testutil.UnsetGitRepoLocationEnv(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "FATAL: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
os.Setenv("BEADS_TEST_MODE", "1")
|
||||
// AD-01 (be-c5p): allow doctor/fix tests through the dolt.New
|
||||
// database-name firewall when they connect to the spawned test server.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,14 @@ func TestMain(m *testing.M) {
|
|||
}
|
||||
|
||||
func testMainInner(m *testing.M) int {
|
||||
// A GIT_DIR/GIT_WORK_TREE leaked in from the invoking shell or a git hook
|
||||
// would route the fixture `git init`/`git config` writes in this suite
|
||||
// into that repository: the host checkout in the r880 clobber (wy-qlvlmf).
|
||||
if err := testutil.UnsetGitRepoLocationEnv(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "FATAL: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
// Clear out the roots of earlier runs of this suite whose process is
|
||||
// gone, before claiming one of our own. A `go test -timeout` panic skips
|
||||
// every defer here AND the post-run sweep, so the servers such a run
|
||||
|
|
|
|||
|
|
@ -30,8 +30,13 @@ func initGitTemplate() {
|
|||
}
|
||||
gitTemplateDir = dir
|
||||
|
||||
// The template is built once, inside whichever test asks first. Its
|
||||
// writes must land in dir even if that test set GIT_DIR/GIT_WORK_TREE,
|
||||
// or they hit that repository (the r880 clobber class, wy-qlvlmf).
|
||||
env := testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
cmd := gitCommand("init", "--initial-branch=main")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
if err := cmd.Run(); err != nil {
|
||||
gitTemplateErr = fmt.Errorf("git init failed: %w", err)
|
||||
return
|
||||
|
|
@ -43,6 +48,7 @@ func initGitTemplate() {
|
|||
} {
|
||||
cmd = gitCommand(args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
if err := cmd.Run(); err != nil {
|
||||
gitTemplateErr = fmt.Errorf("git %v failed: %w", args, err)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ import (
|
|||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/testutil"
|
||||
)
|
||||
|
||||
// setupGitRepo creates a temporary git repository for testing
|
||||
|
|
@ -51,6 +53,15 @@ func TestCheckGitHooks(t *testing.T) {
|
|||
// setupGitRepoInDir initializes a git repo in the given directory with .beads
|
||||
func setupGitRepoInDir(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if dir == "" {
|
||||
// cmd.Dir = "" inherits the test process cwd — this checkout's own
|
||||
// package dir — so the config write below would hit the host .git
|
||||
// (the r880 clobber class, wy-qlvlmf).
|
||||
t.Fatal("setupGitRepoInDir: empty dir would run git against the host checkout")
|
||||
}
|
||||
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
|
||||
t.Fatalf("setupGitRepoInDir: %q is not an existing directory (err=%v)", dir, err)
|
||||
}
|
||||
|
||||
// Create .beads directory
|
||||
beadsDir := filepath.Join(dir, ".beads")
|
||||
|
|
@ -68,11 +79,14 @@ func setupGitRepoInDir(t *testing.T, dir string) {
|
|||
}
|
||||
|
||||
// Force repo-local hooks path for test isolation. This prevents global
|
||||
// core.hooksPath from affecting hook detection behavior in tests.
|
||||
// core.hooksPath from affecting hook detection behavior in tests. The env
|
||||
// scrub keeps a leaked GIT_DIR/GIT_WORK_TREE from routing the write at
|
||||
// some other repository.
|
||||
cmd := gitCommand("config", "core.hooksPath", ".git/hooks")
|
||||
cmd.Dir = dir
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("failed to set core.hooksPath for test repo: %v", err)
|
||||
cmd.Env = testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to set core.hooksPath for test repo: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,6 +19,14 @@ func TestMain(m *testing.M) {
|
|||
}
|
||||
|
||||
func testMainInner(m *testing.M) int {
|
||||
// A GIT_DIR/GIT_WORK_TREE leaked in from the invoking shell or a git hook
|
||||
// would route the fixture `git init`/`git config` writes in this suite
|
||||
// into that repository: the host checkout in the r880 clobber (wy-qlvlmf).
|
||||
if err := testutil.UnsetGitRepoLocationEnv(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "FATAL: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
// Clear out the roots of earlier runs of this suite whose process is
|
||||
// gone, before claiming one of our own. A `go test -timeout` panic skips
|
||||
// every defer here AND the post-run sweep, so the servers such a run
|
||||
|
|
|
|||
|
|
@ -33,8 +33,13 @@ func initGitTemplate() {
|
|||
}
|
||||
gitTemplateDir = dir
|
||||
|
||||
// The template is built once, inside whichever test asks first. Its
|
||||
// writes must land in dir even if that test set GIT_DIR/GIT_WORK_TREE,
|
||||
// or they hit that repository (the r880 clobber class, wy-qlvlmf).
|
||||
env := testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
cmd := gitCommand("init", "--initial-branch=main")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
if err := cmd.Run(); err != nil {
|
||||
gitTemplateErr = fmt.Errorf("git init failed: %w", err)
|
||||
return
|
||||
|
|
@ -46,6 +51,7 @@ func initGitTemplate() {
|
|||
} {
|
||||
cmd = gitCommand(args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
if err := cmd.Run(); err != nil {
|
||||
gitTemplateErr = fmt.Errorf("git %v failed: %w", args, err)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/testutil"
|
||||
"github.com/steveyegge/beads/internal/testutil/bazeltest"
|
||||
)
|
||||
|
||||
|
|
@ -440,12 +441,21 @@ func buildBDForInitTests(t *testing.T) string {
|
|||
|
||||
// runGitForBootstrapTest runs a git subcommand in the given directory and
|
||||
// fails the test on error. Used by bootstrap and init-safety subprocess tests.
|
||||
//
|
||||
// An empty dir never inherits the test process cwd: that cwd is this package's
|
||||
// directory inside this checkout, so a cwd-resolved git write (config, init)
|
||||
// lands in the checkout's own .git — the r880 host .git/config clobber
|
||||
// (wy-qlvlmf). Callers that pass "" operate on absolute paths in args and get
|
||||
// a neutral scratch cwd instead. The env scrub keeps a leaked GIT_DIR /
|
||||
// GIT_WORK_TREE from routing the command at some other repository.
|
||||
func runGitForBootstrapTest(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := gitCommand(args...)
|
||||
if dir != "" {
|
||||
cmd.Dir = dir
|
||||
if dir == "" {
|
||||
dir = t.TempDir()
|
||||
}
|
||||
cmd.Dir = dir
|
||||
cmd.Env = testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git %v failed: %v\n%s", args, err, string(output))
|
||||
|
|
@ -459,9 +469,15 @@ func runGitForBootstrapTest(t *testing.T, dir string, args ...string) {
|
|||
// This lives in the pure-Go helper file, not alongside the embedded-Dolt
|
||||
// helpers: cmd/bd/where_test.go carries no build tag, so it compiles under
|
||||
// CGO_ENABLED=0 where every `//go:build cgo` file is excluded. Keep this
|
||||
// helper stdlib-only and keep it here.
|
||||
// helper free of cgo-only dependencies and keep it here.
|
||||
func initGitRepoAt(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if dir == "" {
|
||||
// cmd.Dir = "" inherits the test process cwd — this checkout's own
|
||||
// package dir — so the init and configs would hit the host .git
|
||||
// (the r880 clobber class, wy-qlvlmf).
|
||||
t.Fatal("initGitRepoAt: empty dir would run git against the host checkout")
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"init"},
|
||||
{"config", "user.email", "test@test.com"},
|
||||
|
|
@ -471,6 +487,7 @@ func initGitRepoAt(t *testing.T, dir string) {
|
|||
} {
|
||||
cmd := gitCommand(args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = testutil.WithoutGitRepoLocationEnv(os.Environ())
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %s failed: %v\n%s", args[0], err, out)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
|
|
@ -130,6 +132,21 @@ func testMainInner(m *testing.M) int {
|
|||
}
|
||||
beads.ResetCaches()
|
||||
|
||||
// Drop inherited git repository-location vars (GIT_DIR, GIT_WORK_TREE,
|
||||
// GIT_COMMON_DIR, GIT_INDEX_FILE, GIT_CONFIG, ...) for the whole test
|
||||
// process. Fixture helpers in this package run `git config`/`git init`
|
||||
// with only cmd.Dir set; a location var leaked in from the invoking shell
|
||||
// or a hook overrides that Dir and points every such write at a
|
||||
// repository the suite does not own — one of the vectors behind the r880
|
||||
// host .git/config clobber (wy-qlvlmf). GIT_CEILING_DIRECTORIES,
|
||||
// GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM stay: tools/bazel/test_env.sh
|
||||
// sets them on purpose. Tests that need a location var set it per-test
|
||||
// with t.Setenv.
|
||||
if err := testutil.UnsetGitRepoLocationEnv(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "FATAL: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
// Separately bound any literal ancestor-directory walk that starts
|
||||
// at (or under) this checkout: the pin above only defeats the
|
||||
// git-context-cache vector, not a plain upward walk from a worktree
|
||||
|
|
@ -356,7 +373,26 @@ func testMainInner(m *testing.M) int {
|
|||
guardDirs = append(guardDirs, fallbackBeadsDir)
|
||||
}
|
||||
}
|
||||
if len(guardDirs) == 0 {
|
||||
|
||||
// The checkout's own git state is guarded alongside its .beads state: on
|
||||
// 2026-10-16 a `go test ./cmd/bd` run from a linked worktree rewrote the
|
||||
// host rig's shared .git/config (core.bare=true, extensions.worktreeConfig,
|
||||
// a test remote.origin.url over the real origin) and its hooks, breaking
|
||||
// every worktree of that clone (wy-qlvlmf, r880). The common config and
|
||||
// hooks are shared by every worktree of the clone, so the keys other
|
||||
// worktrees rewrite routinely (branch tracking, a remote other than origin
|
||||
// added or removed whole) only draw a note; any other change means a test
|
||||
// most likely ran git against this checkout instead of a fixture it owns.
|
||||
gitDirs, err := locateRepoGitDirs(repoRoot)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: this checkout's own git state is not guarded in this run: %v\n", err)
|
||||
}
|
||||
var gitStateBefore repoGitState
|
||||
if gitDirs.common != "" {
|
||||
gitStateBefore = readRepoGitState(gitDirs)
|
||||
}
|
||||
|
||||
if len(guardDirs) == 0 && gitDirs.common == "" {
|
||||
return runTestsAndSweep(m)
|
||||
}
|
||||
|
||||
|
|
@ -417,9 +453,360 @@ func testMainInner(m *testing.M) int {
|
|||
}
|
||||
}
|
||||
|
||||
if gitDirs.common != "" {
|
||||
changes := diffRepoGitState(gitStateBefore, readRepoGitState(gitDirs))
|
||||
// PinSuiteTempRoot pointed TMPDIR at the suite root, which the
|
||||
// deferred cleanup deletes; keep the pre-run copies beside it.
|
||||
report, failed := reportGitStateChanges(changes, gitStateBefore, filepath.Dir(testTempRoot))
|
||||
fmt.Fprint(os.Stderr, report)
|
||||
if failed && code == 0 {
|
||||
code = 1
|
||||
}
|
||||
}
|
||||
|
||||
return code
|
||||
}
|
||||
|
||||
// repoGitDirs names a checkout's git directories: gitDir is its own (a linked
|
||||
// worktree's .git/worktrees/<name>), common is the one every worktree of the
|
||||
// clone shares. They are the same directory for a main checkout.
|
||||
type repoGitDirs struct {
|
||||
gitDir, common string
|
||||
}
|
||||
|
||||
func (d repoGitDirs) commonConfig() string { return filepath.Join(d.common, "config") }
|
||||
|
||||
// worktreeConfig is the checkout's own config.worktree. A main checkout's sits
|
||||
// in the common dir beside the shared config. With extensions.worktreeConfig
|
||||
// set, git reads it after the shared config, so its keys win, and
|
||||
// `git config --worktree` writes there.
|
||||
func (d repoGitDirs) worktreeConfig() string {
|
||||
if d.gitDir == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(d.gitDir, "config.worktree")
|
||||
}
|
||||
|
||||
// locateRepoGitDirs resolves repoRoot's git directories once, before the run,
|
||||
// so the post-run read looks at the same files even if a test rewrote the
|
||||
// checkout's .git pointer. A repoRoot outside any checkout (Bazel runfiles, a
|
||||
// source tarball) has nothing to guard and is not an error.
|
||||
func locateRepoGitDirs(repoRoot string) (repoGitDirs, error) {
|
||||
if repoRoot == "" {
|
||||
return repoGitDirs{}, nil
|
||||
}
|
||||
cmd := gitCommand("-C", repoRoot, "rev-parse", "--git-dir", "--git-common-dir")
|
||||
var stderr strings.Builder
|
||||
cmd.Stderr = &stderr
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
if _, statErr := os.Lstat(filepath.Join(repoRoot, ".git")); errors.Is(statErr, os.ErrNotExist) {
|
||||
return repoGitDirs{}, nil
|
||||
}
|
||||
return repoGitDirs{}, fmt.Errorf("git rev-parse in %s: %w: %s", repoRoot, err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
|
||||
if len(lines) < 2 {
|
||||
return repoGitDirs{}, fmt.Errorf("git rev-parse in %s: unexpected output %q", repoRoot, out)
|
||||
}
|
||||
dirs := repoGitDirs{
|
||||
gitDir: resolveGitPath(repoRoot, strings.TrimSpace(lines[0])),
|
||||
common: resolveGitPath(repoRoot, strings.TrimSpace(lines[1])),
|
||||
}
|
||||
if dirs.common == "" {
|
||||
return repoGitDirs{}, fmt.Errorf("git rev-parse in %s: no common git dir in %q", repoRoot, out)
|
||||
}
|
||||
return dirs, nil
|
||||
}
|
||||
|
||||
// repoGitState captures the parts of a checkout's own git state that the r880
|
||||
// incident showed a test escape mutates: the common (shared) config, the
|
||||
// checkout's own config.worktree, and every file under the common hooks dir.
|
||||
// Files are keyed by absolute path, and a missing one is recorded as missing,
|
||||
// so a deletion and a re-creation both show up.
|
||||
type repoGitState struct {
|
||||
dirs repoGitDirs
|
||||
files map[string]gitFileSnap
|
||||
}
|
||||
|
||||
type gitFileSnap struct {
|
||||
present bool
|
||||
data string
|
||||
}
|
||||
|
||||
func readRepoGitState(dirs repoGitDirs) repoGitState {
|
||||
state := repoGitState{dirs: dirs, files: map[string]gitFileSnap{}}
|
||||
snapFile := func(p string) {
|
||||
data, err := os.ReadFile(p)
|
||||
state.files[p] = gitFileSnap{present: err == nil, data: string(data)}
|
||||
}
|
||||
snapFile(dirs.commonConfig())
|
||||
if p := dirs.worktreeConfig(); p != "" {
|
||||
snapFile(p)
|
||||
}
|
||||
_ = filepath.Walk(filepath.Join(dirs.common, "hooks"), func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil || info == nil || info.IsDir() {
|
||||
return nil //nolint:nilerr // best-effort snapshot; a walk error just narrows what gets watched
|
||||
}
|
||||
snapFile(path)
|
||||
return nil
|
||||
})
|
||||
return state
|
||||
}
|
||||
|
||||
// gitStateChange is one watched git-state file that differs across the run.
|
||||
// detail names what changed (config keys, or a file-level summary) and never
|
||||
// echoes a value: configs carry remote URLs and can carry credentials.
|
||||
type gitStateChange struct {
|
||||
path string
|
||||
detail string
|
||||
routine bool
|
||||
}
|
||||
|
||||
// diffRepoGitState compares two readRepoGitState results. A common-config
|
||||
// change is routine when every changed key is one that other worktrees of a
|
||||
// shared clone rewrite as a matter of course (routineSharedConfigKey). Any
|
||||
// other change (a hook file, config.worktree, core.*, user.*, extensions.*, an
|
||||
// existing remote's url, origin added or removed) is the clobber class.
|
||||
func diffRepoGitState(before, after repoGitState) []gitStateChange {
|
||||
paths := make([]string, 0, len(before.files))
|
||||
for p := range before.files {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
for p := range after.files {
|
||||
if _, ok := before.files[p]; !ok {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
}
|
||||
slices.Sort(paths)
|
||||
|
||||
var changes []gitStateChange
|
||||
for _, p := range paths {
|
||||
b, a := before.files[p], after.files[p]
|
||||
switch {
|
||||
case b == a:
|
||||
continue
|
||||
case !b.present:
|
||||
changes = append(changes, gitStateChange{path: p, detail: fmt.Sprintf("new file (%d bytes)", len(a.data))})
|
||||
case !a.present:
|
||||
changes = append(changes, gitStateChange{path: p, detail: fmt.Sprintf("deleted (was %d bytes)", len(b.data))})
|
||||
case p == before.dirs.commonConfig():
|
||||
changes = append(changes, diffGitConfig(p, b.data, a.data, true))
|
||||
case p == before.dirs.worktreeConfig():
|
||||
changes = append(changes, diffGitConfig(p, b.data, a.data, false))
|
||||
default:
|
||||
changes = append(changes, gitStateChange{path: p, detail: fmt.Sprintf("changed (%d → %d bytes)", len(b.data), len(a.data))})
|
||||
}
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
// diffGitConfig names the keys that differ between two versions of a git
|
||||
// config file. shared marks the clone's common config, the only file where
|
||||
// routine shared-clone keys do not count as a clobber.
|
||||
func diffGitConfig(path, before, after string, shared bool) gitStateChange {
|
||||
change := gitStateChange{path: path}
|
||||
b, errBefore := gitConfigEntries(before)
|
||||
a, errAfter := gitConfigEntries(after)
|
||||
if err := errors.Join(errBefore, errAfter); err != nil {
|
||||
change.detail = fmt.Sprintf("changed (%d → %d bytes), not parseable as git config: %v", len(before), len(after), err)
|
||||
return change
|
||||
}
|
||||
var clobbered, routine []string
|
||||
for _, key := range changedConfigKeys(b, a) {
|
||||
if shared && routineSharedConfigKey(key, b, a) {
|
||||
routine = append(routine, describeConfigKey(key, b, a))
|
||||
} else {
|
||||
clobbered = append(clobbered, describeConfigKey(key, b, a))
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(clobbered) > 0:
|
||||
change.detail = summarizeConfigKeys(clobbered)
|
||||
if len(routine) > 0 {
|
||||
change.detail += fmt.Sprintf("; also %d branch/remote key change(s)", len(routine))
|
||||
}
|
||||
case len(routine) > 0:
|
||||
change.routine = true
|
||||
change.detail = summarizeConfigKeys(routine)
|
||||
default:
|
||||
// Same keys and values in different bytes: an empty section left
|
||||
// behind by a removal, or reformatting. Nothing git reads changed.
|
||||
change.routine = true
|
||||
change.detail = "rewritten with no key or value change"
|
||||
}
|
||||
return change
|
||||
}
|
||||
|
||||
// gitConfigEntries parses git config file contents with git itself. `git
|
||||
// config --file -` reads only stdin (no includes, no -c or env config), and
|
||||
// each key maps to its raw records in file order, so a multi-valued key
|
||||
// compares as a list.
|
||||
func gitConfigEntries(data string) (map[string][]string, error) {
|
||||
cmd := gitCommand("config", "--file", "-", "--list", "-z")
|
||||
cmd.Dir = os.TempDir()
|
||||
cmd.Stdin = strings.NewReader(data)
|
||||
var stderr strings.Builder
|
||||
cmd.Stderr = &stderr
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
entries := map[string][]string{}
|
||||
for _, record := range strings.Split(string(out), "\x00") {
|
||||
if record == "" {
|
||||
continue
|
||||
}
|
||||
key, _, _ := strings.Cut(record, "\n")
|
||||
entries[key] = append(entries[key], record)
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func changedConfigKeys(before, after map[string][]string) []string {
|
||||
var keys []string
|
||||
for key, values := range before {
|
||||
if !slices.Equal(values, after[key]) {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
for key := range after {
|
||||
if _, ok := before[key]; !ok {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
slices.Sort(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// routineSharedConfigKey reports whether a change to key in a clone's common
|
||||
// config is one that other worktrees of the clone make as a matter of course:
|
||||
// branch tracking (branch.<name>.*, from checkout -b, push -u or branch -d in
|
||||
// any worktree) and a remote other than origin added or removed whole
|
||||
// (remote.<name>.* where that remote exists on only one side). A changed key
|
||||
// of a remote that exists both before and after, such as remote.origin.url,
|
||||
// is the r880 clobber. So is origin itself appearing or disappearing: the
|
||||
// clone's worktrees do not add or remove it, while `git remote add origin` and
|
||||
// `git remote remove origin` are common fixture steps.
|
||||
func routineSharedConfigKey(key string, before, after map[string][]string) bool {
|
||||
section, subsection, _ := splitConfigKey(key)
|
||||
switch {
|
||||
case subsection == "":
|
||||
return false
|
||||
case section == "branch":
|
||||
return true
|
||||
case section == "remote" && subsection != "origin":
|
||||
return !hasConfigSubsection(before, section, subsection) || !hasConfigSubsection(after, section, subsection)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// splitConfigKey splits a `git config --list` key into section, subsection and
|
||||
// variable name. A subsection may contain dots; section and name cannot.
|
||||
func splitConfigKey(key string) (section, subsection, name string) {
|
||||
first, last := strings.IndexByte(key, '.'), strings.LastIndexByte(key, '.')
|
||||
if first < 0 || first == last {
|
||||
section, name, _ = strings.Cut(key, ".")
|
||||
return section, "", name
|
||||
}
|
||||
return key[:first], key[first+1 : last], key[last+1:]
|
||||
}
|
||||
|
||||
func hasConfigSubsection(entries map[string][]string, section, subsection string) bool {
|
||||
for key := range entries {
|
||||
if s, sub, _ := splitConfigKey(key); s == section && sub == subsection {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func describeConfigKey(key string, before, after map[string][]string) string {
|
||||
_, had := before[key]
|
||||
_, has := after[key]
|
||||
switch {
|
||||
case !had:
|
||||
return key + " added"
|
||||
case !has:
|
||||
return key + " removed"
|
||||
}
|
||||
return key + " changed"
|
||||
}
|
||||
|
||||
// summarizeConfigKeys joins key descriptions, capped so a sibling deleting a
|
||||
// few hundred branches cannot flood the test log.
|
||||
func summarizeConfigKeys(descriptions []string) string {
|
||||
const limit = 12
|
||||
if len(descriptions) <= limit {
|
||||
return strings.Join(descriptions, ", ")
|
||||
}
|
||||
return fmt.Sprintf("%s, and %d more", strings.Join(descriptions[:limit], ", "), len(descriptions)-limit)
|
||||
}
|
||||
|
||||
// reportGitStateChanges renders the guard's verdict on changes. Routine
|
||||
// shared-clone changes get a NOTE and leave the run green: this suite and any
|
||||
// other process using the clone could have made them. Anything else is an
|
||||
// ERROR that fails the run, and the pre-run copies of the affected files are
|
||||
// saved under saveDir so a clobbered config can be restored by hand.
|
||||
func reportGitStateChanges(changes []gitStateChange, before repoGitState, saveDir string) (report string, failed bool) {
|
||||
var routine, clobbered []gitStateChange
|
||||
for _, c := range changes {
|
||||
if c.routine {
|
||||
routine = append(routine, c)
|
||||
} else {
|
||||
clobbered = append(clobbered, c)
|
||||
}
|
||||
}
|
||||
var out strings.Builder
|
||||
if len(routine) > 0 {
|
||||
fmt.Fprintf(&out, "NOTE: this clone's shared git config changed during the run, by this suite or another "+
|
||||
"process using the clone; branch tracking and whole-remote changes are routine for a shared clone "+
|
||||
"(values not shown):\n%s\n", formatGitStateChanges(routine))
|
||||
}
|
||||
if len(clobbered) > 0 {
|
||||
saved := "pre-run copies of the changed files: "
|
||||
if dir, err := saveGitStateBefore(saveDir, before, clobbered); err != nil {
|
||||
saved = fmt.Sprintf("could not save pre-run copies of the changed files: %v", err)
|
||||
} else {
|
||||
saved += dir
|
||||
}
|
||||
fmt.Fprintf(&out, "ERROR: test suite modified this checkout's own git state "+
|
||||
"(the wy-qlvlmf host-clobber class — a test ran git against the checkout instead of a fixture, "+
|
||||
"unless another process rewrote the clone during the run; values not shown):\n%s\n%s\n",
|
||||
formatGitStateChanges(clobbered), saved)
|
||||
}
|
||||
return out.String(), len(clobbered) > 0
|
||||
}
|
||||
|
||||
func formatGitStateChanges(changes []gitStateChange) string {
|
||||
lines := make([]string, 0, len(changes))
|
||||
for _, c := range changes {
|
||||
lines = append(lines, fmt.Sprintf("- %s: %s", c.path, c.detail))
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// saveGitStateBefore copies the pre-run contents of each changed file that
|
||||
// existed before the run into a new private directory under dir and returns
|
||||
// that directory. Each copy is named after its original absolute path.
|
||||
func saveGitStateBefore(dir string, before repoGitState, changes []gitStateChange) (string, error) {
|
||||
out, err := os.MkdirTemp(dir, "bd-test-git-state-before-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
flatten := strings.NewReplacer("/", "_", `\`, "_", ":", "_")
|
||||
for _, c := range changes {
|
||||
f := before.files[c.path]
|
||||
if !f.present {
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(out, flatten.Replace(c.path)), []byte(f.data), 0o600); err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// worktreeFallbackBeadsDirDirect resolves the shared .beads directory a
|
||||
// linked worktree at repoRoot would fall back to, via a direct git shell-out
|
||||
// independent of internal/git's process-wide cache (which
|
||||
|
|
|
|||
508
cmd/bd/test_repo_git_guard_test.go
Normal file
508
cmd/bd/test_repo_git_guard_test.go
Normal file
|
|
@ -0,0 +1,508 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// These tests drive the TestMain git-state guard in
|
||||
// test_repo_beads_guard_test.go against throwaway clones, never this checkout.
|
||||
// Each fixture is a main checkout plus one linked worktree, the layout the
|
||||
// r880 clobber broke (wy-qlvlmf): the guard reads the clone's shared common
|
||||
// dir through the linked worktree, as it does when the suite runs from one.
|
||||
|
||||
// guardFixtureHost appears in every remote URL the fixtures write. No guard
|
||||
// report may contain it: configs carry remote URLs and can carry credentials.
|
||||
const guardFixtureHost = "guard-fixture.invalid"
|
||||
|
||||
// newGitGuardFixture returns a main checkout with an origin remote and an
|
||||
// origin/main tracking ref, and a detached linked worktree of it.
|
||||
func newGitGuardFixture(t *testing.T) (mainDir, linkedDir string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
mainDir = filepath.Join(root, "main")
|
||||
if err := os.Mkdir(mainDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initGitRepoAt(t, mainDir)
|
||||
runGitForBootstrapTest(t, mainDir, "commit", "--allow-empty", "-m", "init")
|
||||
runGitForBootstrapTest(t, mainDir, "remote", "add", "origin", "https://"+guardFixtureHost+"/upstream.git")
|
||||
runGitForBootstrapTest(t, mainDir, "update-ref", "refs/remotes/origin/main", "HEAD")
|
||||
linkedDir = filepath.Join(root, "linked")
|
||||
runGitForBootstrapTest(t, mainDir, "worktree", "add", "--detach", linkedDir)
|
||||
return mainDir, linkedDir
|
||||
}
|
||||
|
||||
func locateGitGuardFixture(t *testing.T, dir string) repoGitDirs {
|
||||
t.Helper()
|
||||
dirs, err := locateRepoGitDirs(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("locateRepoGitDirs(%s): %v", dir, err)
|
||||
}
|
||||
if dirs.common == "" {
|
||||
t.Fatalf("locateRepoGitDirs(%s) found no common git dir", dir)
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
func evalRealPath(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
real, err := filepath.EvalSymlinks(p)
|
||||
if err != nil {
|
||||
t.Fatalf("EvalSymlinks(%s): %v", p, err)
|
||||
}
|
||||
return real
|
||||
}
|
||||
|
||||
func TestLocateRepoGitDirs(t *testing.T) {
|
||||
mainDir, linkedDir := newGitGuardFixture(t)
|
||||
wantCommon := evalRealPath(t, filepath.Join(mainDir, ".git"))
|
||||
|
||||
t.Run("main checkout", func(t *testing.T) {
|
||||
dirs := locateGitGuardFixture(t, mainDir)
|
||||
if got := evalRealPath(t, dirs.common); got != wantCommon {
|
||||
t.Errorf("common = %s, want %s", got, wantCommon)
|
||||
}
|
||||
if got := evalRealPath(t, dirs.gitDir); got != wantCommon {
|
||||
t.Errorf("gitDir = %s, want the common dir %s", got, wantCommon)
|
||||
}
|
||||
// A main checkout has a config.worktree too, beside the shared config.
|
||||
if got, want := dirs.worktreeConfig(), filepath.Join(dirs.gitDir, "config.worktree"); got != want {
|
||||
t.Errorf("worktreeConfig() = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("linked worktree", func(t *testing.T) {
|
||||
dirs := locateGitGuardFixture(t, linkedDir)
|
||||
if got := evalRealPath(t, dirs.common); got != wantCommon {
|
||||
t.Errorf("common = %s, want %s", got, wantCommon)
|
||||
}
|
||||
if got, want := evalRealPath(t, dirs.gitDir), filepath.Join(wantCommon, "worktrees", "linked"); got != want {
|
||||
t.Errorf("gitDir = %s, want %s", got, want)
|
||||
}
|
||||
if got, want := dirs.worktreeConfig(), filepath.Join(dirs.gitDir, "config.worktree"); got != want {
|
||||
t.Errorf("worktreeConfig() = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not a checkout", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// Keep git from walking up to a repository above the temp dir.
|
||||
t.Setenv("GIT_CEILING_DIRECTORIES", filepath.Dir(dir))
|
||||
dirs, err := locateRepoGitDirs(dir)
|
||||
if err != nil || dirs != (repoGitDirs{}) {
|
||||
t.Fatalf("got (%+v, %v); a tree with no .git (Bazel runfiles, a tarball) has nothing to guard and is not an error", dirs, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("broken checkout", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
gitFile := "gitdir: " + filepath.Join(dir, "missing") + "\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git"), []byte(gitFile), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := locateRepoGitDirs(dir); err == nil {
|
||||
t.Fatal("no error for a .git that points nowhere; the guard would drop its git check without a warning")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestDiffRepoGitStateClassifiesGitWrites runs the git commands that other
|
||||
// worktrees of a shared clone run routinely, and the writes the r880 clobber
|
||||
// made, and checks which ones the guard lets through.
|
||||
func TestDiffRepoGitStateClassifiesGitWrites(t *testing.T) {
|
||||
type fixture struct {
|
||||
mainDir, linkedDir string
|
||||
dirs repoGitDirs
|
||||
}
|
||||
git := func(dir func(fixture) string, args ...string) func(*testing.T, fixture) {
|
||||
return func(t *testing.T, f fixture) {
|
||||
t.Helper()
|
||||
runGitForBootstrapTest(t, dir(f), args...)
|
||||
}
|
||||
}
|
||||
inMain := func(f fixture) string { return f.mainDir }
|
||||
inLinked := func(f fixture) string { return f.linkedDir }
|
||||
writeHook := func(name, content string) func(*testing.T, fixture) {
|
||||
return func(t *testing.T, f fixture) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(f.dirs.common, "hooks", name), []byte(content), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
both := func(steps ...func(*testing.T, fixture)) func(*testing.T, fixture) {
|
||||
return func(t *testing.T, f fixture) {
|
||||
t.Helper()
|
||||
for _, step := range steps {
|
||||
step(t, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
forkURL := "https://" + guardFixtureHost + "/fork.git"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
guardMain bool // guard the main checkout instead of the linked worktree
|
||||
setup func(*testing.T, fixture) // before the first snapshot
|
||||
act func(*testing.T, fixture) // between the snapshots
|
||||
routine bool
|
||||
want []string // fragments of the one change's detail; nil means no change at all
|
||||
}{
|
||||
{
|
||||
name: "read-only git commands",
|
||||
act: both(git(inMain, "rev-parse", "HEAD"), git(inLinked, "config", "--get", "user.email")),
|
||||
},
|
||||
{
|
||||
name: "branch tracking set up by another worktree",
|
||||
act: git(inMain, "branch", "--track", "feature", "origin/main"),
|
||||
routine: true,
|
||||
want: []string{"branch.feature.remote added", "branch.feature.merge added"},
|
||||
},
|
||||
{
|
||||
name: "tracked branch with a dotted name deleted",
|
||||
setup: git(inMain, "branch", "--track", "release/v1.2", "origin/main"),
|
||||
act: git(inMain, "branch", "-D", "release/v1.2"),
|
||||
routine: true,
|
||||
want: []string{"branch.release/v1.2.remote removed", "branch.release/v1.2.merge removed"},
|
||||
},
|
||||
{
|
||||
name: "remote added",
|
||||
act: git(inMain, "remote", "add", "fork", forkURL),
|
||||
routine: true,
|
||||
want: []string{"remote.fork.url added", "remote.fork.fetch added"},
|
||||
},
|
||||
{
|
||||
name: "remote removed",
|
||||
setup: git(inMain, "remote", "add", "fork", forkURL),
|
||||
act: git(inMain, "remote", "remove", "fork"),
|
||||
routine: true,
|
||||
want: []string{"remote.fork.url removed", "remote.fork.fetch removed"},
|
||||
},
|
||||
{
|
||||
name: "existing remote repointed",
|
||||
act: git(inLinked, "remote", "set-url", "origin", "https://"+guardFixtureHost+"/test-fixture.git"),
|
||||
want: []string{"remote.origin.url changed"},
|
||||
},
|
||||
{
|
||||
// Unlike other remotes, the clone's origin is not added or
|
||||
// removed whole by its worktrees.
|
||||
name: "origin removed",
|
||||
act: git(inLinked, "remote", "remove", "origin"),
|
||||
want: []string{"remote.origin.url removed", "remote.origin.fetch removed"},
|
||||
},
|
||||
{
|
||||
name: "origin added",
|
||||
setup: git(inMain, "remote", "remove", "origin"),
|
||||
act: git(inLinked, "remote", "add", "origin", "https://"+guardFixtureHost+"/test-fixture.git"),
|
||||
want: []string{"remote.origin.url added", "remote.origin.fetch added"},
|
||||
},
|
||||
{
|
||||
name: "core.bare flipped",
|
||||
act: git(inLinked, "config", "core.bare", "true"),
|
||||
want: []string{"core.bare changed"},
|
||||
},
|
||||
{
|
||||
name: "worktree config extension enabled",
|
||||
act: git(inLinked, "config", "extensions.worktreeConfig", "true"),
|
||||
want: []string{"extensions.worktreeconfig added"},
|
||||
},
|
||||
{
|
||||
name: "identity rewritten",
|
||||
act: git(inLinked, "config", "user.email", "fixture@"+guardFixtureHost),
|
||||
want: []string{"user.email changed"},
|
||||
},
|
||||
{
|
||||
name: "hooks path rewritten",
|
||||
act: git(inLinked, "config", "core.hooksPath", "/dev/null"),
|
||||
want: []string{"core.hookspath changed"},
|
||||
},
|
||||
{
|
||||
name: "clobber next to routine branch tracking",
|
||||
act: both(
|
||||
git(inMain, "branch", "--track", "feature", "origin/main"),
|
||||
git(inLinked, "config", "core.bare", "true"),
|
||||
),
|
||||
want: []string{"core.bare changed", "also 2 branch/remote key change(s)"},
|
||||
},
|
||||
{
|
||||
name: "hook written",
|
||||
act: writeHook("pre-commit", "#!/bin/sh\nexit 0\n"),
|
||||
want: []string{"new file (17 bytes)"},
|
||||
},
|
||||
{
|
||||
name: "hook rewritten",
|
||||
setup: writeHook("pre-push", "#!/bin/sh\n"),
|
||||
act: writeHook("pre-push", "#!/bin/sh\nexit 1\n"),
|
||||
want: []string{"changed (10 → 17 bytes)"},
|
||||
},
|
||||
{
|
||||
name: "hook deleted",
|
||||
setup: writeHook("pre-push", "#!/bin/sh\n"),
|
||||
act: func(t *testing.T, f fixture) {
|
||||
if err := os.Remove(filepath.Join(f.dirs.common, "hooks", "pre-push")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
want: []string{"deleted (was 10 bytes)"},
|
||||
},
|
||||
{
|
||||
// Only the common config gets the shared-clone allowance: nothing
|
||||
// but this worktree writes its config.worktree.
|
||||
name: "branch key written to config.worktree",
|
||||
setup: both(
|
||||
git(inMain, "config", "extensions.worktreeConfig", "true"),
|
||||
git(inLinked, "config", "--worktree", "core.sparseCheckout", "false"),
|
||||
),
|
||||
act: git(inLinked, "config", "--worktree", "branch.feature.remote", "origin"),
|
||||
want: []string{"branch.feature.remote added"},
|
||||
},
|
||||
{
|
||||
// A main checkout's config.worktree lives in the common dir, and
|
||||
// with the extension on its keys override the shared config.
|
||||
name: "main checkout's config.worktree written",
|
||||
guardMain: true,
|
||||
setup: both(
|
||||
git(inMain, "config", "extensions.worktreeConfig", "true"),
|
||||
git(inMain, "config", "--worktree", "core.sparseCheckout", "false"),
|
||||
),
|
||||
act: git(inMain, "config", "--worktree", "core.hooksPath", "/dev/null"),
|
||||
want: []string{"core.hookspath added"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mainDir, linkedDir := newGitGuardFixture(t)
|
||||
guarded := linkedDir
|
||||
if tt.guardMain {
|
||||
guarded = mainDir
|
||||
}
|
||||
f := fixture{mainDir: mainDir, linkedDir: linkedDir, dirs: locateGitGuardFixture(t, guarded)}
|
||||
if tt.setup != nil {
|
||||
tt.setup(t, f)
|
||||
}
|
||||
before := readRepoGitState(f.dirs)
|
||||
tt.act(t, f)
|
||||
changes := diffRepoGitState(before, readRepoGitState(f.dirs))
|
||||
|
||||
if tt.want == nil {
|
||||
if len(changes) != 0 {
|
||||
t.Fatalf("got changes %+v, want none", changes)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(changes) != 1 {
|
||||
t.Fatalf("got %d changes %+v, want 1", len(changes), changes)
|
||||
}
|
||||
c := changes[0]
|
||||
if c.routine != tt.routine {
|
||||
t.Errorf("routine = %v, want %v (detail %q)", c.routine, tt.routine, c.detail)
|
||||
}
|
||||
for _, w := range tt.want {
|
||||
if !strings.Contains(c.detail, w) {
|
||||
t.Errorf("detail %q does not mention %q", c.detail, w)
|
||||
}
|
||||
}
|
||||
if strings.Contains(c.detail, guardFixtureHost) {
|
||||
t.Errorf("detail %q echoes a config value", c.detail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffGitConfigText(t *testing.T) {
|
||||
const base = "[core]\n\tbare = false\n" +
|
||||
"[remote \"origin\"]\n\turl = https://" + guardFixtureHost + "/upstream.git\n" +
|
||||
"\tfetch = +refs/heads/*:refs/remotes/origin/*\n"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
after string
|
||||
shared bool
|
||||
routine bool
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "comments and layout only",
|
||||
after: "# reformatted\n[core]\nbare=false\n[remote \"origin\"]\n" +
|
||||
"url = https://" + guardFixtureHost + "/upstream.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n",
|
||||
shared: true,
|
||||
routine: true,
|
||||
want: "rewritten with no key or value change",
|
||||
},
|
||||
{
|
||||
name: "empty section left behind by a removal",
|
||||
after: base + "[branch \"gone\"]\n",
|
||||
shared: true,
|
||||
routine: true,
|
||||
want: "rewritten with no key or value change",
|
||||
},
|
||||
{
|
||||
name: "not parseable",
|
||||
after: "[core\n\tbare = true\n",
|
||||
shared: true,
|
||||
want: "not parseable as git config",
|
||||
},
|
||||
{
|
||||
name: "existing remote gains a fetch refspec",
|
||||
after: base + "[remote \"origin\"]\n\tfetch = +refs/pull/*/head:refs/remotes/origin/pr/*\n",
|
||||
shared: true,
|
||||
want: "remote.origin.fetch changed",
|
||||
},
|
||||
{
|
||||
name: "remote with a dotted name added",
|
||||
after: base + "[remote \"my.fork\"]\n\turl = https://" + guardFixtureHost + "/fork.git\n",
|
||||
shared: true,
|
||||
routine: true,
|
||||
want: "remote.my.fork.url added",
|
||||
},
|
||||
{
|
||||
name: "branch key outside the shared config",
|
||||
after: base + "[branch \"feature\"]\n\tremote = origin\n",
|
||||
shared: false,
|
||||
want: "branch.feature.remote added",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := diffGitConfig("config", base, tt.after, tt.shared)
|
||||
if c.routine != tt.routine {
|
||||
t.Errorf("routine = %v, want %v (detail %q)", c.routine, tt.routine, c.detail)
|
||||
}
|
||||
if !strings.Contains(c.detail, tt.want) {
|
||||
t.Errorf("detail %q does not mention %q", c.detail, tt.want)
|
||||
}
|
||||
if strings.Contains(c.detail, guardFixtureHost) {
|
||||
t.Errorf("detail %q echoes a config value", c.detail)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("long key lists are capped", func(t *testing.T) {
|
||||
var after strings.Builder
|
||||
after.WriteString(base)
|
||||
for i := range 20 {
|
||||
fmt.Fprintf(&after, "[branch \"b%02d\"]\n\tremote = origin\n", i)
|
||||
}
|
||||
c := diffGitConfig("config", base, after.String(), true)
|
||||
if !c.routine || !strings.HasSuffix(c.detail, ", and 8 more") {
|
||||
t.Errorf("got routine=%v detail %q, want a routine change listing 12 keys and 8 more", c.routine, c.detail)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSplitConfigKey(t *testing.T) {
|
||||
for _, tt := range []struct{ key, section, subsection, name string }{
|
||||
{"core.bare", "core", "", "bare"},
|
||||
{"remote.origin.url", "remote", "origin", "url"},
|
||||
{"branch.release/v1.2.merge", "branch", "release/v1.2", "merge"},
|
||||
{"remote.my.fork.gh-resolved", "remote", "my.fork", "gh-resolved"},
|
||||
} {
|
||||
section, subsection, name := splitConfigKey(tt.key)
|
||||
if section != tt.section || subsection != tt.subsection || name != tt.name {
|
||||
t.Errorf("splitConfigKey(%q) = (%q, %q, %q), want (%q, %q, %q)",
|
||||
tt.key, section, subsection, name, tt.section, tt.subsection, tt.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportGitStateChanges(t *testing.T) {
|
||||
common := t.TempDir()
|
||||
configPath := filepath.Join(common, "config")
|
||||
hookPath := filepath.Join(common, "hooks", "pre-commit")
|
||||
const configBefore = "[core]\n\tbare = false\n"
|
||||
before := repoGitState{
|
||||
dirs: repoGitDirs{gitDir: common, common: common},
|
||||
files: map[string]gitFileSnap{
|
||||
configPath: {present: true, data: configBefore},
|
||||
hookPath: {present: false},
|
||||
},
|
||||
}
|
||||
routine := gitStateChange{path: configPath, detail: "branch.feature.remote added", routine: true}
|
||||
clobber := gitStateChange{path: configPath, detail: "core.bare changed"}
|
||||
newHook := gitStateChange{path: hookPath, detail: "new file (17 bytes)"}
|
||||
const savedPrefix = "pre-run copies of the changed files: "
|
||||
|
||||
t.Run("no changes", func(t *testing.T) {
|
||||
if report, failed := reportGitStateChanges(nil, before, t.TempDir()); report != "" || failed {
|
||||
t.Errorf("got (%q, %v), want an empty passing report", report, failed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("routine changes only draw a note", func(t *testing.T) {
|
||||
saveDir := t.TempDir()
|
||||
report, failed := reportGitStateChanges([]gitStateChange{routine}, before, saveDir)
|
||||
if failed {
|
||||
t.Error("a routine shared-clone change failed the run")
|
||||
}
|
||||
if !strings.HasPrefix(report, "NOTE: ") || !strings.Contains(report, routine.detail) || strings.Contains(report, "ERROR") {
|
||||
t.Errorf("report %q, want a NOTE naming %q and no ERROR", report, routine.detail)
|
||||
}
|
||||
if entries, err := os.ReadDir(saveDir); err != nil || len(entries) != 0 {
|
||||
t.Errorf("save dir holds %v (err %v), want nothing saved for routine changes", entries, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("clobber fails and saves the pre-run copies", func(t *testing.T) {
|
||||
saveDir := t.TempDir()
|
||||
report, failed := reportGitStateChanges([]gitStateChange{clobber, newHook}, before, saveDir)
|
||||
if !failed {
|
||||
t.Error("a clobber did not fail the run")
|
||||
}
|
||||
for _, want := range []string{"ERROR: ", "wy-qlvlmf", clobber.detail, newHook.detail} {
|
||||
if !strings.Contains(report, want) {
|
||||
t.Errorf("report %q does not mention %q", report, want)
|
||||
}
|
||||
}
|
||||
var savedDir string
|
||||
for _, line := range strings.Split(report, "\n") {
|
||||
if dir, ok := strings.CutPrefix(line, savedPrefix); ok {
|
||||
savedDir = dir
|
||||
}
|
||||
}
|
||||
if filepath.Dir(savedDir) != saveDir {
|
||||
t.Fatalf("report %q names no save dir under %s", report, saveDir)
|
||||
}
|
||||
entries, err := os.ReadDir(savedDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The hook did not exist before the run, so only the config is saved.
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("saved %v, want exactly the pre-run config", entries)
|
||||
}
|
||||
saved := filepath.Join(savedDir, entries[0].Name())
|
||||
if data, err := os.ReadFile(saved); err != nil || string(data) != configBefore {
|
||||
t.Errorf("saved copy = %q (err %v), want %q", data, err, configBefore)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
for path, want := range map[string]os.FileMode{savedDir: 0o700, saved: 0o600} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
} else if got := info.Mode().Perm(); got != want {
|
||||
t.Errorf("%s: mode %v, want %v: a config copy can hold credentials", path, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("notes and errors together", func(t *testing.T) {
|
||||
report, failed := reportGitStateChanges([]gitStateChange{routine, newHook}, before, t.TempDir())
|
||||
note, errPart, found := strings.Cut(report, "ERROR: ")
|
||||
if !failed || !found || !strings.Contains(note, routine.detail) || !strings.Contains(errPart, newHook.detail) {
|
||||
t.Errorf("got (%q, %v), want the routine change under NOTE, the hook under ERROR, and a failed run", report, failed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a failed save is reported and still fails", func(t *testing.T) {
|
||||
report, failed := reportGitStateChanges([]gitStateChange{clobber}, before, filepath.Join(t.TempDir(), "missing"))
|
||||
if !failed || !strings.Contains(report, "could not save pre-run copies") {
|
||||
t.Errorf("got (%q, %v), want a failed run that says the copies were not saved", report, failed)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ go_library(
|
|||
"container_provider.go",
|
||||
"container_provider_windows.go",
|
||||
"dockercontext.go",
|
||||
"git_env.go",
|
||||
"git_test_hooks.go",
|
||||
"localdoltserver.go",
|
||||
"localdoltserver_linux.go",
|
||||
|
|
@ -22,6 +23,7 @@ go_library(
|
|||
importpath = "github.com/steveyegge/beads/internal/testutil",
|
||||
visibility = ["//:__subpackages__"],
|
||||
deps = [
|
||||
"//internal/execenv",
|
||||
"//internal/storage/doltutil",
|
||||
"//internal/testutil/bazeltest",
|
||||
"@com_github_go_sql_driver_mysql//:mysql",
|
||||
|
|
@ -109,6 +111,7 @@ go_test(
|
|||
name = "testutil_test",
|
||||
srcs = [
|
||||
"dockercontext_test.go",
|
||||
"git_env_test.go",
|
||||
"gm2g3g5r_failopen_test.go",
|
||||
"gm2g3g5r_failopen_unix_test.go",
|
||||
"gm2g3g5r_failopen_windows_test.go",
|
||||
|
|
|
|||
52
internal/testutil/git_env.go
Normal file
52
internal/testutil/git_env.go
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package testutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/steveyegge/beads/internal/execenv"
|
||||
)
|
||||
|
||||
// gitRepoLocationKeys are the git environment variables that name a
|
||||
// repository, work tree, index, object store, ref namespace or config file
|
||||
// outright. Each one overrides what git would find from cmd.Dir or -C, so a
|
||||
// value leaked in from the invoking shell or a git hook (git exports GIT_DIR to
|
||||
// every hook it runs) points a fixture's `git init`/`git config` at a
|
||||
// repository or file the test does not own: the r880 host .git/config clobber
|
||||
// (wy-qlvlmf). GIT_CONFIG is the legacy single-file override: `git config`
|
||||
// reads and writes the file it names instead of the repository's config.
|
||||
//
|
||||
// The set is deliberately narrower than internal/gitenv's routing keys. It
|
||||
// leaves GIT_CEILING_DIRECTORIES, GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM
|
||||
// alone because the Bazel and CI test wrappers set those on purpose: a
|
||||
// discovery fence, and a hermetic global config that carries the test
|
||||
// identity. Keys match exactly, so dropping GIT_CONFIG keeps all three.
|
||||
var gitRepoLocationKeys = []string{
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_CONFIG",
|
||||
"GIT_DIR",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_NAMESPACE",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_WORK_TREE",
|
||||
}
|
||||
|
||||
// WithoutGitRepoLocationEnv returns a copy of env without the variables that
|
||||
// name a git repository location, for a fixture command's cmd.Env: the command
|
||||
// then operates on the repository its cmd.Dir resolves to and nothing else.
|
||||
func WithoutGitRepoLocationEnv(env []string) []string {
|
||||
return execenv.Without(env, gitRepoLocationKeys...)
|
||||
}
|
||||
|
||||
// UnsetGitRepoLocationEnv removes the same variables from the current process.
|
||||
// Suites call it first in TestMain so no fixture git command inherits a leaked
|
||||
// location; a test that needs one sets it with t.Setenv.
|
||||
func UnsetGitRepoLocationEnv() error {
|
||||
for _, key := range gitRepoLocationKeys {
|
||||
if err := os.Unsetenv(key); err != nil {
|
||||
return fmt.Errorf("unset %s: %w", key, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
114
internal/testutil/git_env_test.go
Normal file
114
internal/testutil/git_env_test.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package testutil
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// wrapperGitEnv is what tools/bazel/test_env.sh and scripts/ci/lib/test-env.sh
|
||||
// export for every test. The location scrub must leave all of it in place.
|
||||
var wrapperGitEnv = []string{
|
||||
"GIT_CEILING_DIRECTORIES=/sandbox/srcdir:/sandbox/tmp",
|
||||
"GIT_CONFIG_GLOBAL=/sandbox/gitconfig",
|
||||
"GIT_CONFIG_NOSYSTEM=1",
|
||||
}
|
||||
|
||||
func TestWithoutGitRepoLocationEnvKeepsWrapperGitControls(t *testing.T) {
|
||||
env := append([]string{
|
||||
"GIT_DIR=/host/.git/worktrees/wt",
|
||||
"GIT_WORK_TREE=/host",
|
||||
"GIT_COMMON_DIR=/host/.git",
|
||||
"GIT_INDEX_FILE=/host/.git/worktrees/wt/index",
|
||||
"GIT_OBJECT_DIRECTORY=/host/.git/objects",
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES=/host/.git/objects",
|
||||
"GIT_NAMESPACE=host",
|
||||
"GIT_CONFIG=/host/.git/config",
|
||||
"HOME=/sandbox/home",
|
||||
}, wrapperGitEnv...)
|
||||
|
||||
got := WithoutGitRepoLocationEnv(env)
|
||||
want := append([]string{"HOME=/sandbox/home"}, wrapperGitEnv...)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("WithoutGitRepoLocationEnv:\n got %q\nwant %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetGitRepoLocationEnvKeepsWrapperGitControls(t *testing.T) {
|
||||
for _, key := range gitRepoLocationKeys {
|
||||
t.Setenv(key, "/host/"+key)
|
||||
}
|
||||
for _, entry := range wrapperGitEnv {
|
||||
key, value, _ := strings.Cut(entry, "=")
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
if err := UnsetGitRepoLocationEnv(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range gitRepoLocationKeys {
|
||||
if value, ok := os.LookupEnv(key); ok {
|
||||
t.Errorf("%s=%q survived UnsetGitRepoLocationEnv", key, value)
|
||||
}
|
||||
}
|
||||
for _, entry := range wrapperGitEnv {
|
||||
key, want, _ := strings.Cut(entry, "=")
|
||||
if got := os.Getenv(key); got != want {
|
||||
t.Errorf("%s=%q after UnsetGitRepoLocationEnv, want %q kept", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestForceRepoLocalHooksPathIgnoresLeakedGitDir pins the write target: with
|
||||
// GIT_DIR and GIT_WORK_TREE naming another repository, or GIT_CONFIG naming
|
||||
// another config file, the hooksPath write must still land in repoDir and leave
|
||||
// the other config untouched.
|
||||
func TestForceRepoLocalHooksPathIgnoresLeakedGitDir(t *testing.T) {
|
||||
decoy, target := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{decoy, target} {
|
||||
cmd := exec.Command("git", "init", "--quiet", dir)
|
||||
cmd.Env = WithoutGitRepoLocationEnv(os.Environ())
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git init %s: %v\n%s", dir, err, out)
|
||||
}
|
||||
}
|
||||
decoyConfig := filepath.Join(decoy, ".git", "config")
|
||||
before, err := os.ReadFile(decoyConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoyFile := filepath.Join(t.TempDir(), "leaked.gitconfig")
|
||||
const decoyFileBefore = "[user]\n\tname = decoy\n"
|
||||
if err := os.WriteFile(decoyFile, []byte(decoyFileBefore), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
t.Setenv("GIT_CONFIG", decoyFile)
|
||||
if err := ForceRepoLocalHooksPath(target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
after, err := os.ReadFile(decoyConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(after) != string(before) {
|
||||
t.Fatalf("leaked GIT_DIR routed the hooksPath write into %s:\n%s", decoyConfig, after)
|
||||
}
|
||||
if got, err := os.ReadFile(decoyFile); err != nil || string(got) != decoyFileBefore {
|
||||
t.Fatalf("leaked GIT_CONFIG routed the hooksPath write into %s (err %v):\n%s", decoyFile, err, got)
|
||||
}
|
||||
get := exec.Command("git", "config", "--file", filepath.Join(target, ".git", "config"), "--get", "core.hooksPath")
|
||||
out, err := get.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("read target core.hooksPath: %v\n%s", err, out)
|
||||
}
|
||||
if got := strings.TrimSpace(string(out)); got != ".git/hooks" {
|
||||
t.Fatalf("target core.hooksPath=%q, want %q", got, ".git/hooks")
|
||||
}
|
||||
}
|
||||
|
|
@ -2,15 +2,18 @@ package testutil
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ForceRepoLocalHooksPath configures a git test repository to use .git/hooks
|
||||
// regardless of any global core.hooksPath configuration.
|
||||
// regardless of any global core.hooksPath configuration. The write goes to
|
||||
// repoDir even when a GIT_DIR or GIT_WORK_TREE leaked into the process.
|
||||
func ForceRepoLocalHooksPath(repoDir string) error {
|
||||
cmd := exec.Command("git", "config", "core.hooksPath", ".git/hooks")
|
||||
cmd.Dir = repoDir
|
||||
cmd.Env = WithoutGitRepoLocationEnv(os.Environ())
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
trimmed := strings.TrimSpace(string(out))
|
||||
if trimmed != "" {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue