* fix(worktree): scrub inherited Git routing state Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics. Fixes #5531 Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell * refactor(worktree): explain owned filtering and remove an unused shim Document why filtering the fresh routing slice in place is safe and call the shared routing-key classifier directly from tests. Retain the two forwarders used by production worktree subprocess/removal paths. Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671 Bead: saa-cgh.23 Agent-Signature: unknown-model/unknown-reasoning * fix(config): isolate identity and tracked-file Git probes from routing Reuse the worktree routing owner for GetIdentity and isGitTracked so explicit cwd/path selection is not displaced by inherited repository, index or injected config state. Preserve identity precedence and the tracked-secret refusal contract, with real target/decoy regressions. Follow-up: https://github.com/gastownhall/beads/issues/6222 Dependency: https://github.com/gastownhall/beads/pull/5623 Reported-by: bee-ghosttrack Bead: saa-cgh.93 Agent-Signature: unknown-model/unknown-reasoning * fix(config): share subprocess key identity for Git routing (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(exec): match Windows environment key identity (#5618) Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com> * test(execenv): exercise every environment operation under both host rules Thread the host choice through narrow private helpers behind the existing exported functions. Keep one normalization owner and retain native wrapper tests; the additional table covers both host branches for equality, prefix matching, last-wins lookup, filtering and input preservation. Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965 Bead: saa-cgh.78 Agent-Signature: unknown-model/unknown-reasoning * test(execenv): exercise exported host policy wiring (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(worktree): explain startup Git environment scope (saa-cgh.23) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): isolate role commands from Git routing (saa-cgh.99) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(env): exercise shared key helpers on native Windows (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(config): explain role command routing policy (saa-cgh.99) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): isolate role configuration from inherited Git routing (saa-cgh.109.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): use the selected origin in contributor setup (saa-cgh.109.7) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): isolate Git writes in planning repositories (saa-cgh.109.9) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): retain inherited planning commit author (saa-cgh.109.9) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): align embedded role gates with selected Git context (saa-cgh.109.12) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): scope embedded artifact Git operations to selected directory (saa-cgh.109.15) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): cover selected optional artifacts and explain refused commits (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Honor role-probe cancellation and exercise actual fork planning (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(init): warn when automatic contributor role write fails (saa-cgh.109.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(init): cover successful nonquiet contributor role writes (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Assert the automatic contributor setup banner alongside warnings (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * test(init): read persisted role routing from the store (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): probe the selected repository before configuring roles (saa-cgh.109.8) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96) Reported by bee-ghosttrack in gastownhall/beads#6343. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): clarify exclude fixture path variable (saa-cgh.104) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): refuse exclude writes after read errors (saa-cgh.110) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitignore): share append byte composition (saa-cgh.105) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitignore): use shared composition for exclude rules (saa-cgh.111) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(gitignore): omit the empty exclude leading separator (saa-cgh.112) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): retain legitimate inherited tracking context (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(hooks): isolate trusted global configuration fixture (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(hooks): explain conservative tracked-file guard (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(git): resolve hooks paths in an explicit read-only context (saa-cgh.109.17.1) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * Bind init hook operations to the selected repository (saa-cgh.109.17) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * Give the hooks tail fixture an explicit remote context (saa-cgh.109.17) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(git): canonicalize the hooks fixture repository root (saa-cgh.109.17.1) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init): complete selected hook options and alias handling (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Clarify hooks resolver ownership and preserve work-tree diagnostics (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Explain restoration of absent routing variables in selected exclude tests (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Keep init role operations on the captured selected Git context (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Align selected-tail fixtures with captured role authority (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(init): keep embedded hook setup in the selected project (saa-cgh.120.12) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(init,config): maintainer fixup for #6464 Pre-review CI repair: - Annotate #nosec G702 on the selected hooks-path git invocation. No shell is involved, every path is passed as its own argv element, and both values reach that line absolute via resolveInitHooksContext. Review iteration 1, blocking: - internal/config: give the secret-config guard the inherited-env fallback that the structurally identical hook guard in cmd/bd/hooks.go already has. isGitTracked is the fail-open half of "refuse to write a secret key into a git-tracked config.yaml", and the scrub alone narrowed it to upward discovery from the config file's directory: under a detached work tree (GIT_DIR + GIT_WORK_TREE with no in-tree .git) the probe reported "untracked" and the secret was written into the tracked file. Probe the scrubbed environment first so inherited routing cannot hide a tracked file, then the inherited one; either probe reporting the path as tracked refuses the write. Adds the legitimate-routing subtest that the poisoned-routing matrix could not express. - cmd/bd/config.go: the new comment claimed "All role commands ignore inherited Git routing". Only the writers were hardened - routing.DetectUserRole, beads.RepoContext.Role, `bd config show` and `bd doctor` still resolve beads.role through the inherited environment, so `bd config get beads.role` and `bd config show` can disagree under one environment. Narrow the comment to the four verbs it covers; widening the boundary to the readers is a separate change. Review iteration 1, non-blocking: - cmd/bd/worktree_cmd.go: disclose that ClearRouting unsets the variables on the bd process itself, and state what clearing the discovery-scope controls does to repository selection. The comment previously claimed the opposite of what the init path's own note admits. - cmd/bd/init_proxied_server.go: drop isRoleGitRepo. With workDir set, gitUC is NewInitGitRepository(workDir), whose IsGitRepo runs the same `git rev-parse --git-dir` with the same Dir and scrubbed env; with workDir empty the helper returned its fallback. It was isRepo in both arms, plus a second git subprocess per `bd init --proxied`. - cmd/bd/doctor/gitignore.go: omit the leading blank line when creating a fresh .gitignore, matching the two sibling writers this PR already conditionalized in cff94aa43. Review iteration 2, non-blocking: - cmd/bd/worktree_cmd.go: iteration 1's own rewrite lumped GIT_DISCOVERY_ACROSS_FILESYSTEM in with GIT_CEILING_DIRECTORIES as "removes an inherited stop". That is backwards. git(1) documents that discovery "does not cross filesystem boundaries" by default and that this variable "can be set to true to tell Git not to stop at filesystem boundaries" - it only ever permits, so clearing it *adds* a stop and narrows the walk. Split the clause per control: the ceiling widens, GIT_DISCOVERY_ACROSS_FILESYSTEM narrows (a repository reachable only across a mount point is no longer found by any `bd worktree` verb, with no opt-out), and ClearRouting's GIT_CONFIG prefix match drops the whole GIT_CONFIG* family for the command's lifetime rather than for one child probe. This comment is the only in-tree assertion about the variable's direction; export_auto.go:1083-1085 groups the two without claiming one. - cmd/bd/config.go: "bd config's own beads.role reads and writes" covered `bd config show`, which the very next sentence lists as an exception. Name the four verbs that do scrub (get/set/unset/set-many, at config.go:209, :355, :609 and :902 - the only four git invocations in the file). - internal/config: make the guard's fail-open default unspellable. The mirrored helper took `envs ...[]string`, so a future zero-probe call would fall through to "untracked" and write the secret with no compiler backstop. Promote the first environment to a required parameter. The tail stays variadic rather than matching the twin's fixed (clean, inherited) arity because the fallback's fixture guard has to probe one environment alone, and exec treats a nil Env as "inherit the current process" rather than as a disabled probe. Pre-approval CI repair: - Annotate the four gosec taint findings this PR newly introduces in package cmd/bd: G704 on the two connectivity probes in dolt.go, G702 on the staged-deletion probe in hooks.go and on the ls-remote probe in sync_git.go. None of the four is reported by the PR lane, whose lint is scoped to the diff (only-new-issues / --new-from-merge-base), and all four sit on lines this PR does not otherwise touch - but main.yml runs the same wrapper with BD_LINT_NEW_FROM_MERGE_BASE unset and sweeps the whole tree, so merging as-is turns main's Lint and PR Lint jobs red. Measured whole-tree at pr.yml's pinned golangci-lint v2.10.1 with --build-tags=gms_pure_go: origin/main 0 issues, this head 4, this head with the annotations 0. The findings are taint over-approximation rather than new exposure: gosec's analysis is not field-sensitive, so routing config discovery through env-derived paths marks the whole store value tainted and every remote URL read back off it inherits that. Each annotation states why its own call site is safe; the additions are comment-only, with no deletions and no behaviour change. The hooks.go annotation sits on the isExportFileStagedForDeletion declaration rather than on the exec.Command call. main has since rewritten that body to address the export file through nearestExistingDir + filepath.Rel, so a call-site comment both conflicted with the merge and described an argument the merged body no longer builds. On the declaration it merges cleanly and its justification holds for either body. Pre-approval base refresh (rebased onto511849496): - Reconcile this PR with gastownhall/beads#6477, which landed on main after this branch was first rebased and which changes the same reader. The two changes collide in both directions, and neither side's CI can see it: the PR lane builds this branch against its own base, main's lane never has the PR, and only the merged tree fails. - #6477 direction: its new subtest TestConfig_ReadFailuresAreNotMissing/invalid_routing_boolean poisons GIT_CONFIG_NOSYSTEM and expects the beads.role read to exit 128. This PR scrubs GIT_CONFIG* for exactly that key, so git never sees the poison and the read succeeds. Replaced that row with TestConfig_BeadsRoleScrubsInheritedRoutingEnv, which pins both halves of the new contract: beads.role reads through the scrub, and a key outside it (user.name) still surfaces the same poison as an exit-128 read error rather than as an absent key. #6477's general guarantee is untouched - malformed_config still proves it for beads.role through the repository's own config file. - Opposite direction: this PR's own TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted require.NoError on a generic-constructor read, commented "The existing reader maps Git exit errors to absence" - the precise behaviour #6477 removed. Expect the propagated exit error instead. The test's intent is unchanged and in fact better served: only the current caller environment can see the changed HOME's broken .gitconfig, so that error is itself the proof that generic role reads still use it. * test(init): retarget the bare row to the work-tree-less install policy This PR's TestInitEmbeddedHooksSelectedTail/bare row (authored 2026-09-09) asserted that a bare repository fails to resolve hooks and installs nothing. #6457 (6a4b4aa14e, 2026-09-27) added git.ResolveWorkTreelessHooksContext specifically to end that behavior -- its own comment calls out "turning a supported repository into a warning and no install at all" as the defect it fixes -- so the row pinned a policy main had deliberately superseded by the time the two met. Retargeted in place rather than deleted, so the bare shape keeps coverage through the embedded-init entry point (main's new bare/git_dir_cwd rows cover only the proxied path): bare now installs like any other selected repository, and being its own common directory, its hooks path lands in its own config. Mutation-proved load-bearing: removing the work-tree-less fallback reds this row alone (the other eight rows stay green) with ".../hooks/pre-commit: no such file or directory" -- i.e. it reproduces the original expectation exactly. --------- Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
792 lines
32 KiB
Go
792 lines
32 KiB
Go
package main
|
|
|
|
import (
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/cmd/bd/doctor"
|
|
"github.com/steveyegge/beads/internal/git"
|
|
"github.com/steveyegge/beads/internal/gitenv"
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestConfigureBeadsHooksPath_WorktreeUsesMainRepo(t *testing.T) {
|
|
tmpDir, err := os.MkdirTemp("", "beads-hooks-worktree-test-*")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { os.RemoveAll(tmpDir) })
|
|
|
|
mainRepoDir := filepath.Join(tmpDir, "main-repo")
|
|
if err := os.MkdirAll(mainRepoDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
run := func(args ...string) {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Skipf("git %v failed: %v", args, err)
|
|
}
|
|
}
|
|
run("init")
|
|
run("config", "user.email", "test@example.com")
|
|
run("config", "user.name", "Test User")
|
|
if err := os.WriteFile(filepath.Join(mainRepoDir, "README.md"), []byte("# Test\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
run("add", "README.md")
|
|
run("commit", "-m", "Initial commit")
|
|
|
|
worktreeDir := filepath.Join(tmpDir, "worktree")
|
|
cmd := exec.Command("git", "worktree", "add", worktreeDir, "HEAD")
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Fatalf("git worktree add failed: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
cmd := exec.Command("git", "worktree", "remove", "--force", worktreeDir)
|
|
cmd.Dir = mainRepoDir
|
|
_ = cmd.Run()
|
|
})
|
|
|
|
if err := os.MkdirAll(filepath.Join(mainRepoDir, ".beads", "hooks"), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Chdir(worktreeDir)
|
|
git.ResetCaches()
|
|
|
|
if !git.IsWorktree() {
|
|
t.Fatal("expected git.IsWorktree() to return true")
|
|
}
|
|
|
|
if err := configureBeadsHooksPath(); err != nil {
|
|
t.Fatalf("configureBeadsHooksPath failed: %v", err)
|
|
}
|
|
|
|
cmd = exec.Command("git", "config", "--get", "core.hooksPath")
|
|
cmd.Dir = mainRepoDir
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
t.Fatalf("git config --get core.hooksPath failed: %v", err)
|
|
}
|
|
hooksPath := filepath.Clean(strings.TrimSpace(string(out)))
|
|
expected := filepath.Join(mainRepoDir, ".beads", "hooks")
|
|
hooksPath, _ = filepath.EvalSymlinks(hooksPath)
|
|
expected, _ = filepath.EvalSymlinks(expected)
|
|
if hooksPath != expected {
|
|
t.Errorf("core.hooksPath = %q, want %q", hooksPath, expected)
|
|
}
|
|
}
|
|
|
|
func TestConfigureSharedHooksPath_WorktreeUsesMainRepo(t *testing.T) {
|
|
tmpDir, err := os.MkdirTemp("", "beads-shared-hooks-worktree-test-*")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { os.RemoveAll(tmpDir) })
|
|
|
|
mainRepoDir := filepath.Join(tmpDir, "main-repo")
|
|
if err := os.MkdirAll(mainRepoDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
run := func(args ...string) {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Skipf("git %v failed: %v", args, err)
|
|
}
|
|
}
|
|
run("init")
|
|
run("config", "user.email", "test@example.com")
|
|
run("config", "user.name", "Test User")
|
|
if err := os.WriteFile(filepath.Join(mainRepoDir, "README.md"), []byte("# Test\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
run("add", "README.md")
|
|
run("commit", "-m", "Initial commit")
|
|
|
|
worktreeDir := filepath.Join(tmpDir, "worktree")
|
|
cmd := exec.Command("git", "worktree", "add", worktreeDir, "HEAD")
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Fatalf("git worktree add failed: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
cmd := exec.Command("git", "worktree", "remove", "--force", worktreeDir)
|
|
cmd.Dir = mainRepoDir
|
|
_ = cmd.Run()
|
|
})
|
|
|
|
if err := os.MkdirAll(filepath.Join(mainRepoDir, ".beads-hooks"), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Chdir(worktreeDir)
|
|
git.ResetCaches()
|
|
|
|
if !git.IsWorktree() {
|
|
t.Fatal("expected git.IsWorktree() to return true")
|
|
}
|
|
|
|
if err := configureSharedHooksPath(); err != nil {
|
|
t.Fatalf("configureSharedHooksPath failed: %v", err)
|
|
}
|
|
|
|
cmd = exec.Command("git", "config", "--get", "core.hooksPath")
|
|
cmd.Dir = mainRepoDir
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
t.Fatalf("git config --get core.hooksPath failed: %v", err)
|
|
}
|
|
hooksPath := filepath.Clean(strings.TrimSpace(string(out)))
|
|
expected := filepath.Join(mainRepoDir, ".beads-hooks")
|
|
hooksPath, _ = filepath.EvalSymlinks(hooksPath)
|
|
expected, _ = filepath.EvalSymlinks(expected)
|
|
if hooksPath != expected {
|
|
t.Errorf("core.hooksPath = %q, want %q", hooksPath, expected)
|
|
}
|
|
}
|
|
|
|
func TestResetHooksPathIfBeadsManaged_Worktree(t *testing.T) {
|
|
tmpDir, err := os.MkdirTemp("", "beads-reset-hooks-worktree-test-*")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { os.RemoveAll(tmpDir) })
|
|
|
|
mainRepoDir := filepath.Join(tmpDir, "main-repo")
|
|
if err := os.MkdirAll(mainRepoDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
run := func(args ...string) {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Skipf("git %v failed: %v", args, err)
|
|
}
|
|
}
|
|
run("init")
|
|
run("config", "user.email", "test@example.com")
|
|
run("config", "user.name", "Test User")
|
|
if err := os.WriteFile(filepath.Join(mainRepoDir, "README.md"), []byte("# Test\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
run("add", "README.md")
|
|
run("commit", "-m", "Initial commit")
|
|
|
|
worktreeDir := filepath.Join(tmpDir, "worktree")
|
|
cmd := exec.Command("git", "worktree", "add", worktreeDir, "HEAD")
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Fatalf("git worktree add failed: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
cmd := exec.Command("git", "worktree", "remove", "--force", worktreeDir)
|
|
cmd.Dir = mainRepoDir
|
|
_ = cmd.Run()
|
|
})
|
|
|
|
if err := os.MkdirAll(filepath.Join(mainRepoDir, ".beads", "hooks"), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
hooksPathToSet := filepath.Join(mainRepoDir, ".beads", "hooks")
|
|
evaluated, _ := filepath.EvalSymlinks(hooksPathToSet)
|
|
if evaluated != "" {
|
|
hooksPathToSet = evaluated
|
|
}
|
|
cmd = exec.Command("git", "config", "core.hooksPath", hooksPathToSet)
|
|
cmd.Dir = mainRepoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Fatalf("git config core.hooksPath failed: %v", err)
|
|
}
|
|
|
|
run("config", "beads.role", "primary")
|
|
run("config", "extensions.worktreeConfig", "true")
|
|
cmd = exec.Command("git", "config", "--worktree", "beads.role", "worktree-only")
|
|
cmd.Dir = worktreeDir
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("configure worktree role: %v\n%s", err, out)
|
|
}
|
|
cmd = exec.Command("git", "config", "--worktree", "core.hooksPath", ".beads/hooks")
|
|
cmd.Dir = worktreeDir
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("configure worktree hooksPath: %v\n%s", err, out)
|
|
}
|
|
t.Chdir(worktreeDir)
|
|
git.ResetCaches()
|
|
|
|
if !git.IsWorktree() {
|
|
t.Fatal("expected git.IsWorktree() to return true")
|
|
}
|
|
|
|
git.ResetCaches() // Exercise the actual reset with a cold context.
|
|
if err := resetHooksPathIfBeadsManaged(); err != nil {
|
|
t.Fatalf("resetHooksPathIfBeadsManaged failed: %v", err)
|
|
}
|
|
|
|
cmd = exec.Command("git", "config", "--local", "--get", "core.hooksPath")
|
|
cmd.Dir = mainRepoDir
|
|
out, _ := cmd.Output()
|
|
if strings.TrimSpace(string(out)) != "" {
|
|
t.Errorf("core.hooksPath = %q after reset, want empty", strings.TrimSpace(string(out)))
|
|
}
|
|
cmd = exec.Command("git", "config", "--local", "--get", "beads.role")
|
|
cmd.Dir = mainRepoDir
|
|
out, err = cmd.Output()
|
|
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
|
|
t.Errorf("main role remains after reset: %q, %v", out, err)
|
|
}
|
|
cmd = exec.Command("git", "config", "--worktree", "--get", "beads.role")
|
|
cmd.Dir = worktreeDir
|
|
out, err = cmd.Output()
|
|
if err != nil || strings.TrimSpace(string(out)) != "worktree-only" {
|
|
t.Errorf("worktree-specific role changed: %q, %v", out, err)
|
|
}
|
|
cmd = exec.Command("git", "config", "--worktree", "--get", "core.hooksPath")
|
|
cmd.Dir = worktreeDir
|
|
out, err = cmd.Output()
|
|
if err != nil || strings.TrimSpace(string(out)) != ".beads/hooks" {
|
|
t.Errorf("worktree-specific hooksPath changed: %q, %v", out, err)
|
|
}
|
|
t.Run("preserve_worktree_role", func(t *testing.T) {
|
|
// Seed a new common role so this reset proves removal independently of the first call.
|
|
run("config", "--local", "beads.role", "primary")
|
|
privateDir, err := git.GetGitDir()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
privateConfig := filepath.Join(privateDir, "config.worktree")
|
|
before, err := os.ReadFile(privateConfig)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
git.ResetCaches()
|
|
t.Cleanup(git.ResetCaches)
|
|
if err := resetHooksPathIfBeadsManaged(); err != nil {
|
|
t.Fatalf("reset while preserving a worktree role failed: %v", err)
|
|
}
|
|
if after, err := os.ReadFile(privateConfig); err != nil || string(after) != string(before) {
|
|
t.Fatalf("private worktree config changed: %v", err)
|
|
}
|
|
get := exec.Command("git", "config", "--local", "--get", "beads.role")
|
|
get.Dir = mainRepoDir
|
|
out, err := get.Output()
|
|
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
|
|
t.Errorf("common role after reset = %q, %v; want absent", out, err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestConfigureBeadsHooksPath_NormalRepoUnchanged(t *testing.T) {
|
|
tmpDir, err := os.MkdirTemp("", "beads-hooks-normal-test-*")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { os.RemoveAll(tmpDir) })
|
|
|
|
repoDir := filepath.Join(tmpDir, "repo")
|
|
if err := os.MkdirAll(repoDir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
run := func(args ...string) {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = repoDir
|
|
if err := cmd.Run(); err != nil {
|
|
t.Skipf("git %v failed: %v", args, err)
|
|
}
|
|
}
|
|
run("init")
|
|
run("config", "user.email", "test@example.com")
|
|
run("config", "user.name", "Test User")
|
|
if err := os.WriteFile(filepath.Join(repoDir, "README.md"), []byte("# Test\n"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
run("add", "README.md")
|
|
run("commit", "-m", "Initial commit")
|
|
|
|
if err := os.MkdirAll(filepath.Join(repoDir, ".beads", "hooks"), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Chdir(repoDir)
|
|
git.ResetCaches()
|
|
|
|
if git.IsWorktree() {
|
|
t.Fatal("expected git.IsWorktree() to return false in normal repo")
|
|
}
|
|
|
|
if err := configureBeadsHooksPath(); err != nil {
|
|
t.Fatalf("configureBeadsHooksPath failed: %v", err)
|
|
}
|
|
|
|
cmd := exec.Command("git", "config", "--get", "core.hooksPath")
|
|
cmd.Dir = repoDir
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
t.Fatalf("git config --get core.hooksPath failed: %v", err)
|
|
}
|
|
hooksPath := filepath.Clean(strings.TrimSpace(string(out)))
|
|
expected := filepath.Join(repoDir, ".beads", "hooks")
|
|
hooksPath, _ = filepath.EvalSymlinks(hooksPath)
|
|
expected, _ = filepath.EvalSymlinks(expected)
|
|
if hooksPath != expected {
|
|
t.Errorf("core.hooksPath = %q, want %q", hooksPath, expected)
|
|
}
|
|
}
|
|
|
|
// newInitHooksFixture keeps the selected worktree, ambient repository and
|
|
// storage physically distinct. Git's default HOME is owned by the parent helper.
|
|
func newInitHooksFixture(t *testing.T) (selected, decoy, storage, common string) {
|
|
t.Helper()
|
|
selected, decoy, exclude, _ := newInitExcludeRepos(t)
|
|
common = filepath.Dir(filepath.Dir(exclude))
|
|
storage = filepath.Join(t.TempDir(), "separate storage")
|
|
require.NoError(t, os.Mkdir(storage, 0755))
|
|
require.NoError(t, os.WriteFile(filepath.Join(decoy, "seed"), []byte("decoy\n"), 0600))
|
|
initExcludeGit(t, decoy, "add", "seed")
|
|
initExcludeGit(t, selected, "config", "beads.role", "contributor")
|
|
t.Setenv("BEADS_DIR", filepath.Join(decoy, ".beads"))
|
|
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
|
t.Setenv("GIT_WORK_TREE", decoy)
|
|
t.Setenv("GIT_INDEX_FILE", filepath.Join(decoy, ".git", "index"))
|
|
git.ResetCaches()
|
|
t.Cleanup(git.ResetCaches)
|
|
return selected, decoy, storage, common
|
|
}
|
|
|
|
func readInitHooksFile(t *testing.T, path string) []byte {
|
|
t.Helper()
|
|
data, err := os.ReadFile(path)
|
|
require.NoError(t, err)
|
|
return data
|
|
}
|
|
|
|
func TestInitEmbeddedHooksSelectedTail(t *testing.T) {
|
|
for _, name := range []string{"missing", "skip", "nonrepo", "pure_jj", "quiet_pure_jj", "colocated", "bare", "config_lock", "quiet_config_lock"} {
|
|
t.Run(name, func(t *testing.T) {
|
|
selected, decoy, storage, common := newInitHooksFixture(t)
|
|
preserveInitRoleInputs(t, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index"))
|
|
if name == "nonrepo" || strings.Contains(name, "pure_jj") || name == "bare" {
|
|
selected = t.TempDir()
|
|
}
|
|
if name == "bare" {
|
|
initExcludeGit(t, selected, "init", "--bare")
|
|
}
|
|
if strings.Contains(name, "pure_jj") || name == "colocated" {
|
|
require.NoError(t, os.Mkdir(filepath.Join(selected, ".jj"), 0755))
|
|
}
|
|
if name == "colocated" {
|
|
initExcludeGit(t, selected, "config", "--local", "core.hooksPath", filepath.Join(common, "hooks"))
|
|
}
|
|
locked, quiet := strings.Contains(name, "config_lock"), strings.HasPrefix(name, "quiet")
|
|
if locked {
|
|
require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600))
|
|
preserveInitRoleInputs(t, filepath.Join(common, "config"))
|
|
}
|
|
run := func() { runEmbeddedInitHooks(t.Context(), selected, storage, name == "skip", quiet) }
|
|
if locked {
|
|
stderr := captureStderr(t, run)
|
|
require.Equal(t, !quiet, strings.Contains(stderr, "Failed to install git hooks"))
|
|
require.Equal(t, !quiet, strings.Contains(stderr, "bd hooks install --beads"))
|
|
} else {
|
|
stdout := captureStdout(t, func() error { run(); return nil })
|
|
require.Equal(t, name == "pure_jj", strings.Contains(stdout, "Jujutsu repository detected"))
|
|
}
|
|
destination := filepath.Join(storage, "hooks")
|
|
if name == "colocated" {
|
|
destination = filepath.Join(common, "hooks")
|
|
}
|
|
if name == "skip" || name == "nonrepo" || strings.Contains(name, "pure_jj") {
|
|
_, err := os.Stat(destination)
|
|
require.ErrorIs(t, err, os.ErrNotExist)
|
|
return
|
|
}
|
|
require.Contains(t, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit"))), hookSectionBeginPrefix)
|
|
if !locked && name != "colocated" {
|
|
// A bare repository has no work tree to anchor, so it resolves
|
|
// through the work-tree-less hooks context (GH#6457) and is its own
|
|
// common directory. It installs like any other selected repository
|
|
// rather than degrading to a warning and no install at all.
|
|
configRoot := common
|
|
if name == "bare" {
|
|
configRoot = selected
|
|
}
|
|
got := initExcludeGit(t, selected, "config", "--file", filepath.Join(configRoot, "config"), "--get", "core.hooksPath")
|
|
require.Equal(t, filepath.Clean(destination), filepath.Clean(got))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInitEmbeddedHooksSelectedStatus(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("hook current-status checks require POSIX executable bits")
|
|
}
|
|
for _, name := range []string{"decoy_current", "target_current", "target_outdated"} {
|
|
t.Run(name, func(t *testing.T) {
|
|
selected, decoy, storage, common := newInitHooksFixture(t)
|
|
current := filepath.Join(decoy, ".git", "hooks")
|
|
configuredRepo := decoy
|
|
if name != "decoy_current" {
|
|
current = filepath.Join(common, "hooks")
|
|
configuredRepo = selected
|
|
}
|
|
initExcludeGit(t, configuredRepo, "config", "--local", "core.hooksPath", current)
|
|
require.NoError(t, os.MkdirAll(current, 0755))
|
|
for _, hook := range managedHookNames {
|
|
content := "#!/bin/sh\n" + generateHookSection(hook)
|
|
if name == "target_outdated" {
|
|
content = "#!/bin/sh\n" + hookVersionPrefix + "0.0.0\n# bd (beads) " + hook + " hook\n"
|
|
}
|
|
require.NoError(t, os.WriteFile(filepath.Join(current, hook), []byte(content), 0755))
|
|
}
|
|
require.True(t, hooksInstalledAt(current))
|
|
require.Equal(t, name == "target_outdated", hookStatusesNeedUpdate(checkGitHooksAt(current)))
|
|
if name == "decoy_current" {
|
|
require.True(t, hooksInstalled() && !hooksNeedUpdate(), "inherited decoy hooks must be current")
|
|
}
|
|
preserveInitRoleInputs(t, filepath.Join(current, "pre-commit"), filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index"))
|
|
stdout := captureStdout(t, func() error {
|
|
runEmbeddedInitHooks(t.Context(), selected, storage, false, false)
|
|
return nil
|
|
})
|
|
require.Equal(t, name == "target_outdated", strings.Contains(stdout, "Updating hooks to version"))
|
|
if name == "target_current" {
|
|
_, err := os.Stat(filepath.Join(storage, "hooks"))
|
|
require.ErrorIs(t, err, os.ErrNotExist)
|
|
} else {
|
|
require.Contains(t, string(readInitHooksFile(t, filepath.Join(storage, "hooks", "pre-commit"))), hookSectionBeginLine())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func preserveStandaloneHookInputs(t *testing.T, paths ...string) {
|
|
t.Helper()
|
|
beforeEnv := os.Environ()
|
|
t.Cleanup(func() { require.Equal(t, beforeEnv, os.Environ()) })
|
|
for _, path := range paths {
|
|
before := readInitHooksFile(t, path)
|
|
t.Cleanup(func() { require.Equal(t, before, readInitHooksFile(t, path), "changed %s", path) })
|
|
}
|
|
}
|
|
|
|
func setStandaloneHookMode(t *testing.T, mode string) {
|
|
t.Helper()
|
|
oldJSON := jsonOutput
|
|
jsonOutput = false // These command fixtures assert the human-readable stderr contract.
|
|
t.Cleanup(func() { jsonOutput = oldJSON })
|
|
for _, flag := range []string{"force", "shared", "chain", "beads"} {
|
|
f := hooksInstallCmd.Flags().Lookup(flag)
|
|
old, changed := f.Value.String(), f.Changed
|
|
t.Cleanup(func() {
|
|
require.NoError(t, hooksInstallCmd.Flags().Set(flag, old))
|
|
f.Changed = changed
|
|
})
|
|
value := "false"
|
|
if flag == mode {
|
|
value = "true"
|
|
}
|
|
require.NoError(t, hooksInstallCmd.Flags().Set(flag, value))
|
|
}
|
|
}
|
|
|
|
func TestStandaloneHookCommandsUseSelectedContext(t *testing.T) {
|
|
for _, name := range []string{"regular", "linked", "private", "shared", "beads", "bare_external", "inline", "config_file", "config_lock"} {
|
|
t.Run(name, func(t *testing.T) {
|
|
selected, decoy, storage, common := newInitHooksFixture(t)
|
|
require.True(t, utils.PathsEqual(decoy, git.GetRepoRoot()), "seed stale decoy cache")
|
|
cwd, mainRoot := decoy, filepath.Dir(common)
|
|
if name == "regular" {
|
|
selected = mainRoot
|
|
}
|
|
private := initExcludeGit(t, selected, "rev-parse", "--absolute-git-dir")
|
|
if name == "bare_external" {
|
|
root := t.TempDir()
|
|
common, selected = filepath.Join(root, "selected bare.git"), filepath.Join(root, "external tree")
|
|
initExcludeGit(t, root, "init", "--bare", common)
|
|
require.NoError(t, os.Mkdir(selected, 0755))
|
|
cwd, mainRoot, private = selected, selected, filepath.Join("..", "selected bare.git")
|
|
}
|
|
t.Chdir(cwd)
|
|
t.Setenv("GIT_DIR", private)
|
|
t.Setenv("GIT_WORK_TREE", selected)
|
|
t.Setenv("BEADS_DIR", storage)
|
|
require.NoError(t, os.WriteFile(filepath.Join(storage, "metadata.json"), []byte("{}\n"), 0600))
|
|
destination := filepath.Join(mainRoot, ".beads", "hooks")
|
|
initExcludeGit(t, cwd, "--git-dir", common, "config", "--local", "core.hooksPath", destination)
|
|
initExcludeGit(t, cwd, "--git-dir", common, "config", "--local", "beads.role", "contributor")
|
|
if name == "private" {
|
|
destination = t.TempDir()
|
|
initExcludeGit(t, selected, "config", "extensions.worktreeConfig", "true")
|
|
initExcludeGit(t, selected, "config", "--worktree", "core.hooksPath", destination)
|
|
preserveStandaloneHookInputs(t, filepath.Join(private, "config.worktree"))
|
|
}
|
|
if name == "shared" {
|
|
destination = filepath.Join(mainRoot, ".beads-hooks")
|
|
} else if name == "beads" {
|
|
destination = filepath.Join(storage, "hooks")
|
|
}
|
|
decoyHook := filepath.Join(decoy, ".git", "hooks", "pre-commit")
|
|
require.NoError(t, os.WriteFile(decoyHook, []byte("#!/bin/sh\n"+generateHookSection("pre-commit")), 0755))
|
|
if name == "inline" {
|
|
t.Setenv("GIT_CONFIG_COUNT", "1")
|
|
t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath")
|
|
t.Setenv("GIT_CONFIG_VALUE_0", filepath.Dir(decoyHook))
|
|
}
|
|
if name == "config_file" {
|
|
initExcludeGit(t, decoy, "config", "--local", "core.hooksPath", filepath.Dir(decoyHook))
|
|
t.Setenv("GIT_CONFIG", filepath.Join(decoy, ".git", "config"))
|
|
}
|
|
preserveStandaloneHookInputs(t, decoyHook, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index"))
|
|
setStandaloneHookMode(t, name)
|
|
require.NoError(t, hooksInstallCmd.RunE(hooksInstallCmd, nil))
|
|
require.Contains(t, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit"))), hookSectionBeginPrefix)
|
|
if name == "shared" || name == "beads" {
|
|
got := initExcludeGit(t, cwd, "--git-dir", common, "config", "--local", "--get", "core.hooksPath")
|
|
require.True(t, utils.PathsEqual(destination, got), "selected hooks path = %q, want %q", got, destination)
|
|
}
|
|
if name == "config_lock" {
|
|
require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600))
|
|
var err error
|
|
stderr := captureStderr(t, func() { err = hooksUninstallCmd.RunE(hooksUninstallCmd, nil) })
|
|
require.Equal(t, &exitError{Code: 1}, err)
|
|
require.Contains(t, stderr, "failed to reset")
|
|
return
|
|
}
|
|
require.NoError(t, hooksUninstallCmd.RunE(hooksUninstallCmd, nil))
|
|
_, err := os.Stat(filepath.Join(destination, "pre-commit"))
|
|
require.ErrorIs(t, err, os.ErrNotExist)
|
|
query := exec.Command("git", "--git-dir", common, "config", "--local", "--get", "beads.role")
|
|
query.Dir, query.Env = cwd, gitenv.ScrubRouting(os.Environ())
|
|
var exit *exec.ExitError
|
|
require.ErrorAs(t, query.Run(), &exit)
|
|
require.Equal(t, 1, exit.ExitCode(), "selected local role must be absent")
|
|
if name == "beads" {
|
|
// The value install wrote is the out-of-repo <BEADS_DIR>/hooks
|
|
// directory whose hook files uninstall just deleted. Leaving it
|
|
// configured keeps .git/hooks shadowed by an emptied directory,
|
|
// i.e. every hook silently disabled while beads-managed config is
|
|
// still installed — the GH#4440 contract this command enforces.
|
|
pathQuery := exec.Command("git", "--git-dir", common, "config", "--local", "--get", "core.hooksPath")
|
|
pathQuery.Dir, pathQuery.Env = cwd, gitenv.ScrubRouting(os.Environ())
|
|
var pathExit *exec.ExitError
|
|
require.ErrorAs(t, pathQuery.Run(), &pathExit)
|
|
require.Equal(t, 1, pathExit.ExitCode(), "out-of-storage hooks path must be cleared, not left behind")
|
|
}
|
|
require.True(t, utils.PathsEqual(decoy, git.GetRepoRoot()), "fresh commands must leave the legacy cache untouched")
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestStandaloneBeadsUninstallLeavesHooksPathWhenResolutionDrifts records an
|
|
// accepted limitation, not a desired behavior. The shared predicate recognizes the
|
|
// directory `bd hooks install --beads` would configure *right now*
|
|
// (doctor.BeadsManagedStorageHooksDir -> beads.FindBeadsDir), not the value install
|
|
// actually wrote, and every FindBeadsDir arm reads live inputs: BEADS_DIR, the
|
|
// .beads/redirect contents, storage existence plus project files, and the process
|
|
// cwd. core.hooksPath lives in the shared common dir, so an installing shell with
|
|
// BEADS_DIR set and an uninstalling shell without it see the same configured value
|
|
// and resolve different storage. Uninstall then deletes the hook files and leaves
|
|
// core.hooksPath pointing at the emptied directory — .git/hooks stays shadowed,
|
|
// which is the GH#4440 shape the clearance exists to prevent.
|
|
//
|
|
// Tracked in bd-s76jm: record what install configured (a local beads.hooksPath key)
|
|
// and match the record, with the current recomputation as the fallback. When that
|
|
// lands this expectation flips to "cleared" and this test becomes its
|
|
// counterfactual.
|
|
func TestStandaloneBeadsUninstallLeavesHooksPathWhenResolutionDrifts(t *testing.T) {
|
|
selected, decoy, storage, common := newInitHooksFixture(t)
|
|
require.True(t, utils.PathsEqual(decoy, git.GetRepoRoot()), "seed stale decoy cache")
|
|
mainRoot := filepath.Dir(common)
|
|
private := initExcludeGit(t, selected, "rev-parse", "--absolute-git-dir")
|
|
t.Chdir(decoy)
|
|
t.Setenv("GIT_DIR", private)
|
|
t.Setenv("GIT_WORK_TREE", selected)
|
|
t.Setenv("BEADS_DIR", storage)
|
|
require.NoError(t, os.WriteFile(filepath.Join(storage, "metadata.json"), []byte("{}\n"), 0600))
|
|
destination := filepath.Join(storage, "hooks")
|
|
initExcludeGit(t, decoy, "--git-dir", common, "config", "--local", "core.hooksPath",
|
|
filepath.Join(mainRoot, ".beads", "hooks"))
|
|
setStandaloneHookMode(t, "beads")
|
|
require.NoError(t, hooksInstallCmd.RunE(hooksInstallCmd, nil))
|
|
require.Contains(t, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit"))), hookSectionBeginPrefix)
|
|
require.True(t, utils.PathsEqual(destination, readSelectedHooksPath(t, decoy, common)),
|
|
"install must configure the out-of-repo storage hooks directory")
|
|
|
|
// Same repository and same configured value; only the resolution inputs move.
|
|
require.NoError(t, os.Unsetenv("BEADS_DIR"))
|
|
require.NotEqual(t, destination, doctor.BeadsManagedStorageHooksDir(),
|
|
"precondition: cleanup must no longer re-derive the value install wrote")
|
|
|
|
require.NoError(t, hooksUninstallCmd.RunE(hooksUninstallCmd, nil))
|
|
_, err := os.Stat(filepath.Join(destination, "pre-commit"))
|
|
require.ErrorIs(t, err, os.ErrNotExist, "uninstall still deletes the hook files it can no longer recognize")
|
|
require.True(t, utils.PathsEqual(destination, readSelectedHooksPath(t, decoy, common)),
|
|
"known gap (bd-s76jm): the configured value survives an install/uninstall resolution drift")
|
|
}
|
|
|
|
// readSelectedHooksPath returns the selected repository's local core.hooksPath,
|
|
// read through the common dir with routing overrides dropped, exactly as
|
|
// resetHooksPathAt reads it.
|
|
func readSelectedHooksPath(t *testing.T, workDir, commonDir string) string {
|
|
t.Helper()
|
|
return initExcludeGit(t, workDir, "--git-dir", commonDir, "config", "--local", "--get", "core.hooksPath")
|
|
}
|
|
|
|
// TestStandaloneHooksWarnOnEffectivePathDivergence pins the warning that names
|
|
// both hook paths when they disagree. install/uninstall act on the selected,
|
|
// config-scrubbed directory, while every status and execution reader
|
|
// (bd hooks list, bd doctor, runChainedHook) still resolves hooks through the
|
|
// inherited context — and git itself honors the inherited core.hooksPath. A
|
|
// bare success would leave the user comparing an install that reported one
|
|
// directory against a status that reports another, with nothing saying why.
|
|
func TestStandaloneHooksWarnOnEffectivePathDivergence(t *testing.T) {
|
|
selected, decoy, _, common := newInitHooksFixture(t)
|
|
mainRoot := filepath.Dir(common)
|
|
private := initExcludeGit(t, selected, "rev-parse", "--absolute-git-dir")
|
|
t.Chdir(decoy)
|
|
t.Setenv("GIT_DIR", private)
|
|
t.Setenv("GIT_WORK_TREE", selected)
|
|
destination := filepath.Join(mainRoot, ".beads", "hooks")
|
|
initExcludeGit(t, decoy, "--git-dir", common, "config", "--local", "core.hooksPath", destination)
|
|
injected := filepath.Join(decoy, ".git", "hooks")
|
|
t.Setenv("GIT_CONFIG_COUNT", "1")
|
|
t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath")
|
|
t.Setenv("GIT_CONFIG_VALUE_0", injected)
|
|
setStandaloneHookMode(t, "")
|
|
|
|
var err error
|
|
stderr := captureStderr(t, func() { err = hooksInstallCmd.RunE(hooksInstallCmd, nil) })
|
|
require.NoError(t, err)
|
|
require.Contains(t, stderr, injected, "warning must name the effective inherited hooks directory")
|
|
require.Contains(t, stderr, destination, "warning must name the selected directory bd operated on")
|
|
require.Contains(t, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit"))), hookSectionBeginPrefix)
|
|
}
|
|
|
|
func TestInitHooksPreservesManagedDirectoryAliases(t *testing.T) {
|
|
for _, managed := range []string{".beads/hooks", ".beads-hooks"} {
|
|
t.Run(managed, func(t *testing.T) {
|
|
selected, _, storage, common := newInitHooksFixture(t)
|
|
root := filepath.Dir(common)
|
|
source := filepath.Join(root, managed)
|
|
require.NoError(t, os.MkdirAll(source, 0755))
|
|
const content = "#!/bin/sh\necho existing managed-directory hook\n"
|
|
require.NoError(t, os.WriteFile(filepath.Join(source, "post-rewrite"), []byte(content), 0755))
|
|
alias := filepath.Join(t.TempDir(), "repository alias")
|
|
if err := os.Symlink(root, alias); err != nil {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skipf("directory symlink capability unavailable: %v", err)
|
|
}
|
|
t.Fatal(err)
|
|
}
|
|
initExcludeGit(t, selected, "config", "--local", "core.hooksPath", filepath.Join(alias, managed))
|
|
fs, _, err := withInitHooks(nil, selected, storage)
|
|
require.NoError(t, err)
|
|
require.NoError(t, fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true}))
|
|
_, err = os.Stat(filepath.Join(storage, "hooks", "post-rewrite"))
|
|
require.ErrorIs(t, err, os.ErrNotExist, "an existing managed hooks directory must not be copied through an alias")
|
|
require.Equal(t, content, string(readInitHooksFile(t, filepath.Join(source, "post-rewrite"))))
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInitHooksRefusesSharedMode(t *testing.T) {
|
|
selected, _, storage, common := newInitHooksFixture(t)
|
|
fs, _, err := withInitHooks(nil, selected, storage)
|
|
require.NoError(t, err)
|
|
require.ErrorContains(t, fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, Shared: true}), "shared hooks mode")
|
|
for _, path := range []string{filepath.Join(storage, "hooks"), filepath.Join(filepath.Dir(common), ".beads-hooks")} {
|
|
_, err := os.Stat(path)
|
|
require.ErrorIs(t, err, os.ErrNotExist)
|
|
}
|
|
}
|
|
|
|
func TestInitHooksContextPreservesSelectedPaths(t *testing.T) {
|
|
for _, name := range []string{"foreign", "global", "private", "config_lock"} {
|
|
t.Run(name, func(t *testing.T) {
|
|
selected, decoy, storage, common := newInitHooksFixture(t)
|
|
current := t.TempDir()
|
|
const foreign = "#!/bin/sh\necho selected hook\n"
|
|
for _, hook := range []string{"pre-commit", "post-rewrite"} {
|
|
require.NoError(t, os.WriteFile(filepath.Join(current, hook), []byte(foreign), 0755))
|
|
}
|
|
initExcludeGit(t, selected, "config", "--local", "core.hooksPath", current)
|
|
if name == "global" {
|
|
initExcludeGit(t, selected, "config", "--local", "--unset", "core.hooksPath")
|
|
initExcludeGit(t, selected, "config", "--global", "core.hooksPath", current)
|
|
}
|
|
preserved := map[string][]byte{}
|
|
if name == "private" {
|
|
initExcludeGit(t, selected, "config", "extensions.worktreeConfig", "true")
|
|
initExcludeGit(t, selected, "config", "--worktree", "core.hooksPath", current)
|
|
path := filepath.Join(initExcludeGit(t, selected, "rev-parse", "--absolute-git-dir"), "config.worktree")
|
|
preserved[path] = readInitHooksFile(t, path)
|
|
}
|
|
for _, path := range []string{filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index")} {
|
|
preserved[path] = readInitHooksFile(t, path)
|
|
}
|
|
if name == "global" {
|
|
path := filepath.Join(os.Getenv("HOME"), ".gitconfig")
|
|
preserved[path] = readInitHooksFile(t, path)
|
|
}
|
|
fs, hooks, err := withInitHooks(nil, selected, storage)
|
|
require.NoError(t, err)
|
|
require.False(t, hooks.installed())
|
|
if name == "config_lock" {
|
|
require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600))
|
|
preserved[filepath.Join(common, "config")] = readInitHooksFile(t, filepath.Join(common, "config"))
|
|
}
|
|
// Later ambient routing must not rebind the captured hook operation.
|
|
t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), "missing"))
|
|
t.Setenv("GIT_CONFIG_COUNT", "1")
|
|
t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath")
|
|
t.Setenv("GIT_CONFIG_VALUE_0", filepath.Join(decoy, "wrong hooks"))
|
|
env := os.Environ()
|
|
destination := filepath.Join(storage, "hooks")
|
|
for range 2 {
|
|
err := fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true})
|
|
if name == "config_lock" {
|
|
require.ErrorContains(t, err, "failed to configure git hooks path")
|
|
} else {
|
|
require.NoError(t, err)
|
|
got := initExcludeGit(t, selected, "config", "--file", filepath.Join(common, "config"), "--get", "core.hooksPath")
|
|
gotInfo, err := os.Stat(got)
|
|
require.NoError(t, err)
|
|
wantInfo, err := os.Stat(destination)
|
|
require.NoError(t, err)
|
|
require.True(t, os.SameFile(gotInfo, wantInfo), "common config must name the installed storage hooks")
|
|
}
|
|
installed := string(readInitHooksFile(t, filepath.Join(destination, "pre-commit")))
|
|
require.Contains(t, installed, foreign)
|
|
require.Equal(t, 1, strings.Count(installed, hookSectionBeginPrefix))
|
|
require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit.backup"))))
|
|
require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(destination, "post-rewrite"))))
|
|
}
|
|
for path, before := range preserved {
|
|
require.Equal(t, before, readInitHooksFile(t, path), "changed %s", path)
|
|
}
|
|
for _, hook := range []string{"pre-commit", "post-rewrite"} {
|
|
require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(current, hook))))
|
|
}
|
|
if name == "private" {
|
|
paths, err := git.ResolveHooksContext(selected, hooks.env)
|
|
require.NoError(t, err)
|
|
require.Equal(t, current, paths.HooksDir, "private override remains effective")
|
|
}
|
|
require.Equal(t, env, os.Environ())
|
|
})
|
|
}
|
|
}
|