* 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>
143 lines
4.1 KiB
Go
143 lines
4.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/internal/testutil"
|
|
)
|
|
|
|
// Template git repository optimization (bd-ktng):
|
|
// Instead of spawning `git init` per test (~20-30ms each, 60+ calls = 1-2s),
|
|
// create a single template repo and copy its .git/ directory for each test.
|
|
// Directory copy is ~100x faster than subprocess spawn + git initialization.
|
|
|
|
var (
|
|
gitTemplateDir string
|
|
gitTemplateOnce sync.Once
|
|
gitTemplateErr error
|
|
)
|
|
|
|
// initGitTemplate creates a template git repository once via sync.Once.
|
|
// The template includes git init --initial-branch=main plus user.email/user.name config.
|
|
func initGitTemplate() {
|
|
gitTemplateOnce.Do(func() {
|
|
dir, err := os.MkdirTemp("", "git-template-*")
|
|
if err != nil {
|
|
gitTemplateErr = fmt.Errorf("failed to create git template dir: %w", err)
|
|
return
|
|
}
|
|
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
|
|
}
|
|
|
|
for _, args := range [][]string{
|
|
{"config", "user.email", "test@test.com"},
|
|
{"config", "user.name", "Test User"},
|
|
} {
|
|
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
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
// newGitRepo creates a fresh git repository by copying the cached template's .git/ directory.
|
|
// Returns the path to the new directory. Cleanup is handled by t.TempDir().
|
|
func newGitRepo(t *testing.T) string {
|
|
t.Helper()
|
|
initGitTemplate()
|
|
if gitTemplateErr != nil {
|
|
t.Fatalf("Git template initialization failed: %v", gitTemplateErr)
|
|
}
|
|
|
|
dir := t.TempDir()
|
|
if err := copyGitDir(gitTemplateDir, dir); err != nil {
|
|
t.Fatalf("Failed to copy git template: %v", err)
|
|
}
|
|
return dir
|
|
}
|
|
|
|
// copyGitDir copies the .git directory from src to dst.
|
|
func copyGitDir(src, dst string) error {
|
|
if err := copyDirRecursive(filepath.Join(src, ".git"), filepath.Join(dst, ".git")); err != nil {
|
|
return err
|
|
}
|
|
return testutil.ForceRepoLocalHooksPath(dst)
|
|
}
|
|
|
|
// copyDirRecursive recursively copies a directory tree.
|
|
func copyDirRecursive(src, dst string) error {
|
|
entries, err := os.ReadDir(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(dst, 0750); err != nil {
|
|
return err
|
|
}
|
|
for _, entry := range entries {
|
|
srcPath := filepath.Join(src, entry.Name())
|
|
dstPath := filepath.Join(dst, entry.Name())
|
|
if entry.IsDir() {
|
|
if err := copyDirRecursive(srcPath, dstPath); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
data, err := os.ReadFile(srcPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.WriteFile(dstPath, data, 0600); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func TestNewGitRepo_UsesRepoLocalHooksPathDespiteGlobalConfig(t *testing.T) {
|
|
fakeHome := t.TempDir()
|
|
t.Setenv("HOME", fakeHome)
|
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(fakeHome, ".config"))
|
|
t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(fakeHome, ".gitconfig"))
|
|
|
|
globalHooks := filepath.Join(fakeHome, "global-hooks")
|
|
if err := os.MkdirAll(globalHooks, 0755); err != nil {
|
|
t.Fatalf("failed to create fake global hooks dir: %v", err)
|
|
}
|
|
|
|
setGlobal := gitCommand("config", "--global", "core.hooksPath", globalHooks)
|
|
if out, err := setGlobal.CombinedOutput(); err != nil {
|
|
t.Fatalf("failed to set global core.hooksPath: %v (%s)", err, strings.TrimSpace(string(out)))
|
|
}
|
|
|
|
repoDir := newGitRepo(t)
|
|
getLocal := gitCommand("config", "--get", "core.hooksPath")
|
|
getLocal.Dir = repoDir
|
|
out, err := getLocal.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("failed to read repo core.hooksPath: %v (%s)", err, strings.TrimSpace(string(out)))
|
|
}
|
|
|
|
if got := strings.TrimSpace(string(out)); got != ".git/hooks" {
|
|
t.Fatalf("core.hooksPath=%q, want %q", got, ".git/hooks")
|
|
}
|
|
}
|