beads/cmd/bd/init_hooks_test.go
Tomasz Feliksik 33bed587e0
Accept uutils coreutils timeout in generated hooks, and check the shims against real implementations (#6561)
* Accept uutils coreutils timeout in generated hooks

The generated hook selects a timeout helper only when its --version
banner starts with "timeout (GNU coreutils) ". uutils coreutils reports
"timeout (uutils coreutils) " with the same command line and the same
exit 124 on expiry, so hosts that ship it (Ubuntu 25.10+, NixOS with
uutils-coreutils-noprefix) silently fell through to the Perl alarm, or
to the unbounded direct run when Perl is absent. Follow-up from #5522,
tracked in #5541.

- Widen the identity allowlist to uutils; the match stays by banner so
  Windows timeout.exe is still never probed (#5503).
- Add a backend-selection case using the GNU stub with the uutils
  banner: fails on the old shim (selects gtimeout), passes with the
  widening.
- Regenerate the managed sections in the tracked .githooks/* so
  TestTrackedManagedHookSectionsMatchGenerator stays green.
- Update the hook-timeout passages in docs/reference/git-integration.md
  and troubleshooting.md, which described the probe as GNU-only.

Verified on NixOS with uutils 0.10.0 as /run/current-system/sw/bin/timeout:
with Perl removed from PATH and a bd that hangs, the old shim runs
"without timeout" for the full duration; the new shim expires at
BEADS_HOOK_TIMEOUT and continues.

Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of Tomasz Feliksik

* Regenerate tracked .githooks managed sections with make githooks-regen

TestTrackedManagedHookSectionsMatchGenerator holds the managed section in
each tracked .githooks/* byte-equal to the cmd/bd/hooks.go generator, but
nothing regenerated them: after a generator change a contributor had to
splice the new section in by hand, and the failure only dumped both
texts. The v1.2.0 bump reddened main this way (ce20a64bb), and #6561 shipped
its first revision with the five hooks stale.

- BD_UPDATE_GOLDEN=1 makes the test rewrite the section in place, keeping
  everything around the markers (the project's own hook logic) untouched.
  Same switch the package's events golden already uses.
- `make githooks-regen` wraps it, next to `corpus-regen`.
- The drift failure now names that command.
- The exactly-one-section check runs before any rewrite.

Verified: drifting one byte inside .githooks/pre-push fails the test with
the hint; `make githooks-regen` restores the file to the same blob SHA;
the test is green again.

Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of Tomasz Feliksik

* Check the tracked hook shims against real timeout implementations

The Go tests pin the shim's helper selection with scripted stand-ins, so
they can only encode what the author believes each real `timeout` does.
That is where the last two defects lived: uutils prints a banner the
allowlist did not know (#5541), and busybox — which #5541 suggests
adding — exits 143 on expiry rather than 124, so allowlisting it would
turn every deadline into a failed hook and a blocked push.

checks.nix adds a flake check that runs the tracked .githooks/* managed
sections (held equal to the generator by
TestTrackedManagedHookSectionsMatchGenerator) against the binaries
themselves: GNU coreutils, uutils, busybox and toybox `timeout`, each
with and without perl, under dash, bash and busybox ash, for all five
hooks — 150 cases. Expectations come from a model of the contract (the
allowlist as data), so widening it is one line here and the binaries
either agree or they do not.

A fake bd on the shim's restricted PATH blocks on a held-open fifo until
a helper kills it, records the signal and re-raises it, so each case
asserts the backend that ran (TERM from timeout, ALRM from perl's alarm)
and not merely that the shim finished. No clock: a helper that fails to
kill the fake trips the harness's own `timeout 10`. Every case asserts
exit 0, since anything else blocks the user's push. Reading .githooks/*
instead of building bd keeps it at ~1 s and off the Go build's critical
path; CI's test-nix job runs it after its existing help-text smoke test.

Mutation-checked: restoring main's GNU-only sections fails all 30 uutils
cases (15 unbounded, 15 on the perl backend); allowlisting busybox with
a loosened probe fails all 30 busybox cases with hook exit 143.

Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of Tomasz Feliksik

* Run the hook-timeout check under the gtimeout candidate name too

The shim probes `timeout` and then `gtimeout`, but the matrix only ever
put a binary named `timeout` on PATH, so the second candidate was never
run against a real implementation. Whether a helper is accepted under
that name depends on what its banner does with argv[0].

Measured: the uutils multicall dispatches on the argv[0] SUFFIX
(src/bin/coreutils.rs, `binary_as_util.ends_with(util)`) and then prints
the canonical utility name — invoked as gtimeout it reports
"timeout (uutils coreutils) 0.8.0" (this flake's nixos-25.11 pin; 0.11.0
identical), which the allowlist accepts. busybox and toybox know no
gtimeout applet and fail the probe outright, rejected as before. GNU is
immune by construction: Homebrew's gtimeout is a separate binary whose
banner is the fixed "timeout (GNU coreutils) 9.11"; nixpkgs' coreutils
is a single-binary multicall that refuses a foreign name ("unknown
program 'gtimeout'"), so it gets no variant here.

Each multicall is now also installed on a case PATH as `gtimeout` ALONE
(`installs`, derived from `implementations`; `backendFor` stays keyed on
the implementation, so the model's claim is "uutils is allowlisted
whatever it is called"). 240 cases on Linux, 80 on darwin (no busybox or
toybox there, and no busybox-ash shell). The shadowed
`out=` inside run_case is `case_out` now: it only survived because every
case is a backgrounded subshell, and a de-backgrounded case would have
died on the final `touch "$out"`.

Mutation-checked: installing the variant as `xtimeout` (a name the shim
never probes) fails exactly the 30 uutils-as-gtimeout cases — 15 with
nothing killing the fake bd, 15 on the perl backend (ALRM) instead of
coreutils; restored, 240 of 240 pass. The busybox/toybox variants cannot
distinguish (their expectation is rejection either way); their weight is
that the probe does not blow up on a foreign name.

* Run the flake checks on main too, by nix flake check; docs wording

pr-risk.yml's test-nix job ran the hook-timeout check on PRs only; the
byte-identical job in main.yml never got the step, so post-merge main
never ran it. Both jobs now run `nix flake check -L`: no hardcoded
`x86_64-linux` (the step beside it, `nix run .#default`, was already
system-agnostic), and a check added to checks.nix runs without a
workflow edit. checks.aarch64-darwin and .x86_64-darwin evaluate.

Measured on ubuntu-latest with a cold Nix store (fork run 35700791032,
this tree, 240 cases): `nix flake check -L` 3.6 s including substitution
of uutils, busybox, toybox, dash and perl; 0.08 s warm — beside the
4 min 9 s the existing `nix run .#default` step spends building bd in
the same job. The 10-minute timeout is not in question.

git-integration.md: on Git for Windows the preferred deadline backend is
"a coreutils timeout (GNU or uutils)", not GNU alone, since both now
qualify. troubleshooting.md: reflow a ragged paragraph.

* review: close the duplicated contracts around the uutils timeout accept

Maintainer review fixes for #6561. No change to the shim's behavior or to the
generated/tracked hook sections.

- cmd/bd/hooks_timeout_process_test.go: the uutils fixture was built with
  strings.Replace, which returns its input unchanged when the pattern is
  absent, so a later edit to the GNU stub's banner would silently degenerate
  the uutils case into a second copy of the GNU one — still green, no longer
  testing the new accept. Hoist the derivation and fail loudly when the banner
  no longer matches.
- cmd/bd/hooks_timeout_process_test.go: findHookProcessGNUTimeout held a second,
  un-widened copy of the identity allowlist, so on exactly the hosts this PR
  exists for (uutils timeout, no gtimeout) the only Go test that drives a real
  timeout binary skipped with a reason the fix had just made false. Widen the
  probe's case, rename it findHookProcessCoreutilsTimeout, and reword the skip
  and the subtest. Measured against stub PATHs: uutils goes rc=1 -> rc=0, GNU
  stays rc=0, a busybox banner stays rc=1.
- cmd/bd/init_hooks_test.go: TestGenerateHookSection_Timeout asserted only the
  GNU alternative, so deleting the new uutils one from the generator left the
  structural contract green (verified: it passes under that mutation before
  this change, and reports "section missing uutils coreutils identity check"
  after). Add the companion assertion.
- cmd/bd/init_hooks_test.go, Makefile: the regen arm rewrites tracked source
  files, so give it its own BD_UPDATE_HOOKS_GOLDEN rather than the package's
  shared BD_UPDATE_GOLDEN — an unscoped `BD_UPDATE_GOLDEN=1 go test ./cmd/bd/`
  used to turn genuine hook drift into a silent working-tree rewrite that
  reported PASS.
- cmd/bd/init_hooks_test.go: locate the managed section by marker prefix
  instead of the versioned marker line. Tracked hooks drift both from generator
  content and from the release version stamp; the exact-line lookup made the
  second class fatal ("tracked hook missing ...") before the regen arm was
  reachable, so `make githooks-regen` failed at exactly the moment a release
  engineer reaches for it. The versioned markers are still verified — they are
  part of the byte compare.
- checks.nix: the `rc -eq 124` safety-net verdict discarded both $case_out and
  the already-captured $signal, so the one failure mode that is intermittent
  and not locally reproducible was also the only one with no diagnostics.
  Report them like the `rc -ne 0` branch below it.
- docs/reference/troubleshooting.md, docs/reference/git-integration.md: mirror
  the coreutils wording across both docs this PR touches, and generalize the
  re-install guidance in both. Managed sections are never reported Outdated
  (getHookVersion returns IsShim for them and computeHookStatuses gates on
  !IsShim), so nothing tells an existing install it is stale; the sentence was
  still scoped to the older name-only check (#5503).
- CHANGELOG.md: add the [Unreleased] entry for #5541, worded to the actual
  scope — with Perl installed the shim still reached the Perl alarm arm, so the
  lost deadline bit uutils hosts without Perl — say that existing installs must
  run `bd hooks install` once, and drop the claim that stock NixOS ships uutils
  (this PR's own checks.nix takes GNU from pkgs.coreutils).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 03:38:45 -07:00

1399 lines
49 KiB
Go

package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/git"
)
func TestDetectExistingHooks(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
tests := []struct {
name string
setupHook string
hookContent string
wantExists bool
wantIsBdHook bool
wantIsPreCommitFramework bool
}{
{
name: "no hook",
setupHook: "",
wantExists: false,
},
{
name: "bd hook",
setupHook: "pre-commit",
hookContent: "#!/bin/sh\n# bd (beads) pre-commit hook\necho test",
wantExists: true,
wantIsBdHook: true,
},
{
name: "pre-commit framework hook",
setupHook: "pre-commit",
hookContent: "#!/bin/sh\n# pre-commit framework\npre-commit run",
wantExists: true,
wantIsPreCommitFramework: true,
},
{
name: "custom hook",
setupHook: "pre-commit",
hookContent: "#!/bin/sh\necho custom",
wantExists: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
os.RemoveAll(hooksDir)
os.MkdirAll(hooksDir, 0750)
if tt.setupHook != "" {
hookPath := filepath.Join(hooksDir, tt.setupHook)
if err := os.WriteFile(hookPath, []byte(tt.hookContent), 0700); err != nil {
t.Fatal(err)
}
}
hooks := detectExistingHooks()
var found *hookInfo
for i := range hooks {
if hooks[i].name == "pre-commit" {
found = &hooks[i]
break
}
}
if found == nil {
t.Fatal("pre-commit hook not found in results")
}
if found.exists != tt.wantExists {
t.Errorf("exists = %v, want %v", found.exists, tt.wantExists)
}
if found.isBdHook != tt.wantIsBdHook {
t.Errorf("isBdHook = %v, want %v", found.isBdHook, tt.wantIsBdHook)
}
if found.isPreCommitFramework != tt.wantIsPreCommitFramework {
t.Errorf("isPreCommitFramework = %v, want %v", found.isPreCommitFramework, tt.wantIsPreCommitFramework)
}
})
}
})
}
func TestInstallGitHooks_NoExistingHooks(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
// Note: Can't fully test interactive prompt in automated tests
// This test verifies the logic works when no existing hooks present
// For full testing, we'd need to mock user input
// Check hooks were created
preCommitPath := filepath.Join(hooksDir, "pre-commit")
postMergePath := filepath.Join(hooksDir, "post-merge")
if _, err := os.Stat(preCommitPath); err == nil {
content, _ := os.ReadFile(preCommitPath)
if !strings.Contains(string(content), "bd (beads)") {
t.Error("pre-commit hook doesn't contain bd marker")
}
if strings.Contains(string(content), "chained") {
t.Error("pre-commit hook shouldn't be chained when no existing hooks")
}
}
if _, err := os.Stat(postMergePath); err == nil {
content, _ := os.ReadFile(postMergePath)
if !strings.Contains(string(content), "bd (beads)") {
t.Error("post-merge hook doesn't contain bd marker")
}
}
})
}
func TestInstallGitHooks_ExistingHookBackup(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
// Ensure hooks directory exists
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("Failed to create hooks directory: %v", err)
}
// Create an existing pre-commit hook
preCommitPath := filepath.Join(hooksDir, "pre-commit")
existingContent := "#!/bin/sh\necho existing hook"
if err := os.WriteFile(preCommitPath, []byte(existingContent), 0700); err != nil {
t.Fatal(err)
}
// Detect that hook exists
hooks := detectExistingHooks()
hasExisting := false
for _, hook := range hooks {
if hook.exists && !hook.isBdHook && hook.name == "pre-commit" {
hasExisting = true
break
}
}
if !hasExisting {
t.Error("should detect existing non-bd hook")
}
})
}
func TestGenerateHookSection(t *testing.T) {
section := generateHookSection("pre-commit")
if !strings.Contains(section, hookSectionBeginPrefix) {
t.Error("section missing begin marker")
}
if !strings.Contains(section, hookSectionEndPrefix) {
t.Error("section missing end marker prefix")
}
if !strings.Contains(section, "bd hooks run pre-commit") {
t.Error("section missing hook invocation")
}
if !strings.Contains(section, Version) {
t.Errorf("section missing version %s", Version)
}
// Verify versioned END marker format
expectedEnd := hookSectionEndLine()
if !strings.Contains(section, expectedEnd) {
t.Errorf("section missing versioned end marker %q\ngot:\n%s", expectedEnd, section)
}
}
// TestGenerateHookSection_Timeout verifies the timeout wrapper around bd hooks run (GH#2453).
func TestGenerateHookSection_Timeout(t *testing.T) {
section := generateHookSection("pre-push")
// The duration is configurable but must be validated before it reaches a
// helper command line.
if !strings.Contains(section, "BEADS_HOOK_TIMEOUT") {
t.Error("section missing BEADS_HOOK_TIMEOUT env var")
}
if !strings.Contains(section, fmt.Sprintf("%d", hookTimeoutSeconds)) {
t.Errorf("section missing default timeout %d", hookTimeoutSeconds)
}
if !strings.Contains(section, `*[^0-9]*`) && !strings.Contains(section, `*[!0-9]*`) {
t.Error("section missing positive-integer timeout validation")
}
if !strings.Contains(section, "invalid BEADS_HOOK_TIMEOUT") {
t.Error("section missing invalid-timeout warning")
}
// A name match is insufficient: native Windows has an incompatible
// timeout.exe. Require a successful GNU identity probe for timeout or
// gtimeout before invoking it.
if !strings.Contains(section, "for _bd_timeout_candidate in timeout gtimeout") {
t.Error("section missing ordered timeout/gtimeout capability probes")
}
if !strings.Contains(section, `if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then`) {
t.Error("section does not require a successful version probe")
}
if !strings.Contains(section, `"timeout (GNU coreutils) "*`) {
t.Error("section missing GNU coreutils identity check")
}
if !strings.Contains(section, `"timeout (uutils coreutils) "*`) {
t.Error("section missing uutils coreutils identity check")
}
if !strings.Contains(section, `"$_bd_timeout_command" -- "$_bd_timeout"`) {
t.Error("section missing GNU timeout argv separator")
}
if !strings.Contains(section, "perl -e 'alarm shift; exec @ARGV' --") {
t.Error("section missing perl alarm fallback for stock macOS")
}
if !strings.Contains(section, "_bd_timeout_backend=perl") {
t.Error("section missing scoped perl backend marker")
}
// GNU deadline statuses and Perl SIGALRM are scoped to the backend that can
// synthesize them. The direct fallback must not swallow a natural 124/142.
if !strings.Contains(section, `"$_bd_exit" -eq 124`) {
t.Error("section missing timeout exit code handling")
}
if !strings.Contains(section, `"$_bd_timeout_backend" = perl`) || !strings.Contains(section, `"$_bd_exit" -eq 142`) {
t.Error("section missing perl-scoped SIGALRM timeout exit code handling")
}
if !strings.Contains(section, "timed out") {
t.Error("section missing timeout warning message")
}
// Last-resort path is explicit when no timeout implementation is available.
if !strings.Contains(section, "running without timeout") {
t.Error("section missing clear fallback warning for systems without timeout support")
}
}
func TestTrackedManagedHookSectionsMatchGenerator(t *testing.T) {
for _, hookName := range managedHookNames {
hookName := hookName
t.Run(hookName, func(t *testing.T) {
path := filepath.Join("..", "..", ".githooks", hookName)
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read tracked hook %s: %v", path, err)
}
tracked := string(content)
if strings.Count(tracked, hookSectionBeginPrefix) != 1 || strings.Count(tracked, hookSectionEndPrefix) != 1 {
t.Fatal("tracked hook must contain exactly one managed section")
}
// Locate the section by marker PREFIX, not by the versioned marker
// line. Tracked hooks drift for two reasons — generator content and
// the release version stamp — and a prefix scan makes the second one
// ordinary drift that the byte compare below reports and the regen
// arm repairs. Matching hookSectionBeginLine() here would instead
// fail with "missing marker" after a Version bump, before the regen
// arm is reachable. The versioned markers are still verified: they
// are part of `want`.
begin := strings.Index(tracked, hookSectionBeginPrefix)
if begin < 0 {
t.Fatalf("tracked hook missing %q", hookSectionBeginPrefix)
}
relativeEnd := strings.Index(tracked[begin:], hookSectionEndPrefix)
if relativeEnd < 0 {
t.Fatalf("tracked hook missing %q", hookSectionEndPrefix)
}
end := begin + relativeEnd
newline := strings.IndexByte(tracked[end:], '\n')
if newline < 0 {
t.Fatalf("tracked hook %q line is not newline-terminated", hookSectionEndPrefix)
}
end += newline + 1
got, want := tracked[begin:end], generateHookSection(hookName)
// A dedicated variable, not the package's shared BD_UPDATE_GOLDEN:
// this arm rewrites tracked SOURCE files, so an unscoped
// `BD_UPDATE_GOLDEN=1 go test ./cmd/bd/` must not silently convert
// real hook drift into a working-tree mutation that reports PASS.
if os.Getenv("BD_UPDATE_HOOKS_GOLDEN") == "1" {
if got == want {
return
}
if err := os.WriteFile(path, []byte(tracked[:begin]+want+tracked[end:]), 0o755); err != nil {
t.Fatalf("write tracked hook: %v", err)
}
t.Logf("regenerated managed section in %s", path)
return
}
if got != want {
t.Fatalf("tracked managed section drifted from generator (regenerate with `make githooks-regen`)\nwant:\n%s\ngot:\n%s", want, got)
}
})
}
}
// TestGenerateHookSection_DBNotInitialized verifies exit code 3 handling (GH#2449).
func TestGenerateHookSection_DBNotInitialized(t *testing.T) {
section := generateHookSection("pre-commit")
// Exit code 3 = beads database not initialized; hook must continue gracefully
if !strings.Contains(section, `"$_bd_exit" -eq 3`) {
t.Error("section missing exit code 3 (DB not initialized) handling")
}
if !strings.Contains(section, "database not initialized") {
t.Error("section missing DB-not-initialized warning message")
}
// After handling exit code 3, the effective exit must be 0 (success)
// Verify the pattern: set _bd_exit=0 after detecting code 3
if !strings.Contains(section, `if [ "$_bd_exit" -eq 3 ]; then`) {
t.Error("section missing exit code 3 conditional")
}
}
// TestGenerateHookSection_HookNameInMessages verifies hook name appears in warning messages.
func TestGenerateHookSection_HookNameInMessages(t *testing.T) {
for _, hook := range managedHookNames {
section := generateHookSection(hook)
// Each hook's timeout and DB-missing messages should include the hook name
if !strings.Contains(section, "hook '"+hook+"'") {
t.Errorf("section for %q missing hook name in warning messages", hook)
}
}
}
func TestInjectHookSection(t *testing.T) {
section := generateHookSection("pre-commit")
tests := []struct {
name string
existing string
wantHas []string // substrings the result must contain
}{
{
name: "inject into empty file",
existing: "#!/bin/sh\n",
wantHas: []string{"#!/bin/sh\n", hookSectionBeginPrefix, hookSectionEndPrefix},
},
{
name: "inject preserving user content",
existing: "#!/bin/sh\necho before\n",
wantHas: []string{"echo before", hookSectionBeginPrefix, hookSectionEndPrefix},
},
{
name: "update existing section",
existing: "#!/bin/sh\necho before\n# --- BEGIN BEADS INTEGRATION v0.40.0 ---\nold content\n# --- END BEADS INTEGRATION ---\necho after\n",
wantHas: []string{"echo before", "echo after", "bd hooks run pre-commit", hookSectionEndPrefix},
},
{
name: "orphaned BEGIN without END",
existing: "#!/bin/sh\n# --- BEGIN BEADS INTEGRATION v0.57.0 ---\nbd hook pre-commit \"$@\"\n",
wantHas: []string{"#!/bin/sh\n", hookSectionBeginPrefix, "bd hooks run pre-commit"},
},
{
name: "orphaned BEGIN followed by valid block",
existing: "#!/bin/sh\n" +
"# --- BEGIN BEADS INTEGRATION v0.57.0 ---\n" +
"bd hook pre-commit \"$@\"\n" +
"\n" +
"# --- BEGIN BEADS INTEGRATION v0.58.0 ---\n" +
"# This section is managed by beads. Do not remove these markers.\n" +
"if command -v bd >/dev/null 2>&1; then\n" +
" export BD_GIT_HOOK=1\n" +
" bd hooks run pre-commit \"$@\"\n" +
" _bd_exit=$?; if [ $_bd_exit -ne 0 ]; then exit $_bd_exit; fi\n" +
"fi\n" +
"# --- END BEADS INTEGRATION ---\n",
wantHas: []string{"#!/bin/sh\n", hookSectionBeginPrefix, "bd hooks run pre-commit"},
},
{
name: "reversed markers (END before BEGIN)",
existing: "#!/bin/sh\necho user-linter\n" +
"# --- END BEADS INTEGRATION ---\n" +
"# --- BEGIN BEADS INTEGRATION v0.57.0 ---\n" +
"bd hook pre-commit \"$@\"\n",
wantHas: []string{"#!/bin/sh\n", "echo user-linter", hookSectionBeginPrefix, "bd hooks run pre-commit"},
},
{
name: "update existing section with versioned END marker",
existing: "#!/bin/sh\necho before\n# --- BEGIN BEADS INTEGRATION v0.57.0 ---\nold content\n# --- END BEADS INTEGRATION v0.57.0 ---\necho after\n",
wantHas: []string{"echo before", "echo after", "bd hooks run pre-commit", hookSectionEndPrefix},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := injectHookSection(tt.existing, section)
for _, want := range tt.wantHas {
if !strings.Contains(result, want) {
t.Errorf("result missing %q\ngot:\n%s", want, result)
}
}
// Verify old content is not present when updating
if tt.name == "update existing section" {
if strings.Contains(result, "old content") {
t.Error("old section content should have been replaced")
}
if strings.Contains(result, "v0.40.0") {
t.Error("old version should have been replaced")
}
}
// Verify broken marker scenarios leave exactly one clean section
brokenCases := map[string]bool{
"orphaned BEGIN without END": true,
"orphaned BEGIN followed by valid block": true,
"reversed markers (END before BEGIN)": true,
}
if brokenCases[tt.name] {
beginCount := strings.Count(result, hookSectionBeginPrefix)
if beginCount != 1 {
t.Errorf("expected exactly 1 BEGIN marker, got %d\ngot:\n%s", beginCount, result)
}
endCount := strings.Count(result, hookSectionEndPrefix)
if endCount != 1 {
t.Errorf("expected exactly 1 END marker, got %d\ngot:\n%s", endCount, result)
}
if strings.Contains(result, "bd hook pre-commit") && !strings.Contains(result, "bd hooks run pre-commit") {
t.Error("stale 'bd hook' command should have been removed")
}
if strings.Contains(result, "v0.57.0") {
t.Error("stale v0.57.0 marker should have been removed")
}
}
})
}
}
func TestRemoveHookSection(t *testing.T) {
tests := []struct {
name string
content string
wantFound bool
wantHas []string
wantNot []string
}{
{
name: "remove section preserving user content",
content: "#!/bin/sh\necho before\n\n" + generateHookSection("pre-commit") + "echo after\n",
wantFound: true,
wantHas: []string{"echo before", "echo after"},
wantNot: []string{hookSectionBeginPrefix, hookSectionEndPrefix},
},
{
name: "no section to remove",
content: "#!/bin/sh\necho custom\n",
wantFound: false,
wantHas: []string{"echo custom"},
},
{
name: "only section — leaves shebang",
content: "#!/bin/sh\n" + generateHookSection("pre-commit"),
wantFound: true,
wantNot: []string{hookSectionBeginPrefix},
},
{
name: "orphaned BEGIN without END",
content: "#!/bin/sh\necho before\n\n# --- BEGIN BEADS INTEGRATION v0.57.0 ---\nbd hook pre-commit \"$@\"\n",
wantFound: true,
wantHas: []string{"echo before"},
wantNot: []string{hookSectionBeginPrefix, "bd hook pre-commit"},
},
{
name: "reversed markers (END before BEGIN)",
content: "#!/bin/sh\necho user-linter\n" +
"# --- END BEADS INTEGRATION ---\n" +
"# --- BEGIN BEADS INTEGRATION v0.57.0 ---\n" +
"bd hook pre-commit \"$@\"\n",
wantFound: true,
wantHas: []string{"echo user-linter"},
wantNot: []string{hookSectionBeginPrefix, hookSectionEndPrefix, "bd hook pre-commit"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := removeHookSection(tt.content)
if found != tt.wantFound {
t.Errorf("found = %v, want %v", found, tt.wantFound)
}
for _, want := range tt.wantHas {
if !strings.Contains(result, want) {
t.Errorf("result missing %q\ngot:\n%s", want, result)
}
}
for _, notWant := range tt.wantNot {
if strings.Contains(result, notWant) {
t.Errorf("result should not contain %q\ngot:\n%s", notWant, result)
}
}
})
}
}
func TestInstallHooksWithSectionMarkers(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("Failed to create hooks directory: %v", err)
}
// Create an existing non-bd hook
preCommitPath := filepath.Join(hooksDir, "pre-commit")
if err := os.WriteFile(preCommitPath, []byte("#!/bin/sh\necho my-linter\n"), 0700); err != nil {
t.Fatal(err)
}
// Install hooks — should inject section, not replace file
if err := installHooksWithOptions(managedHookNames, false, false, false, false); err != nil {
t.Fatalf("installHooksWithOptions() failed: %v", err)
}
// Verify pre-commit has both user content and section
content, err := os.ReadFile(preCommitPath)
if err != nil {
t.Fatal(err)
}
contentStr := string(content)
if !strings.Contains(contentStr, "echo my-linter") {
t.Error("user content should be preserved")
}
if !strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Error("section marker should be present")
}
if !strings.Contains(contentStr, "bd hooks run pre-commit") {
t.Error("hook invocation should be present")
}
// Run install again — should be idempotent (update section only)
if err := installHooksWithOptions(managedHookNames, false, false, false, false); err != nil {
t.Fatalf("second installHooksWithOptions() failed: %v", err)
}
content2, _ := os.ReadFile(preCommitPath)
if string(content2) != contentStr {
t.Errorf("second install changed content:\nbefore:\n%s\nafter:\n%s", contentStr, string(content2))
}
})
}
func TestInstallHooksWithOptions_MockHookWithoutCurrentHook(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
mockHookName := "pre-commit-mock"
mockHookPath := filepath.Join(hooksDir, mockHookName)
if err := installHooksWithOptions([]string{mockHookName}, false, false, false, false); err != nil {
t.Fatalf("installHooksWithOptions() failed: %v", err)
}
content, err := os.ReadFile(mockHookPath)
if err != nil {
t.Fatalf("failed to read mock hook: %v", err)
}
contentStr := string(content)
if !strings.HasPrefix(contentStr, "#!/usr/bin/env sh\n") {
t.Errorf("mock hook should start with shebang, got:\n%s", contentStr)
}
if !strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Errorf("mock hook should include managed section begin marker, got:\n%s", contentStr)
}
if !strings.Contains(contentStr, "bd hooks run "+mockHookName) {
t.Errorf("mock hook should invoke bd hooks run %s, got:\n%s", mockHookName, contentStr)
}
})
}
func TestInstallHooksWithOptions_MockHookWithCurrentHook(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("failed to create hooks dir: %v", err)
}
mockHookName := "pre-commit-mock"
mockHookPath := filepath.Join(hooksDir, mockHookName)
existing := "#!/bin/sh\necho current-hook\n"
if err := os.WriteFile(mockHookPath, []byte(existing), 0700); err != nil {
t.Fatalf("failed to seed mock hook: %v", err)
}
if err := installHooksWithOptions([]string{mockHookName}, false, false, false, false); err != nil {
t.Fatalf("installHooksWithOptions() failed: %v", err)
}
content, err := os.ReadFile(mockHookPath)
if err != nil {
t.Fatalf("failed to read mock hook: %v", err)
}
contentStr := string(content)
if !strings.Contains(contentStr, "echo current-hook") {
t.Errorf("existing hook content should be preserved, got:\n%s", contentStr)
}
if !strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Errorf("mock hook should include managed section begin marker, got:\n%s", contentStr)
}
if !strings.Contains(contentStr, "bd hooks run "+mockHookName) {
t.Errorf("mock hook should invoke bd hooks run %s, got:\n%s", mockHookName, contentStr)
}
})
}
func TestInstallJJHooks_PreservesContentWithoutOldSidecars(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("Failed to create hooks directory: %v", err)
}
preCommitPath := filepath.Join(hooksDir, "pre-commit")
postMergePath := filepath.Join(hooksDir, "post-merge")
if err := os.WriteFile(preCommitPath, []byte("#!/bin/sh\necho jj-pre\n"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(postMergePath, []byte("#!/bin/sh\necho jj-post\n"), 0700); err != nil {
t.Fatal(err)
}
if err := installJJHooks(); err != nil {
t.Fatalf("installJJHooks() failed: %v", err)
}
preCommitContent, err := os.ReadFile(preCommitPath)
if err != nil {
t.Fatal(err)
}
postMergeContent, err := os.ReadFile(postMergePath)
if err != nil {
t.Fatal(err)
}
preCommitStr := string(preCommitContent)
postMergeStr := string(postMergeContent)
if !strings.Contains(preCommitStr, "echo jj-pre") {
t.Error("pre-commit user content should be preserved")
}
if !strings.Contains(postMergeStr, "echo jj-post") {
t.Error("post-merge user content should be preserved")
}
if !strings.Contains(preCommitStr, hookSectionBeginPrefix) {
t.Error("pre-commit section marker should be present")
}
if !strings.Contains(postMergeStr, hookSectionBeginPrefix) {
t.Error("post-merge section marker should be present")
}
if _, err := os.Stat(preCommitPath + ".old"); !os.IsNotExist(err) {
t.Error("pre-commit .old sidecar should not be created in jj install path")
}
if _, err := os.Stat(postMergePath + ".old"); !os.IsNotExist(err) {
t.Error("post-merge .old sidecar should not be created in jj install path")
}
preCommitOnce := preCommitStr
postMergeOnce := postMergeStr
if err := installJJHooks(); err != nil {
t.Fatalf("second installJJHooks() failed: %v", err)
}
preCommitTwice, _ := os.ReadFile(preCommitPath)
postMergeTwice, _ := os.ReadFile(postMergePath)
if string(preCommitTwice) != preCommitOnce {
t.Errorf("pre-commit changed on second jj install:\nbefore:\n%s\nafter:\n%s", preCommitOnce, string(preCommitTwice))
}
if string(postMergeTwice) != postMergeOnce {
t.Errorf("post-merge changed on second jj install:\nbefore:\n%s\nafter:\n%s", postMergeOnce, string(postMergeTwice))
}
})
}
func TestUninstallHooksWithSectionMarkers(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("Failed to create hooks directory: %v", err)
}
// Create a hook with user content + beads section
preCommitPath := filepath.Join(hooksDir, "pre-commit")
hookContent := "#!/bin/sh\necho my-linter\n\n" + generateHookSection("pre-commit")
if err := os.WriteFile(preCommitPath, []byte(hookContent), 0700); err != nil {
t.Fatal(err)
}
if err := uninstallHooks(); err != nil {
t.Fatalf("uninstallHooks() failed: %v", err)
}
// File should still exist with user content, but no beads section
content, err := os.ReadFile(preCommitPath)
if err != nil {
t.Fatal("hook file should still exist after uninstall")
}
contentStr := string(content)
if !strings.Contains(contentStr, "echo my-linter") {
t.Error("user content should be preserved after uninstall")
}
if strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Error("beads section should be removed after uninstall")
}
})
}
func TestUninstallHooksRemovesEmptyFile(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("Failed to create hooks directory: %v", err)
}
// Create a hook with only beads section (no user content)
preCommitPath := filepath.Join(hooksDir, "pre-commit")
hookContent := "#!/usr/bin/env sh\n" + generateHookSection("pre-commit")
if err := os.WriteFile(preCommitPath, []byte(hookContent), 0700); err != nil {
t.Fatal(err)
}
if err := uninstallHooks(); err != nil {
t.Fatalf("uninstallHooks() failed: %v", err)
}
// File should be removed entirely (only shebang left)
if _, err := os.Stat(preCommitPath); !os.IsNotExist(err) {
t.Error("hook file with only shebang should be removed entirely")
}
})
}
// TestConfigureBeadsHooksPath_AbsolutePath verifies that core.hooksPath is set to
// an absolute path so that git worktrees can find the hooks directory (GH#2414).
func TestConfigureBeadsHooksPath_AbsolutePath(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
// Create .beads/hooks/ directory
beadsHooksDir := filepath.Join(tmpDir, ".beads", "hooks")
if err := os.MkdirAll(beadsHooksDir, 0750); err != nil {
t.Fatalf("Failed to create .beads/hooks/: %v", err)
}
if err := configureBeadsHooksPath(); err != nil {
t.Fatalf("configureBeadsHooksPath() failed: %v", err)
}
// Read back core.hooksPath
out, err := exec.Command("git", "config", "--get", "core.hooksPath").Output()
if err != nil {
t.Fatalf("git config --get core.hooksPath failed: %v", err)
}
hooksPath := strings.TrimSpace(string(out))
// Must be absolute
if !filepath.IsAbs(hooksPath) {
t.Errorf("core.hooksPath should be absolute, got %q", hooksPath)
}
// Must point to .beads/hooks
if !strings.HasSuffix(hooksPath, filepath.Join(".beads", "hooks")) {
t.Errorf("core.hooksPath should end with .beads/hooks, got %q", hooksPath)
}
})
}
// TestInstallHooksBeads_WorktreeAccess verifies that hooks installed with --beads
// are accessible from a git worktree (GH#2414).
func TestInstallHooksBeads_WorktreeAccess(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
// Create .beads/ directory with metadata.json (needed for FindBeadsDir)
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("Failed to create .beads/: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{}`), 0644); err != nil {
t.Fatalf("Failed to create metadata.json: %v", err)
}
cmd := exec.Command("git", "commit", "--allow-empty", "--no-verify", "-m", "init")
cmd.Dir = tmpDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git commit failed: %v\n%s", err, string(output))
}
// Install hooks with --beads
if err := installHooksWithOptions(managedHookNames, false, false, false, true); err != nil {
t.Fatalf("installHooksWithOptions(beads=true) failed: %v", err)
}
// Verify hooks exist in .beads/hooks/
for _, hookName := range managedHookNames {
hookPath := filepath.Join(beadsDir, "hooks", hookName)
if _, err := os.Stat(hookPath); err != nil {
t.Errorf("hook %s not found at %s", hookName, hookPath)
}
}
// Read core.hooksPath and verify it's absolute
out, err := exec.Command("git", "config", "--get", "core.hooksPath").Output()
if err != nil {
t.Fatalf("core.hooksPath not set after --beads install: %v", err)
}
hooksPath := strings.TrimSpace(string(out))
if !filepath.IsAbs(hooksPath) {
t.Errorf("core.hooksPath should be absolute for worktree compatibility, got %q", hooksPath)
}
// Create a worktree and verify hooks are accessible from it
worktreeDir := filepath.Join(t.TempDir(), "worktree")
cmd = exec.Command("git", "worktree", "add", worktreeDir, "-b", "test-worktree")
cmd.Dir = tmpDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git worktree add failed: %v\n%s", err, string(output))
}
defer func() {
exec.Command("git", "worktree", "remove", worktreeDir).Run()
}()
// From the worktree, core.hooksPath should resolve to the same hooks
cmd = exec.Command("git", "config", "--get", "core.hooksPath")
cmd.Dir = worktreeDir
wtOut, err := cmd.Output()
if err != nil {
t.Fatalf("core.hooksPath not visible from worktree: %v", err)
}
wtHooksPath := strings.TrimSpace(string(wtOut))
if wtHooksPath != hooksPath {
t.Errorf("worktree core.hooksPath = %q, want %q", wtHooksPath, hooksPath)
}
// The hooks directory must actually exist at the resolved path
if _, err := os.Stat(wtHooksPath); err != nil {
t.Errorf("hooks directory not accessible from worktree at %q: %v", wtHooksPath, err)
}
// Verify a specific hook file exists
preCommitPath := filepath.Join(wtHooksPath, "pre-commit")
if _, err := os.Stat(preCommitPath); err != nil {
t.Errorf("pre-commit hook not accessible from worktree: %v", err)
}
})
}
// setupBeadsDir creates .beads/ with a minimal metadata.json so FindBeadsDir works.
func setupBeadsDir(t *testing.T, repoDir string) string {
t.Helper()
beadsDir := filepath.Join(repoDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads/: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{}`), 0644); err != nil {
t.Fatalf("failed to create metadata.json: %v", err)
}
return beadsDir
}
// TestInstallHooksBeads_PreservesGlobalHooks is a regression test: bd init sets
// a local core.hooksPath that shadows the global one, silently killing global
// hooks. The fix copies hooks from the effective directory before overriding.
func TestInstallHooksBeads_PreservesGlobalHooks(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"))
globalHooksDir := filepath.Join(fakeHome, "global-hooks")
if err := os.MkdirAll(globalHooksDir, 0755); err != nil {
t.Fatalf("failed to create global hooks dir: %v", err)
}
globalHookContent := "#!/bin/sh\necho global-hook-marker\n"
if err := os.WriteFile(filepath.Join(globalHooksDir, "pre-commit"), []byte(globalHookContent), 0755); err != nil {
t.Fatalf("failed to write global pre-commit hook: %v", err)
}
setGlobal := exec.Command("git", "config", "--global", "core.hooksPath", globalHooksDir)
if out, err := setGlobal.CombinedOutput(); err != nil {
t.Fatalf("failed to set global core.hooksPath: %v (%s)", err, strings.TrimSpace(string(out)))
}
// Manual repo init (can't use newGitRepo which sets a local core.hooksPath).
repoDir := t.TempDir()
initCmd := exec.Command("git", "init", "--initial-branch=main")
initCmd.Dir = repoDir
if err := initCmd.Run(); err != nil {
t.Fatalf("git init failed: %v", err)
}
for _, args := range [][]string{
{"config", "user.email", "test@test.com"},
{"config", "user.name", "Test User"},
} {
cmd := exec.Command("git", args...)
cmd.Dir = repoDir
if err := cmd.Run(); err != nil {
t.Fatalf("git config %v failed: %v", args, err)
}
}
runInDir(t, repoDir, func() {
beadsDir := setupBeadsDir(t, repoDir)
if err := installHooksWithOptions(managedHookNames, false, false, false, true); err != nil {
t.Fatalf("installHooksWithOptions(beads=true) failed: %v", err)
}
content, err := os.ReadFile(filepath.Join(beadsDir, "hooks", "pre-commit"))
if err != nil {
t.Fatalf("failed to read .beads/hooks/pre-commit: %v", err)
}
contentStr := string(content)
if !strings.Contains(contentStr, "echo global-hook-marker") {
t.Errorf("global hook content not preserved in .beads/hooks/pre-commit.\nGot:\n%s", contentStr)
}
if !strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Errorf("beads section marker missing.\nGot:\n%s", contentStr)
}
})
}
// TestInstallHooksBeads_PreservesDefaultGitHooks verifies that hooks in the
// default .git/hooks/ directory (both managed and non-managed) are preserved
// when beads redirects core.hooksPath to .beads/hooks/.
func TestInstallHooksBeads_PreservesDefaultGitHooks(t *testing.T) {
repoDir := newGitRepo(t)
runInDir(t, repoDir, func() {
hooksDir := filepath.Join(repoDir, ".git", "hooks")
if err := os.MkdirAll(hooksDir, 0755); err != nil {
t.Fatalf("failed to create .git/hooks: %v", err)
}
if err := os.WriteFile(filepath.Join(hooksDir, "pre-commit"), []byte("#!/bin/sh\necho custom-default-hook\n"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(hooksDir, "commit-msg"), []byte("#!/bin/sh\necho commit-msg-hook\n"), 0755); err != nil {
t.Fatal(err)
}
// Unset the local core.hooksPath that newGitRepo sets so git falls back to .git/hooks/.
exec.Command("git", "config", "--unset", "core.hooksPath").Run()
beadsDir := setupBeadsDir(t, repoDir)
if err := installHooksWithOptions(managedHookNames, false, false, false, true); err != nil {
t.Fatalf("installHooksWithOptions(beads=true) failed: %v", err)
}
// Managed hook: should be preserved with beads section injected.
content, err := os.ReadFile(filepath.Join(beadsDir, "hooks", "pre-commit"))
if err != nil {
t.Fatalf("failed to read .beads/hooks/pre-commit: %v", err)
}
contentStr := string(content)
if !strings.Contains(contentStr, "echo custom-default-hook") {
t.Errorf(".git/hooks/pre-commit content not preserved.\nGot:\n%s", contentStr)
}
if !strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Errorf("beads section marker missing.\nGot:\n%s", contentStr)
}
// Non-managed hook: should be copied as-is.
cmContent, err := os.ReadFile(filepath.Join(beadsDir, "hooks", "commit-msg"))
if err != nil {
t.Fatalf("non-managed hook commit-msg not copied to .beads/hooks/: %v", err)
}
if !strings.Contains(string(cmContent), "echo commit-msg-hook") {
t.Errorf("Unmanaged hook content not preserved.\nGot:\n%s", string(cmContent))
}
})
}
func TestHooksNeedUpdate(t *testing.T) {
tests := []struct {
name string
setupHooks bool // whether to create .git/hooks/ with hook files
preCommitBody string
postMergeBody string
skipPostMerge bool // skip writing post-merge hook file
fileMode os.FileMode // file mode for hook files (0 = default 0700)
wantNeedUpdate bool
}{
{
name: "no hooks directory",
setupHooks: false,
wantNeedUpdate: false,
},
{
name: "current version hooks",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-hooks-version: " + Version + "\n# bd (beads) pre-commit hook\nbd sync --flush-only\n",
postMergeBody: "#!/bin/sh\n# bd-hooks-version: " + Version + "\n# bd (beads) post-merge hook\nbd import\n",
wantNeedUpdate: false,
},
{
name: "outdated version hooks",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-hooks-version: 0.40.0\n# bd (beads) pre-commit hook\nbd sync --flush-only\n",
postMergeBody: "#!/bin/sh\n# bd-hooks-version: 0.40.0\n# bd (beads) post-merge hook\nbd import\n",
wantNeedUpdate: true,
},
{
name: "inline hooks without version",
setupHooks: true,
preCommitBody: "#!/bin/sh\n#\n# bd (beads) pre-commit hook\n#\nbd sync --flush-only\n",
postMergeBody: "#!/bin/sh\n#\n# bd (beads) post-merge hook\n#\nbd import\n",
wantNeedUpdate: true,
},
{
name: "shim hooks",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-shim 0.40.0\nexec bd hooks run pre-commit \"$@\"\n",
postMergeBody: "#!/bin/sh\n# bd-shim 0.40.0\nexec bd hooks run post-merge \"$@\"\n",
wantNeedUpdate: false,
},
{
name: "non-bd hooks",
setupHooks: true,
preCommitBody: "#!/bin/sh\necho 'custom pre-commit'\n",
postMergeBody: "#!/bin/sh\necho 'custom post-merge'\n",
wantNeedUpdate: false,
},
{
name: "empty hook files",
setupHooks: true,
preCommitBody: "",
postMergeBody: "",
wantNeedUpdate: false,
},
{
name: "version prefix with empty version",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-hooks-version: \n# bd (beads) pre-commit hook\n",
postMergeBody: "#!/bin/sh\n# bd-hooks-version: \n# bd (beads) post-merge hook\n",
wantNeedUpdate: true,
},
{
name: "mixed state: one outdated one current",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-hooks-version: 0.40.0\n# bd (beads) pre-commit hook\nbd sync --flush-only\n",
postMergeBody: "#!/bin/sh\n# bd-hooks-version: " + Version + "\n# bd (beads) post-merge hook\nbd import\n",
wantNeedUpdate: true,
},
{
name: "mixed state: shim and outdated template",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-shim 0.49.6\nexec bd hooks run pre-commit \"$@\"\n",
postMergeBody: "#!/bin/sh\n# bd-hooks-version: 0.40.0\n# bd (beads) post-merge hook\n",
wantNeedUpdate: true,
},
{
name: "only pre-commit exists",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-hooks-version: 0.40.0\n# bd (beads) pre-commit hook\nbd sync --flush-only\n",
skipPostMerge: true,
wantNeedUpdate: true,
},
{
name: "non-executable current version hooks",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# bd-hooks-version: " + Version + "\n# bd (beads) pre-commit hook\nbd sync --flush-only\n",
postMergeBody: "#!/bin/sh\n# bd-hooks-version: " + Version + "\n# bd (beads) post-merge hook\nbd import\n",
fileMode: 0644,
wantNeedUpdate: false, // hooksNeedUpdate checks version, not permissions
},
{
name: "section marker hooks current version",
setupHooks: true,
preCommitBody: "#!/bin/sh\n" + generateHookSection("pre-commit"),
postMergeBody: "#!/bin/sh\n" + generateHookSection("post-merge"),
wantNeedUpdate: false,
},
{
name: "section marker hooks older version (shim-like, not outdated)",
setupHooks: true,
preCommitBody: "#!/bin/sh\n# --- BEGIN BEADS INTEGRATION v0.40.0 ---\nbd hooks run pre-commit \"$@\"\n# --- END BEADS INTEGRATION ---\n",
postMergeBody: "#!/bin/sh\n# --- BEGIN BEADS INTEGRATION v0.40.0 ---\nbd hooks run post-merge \"$@\"\n# --- END BEADS INTEGRATION ---\n",
wantNeedUpdate: false, // section-marker hooks delegate to bd hooks run, like shims
},
{
name: "section marker with user content preserved",
setupHooks: true,
preCommitBody: "#!/bin/sh\necho user-before\n\n" + generateHookSection("pre-commit") + "\necho user-after\n",
postMergeBody: "#!/bin/sh\n" + generateHookSection("post-merge"),
wantNeedUpdate: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpDir := newGitRepo(t)
runInDir(t, tmpDir, func() {
if tt.setupHooks {
gitDirPath, err := git.GetGitDir()
if err != nil {
t.Fatalf("git.GetGitDir() failed: %v", err)
}
hooksDir := filepath.Join(gitDirPath, "hooks")
if err := os.MkdirAll(hooksDir, 0750); err != nil {
t.Fatalf("Failed to create hooks directory: %v", err)
}
mode := tt.fileMode
if mode == 0 {
mode = 0700
}
preCommitPath := filepath.Join(hooksDir, "pre-commit")
if err := os.WriteFile(preCommitPath, []byte(tt.preCommitBody), mode); err != nil {
t.Fatalf("Failed to write pre-commit hook: %v", err)
}
if !tt.skipPostMerge {
postMergePath := filepath.Join(hooksDir, "post-merge")
if err := os.WriteFile(postMergePath, []byte(tt.postMergeBody), mode); err != nil {
t.Fatalf("Failed to write post-merge hook: %v", err)
}
}
}
got := hooksNeedUpdate()
if got != tt.wantNeedUpdate {
t.Errorf("hooksNeedUpdate() = %v, want %v", got, tt.wantNeedUpdate)
}
})
})
}
}
// TestInstallHooksBeads_HuskyV8Helper verifies that the husky v8 _/ helper
// directory is symlinked when hooks are preserved from a husky-managed directory.
// GH#3132 Bug 1: without this, hooks that source $(dirname "$0")/_/husky.sh fail.
func TestInstallHooksBeads_HuskyV8Helper(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"))
// Create a husky v8-style hooks directory
huskyDir := filepath.Join(fakeHome, "husky-hooks")
huskyHelperDir := filepath.Join(huskyDir, "_")
if err := os.MkdirAll(huskyHelperDir, 0755); err != nil {
t.Fatalf("mkdir husky helper: %v", err)
}
huskyShContent := "#!/usr/bin/env sh\n# husky v8 helper\n"
if err := os.WriteFile(filepath.Join(huskyHelperDir, "husky.sh"), []byte(huskyShContent), 0755); err != nil {
t.Fatalf("write husky.sh: %v", err)
}
// Hook that sources the helper via relative path
hookContent := "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\nnpx lint-staged\n"
if err := os.WriteFile(filepath.Join(huskyDir, "pre-commit"), []byte(hookContent), 0755); err != nil {
t.Fatalf("write pre-commit: %v", err)
}
// Set as global hooks path (simulating husky v8)
setGlobal := exec.Command("git", "config", "--global", "core.hooksPath", huskyDir)
if out, err := setGlobal.CombinedOutput(); err != nil {
t.Fatalf("set global core.hooksPath: %v (%s)", err, strings.TrimSpace(string(out)))
}
repoDir := t.TempDir()
initCmd := exec.Command("git", "init", "--initial-branch=main")
initCmd.Dir = repoDir
if err := initCmd.Run(); err != nil {
t.Fatalf("git init: %v", err)
}
for _, args := range [][]string{
{"config", "user.email", "test@test.com"},
{"config", "user.name", "Test"},
} {
cmd := exec.Command("git", args...)
cmd.Dir = repoDir
if err := cmd.Run(); err != nil {
t.Fatalf("git config %v: %v", args, err)
}
}
runInDir(t, repoDir, func() {
beadsDir := setupBeadsDir(t, repoDir)
if err := installHooksWithOptions(managedHookNames, false, false, false, true); err != nil {
t.Fatalf("installHooksWithOptions: %v", err)
}
// Verify the _/ symlink was created
tgtHelper := filepath.Join(beadsDir, "hooks", "_")
info, err := os.Lstat(tgtHelper)
if err != nil {
t.Fatalf("expected _/ symlink in .beads/hooks/: %v", err)
}
if info.Mode()&os.ModeSymlink == 0 {
t.Errorf("expected _/ to be a symlink, got mode %v", info.Mode())
}
// Verify the symlink target resolves to the original helper
target, err := os.Readlink(tgtHelper)
if err != nil {
t.Fatalf("readlink: %v", err)
}
resolved := filepath.Join(filepath.Dir(tgtHelper), target, "husky.sh")
if _, err := os.Stat(resolved); err != nil {
t.Errorf("symlink does not resolve to husky.sh: %v (target=%s)", err, target)
}
// Verify the hook content was preserved
content, err := os.ReadFile(filepath.Join(beadsDir, "hooks", "pre-commit"))
if err != nil {
t.Fatalf("read pre-commit: %v", err)
}
if !strings.Contains(string(content), "npx lint-staged") {
t.Errorf("hook content not preserved.\nGot:\n%s", string(content))
}
})
}
// TestInstallHooksBeads_HuskyV9Shims verifies that husky v9 shims are replaced
// with actual user hook content when preserved.
// GH#3132 Bug 2: husky v9's h dispatcher uses dirname(dirname($0)) which breaks
// when hooks are relocated from .husky/_/ to .beads/hooks/.
func TestInstallHooksBeads_HuskyV9Shims(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"))
// Create husky v9 directory structure:
// .husky/
// pre-commit <- user's actual commands
// _/
// h <- dispatcher
// pre-commit <- shim that sources h
huskyBase := filepath.Join(fakeHome, "project", ".husky")
huskyInner := filepath.Join(huskyBase, "_")
if err := os.MkdirAll(huskyInner, 0755); err != nil {
t.Fatalf("mkdir .husky/_: %v", err)
}
// User's actual hook commands (in .husky/)
userHookContent := "npm run minify-templates\nnpx lint-staged --allow-empty\n"
if err := os.WriteFile(filepath.Join(huskyBase, "pre-commit"), []byte(userHookContent), 0644); err != nil {
t.Fatalf("write user hook: %v", err)
}
// Husky v9 dispatcher (in .husky/_/)
hDispatcher := `#!/usr/bin/env sh
n=$(basename "$0")
s=$(dirname "$(dirname "$0")")/$n
[ ! -f "$s" ] && exit 0
. "$s"
`
if err := os.WriteFile(filepath.Join(huskyInner, "h"), []byte(hDispatcher), 0755); err != nil {
t.Fatalf("write h dispatcher: %v", err)
}
// Husky v9 shim (in .husky/_/)
shimContent := "#!/usr/bin/env sh\n. \"$(dirname \"$0\")/h\"\n"
if err := os.WriteFile(filepath.Join(huskyInner, "pre-commit"), []byte(shimContent), 0755); err != nil {
t.Fatalf("write shim: %v", err)
}
// Set core.hooksPath to .husky/_/ (husky v9 style)
setGlobal := exec.Command("git", "config", "--global", "core.hooksPath", huskyInner)
if out, err := setGlobal.CombinedOutput(); err != nil {
t.Fatalf("set global core.hooksPath: %v (%s)", err, strings.TrimSpace(string(out)))
}
repoDir := t.TempDir()
initCmd := exec.Command("git", "init", "--initial-branch=main")
initCmd.Dir = repoDir
if err := initCmd.Run(); err != nil {
t.Fatalf("git init: %v", err)
}
for _, args := range [][]string{
{"config", "user.email", "test@test.com"},
{"config", "user.name", "Test"},
} {
cmd := exec.Command("git", args...)
cmd.Dir = repoDir
if err := cmd.Run(); err != nil {
t.Fatalf("git config %v: %v", args, err)
}
}
runInDir(t, repoDir, func() {
beadsDir := setupBeadsDir(t, repoDir)
if err := installHooksWithOptions(managedHookNames, false, false, false, true); err != nil {
t.Fatalf("installHooksWithOptions: %v", err)
}
// Verify the h dispatcher was removed
hTarget := filepath.Join(beadsDir, "hooks", "h")
if _, err := os.Stat(hTarget); !os.IsNotExist(err) {
t.Error("h dispatcher should have been removed from .beads/hooks/")
}
// Verify the shim was replaced with actual user hook content
content, err := os.ReadFile(filepath.Join(beadsDir, "hooks", "pre-commit"))
if err != nil {
t.Fatalf("read pre-commit: %v", err)
}
contentStr := string(content)
// Should contain the user's actual commands, not the shim
if strings.Contains(contentStr, `. "$(dirname "$0")/h"`) {
t.Error("shim content should have been replaced with user hook content")
}
if !strings.Contains(contentStr, "npx lint-staged --allow-empty") {
t.Errorf("user hook content not found.\nGot:\n%s", contentStr)
}
if !strings.Contains(contentStr, "npm run minify-templates") {
t.Errorf("user hook content not found.\nGot:\n%s", contentStr)
}
// Should have a shebang (added since user hooks in .husky/ often omit it)
if !strings.HasPrefix(contentStr, "#!") {
t.Error("preserved hook should have a shebang")
}
// Beads section should also be present (injected by installHooksWithOptions)
if !strings.Contains(contentStr, hookSectionBeginPrefix) {
t.Errorf("beads section marker missing.\nGot:\n%s", contentStr)
}
})
}
// TestFixHuskyHookLayout_NoHusky verifies the fix is a no-op for non-husky directories.
func TestFixHuskyHookLayout_NoHusky(t *testing.T) {
sourceDir := t.TempDir()
targetDir := t.TempDir()
// Write a normal hook (no husky)
if err := os.WriteFile(filepath.Join(sourceDir, "pre-commit"), []byte("#!/bin/sh\necho hi\n"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(targetDir, "pre-commit"), []byte("#!/bin/sh\necho hi\n"), 0755); err != nil {
t.Fatal(err)
}
fixHuskyHookLayout(sourceDir, targetDir)
// No _/ symlink should be created
if _, err := os.Lstat(filepath.Join(targetDir, "_")); !os.IsNotExist(err) {
t.Error("_/ should not exist for non-husky directories")
}
// No h file to remove
if _, err := os.Stat(filepath.Join(targetDir, "h")); !os.IsNotExist(err) {
t.Error("h should not exist")
}
}