* 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>
2409 lines
93 KiB
Go
2409 lines
93 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/cmd/bd/doctor"
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/debug"
|
|
"github.com/steveyegge/beads/internal/execenv"
|
|
"github.com/steveyegge/beads/internal/git"
|
|
"github.com/steveyegge/beads/internal/gitenv"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
)
|
|
|
|
// managedHookNames lists the git hooks managed by beads.
|
|
// Hook content is generated dynamically by generateHookSection().
|
|
var managedHookNames = []string{"pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"}
|
|
|
|
const hookVersionPrefix = "# bd-hooks-version: "
|
|
const shimVersionPrefix = "# bd-shim "
|
|
|
|
// inlineHookMarker identifies inline hooks created by bd init (GH#1120)
|
|
// These hooks have the logic embedded directly rather than using shims
|
|
const inlineHookMarker = "# bd (beads)"
|
|
|
|
// Section markers for git hooks (GH#1380) — consistent with AGENTS.md pattern.
|
|
// Only content between markers is managed by beads; user content outside is preserved.
|
|
const hookSectionBeginPrefix = "# --- BEGIN BEADS INTEGRATION"
|
|
const hookSectionEndPrefix = "# --- END BEADS INTEGRATION"
|
|
|
|
// hookSectionBeginLine returns the full begin marker line with the current version.
|
|
func hookSectionBeginLine() string {
|
|
return fmt.Sprintf("%s v%s ---", hookSectionBeginPrefix, Version)
|
|
}
|
|
|
|
// hookSectionEndLine returns the full end marker line with the current version.
|
|
func hookSectionEndLine() string {
|
|
return fmt.Sprintf("%s v%s ---", hookSectionEndPrefix, Version)
|
|
}
|
|
|
|
// hookTimeoutSeconds is the soft deadline for a beads hook. GNU timeout sends
|
|
// SIGTERM at the deadline, while Perl's alarm terminates the direct bd process.
|
|
// Neither backend promises containment of TERM-resistant descendant work. When
|
|
// neither helper is available, the generated hook warns that it is unbounded.
|
|
// The default is 300 seconds (5 minutes) to accommodate chained hooks — e.g.
|
|
// pre-commit framework pipelines that run linters, type-checkers, and builds
|
|
// inside `bd hooks run` via the `.old` hook chain (GH#2732).
|
|
// The value can be overridden via the BEADS_HOOK_TIMEOUT environment variable.
|
|
const hookTimeoutSeconds = 300
|
|
|
|
// generateHookSection returns the marked section content for a given hook name.
|
|
// The section is self-contained: it checks for bd availability, runs the hook
|
|
// via 'bd hooks run', and propagates exit codes — without preventing any user
|
|
// content after the section from executing on success.
|
|
//
|
|
// Resilience (GH#2453, GH#2449):
|
|
// - A compatible timeout helper applies a best-effort soft deadline.
|
|
// - BEADS_HOOK_TIMEOUT accepts positive whole seconds only.
|
|
// - Helper argv is separated with -- so user input cannot become an option.
|
|
// - If no compatible helper exists, the direct fallback is explicitly
|
|
// unbounded rather than silently pretending to enforce a deadline.
|
|
// - Only GNU coreutils timeout and uutils coreutils timeout (same command
|
|
// line, same exit 124; GH#5541) are selected, by --version banner; Windows
|
|
// timeout.exe has the same name but an incompatible command line (GH#5503).
|
|
// The banner match holds under the gtimeout candidate too: GNU prints a
|
|
// fixed program name (Homebrew's gtimeout reports "timeout (GNU
|
|
// coreutils) ..."), and the uutils multicall dispatches on the argv[0]
|
|
// suffix and then prints the canonical name ("timeout (uutils coreutils)
|
|
// ..." when invoked as gtimeout). checks.nix runs that case.
|
|
// - If the beads database is not initialized (exit code 3), the hook exits
|
|
// successfully with a warning so that git operations are not blocked.
|
|
func generateHookSection(hookName string) string {
|
|
return hookSectionBeginLine() + "\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_timeout=${BEADS_HOOK_TIMEOUT:-" + fmt.Sprintf("%d", hookTimeoutSeconds) + "}\n" +
|
|
" case \"$_bd_timeout\" in\n" +
|
|
" *[!0-9]*|'') _bd_timeout_invalid=1 ;;\n" +
|
|
" *[1-9]*) _bd_timeout_invalid=0 ;;\n" +
|
|
" *) _bd_timeout_invalid=1 ;;\n" +
|
|
" esac\n" +
|
|
" if [ \"$_bd_timeout_invalid\" -eq 1 ]; then\n" +
|
|
" echo >&2 \"beads: invalid BEADS_HOOK_TIMEOUT; using " + fmt.Sprintf("%d", hookTimeoutSeconds) + " seconds\"\n" +
|
|
" _bd_timeout=" + fmt.Sprintf("%d", hookTimeoutSeconds) + "\n" +
|
|
" fi\n" +
|
|
" _bd_timeout_backend=none\n" +
|
|
" _bd_timeout_command=\n" +
|
|
" for _bd_timeout_candidate in timeout gtimeout; do\n" +
|
|
" if command -v \"$_bd_timeout_candidate\" >/dev/null 2>&1; then\n" +
|
|
" if _bd_timeout_version=\"$(\"$_bd_timeout_candidate\" --version 2>/dev/null)\"; then\n" +
|
|
" case \"$_bd_timeout_version\" in\n" +
|
|
" \"timeout (GNU coreutils) \"*|\"timeout (uutils coreutils) \"*) _bd_timeout_command=$_bd_timeout_candidate; break ;;\n" +
|
|
" esac\n" +
|
|
" fi\n" +
|
|
" fi\n" +
|
|
" done\n" +
|
|
" if [ -n \"$_bd_timeout_command\" ]; then\n" +
|
|
" _bd_timeout_backend=coreutils\n" +
|
|
" if \"$_bd_timeout_command\" -- \"$_bd_timeout\" bd hooks run " + hookName + " \"$@\"; then\n" +
|
|
" _bd_exit=0\n" +
|
|
" else\n" +
|
|
" _bd_exit=$?\n" +
|
|
" fi\n" +
|
|
" elif command -v perl >/dev/null 2>&1; then\n" +
|
|
" _bd_timeout_backend=perl\n" +
|
|
" if perl -e 'alarm shift; exec @ARGV' -- \"$_bd_timeout\" bd hooks run " + hookName + " \"$@\"; then\n" +
|
|
" _bd_exit=0\n" +
|
|
" else\n" +
|
|
" _bd_exit=$?\n" +
|
|
" fi\n" +
|
|
" else\n" +
|
|
" echo >&2 \"beads: hook '" + hookName + "' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT\"\n" +
|
|
" if bd hooks run " + hookName + " \"$@\"; then\n" +
|
|
" _bd_exit=0\n" +
|
|
" else\n" +
|
|
" _bd_exit=$?\n" +
|
|
" fi\n" +
|
|
" fi\n" +
|
|
" if { [ \"$_bd_timeout_backend\" = coreutils ] && [ \"$_bd_exit\" -eq 124 ]; } || { [ \"$_bd_timeout_backend\" = perl ] && [ \"$_bd_exit\" -eq 142 ]; }; then\n" +
|
|
" echo >&2 \"beads: hook '" + hookName + "' timed out after ${_bd_timeout}s — continuing without beads\"\n" +
|
|
" _bd_exit=0\n" +
|
|
" fi\n" +
|
|
" if [ \"$_bd_exit\" -eq 3 ]; then\n" +
|
|
" echo >&2 \"beads: database not initialized — skipping hook '" + hookName + "'\"\n" +
|
|
" _bd_exit=0\n" +
|
|
" fi\n" +
|
|
" if [ \"$_bd_exit\" -ne 0 ]; then exit \"$_bd_exit\"; fi\n" +
|
|
"fi\n" +
|
|
hookSectionEndLine() + "\n"
|
|
}
|
|
|
|
// injectHookSection merges the beads section into existing hook file content.
|
|
// If section markers are found, only the content between them is replaced.
|
|
// If broken markers exist (orphaned BEGIN, reversed order), the stale markers
|
|
// are removed before injecting the new section.
|
|
// If no markers are found, the section is appended.
|
|
func injectHookSection(existing, section string) string {
|
|
return injectHookSectionWithDepth(existing, section, 0)
|
|
}
|
|
|
|
// maxInjectDepth guards against infinite recursion when cleaning broken markers.
|
|
const maxInjectDepth = 5
|
|
|
|
func injectHookSectionWithDepth(existing, section string, depth int) string {
|
|
if depth > maxInjectDepth {
|
|
// Safety: too many recursive cleanups — append as fallback
|
|
result := existing
|
|
if !strings.HasSuffix(result, "\n") {
|
|
result += "\n"
|
|
}
|
|
return result + "\n" + section
|
|
}
|
|
|
|
beginIdx := strings.Index(existing, hookSectionBeginPrefix)
|
|
endIdx := strings.Index(existing, hookSectionEndPrefix)
|
|
|
|
if beginIdx != -1 && endIdx != -1 && beginIdx < endIdx {
|
|
// Case 1: valid BEGIN...END pair — replace between markers
|
|
lineStart := strings.LastIndex(existing[:beginIdx], "\n")
|
|
if lineStart == -1 {
|
|
lineStart = 0
|
|
} else {
|
|
lineStart++ // skip the newline itself
|
|
}
|
|
|
|
// Find end of the end-marker line (including trailing newline)
|
|
endOfEndMarker := endIdx + len(hookSectionEndPrefix)
|
|
// Consume the rest of the end-marker line (e.g. " v0.58.0 ---\n")
|
|
restAfterPrefix := existing[endOfEndMarker:]
|
|
if nlIdx := strings.Index(restAfterPrefix, "\n"); nlIdx != -1 {
|
|
endOfEndMarker += nlIdx + 1
|
|
} else {
|
|
endOfEndMarker = len(existing)
|
|
}
|
|
|
|
return existing[:lineStart] + section + existing[endOfEndMarker:]
|
|
} else if beginIdx != -1 {
|
|
// Case 2: broken markers — orphaned BEGIN (no END) or reversed (END before BEGIN).
|
|
// Remove the orphaned/stale block, then recurse to handle remaining markers.
|
|
cleaned := removeOrphanedBeginBlock(existing, beginIdx)
|
|
return injectHookSectionWithDepth(cleaned, section, depth+1)
|
|
} else if endIdx != -1 {
|
|
// Case 2b: orphaned END without BEGIN — remove the stale END line
|
|
cleaned := removeMarkerLine(existing, endIdx, hookSectionEndPrefix)
|
|
return injectHookSectionWithDepth(cleaned, section, depth+1)
|
|
}
|
|
|
|
// Case 3: no markers. If the existing hook ends in an exec-replacing
|
|
// block (e.g. the templated hook produced by `pre-commit init-templatedir`,
|
|
// which ends with `exec "$INSTALL_PYTHON" -mpre_commit ...`), appending
|
|
// at the bottom would make the bd section unreachable. Detect that
|
|
// pattern and inject above the exec block instead. (GH#3537)
|
|
if injectAt := findExecBlockInjectionPoint(existing); injectAt >= 0 {
|
|
return existing[:injectAt] + section + "\n" + existing[injectAt:]
|
|
}
|
|
|
|
// Case 3 fallback: no markers, no trailing exec — append at end.
|
|
result := existing
|
|
if !strings.HasSuffix(result, "\n") {
|
|
result += "\n"
|
|
}
|
|
result += "\n" + section
|
|
return result
|
|
}
|
|
|
|
// findExecBlockInjectionPoint inspects the tail of a hook file. If it ends in
|
|
// an exec-replacing chain (a final `exec <cmd>` reachable from the bottom of
|
|
// the file, possibly inside an `if`/`elif`/`else`/`fi` ladder whose other
|
|
// branches only `echo`/`exit`), returns the byte offset where the bd section
|
|
// should be injected — i.e. just above the start of the enclosing control
|
|
// structure (or above the bare `exec` line if there is none). Returns -1 when
|
|
// the file does not end in such a pattern; callers should fall back to
|
|
// appending at the bottom.
|
|
//
|
|
// Motivation: appending below a terminating `exec` makes the appended content
|
|
// unreachable, because `exec` replaces the running shell process. (GH#3537)
|
|
//
|
|
// Limitations (the function uses line-based heuristics, not a shell parser):
|
|
// - A heredoc body containing a literal line that starts with `exec` is
|
|
// treated as code, not data. In practice this is harmless because the
|
|
// terminator line (e.g. `EOF`) is then classified as non-filler and the
|
|
// scan returns -1, but a contrived terminator name could fool it.
|
|
// - A trailing comment on an `exec` line (e.g. `exec /bin/foo # disabled`)
|
|
// is treated as a live `exec` statement. Use a separate comment line if
|
|
// intent is to disable it.
|
|
// - Two disjoint `if/exec` blocks separated by real code: the scan only
|
|
// considers the LAST one; the real code in the middle correctly causes
|
|
// the scan to return -1 and the caller falls back to append.
|
|
func findExecBlockInjectionPoint(content string) int {
|
|
// Trim a trailing newline so strings.Split doesn't produce an empty
|
|
// sentinel as the last element. The scan then sees lines exactly as
|
|
// they appear in the file with no off-by-one ambiguity.
|
|
lines := strings.Split(strings.TrimRight(content, "\n"), "\n")
|
|
|
|
// 1. Find the last line that is an effective `exec ...` statement.
|
|
// Skip blank lines, comments, and the standard tail patterns
|
|
// (`fi`, `else`, `elif`, `exit N`, `echo ...`) when scanning back.
|
|
lastExecLine := -1
|
|
for i := len(lines) - 1; i >= 0; i-- {
|
|
trimmed := strings.TrimSpace(lines[i])
|
|
if isExecLine(trimmed) {
|
|
lastExecLine = i
|
|
break
|
|
}
|
|
if !isAllowedAfterExec(trimmed) {
|
|
// Found non-trivial code at the tail that isn't part of an
|
|
// exec-terminated chain — not a pattern we should rewrite.
|
|
return -1
|
|
}
|
|
}
|
|
if lastExecLine == -1 {
|
|
return -1
|
|
}
|
|
|
|
// 2. Walk backward from lastExecLine to find the start of the enclosing
|
|
// control structure (an `if ...` at column 0, possibly preceded by
|
|
// elif/else/then continuations of the same block). If we don't find
|
|
// one, treat the exec line itself as the injection target.
|
|
blockStartLine := lastExecLine
|
|
for i := lastExecLine - 1; i >= 0; i-- {
|
|
line := lines[i]
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
|
continue
|
|
}
|
|
// Skip continuations of the if-block we're inside: elif/else/then,
|
|
// and any indented body line (they belong to the surrounding block).
|
|
if strings.HasPrefix(trimmed, "elif ") || trimmed == "else" ||
|
|
strings.HasPrefix(trimmed, "else ") || trimmed == "then" {
|
|
continue
|
|
}
|
|
if line != trimmed { // indented body of an enclosing block
|
|
continue
|
|
}
|
|
// Column-0 line that isn't a continuation. If it opens an if-block,
|
|
// that's the start of our construct.
|
|
if strings.HasPrefix(trimmed, "if ") {
|
|
blockStartLine = i
|
|
}
|
|
break
|
|
}
|
|
|
|
// 3. Convert blockStartLine -> byte offset.
|
|
offset := 0
|
|
for i := 0; i < blockStartLine; i++ {
|
|
offset += len(lines[i]) + 1 // +1 for the '\n' that strings.Split removed
|
|
}
|
|
return offset
|
|
}
|
|
|
|
// isExecLine reports whether trimmed is an effective `exec <cmd>` statement.
|
|
func isExecLine(trimmed string) bool {
|
|
return trimmed == "exec" || strings.HasPrefix(trimmed, "exec ") ||
|
|
strings.HasPrefix(trimmed, "exec\t")
|
|
}
|
|
|
|
// isAllowedAfterExec reports whether a trailing line in an exec-terminated
|
|
// chain is harmless filler — control-flow closers, alternative branches,
|
|
// fallback exits, comments, and blanks. Anything else means the file does
|
|
// not strictly terminate via exec, so we should not rewrite it.
|
|
func isAllowedAfterExec(trimmed string) bool {
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
|
return true
|
|
}
|
|
switch trimmed {
|
|
case "fi", "else", "done", "esac", "}", ";;":
|
|
return true
|
|
}
|
|
if strings.HasPrefix(trimmed, "elif ") || strings.HasPrefix(trimmed, "else ") {
|
|
return true
|
|
}
|
|
if strings.HasPrefix(trimmed, "exit") {
|
|
return true
|
|
}
|
|
if strings.HasPrefix(trimmed, "echo ") || strings.HasPrefix(trimmed, "echo\t") {
|
|
// pre-commit's else branch prints a hint before exit 1.
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// removeOrphanedBeginBlock removes an orphaned BEGIN block starting at beginIdx.
|
|
// Scans forward from the BEGIN line to the next blank line, next BEGIN marker, or EOF.
|
|
func removeOrphanedBeginBlock(content string, beginIdx int) string {
|
|
lineStart := strings.LastIndex(content[:beginIdx], "\n")
|
|
if lineStart == -1 {
|
|
lineStart = 0
|
|
} else {
|
|
lineStart++ // skip the newline itself
|
|
}
|
|
|
|
afterBegin := content[beginIdx:]
|
|
blockEnd := len(content)
|
|
|
|
lines := strings.SplitAfter(afterBegin, "\n")
|
|
scanned := beginIdx
|
|
for i, line := range lines {
|
|
if i == 0 {
|
|
// Skip the BEGIN line itself
|
|
scanned += len(line)
|
|
continue
|
|
}
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" {
|
|
// Blank line — end of orphaned block (include the blank line)
|
|
blockEnd = scanned + len(line)
|
|
break
|
|
}
|
|
if strings.Contains(line, hookSectionBeginPrefix) {
|
|
// Next BEGIN marker — end before this line
|
|
blockEnd = scanned
|
|
break
|
|
}
|
|
scanned += len(line)
|
|
}
|
|
|
|
return content[:lineStart] + content[blockEnd:]
|
|
}
|
|
|
|
// removeMarkerLine removes a single marker line from content.
|
|
func removeMarkerLine(content string, markerIdx int, markerPrefix string) string {
|
|
lineStart := strings.LastIndex(content[:markerIdx], "\n")
|
|
if lineStart == -1 {
|
|
lineStart = 0
|
|
} else {
|
|
lineStart++ // skip the newline itself
|
|
}
|
|
|
|
lineEnd := markerIdx + len(markerPrefix)
|
|
restAfterPrefix := content[lineEnd:]
|
|
if nlIdx := strings.Index(restAfterPrefix, "\n"); nlIdx != -1 {
|
|
lineEnd += nlIdx + 1
|
|
} else {
|
|
lineEnd = len(content)
|
|
}
|
|
|
|
return content[:lineStart] + content[lineEnd:]
|
|
}
|
|
|
|
// removeHookSection removes only the beads section from hook file content.
|
|
// Returns the content with the section removed, and true if a section was found.
|
|
// Handles valid BEGIN...END pairs, orphaned BEGIN, orphaned END, and reversed markers.
|
|
func removeHookSection(content string) (string, bool) {
|
|
beginIdx := strings.Index(content, hookSectionBeginPrefix)
|
|
endIdx := strings.Index(content, hookSectionEndPrefix)
|
|
|
|
if beginIdx == -1 && endIdx == -1 {
|
|
return content, false
|
|
}
|
|
|
|
if beginIdx != -1 && endIdx != -1 && beginIdx < endIdx {
|
|
// Valid BEGIN...END pair — remove the whole section
|
|
lineStart := strings.LastIndex(content[:beginIdx], "\n")
|
|
if lineStart == -1 {
|
|
lineStart = 0
|
|
} else {
|
|
lineStart++
|
|
}
|
|
|
|
endOfSection := endIdx + len(hookSectionEndPrefix)
|
|
restAfterPrefix := content[endOfSection:]
|
|
if nlIdx := strings.Index(restAfterPrefix, "\n"); nlIdx != -1 {
|
|
endOfSection += nlIdx + 1
|
|
} else {
|
|
endOfSection = len(content)
|
|
}
|
|
|
|
// Also consume a blank line before the section if present
|
|
if lineStart >= 2 && content[lineStart-1] == '\n' && content[lineStart-2] == '\n' {
|
|
lineStart--
|
|
}
|
|
|
|
return content[:lineStart] + content[endOfSection:], true
|
|
}
|
|
|
|
// Broken markers: orphaned BEGIN, orphaned END, or reversed order.
|
|
// Remove whichever markers exist.
|
|
result := content
|
|
if beginIdx != -1 {
|
|
result = removeOrphanedBeginBlock(result, strings.Index(result, hookSectionBeginPrefix))
|
|
}
|
|
if endIdx != -1 {
|
|
// Re-find END index in the (possibly modified) result
|
|
if newEndIdx := strings.Index(result, hookSectionEndPrefix); newEndIdx != -1 {
|
|
result = removeMarkerLine(result, newEndIdx, hookSectionEndPrefix)
|
|
}
|
|
}
|
|
|
|
// Trim trailing blank lines that may be left from removal
|
|
for strings.HasSuffix(result, "\n\n\n") {
|
|
result = result[:len(result)-1]
|
|
}
|
|
|
|
return result, true
|
|
}
|
|
|
|
// isOnlyShebangOrEmpty reports whether the given hook content consists of
|
|
// nothing meaningful — only an optional shebang line plus blank lines and
|
|
// comments. Used by shouldPreserveHookContent to decide, after stripping a
|
|
// BEADS INTEGRATION block, whether anything user-owned remains worth
|
|
// preserving.
|
|
//
|
|
// Note: non-shebang comment lines (e.g. `# preamble`) are intentionally
|
|
// treated as non-content. A file that's only a shebang plus a comment is
|
|
// classified empty and skipped — comments alone aren't user logic worth
|
|
// carrying forward to .beads/hooks/<name>. (GH#3536)
|
|
func isOnlyShebangOrEmpty(content string) bool {
|
|
for _, line := range strings.Split(content, "\n") {
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#!") || strings.HasPrefix(trimmed, "#") {
|
|
continue
|
|
}
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// shouldPreserveHookContent decides what preservePreexistingHooks should do
|
|
// with one hook file's content. Returns (transformedContent, true) when the
|
|
// file should be preserved into the target directory (possibly with the bd
|
|
// section stripped or the husky helper-layout sanitized); returns
|
|
// ("", false) when preservation should skip this file because it's wholly
|
|
// bd-managed and contains nothing user-owned worth keeping.
|
|
//
|
|
// Decision rules (GH#3536):
|
|
// - inlineHookMarker (the "# bd (beads)" tag from GH#1120) marks files
|
|
// that were always wholly bd-owned one-liners — skip.
|
|
// - hookSectionBeginPrefix marks files that were *user-owned* with bd's
|
|
// block injected into them (the v0.49+ section-marker model). Strip
|
|
// the bd block and preserve the remaining user content. If only a
|
|
// shebang/blank/comments remain, treat as wholly bd-owned and skip.
|
|
// - When fromHusky is true, sanitize the (possibly stripped) content so
|
|
// it doesn't depend on husky's helper-layout being mirrored into the
|
|
// target directory (GH#3132).
|
|
//
|
|
// The function is pure: no I/O, no global state.
|
|
func shouldPreserveHookContent(content string, fromHusky bool) (string, bool) {
|
|
if strings.Contains(content, inlineHookMarker) {
|
|
return "", false
|
|
}
|
|
if strings.Contains(content, hookSectionBeginPrefix) {
|
|
stripped, _ := removeHookSection(content)
|
|
if isOnlyShebangOrEmpty(stripped) {
|
|
return "", false
|
|
}
|
|
// Normalize CRLF → LF on the preserved-and-stripped content so
|
|
// Windows / autocrlf=true repos don't end up with `\r\n` line
|
|
// endings in .beads/hooks/<name>. Mirrors the normalization that
|
|
// injectHookSection does on its output (`hooks.go` ~line 622).
|
|
content = strings.ReplaceAll(stripped, "\r\n", "\n")
|
|
}
|
|
if fromHusky {
|
|
content = sanitizeHuskyHook(content)
|
|
}
|
|
return content, true
|
|
}
|
|
|
|
// HookStatus represents the status of a single git hook
|
|
type HookStatus struct {
|
|
Name string
|
|
Installed bool
|
|
Version string
|
|
IsShim bool // true if this is a thin shim (version-agnostic)
|
|
Outdated bool
|
|
}
|
|
|
|
// CheckGitHooks checks the status of bd git hooks in .git/hooks/
|
|
func CheckGitHooks() []HookStatus {
|
|
hooksDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
// Not a git repo - return all hooks as not installed
|
|
statuses := make([]HookStatus, 0, len(managedHookNames))
|
|
for _, hookName := range managedHookNames {
|
|
statuses = append(statuses, HookStatus{Name: hookName, Installed: false})
|
|
}
|
|
return statuses
|
|
}
|
|
return checkGitHooksAt(hooksDir)
|
|
}
|
|
|
|
func checkGitHooksAt(hooksDir string) []HookStatus {
|
|
statuses := make([]HookStatus, 0, len(managedHookNames))
|
|
for _, hookName := range managedHookNames {
|
|
status := HookStatus{
|
|
Name: hookName,
|
|
}
|
|
|
|
// Check if hook exists
|
|
hookPath := filepath.Join(hooksDir, hookName)
|
|
versionInfo, err := getHookVersion(hookPath)
|
|
if err != nil {
|
|
// Hook doesn't exist or couldn't be read
|
|
status.Installed = false
|
|
} else {
|
|
status.Installed = true
|
|
status.Version = versionInfo.Version
|
|
status.IsShim = versionInfo.IsShim
|
|
|
|
// Thin shims are never outdated (they delegate to bd)
|
|
// bd hooks are outdated if version is missing (legacy inline) or differs
|
|
if !versionInfo.IsShim && versionInfo.IsBdHook && versionInfo.Version != Version {
|
|
status.Outdated = true
|
|
}
|
|
}
|
|
|
|
statuses = append(statuses, status)
|
|
}
|
|
|
|
return statuses
|
|
}
|
|
|
|
// hookVersionInfo contains version information extracted from a hook file
|
|
type hookVersionInfo struct {
|
|
Version string // bd version (for legacy hooks) or shim version
|
|
IsShim bool // true if this is a thin shim
|
|
IsBdHook bool // true if this is any type of bd hook (shim or inline)
|
|
}
|
|
|
|
// getHookVersion extracts the version from a hook file
|
|
func getHookVersion(path string) (hookVersionInfo, error) {
|
|
// #nosec G304 -- hook path constrained to .git/hooks directory
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return hookVersionInfo{}, err
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
// Read the entire file to support section markers anywhere (GH#1380)
|
|
var content strings.Builder
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
content.WriteString(line)
|
|
content.WriteString("\n")
|
|
// Check for section marker (GH#1380) — can appear anywhere in the file
|
|
if strings.HasPrefix(line, hookSectionBeginPrefix) {
|
|
// Extract version from "# --- BEGIN BEADS INTEGRATION v0.56.1 ---"
|
|
after := strings.TrimPrefix(line, hookSectionBeginPrefix)
|
|
after = strings.TrimSpace(after)
|
|
after = strings.TrimPrefix(after, "v")
|
|
after = strings.TrimSuffix(after, "---")
|
|
version := strings.TrimSpace(after)
|
|
return hookVersionInfo{Version: version, IsShim: true, IsBdHook: true}, nil
|
|
}
|
|
// Check for thin shim marker first
|
|
if strings.HasPrefix(line, shimVersionPrefix) {
|
|
version := strings.TrimSpace(strings.TrimPrefix(line, shimVersionPrefix))
|
|
return hookVersionInfo{Version: version, IsShim: true, IsBdHook: true}, nil
|
|
}
|
|
// Check for legacy version marker
|
|
if strings.HasPrefix(line, hookVersionPrefix) {
|
|
version := strings.TrimSpace(strings.TrimPrefix(line, hookVersionPrefix))
|
|
return hookVersionInfo{Version: version, IsShim: false, IsBdHook: true}, nil
|
|
}
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
return hookVersionInfo{}, fmt.Errorf("reading hook file: %w", err)
|
|
}
|
|
|
|
// Check if it's an inline bd hook (from bd init) - GH#1120
|
|
// These don't have version markers but have "# bd (beads)" comment
|
|
if strings.Contains(content.String(), inlineHookMarker) {
|
|
return hookVersionInfo{IsBdHook: true}, nil
|
|
}
|
|
|
|
// No version found and not a bd hook
|
|
return hookVersionInfo{}, nil
|
|
}
|
|
|
|
// FormatHookWarnings returns a formatted warning message if hooks are outdated
|
|
func FormatHookWarnings(statuses []HookStatus) string {
|
|
var warnings []string
|
|
|
|
missingCount := 0
|
|
outdatedCount := 0
|
|
|
|
for _, status := range statuses {
|
|
if !status.Installed {
|
|
missingCount++
|
|
} else if status.Outdated {
|
|
outdatedCount++
|
|
}
|
|
}
|
|
|
|
if missingCount > 0 {
|
|
warnings = append(warnings, fmt.Sprintf("⚠️ Git hooks not installed (%d missing)", missingCount))
|
|
warnings = append(warnings, " Run: bd hooks install")
|
|
}
|
|
|
|
if outdatedCount > 0 {
|
|
warnings = append(warnings, fmt.Sprintf("⚠️ Git hooks are outdated (%d hooks)", outdatedCount))
|
|
warnings = append(warnings, " Run: bd hooks install")
|
|
}
|
|
|
|
if len(warnings) > 0 {
|
|
return strings.Join(warnings, "\n")
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
// Cobra commands
|
|
|
|
var hooksCmd = &cobra.Command{
|
|
Use: "hooks",
|
|
GroupID: "setup",
|
|
Short: "Manage git hooks for beads integration",
|
|
Long: `Install, uninstall, or list git hooks for beads integration.
|
|
|
|
The hooks provide:
|
|
- pre-commit: Run chained hooks before commit
|
|
- post-merge: Run chained hooks after pull/merge
|
|
- pre-push: Run chained hooks before push
|
|
- post-checkout: Run chained hooks after branch checkout
|
|
- prepare-commit-msg: Add agent identity trailers for forensics`,
|
|
}
|
|
|
|
var hooksInstallCmd = &cobra.Command{
|
|
Use: "install",
|
|
Short: "Install bd git hooks",
|
|
Long: `Install git hooks for beads integration.
|
|
|
|
By default, hooks are installed to .git/hooks/ in the current repository.
|
|
Use --beads to install to .beads/hooks/ (recommended for Dolt backend).
|
|
Use --shared to install to a versioned directory (.beads-hooks/) that can be
|
|
committed to git and shared with team members.
|
|
|
|
Hooks use section markers to coexist with existing hooks — any user content
|
|
outside the markers is preserved across installs and upgrades.
|
|
|
|
Installed hooks:
|
|
- pre-commit: Run chained hooks before commit
|
|
- post-merge: Run chained hooks after pull/merge
|
|
- pre-push: Run chained hooks before push
|
|
- post-checkout: Run chained hooks after branch checkout
|
|
- prepare-commit-msg: Add agent identity trailers (for orchestrator agents)`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("hooks-install")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
force, _ := cmd.Flags().GetBool("force")
|
|
shared, _ := cmd.Flags().GetBool("shared")
|
|
chain, _ := cmd.Flags().GetBool("chain")
|
|
beadsHooks, _ := cmd.Flags().GetBool("beads")
|
|
|
|
if err := installStandaloneHooks(managedHookNames, force, shared, chain, beadsHooks); err != nil {
|
|
return HandleErrorRespectJSON("installing hooks: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
output := map[string]interface{}{
|
|
"success": true,
|
|
"message": "Git hooks installed successfully",
|
|
"shared": shared,
|
|
"chained": chain,
|
|
"beadsHooks": beadsHooks,
|
|
}
|
|
jsonBytes, _ := json.MarshalIndent(output, "", " ")
|
|
fmt.Println(string(jsonBytes))
|
|
} else {
|
|
fmt.Println("✓ Git hooks installed successfully")
|
|
fmt.Println()
|
|
if beadsHooks {
|
|
fmt.Println("Hooks installed to: .beads/hooks/")
|
|
fmt.Println("Git config set: core.hooksPath=.beads/hooks")
|
|
fmt.Println()
|
|
} else if shared {
|
|
fmt.Println("Hooks installed to: .beads-hooks/")
|
|
fmt.Println("Git config set: core.hooksPath=.beads-hooks")
|
|
fmt.Println()
|
|
fmt.Println("⚠️ Remember to commit .beads-hooks/ to share with your team!")
|
|
fmt.Println()
|
|
}
|
|
fmt.Println("Installed hooks:")
|
|
for _, hookName := range managedHookNames {
|
|
fmt.Printf(" - %s\n", hookName)
|
|
}
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var hooksUninstallCmd = &cobra.Command{
|
|
Use: "uninstall",
|
|
Short: "Uninstall bd git hooks",
|
|
Long: `Remove bd git hooks from .git/hooks/ directory.`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("hooks-uninstall")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if err := uninstallStandaloneHooks(); err != nil {
|
|
return HandleErrorRespectJSON("uninstalling hooks: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
output := map[string]interface{}{
|
|
"success": true,
|
|
"message": "Git hooks uninstalled successfully",
|
|
}
|
|
jsonBytes, _ := json.MarshalIndent(output, "", " ")
|
|
fmt.Println(string(jsonBytes))
|
|
} else {
|
|
fmt.Println("✓ Git hooks uninstalled successfully")
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var hooksListCmd = &cobra.Command{
|
|
Use: "list",
|
|
Short: "List installed git hooks status",
|
|
Long: `Show the status of bd git hooks (installed, outdated, missing).`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("hooks-list")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
statuses := CheckGitHooks()
|
|
|
|
if jsonOutput {
|
|
output := map[string]interface{}{
|
|
"hooks": statuses,
|
|
}
|
|
jsonBytes, _ := json.MarshalIndent(output, "", " ")
|
|
fmt.Println(string(jsonBytes))
|
|
} else {
|
|
fmt.Println("Git hooks status:")
|
|
for _, status := range statuses {
|
|
if !status.Installed {
|
|
fmt.Printf(" ✗ %s: not installed\n", status.Name)
|
|
} else if status.IsShim {
|
|
fmt.Printf(" ✓ %s: installed (shim %s)\n", status.Name, status.Version)
|
|
} else if status.Outdated {
|
|
fmt.Printf(" ⚠ %s: installed (version %s, current: %s) - outdated\n",
|
|
status.Name, status.Version, Version)
|
|
} else {
|
|
fmt.Printf(" ✓ %s: installed (version %s)\n", status.Name, status.Version)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// guardHookWritePath refuses hook writes that would silently modify files
|
|
// bd does not own (bd-5vdt8):
|
|
// - a symlinked hook path: os.WriteFile follows the link (O_TRUNC) and
|
|
// rewrites the target inode — e.g. a repo-tracked script the hook
|
|
// points at, dirtying every clone that shares it
|
|
// - a hook file tracked by git: writing it dirties the working tree.
|
|
// allowTracked exempts shared installs (.beads-hooks/ is deliberately
|
|
// committed).
|
|
func guardHookWritePath(hookPath string, allowTracked bool) error {
|
|
return guardHookWritePathWithProbe(hookPath, allowTracked, gitTrackedFileContext)
|
|
}
|
|
|
|
func guardHookWritePathWithProbe(hookPath string, allowTracked bool, tracked func(string) string) error {
|
|
fi, err := os.Lstat(hookPath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil // creating a new file — nothing to clobber
|
|
}
|
|
return fmt.Errorf("failed to stat %s: %w", hookPath, err)
|
|
}
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
target := "unresolvable target"
|
|
if resolved, rerr := filepath.EvalSymlinks(hookPath); rerr == nil {
|
|
target = resolved
|
|
} else if link, lerr := os.Readlink(hookPath); lerr == nil {
|
|
target = link
|
|
}
|
|
return fmt.Errorf("%s is a symlink to %s; writing would rewrite the link target, not the hook\nRemove the symlink (or leave that hook to its owner) and re-run", hookPath, target)
|
|
}
|
|
if allowTracked {
|
|
return nil
|
|
}
|
|
// A tracked file is refused only when bd does NOT own it: writing into a
|
|
// foreign tracked file dirties every clone that shares it (the wy-81fnur
|
|
// incident). A bd-owned hook the user chose to commit (e.g. a team-shared
|
|
// .beads/hooks/) is bd's to maintain — same policy as shared installs.
|
|
if proof := tracked(hookPath); proof != "" && !isBdOwnedHookFile(hookPath) {
|
|
// `git rm --cached` only aims at the index that supplied the proof if the
|
|
// operator's shell still carries the same routing bd saw, so the inherited
|
|
// case names clearing that routing as the remedy instead. Both remediations
|
|
// are fixed strings; neither exposes an inherited value.
|
|
remediation := "Untrack it (git rm --cached) or move hooks to an untracked directory and re-run"
|
|
if proof == trackedProofInheritedIndex {
|
|
remediation = "Clear the inherited Git routing environment and re-run, or untrack it (git rm --cached) in the index that routing selects"
|
|
}
|
|
return fmt.Errorf("%s is tracked by git (%s) and not a bd-managed hook; bd will not modify committed files it does not own\n%s", hookPath, proof, remediation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// isBdOwnedHookFile reports whether the hook file at path is bd-managed:
|
|
// either section-marker format or a legacy bd hook (shim or inline).
|
|
func isBdOwnedHookFile(path string) bool {
|
|
content, err := os.ReadFile(path) // #nosec G304 -- path is a hook location bd resolved
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if strings.Contains(string(content), hookSectionBeginPrefix) {
|
|
return true
|
|
}
|
|
versionInfo, err := getHookVersion(path)
|
|
return err == nil && versionInfo.IsBdHook
|
|
}
|
|
|
|
// Fixed labels naming which index supplied a tracked-file proof. They are
|
|
// constants so the refusal can branch on the evidence source without
|
|
// reproducing the wording.
|
|
const (
|
|
trackedProofContainingIndex = "containing repository index"
|
|
trackedProofInheritedIndex = "inherited Git index"
|
|
)
|
|
|
|
// isGitTrackedFile reports whether either the containing repository or the
|
|
// inherited Git context tracks path. If neither probe succeeds, errors count
|
|
// as untracked — the guard only blocks writes it can prove are unsafe.
|
|
//
|
|
// This and isGitTrackedFileWithEnv are test-only conveniences. Production
|
|
// callers should use the Context variants, whose label feeds the refusal
|
|
// diagnostic; the boolean form discards it.
|
|
func isGitTrackedFile(path string) bool {
|
|
return gitTrackedFileContext(path) != ""
|
|
}
|
|
|
|
func gitTrackedFileContext(path string) string {
|
|
inherited := os.Environ()
|
|
return gitTrackedFileContextWithEnv(path, gitenv.ScrubRouting(inherited), inherited)
|
|
}
|
|
|
|
func isGitTrackedFileWithEnv(path string, clean, inherited []string) bool {
|
|
return gitTrackedFileContextWithEnv(path, clean, inherited) != ""
|
|
}
|
|
|
|
// gitTrackedFileContextWithEnv returns a fixed label for the first successful
|
|
// proof. It never includes inherited environment values or Git output.
|
|
func gitTrackedFileContextWithEnv(path string, clean, inherited []string) string {
|
|
dir := filepath.Dir(path)
|
|
base := filepath.Base(path)
|
|
// Check the containing repository first so inherited routing cannot hide a
|
|
// tracked hook. The fallback preserves bare work trees and trusted config,
|
|
// and whichever index answers first is sufficient to refuse the write, even
|
|
// if the other view does not track the path. The fallback is reached only
|
|
// when the clean probe failed for a configuration reason (no reachable
|
|
// repository): exit 1 is git's "repository reached, path is not tracked"
|
|
// answer and is final, so a repository that reports the path untracked ends
|
|
// the search instead of spawning a second `git ls-files` on every ordinary
|
|
// miss.
|
|
for index, env := range [][]string{clean, inherited} {
|
|
// #nosec G204 G702 - fixed "git" command; dir/base come from the hooks
|
|
// directory bd itself resolved, not user input
|
|
cmd := exec.Command("git", "-C", dir, "ls-files", "--error-unmatch", "--", base)
|
|
cmd.Env = env
|
|
err := cmd.Run()
|
|
if err == nil {
|
|
if index == 0 {
|
|
return trackedProofContainingIndex
|
|
}
|
|
return trackedProofInheritedIndex
|
|
}
|
|
if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 1 {
|
|
return ""
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func installHooksWithOptions(hookNames []string, force bool, shared bool, chain bool, beadsHooks bool) error {
|
|
return installHooksWithContext(hookNames, force, shared, chain, beadsHooks, nil)
|
|
}
|
|
|
|
func resolveStandaloneHooksContext() (*initHooksContext, error) {
|
|
workDir, err := os.Getwd()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inherited := os.Environ()
|
|
clean := gitenv.ScrubRouting(inherited)
|
|
paths, err := git.ResolveHooksContext(workDir, inherited)
|
|
if err != nil {
|
|
// Preserve legacy absolute-path file operations without borrowing cached
|
|
// repository authority for configuration or managed-directory installs.
|
|
dir, pathErr := git.GetGitHooksDirFrom(workDir, inherited)
|
|
if pathErr != nil || !filepath.IsAbs(dir) {
|
|
return nil, err
|
|
}
|
|
return &initHooksContext{workDir: workDir, paths: git.HooksContext{HooksDir: dir}, env: clean, inheritedEnv: inherited}, nil
|
|
}
|
|
cmd := exec.Command("git", "rev-parse", "--absolute-git-dir")
|
|
cmd.Dir, cmd.Env = workDir, inherited
|
|
gitDir, err := cmd.Output()
|
|
if err != nil {
|
|
// Attach git's own diagnostic, as loadGitContext does for the same
|
|
// class of failure; the bare status alone is not actionable.
|
|
captureErr := fmt.Errorf("capture selected Git directory: %w", err)
|
|
if exit, ok := err.(*exec.ExitError); ok && len(exit.Stderr) > 0 {
|
|
captureErr = fmt.Errorf("%w: %s", captureErr, strings.TrimSpace(string(exit.Stderr)))
|
|
}
|
|
return nil, captureErr
|
|
}
|
|
// Keep the private admin directory for effective worktree config reads.
|
|
// The unpinned clean environment remains the containing-index proof.
|
|
pinned := append(append([]string(nil), clean...), "GIT_DIR="+strings.TrimSpace(string(gitDir)),
|
|
"GIT_COMMON_DIR="+paths.CommonDir, "GIT_WORK_TREE="+paths.RepoRoot)
|
|
effective := paths.HooksDir
|
|
paths, err = git.ResolveHooksContext(workDir, pinned)
|
|
if err != nil {
|
|
return nil, err // Never recover a selected read through inherited routing.
|
|
}
|
|
// These commands act on the selected, config-scrubbed path, while every
|
|
// status and execution reader (bd hooks list, bd doctor, runChainedHook)
|
|
// still resolves hooks through the inherited context. When inherited config
|
|
// moves the effective directory the two disagree, so name both paths rather
|
|
// than reporting a bare success the next status call will contradict.
|
|
if !utils.PathsEqual(effective, paths.HooksDir) {
|
|
fmt.Fprintf(os.Stderr, "Warning: inherited Git config makes %s the effective hooks directory; "+
|
|
"operating on the selected repository's %s instead\n", effective, paths.HooksDir)
|
|
}
|
|
return &initHooksContext{workDir: paths.RepoRoot, paths: paths, env: clean, inheritedEnv: inherited}, nil
|
|
}
|
|
|
|
func installStandaloneHooks(hookNames []string, force, shared, chain, beadsHooks bool) error {
|
|
selected, err := resolveStandaloneHooksContext()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if shared || beadsHooks {
|
|
if selected.paths.CommonDir == "" {
|
|
return fmt.Errorf("shared or beads hooks require a working Git repository")
|
|
}
|
|
if beadsHooks {
|
|
selected.beadsDir = beads.FindBeadsDir()
|
|
}
|
|
}
|
|
return installHooksAt(hookNames, force, shared, chain, beadsHooks, selected)
|
|
}
|
|
|
|
//nolint:unparam // force and chain kept for CLI flag compatibility; section markers make them no-ops
|
|
func installHooksWithContext(hookNames []string, force, shared, chain, beadsHooks bool, selected *initHooksContext) error {
|
|
if selected != nil && shared {
|
|
return fmt.Errorf("shared hooks mode is not supported by selected init")
|
|
}
|
|
return installHooksAt(hookNames, force, shared, chain, beadsHooks, selected)
|
|
}
|
|
|
|
//nolint:unparam // force and chain remain accepted compatibility no-ops
|
|
func installHooksAt(hookNames []string, force, shared, chain, beadsHooks bool, selected *initHooksContext) error {
|
|
var hooksDir string
|
|
if selected != nil {
|
|
hooksDir = selected.paths.HooksDir
|
|
if beadsHooks {
|
|
if selected.beadsDir == "" {
|
|
return fmt.Errorf("%s", activeWorkspaceNotFoundError())
|
|
}
|
|
hooksDir = filepath.Join(selected.beadsDir, "hooks")
|
|
} else if shared {
|
|
hooksDir = filepath.Join(selected.paths.MainRepoRoot, ".beads-hooks")
|
|
}
|
|
} else if beadsHooks {
|
|
// Use .beads/hooks/ directory (preferred for Dolt backend)
|
|
beadsDir := beads.FindBeadsDir()
|
|
if beadsDir == "" {
|
|
return fmt.Errorf("%s", activeWorkspaceNotFoundError())
|
|
}
|
|
hooksDir = filepath.Join(beadsDir, "hooks")
|
|
} else if shared {
|
|
// Use versioned directory for shared hooks
|
|
if mainRoot, err := git.GetMainRepoRoot(); err == nil && mainRoot != "" {
|
|
hooksDir = filepath.Join(mainRoot, ".beads-hooks")
|
|
} else {
|
|
hooksDir = ".beads-hooks"
|
|
}
|
|
} else {
|
|
// Use common git directory for hooks (shared across worktrees)
|
|
var err error
|
|
hooksDir, err = git.GetGitHooksDir()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// Create hooks directory if it doesn't exist.
|
|
// Directories inside .beads/ use BeadsDirPerm (0700); git-managed hook
|
|
// dirs (.git/hooks, .beads-hooks) use 0755 so git can execute them.
|
|
hooksDirPerm := os.FileMode(0755)
|
|
if beadsHooks {
|
|
hooksDirPerm = config.BeadsDirPerm
|
|
}
|
|
if err := os.MkdirAll(hooksDir, hooksDirPerm); err != nil {
|
|
return fmt.Errorf("failed to create hooks directory: %w", err)
|
|
}
|
|
|
|
// When setting a local core.hooksPath (beads or shared mode), preserve any
|
|
// hooks from the previously effective hooks directory (e.g. a global
|
|
// core.hooksPath or the default .git/hooks). Without this, setting a local
|
|
// core.hooksPath silently shadows the global one and those hooks stop running.
|
|
if beadsHooks || shared {
|
|
if selected == nil {
|
|
preservePreexistingHooks(hooksDir)
|
|
} else {
|
|
preservePreexistingHooksAt(hooksDir, selected.paths.HooksDir, func() string { return selected.paths.MainRepoRoot })
|
|
}
|
|
}
|
|
|
|
tracked := gitTrackedFileContext
|
|
if selected != nil {
|
|
tracked = func(path string) string {
|
|
return gitTrackedFileContextWithEnv(path, selected.env, selected.inheritedEnv)
|
|
}
|
|
}
|
|
// Refuse the whole install up front if any target is unsafe to write —
|
|
// stopping midway through the loop would leave hooks half-installed.
|
|
for _, hookName := range hookNames {
|
|
if err := guardHookWritePathWithProbe(filepath.Join(hooksDir, hookName), shared, tracked); err != nil {
|
|
return fmt.Errorf("refusing to install %s hook: %w", hookName, err)
|
|
}
|
|
}
|
|
|
|
// Install each hook using section markers (GH#1380).
|
|
// Only the content between markers is managed by beads; user content
|
|
// outside the markers is preserved across reinstalls and upgrades.
|
|
for _, hookName := range hookNames {
|
|
hookPath := filepath.Join(hooksDir, hookName)
|
|
section := generateHookSection(hookName)
|
|
|
|
// Read existing hook file (if any)
|
|
// #nosec G304 -- hook path constrained to hooks directory
|
|
existing, readErr := os.ReadFile(hookPath)
|
|
|
|
if readErr != nil && !os.IsNotExist(readErr) {
|
|
return fmt.Errorf("failed to read %s: %w", hookName, readErr)
|
|
}
|
|
|
|
var newContent string
|
|
if os.IsNotExist(readErr) {
|
|
// No existing file — create with shebang + section
|
|
newContent = "#!/usr/bin/env sh\n" + section
|
|
} else {
|
|
existingStr := string(existing)
|
|
// Check if file already has section markers
|
|
if strings.Contains(existingStr, hookSectionBeginPrefix) {
|
|
// Update only the section between markers
|
|
newContent = injectHookSection(existingStr, section)
|
|
} else {
|
|
// Check if this is a legacy bd hook (shim or inline)
|
|
versionInfo, _ := getHookVersion(hookPath)
|
|
if versionInfo.IsBdHook {
|
|
// Legacy bd hook — replace entire file with section format
|
|
newContent = "#!/usr/bin/env sh\n" + section
|
|
} else {
|
|
// Non-bd hook — this is the one write that modifies a file
|
|
// bd does not own. Preserve the original as a one-time
|
|
// .backup sidecar before injecting (bd-5vdt8).
|
|
backupPath := hookPath + ".backup"
|
|
if _, statErr := os.Lstat(backupPath); os.IsNotExist(statErr) {
|
|
// #nosec G306 -- keep executable so a rename restores a working hook
|
|
if backupErr := os.WriteFile(backupPath, existing, 0755); backupErr != nil {
|
|
return fmt.Errorf("failed to back up %s before injecting bd section: %w", hookName, backupErr)
|
|
}
|
|
}
|
|
// Inject section, preserving existing content
|
|
newContent = injectHookSection(existingStr, section)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Normalize line endings to LF
|
|
newContent = strings.ReplaceAll(newContent, "\r\n", "\n")
|
|
|
|
// Write hook file
|
|
// #nosec G306 -- git hooks must be executable for Git to run them
|
|
if err := os.WriteFile(hookPath, []byte(newContent), 0755); err != nil {
|
|
return fmt.Errorf("failed to write %s: %w", hookName, err)
|
|
}
|
|
}
|
|
|
|
// Configure git to use the hooks directory after writing, as in ordinary installs.
|
|
if selected != nil && (beadsHooks || shared) {
|
|
if err := selected.configureHooksPath(hooksDir); err != nil {
|
|
return fmt.Errorf("failed to configure git hooks path: %w", err)
|
|
}
|
|
} else if beadsHooks {
|
|
if err := configureBeadsHooksPath(); err != nil {
|
|
return fmt.Errorf("failed to configure git hooks path: %w", err)
|
|
}
|
|
} else if shared {
|
|
if err := configureSharedHooksPath(); err != nil {
|
|
return fmt.Errorf("failed to configure git hooks path: %w", err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// preservePreexistingHooks copies non-beads hooks from the currently effective
|
|
// hooks directory into targetDir. This prevents hooks from a global
|
|
// core.hooksPath (or the default .git/hooks/) from being silently lost when
|
|
// beads sets a local core.hooksPath override.
|
|
func preservePreexistingHooks(targetDir string) {
|
|
// Get the hooks directory git would currently use (before we override it).
|
|
currentDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
preservePreexistingHooksAt(targetDir, currentDir, func() string {
|
|
repoRoot, _ := git.GetMainRepoRoot()
|
|
if repoRoot == "" {
|
|
repoRoot = git.GetRepoRoot()
|
|
}
|
|
return repoRoot
|
|
})
|
|
}
|
|
|
|
func preservePreexistingHooksAt(targetDir, currentDir string, mainRoot func() string) {
|
|
// Resolve to absolute paths for reliable comparison.
|
|
absTarget, err := filepath.Abs(targetDir)
|
|
if err != nil {
|
|
return
|
|
}
|
|
absCurrent, err := filepath.Abs(currentDir)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
// If the current dir is already our target, this is a re-install — skip.
|
|
if utils.PathsEqual(absTarget, absCurrent) {
|
|
return
|
|
}
|
|
|
|
// If current dir is already a beads-managed directory, skip.
|
|
repoRoot := mainRoot()
|
|
if repoRoot != "" {
|
|
absBeadsHooks, _ := filepath.Abs(filepath.Join(repoRoot, ".beads", "hooks"))
|
|
absSharedHooks, _ := filepath.Abs(filepath.Join(repoRoot, ".beads-hooks"))
|
|
if utils.PathsEqual(absCurrent, absBeadsHooks) || utils.PathsEqual(absCurrent, absSharedHooks) {
|
|
return
|
|
}
|
|
}
|
|
|
|
// Detect whether the source hooks live inside a husky directory. Husky v8
|
|
// hooks source `.husky/_/husky.sh`; husky v9 hooks source `.husky/_/h`.
|
|
// When the copy target is a beads-managed directory (e.g. .beads/hooks/),
|
|
// those sourced helpers are not present relative to the copied hook, so
|
|
// we must either also copy the helpers or rewrite the hooks to not need
|
|
// them. We choose the latter: inline-sanitize the hook body and skip the
|
|
// dispatcher files entirely. (GH#3132)
|
|
fromHusky := isHuskyDir(currentDir)
|
|
|
|
// Copy all hooks from the source directory, not just managed ones.
|
|
entries, err := os.ReadDir(currentDir)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
for _, entry := range entries {
|
|
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") || strings.HasSuffix(entry.Name(), ".sample") {
|
|
continue
|
|
}
|
|
|
|
// Husky v9 installs a dispatcher named `h` alongside per-hook files;
|
|
// it relies on husky's `.husky/_/<hook>` path layout to locate the
|
|
// "real" hook. Once we inline the hook bodies below the dispatcher
|
|
// is no longer needed (and would silently no-op if copied). Skip it.
|
|
if fromHusky && entry.Name() == "h" {
|
|
continue
|
|
}
|
|
// husky.sh (v8 helper) is similarly useless once hooks are inlined.
|
|
if fromHusky && entry.Name() == "husky.sh" {
|
|
continue
|
|
}
|
|
|
|
srcPath := filepath.Join(currentDir, entry.Name())
|
|
// #nosec G304 -- hook path constrained to known hooks directories
|
|
content, err := os.ReadFile(srcPath)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
newContent, keep := shouldPreserveHookContent(string(content), fromHusky)
|
|
if !keep {
|
|
continue
|
|
}
|
|
contentStr := newContent
|
|
|
|
// Don't overwrite existing files in target
|
|
dstPath := filepath.Join(targetDir, entry.Name())
|
|
if _, err := os.Stat(dstPath); err == nil {
|
|
continue
|
|
}
|
|
|
|
// #nosec G306 -- git hooks must be executable
|
|
if err := os.WriteFile(dstPath, []byte(contentStr), 0755); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to preserve %s hook from %s: %v\n", entry.Name(), currentDir, err)
|
|
continue
|
|
}
|
|
fmt.Printf(" Preserving existing %s hook from %s\n", entry.Name(), currentDir)
|
|
}
|
|
|
|
// GH#3132: Fix husky hook layout after copying.
|
|
fixHuskyHookLayout(currentDir, targetDir)
|
|
}
|
|
|
|
// fixHuskyHookLayout handles two husky-specific issues when hooks are copied
|
|
// from a husky-managed directory into .beads/hooks/.
|
|
//
|
|
// Bug 1 (v8): Husky v8 hooks source "$(dirname "$0")/_/husky.sh", but the
|
|
// _/ subdirectory is not copied because preservePreexistingHooks skips
|
|
// directories. Fix: create a relative symlink to the original _/ directory.
|
|
//
|
|
// Bug 2 (v9): Husky v9 uses a "h" dispatcher that resolves user hooks via
|
|
// dirname(dirname($0)), which breaks when relocated. The shims in .husky/_/
|
|
// are wrappers, not actual user hooks. Fix: replace copied shims with the
|
|
// real user hook content from the parent directory (.husky/).
|
|
func fixHuskyHookLayout(sourceDir, targetDir string) {
|
|
// Bug 1: Symlink _/ helper directory for husky v8 compatibility.
|
|
// Husky v8 hooks source $(dirname "$0")/_/husky.sh — the _/ directory
|
|
// must be reachable from the target hooks directory.
|
|
srcHelper := filepath.Join(sourceDir, "_")
|
|
if info, err := os.Stat(srcHelper); err == nil && info.IsDir() {
|
|
tgtHelper := filepath.Join(targetDir, "_")
|
|
if _, err := os.Lstat(tgtHelper); os.IsNotExist(err) {
|
|
relPath, relErr := filepath.Rel(targetDir, srcHelper)
|
|
if relErr == nil {
|
|
if symlinkErr := os.Symlink(relPath, tgtHelper); symlinkErr != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to symlink husky helper directory: %v\n", symlinkErr)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Bug 2: Replace husky v9 shims with actual user hook content.
|
|
// Husky v9 sets core.hooksPath=.husky/_/ where each hook is a shim that
|
|
// sources "h" (the dispatcher). The dispatcher uses dirname(dirname($0))
|
|
// to find user hooks in the parent .husky/ directory — this path math
|
|
// breaks when the shim is relocated to .beads/hooks/.
|
|
//
|
|
// Detect v9 by checking for the dispatcher in the *source* directory:
|
|
// preservePreexistingHooks intentionally skips copying `h` to target, so
|
|
// keying off targetDir would never match.
|
|
srcH := filepath.Join(sourceDir, "h")
|
|
hContent, err := os.ReadFile(srcH) // #nosec G304 -- path is in known hooks directory
|
|
if err != nil {
|
|
return // No h dispatcher in source — not a husky v9 source directory
|
|
}
|
|
if !strings.Contains(string(hContent), `dirname "$(dirname`) {
|
|
return // Not the husky v9 dispatcher
|
|
}
|
|
|
|
// Source is .husky/_/ — user hooks live in the parent .husky/ directory.
|
|
// Iterate the source shims rather than the target: preservePreexistingHooks
|
|
// has already run sanitizeHuskyHook on the copied shims, which strips the
|
|
// `. "$(dirname "$0")/h"` line, so a content-based shim check against
|
|
// target would no longer match. Because every non-`h` file in sourceDir
|
|
// is a v9 shim by construction, we can map source entry → user hook
|
|
// directly.
|
|
userHooksDir := filepath.Dir(sourceDir)
|
|
|
|
entries, readErr := os.ReadDir(sourceDir)
|
|
if readErr != nil {
|
|
return
|
|
}
|
|
for _, entry := range entries {
|
|
if entry.IsDir() || entry.Name() == "h" {
|
|
continue
|
|
}
|
|
hookPath := filepath.Join(targetDir, entry.Name())
|
|
if _, statErr := os.Stat(hookPath); statErr != nil {
|
|
continue // target hook not copied — nothing to replace
|
|
}
|
|
userHookPath := filepath.Join(userHooksDir, entry.Name())
|
|
userContent, readErr := os.ReadFile(userHookPath) // #nosec G304 -- constrained to husky dir
|
|
if readErr != nil {
|
|
continue // No corresponding user hook — leave copied content as-is
|
|
}
|
|
// Ensure the content has a shebang (user hooks in .husky/ often omit it)
|
|
replacement := string(userContent)
|
|
if !strings.HasPrefix(replacement, "#!") {
|
|
replacement = "#!/usr/bin/env sh\n" + replacement
|
|
}
|
|
// #nosec G306 -- git hooks must be executable
|
|
if writeErr := os.WriteFile(hookPath, []byte(replacement), 0755); writeErr != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to replace husky v9 shim %s: %v\n", entry.Name(), writeErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
// isHuskyDir reports whether dir looks like a husky-managed hooks directory
|
|
// (either `.husky` itself or `.husky/_`, the helper dir used by v9).
|
|
func isHuskyDir(dir string) bool {
|
|
if dir == "" {
|
|
return false
|
|
}
|
|
base := filepath.Base(dir)
|
|
parent := filepath.Base(filepath.Dir(dir))
|
|
if base == ".husky" {
|
|
return true
|
|
}
|
|
// .husky/_ (husky v9 helper directory that is sometimes set as
|
|
// core.hooksPath directly).
|
|
if base == "_" && parent == ".husky" {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// sanitizeHuskyHook rewrites a husky hook body so it can run standalone
|
|
// without the `.husky/_/husky.sh` (v8) or `.husky/_/h` (v9) helper being
|
|
// reachable relative to $0. It removes the helper-source line and prepends
|
|
// `node_modules/.bin` to PATH so that tools like `npx`, `lint-staged`, and
|
|
// project-local binaries continue to resolve — which is what husky v9's `h`
|
|
// normally does for the user. (GH#3132)
|
|
//
|
|
// Hooks that don't look like husky hooks are returned unchanged.
|
|
func sanitizeHuskyHook(content string) string {
|
|
// Normalize CRLF first so our line-by-line rewrite works on
|
|
// Windows-authored hooks too.
|
|
normalized := strings.ReplaceAll(content, "\r\n", "\n")
|
|
|
|
lines := strings.Split(normalized, "\n")
|
|
out := make([]string, 0, len(lines)+2)
|
|
sourcedHelper := false
|
|
|
|
for _, line := range lines {
|
|
trimmed := strings.TrimSpace(line)
|
|
// Match husky v8 helper: `. "$(dirname -- "$0")/_/husky.sh"` and
|
|
// common variants (single-quoted, no `--`, `source` instead of `.`).
|
|
if isHuskyHelperSourceLine(trimmed) {
|
|
sourcedHelper = true
|
|
// Drop the line entirely.
|
|
continue
|
|
}
|
|
out = append(out, line)
|
|
}
|
|
|
|
if !sourcedHelper {
|
|
// Not recognizably a husky-sourcing hook — leave it alone.
|
|
return content
|
|
}
|
|
|
|
// Rebuild, injecting a PATH export right after the shebang (if any) so
|
|
// that `npx`, `lint-staged`, etc. keep working. Husky v9's `h` normally
|
|
// does this for the user.
|
|
result := make([]string, 0, len(out)+2)
|
|
injected := false
|
|
pathLine := `export PATH="$PWD/node_modules/.bin:$PATH"`
|
|
|
|
for i, line := range out {
|
|
result = append(result, line)
|
|
if !injected && i == 0 && strings.HasPrefix(strings.TrimSpace(line), "#!") {
|
|
result = append(result, "# Injected by beads (GH#3132): husky helper layout not mirrored into this dir.")
|
|
result = append(result, pathLine)
|
|
injected = true
|
|
}
|
|
}
|
|
if !injected {
|
|
// No shebang — inject at the top.
|
|
result = append([]string{pathLine}, result...)
|
|
}
|
|
|
|
return strings.Join(result, "\n")
|
|
}
|
|
|
|
// isHuskyHelperSourceLine reports whether line (already trimmed) sources one
|
|
// of the husky helper scripts. Matches husky v8 (`_/husky.sh`) and husky v9
|
|
// (`/h`) dispatchers, tolerating quoting and `source` vs `.` variants.
|
|
func isHuskyHelperSourceLine(line string) bool {
|
|
if line == "" {
|
|
return false
|
|
}
|
|
// Must start with POSIX source (`. `) or bash `source `.
|
|
if !strings.HasPrefix(line, ". ") && !strings.HasPrefix(line, "source ") {
|
|
return false
|
|
}
|
|
// v8: references `/_/husky.sh`
|
|
if strings.Contains(line, "/_/husky.sh") || strings.Contains(line, `\_\husky.sh`) {
|
|
return true
|
|
}
|
|
// v9: `. "$(dirname "$0")/h"` (or with `--` / single quotes).
|
|
// Require both `dirname` and a trailing `/h"` or `/h'` to avoid matching
|
|
// unrelated sourcing of files that happen to end in "h".
|
|
if strings.Contains(line, "dirname") && (strings.HasSuffix(line, `/h"`) || strings.HasSuffix(line, `/h'`) || strings.HasSuffix(line, "/h")) {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func configureSharedHooksPath() error {
|
|
// Set git config core.hooksPath to an absolute path pointing to .beads-hooks.
|
|
// Using an absolute path is critical for git worktrees (GH#2414):
|
|
// git resolves relative core.hooksPath relative to the working tree root.
|
|
repoRoot, _ := git.GetMainRepoRoot()
|
|
if repoRoot == "" {
|
|
repoRoot = git.GetRepoRoot()
|
|
}
|
|
if repoRoot == "" {
|
|
return fmt.Errorf("not in a git repository")
|
|
}
|
|
absHooksPath := filepath.Join(repoRoot, ".beads-hooks")
|
|
cmd := exec.Command("git", "config", "core.hooksPath", absHooksPath)
|
|
cmd.Dir = repoRoot
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
return fmt.Errorf("git config failed: %w (output: %s)", err, string(output))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func configureBeadsHooksPath() error {
|
|
// Set git config core.hooksPath to an absolute path pointing to .beads/hooks.
|
|
// Using an absolute path is critical for git worktrees (GH#2414):
|
|
// git resolves relative core.hooksPath relative to the working tree root,
|
|
// so in a worktree ".beads/hooks" would resolve to <worktree>/.beads/hooks/
|
|
// which doesn't exist — the hooks live in the main repo's .beads/hooks/.
|
|
repoRoot, _ := git.GetMainRepoRoot()
|
|
if repoRoot == "" {
|
|
repoRoot = git.GetRepoRoot()
|
|
}
|
|
if repoRoot == "" {
|
|
return fmt.Errorf("not in a git repository")
|
|
}
|
|
absHooksPath := filepath.Join(repoRoot, ".beads", "hooks")
|
|
cmd := exec.Command("git", "config", "core.hooksPath", absHooksPath)
|
|
cmd.Dir = repoRoot
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
return fmt.Errorf("git config failed: %w (output: %s)", err, string(output))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func uninstallStandaloneHooks() error {
|
|
selected, err := resolveStandaloneHooksContext()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return uninstallHooksAt(selected.paths.HooksDir, func() error {
|
|
if selected.paths.CommonDir == "" {
|
|
return nil // Absolute-path fallback has no repository config authority.
|
|
}
|
|
return resetHooksPathAt(selected.paths.MainRepoRoot, selected.paths.CommonDir,
|
|
doctor.BeadsManagedStorageHooksDir(), selected.env)
|
|
})
|
|
}
|
|
|
|
func uninstallHooks() error {
|
|
// Get hooks directory from common git dir (hooks are shared across worktrees)
|
|
hooksDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return uninstallHooksAt(hooksDir, resetHooksPathIfBeadsManaged)
|
|
}
|
|
|
|
func uninstallHooksAt(hooksDir string, reset func() error) error {
|
|
hookNames := []string{"pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"}
|
|
|
|
for _, hookName := range hookNames {
|
|
hookPath := filepath.Join(hooksDir, hookName)
|
|
|
|
// #nosec G304 -- hook path constrained to .git/hooks directory
|
|
content, err := os.ReadFile(hookPath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
continue
|
|
}
|
|
return fmt.Errorf("failed to read %s: %w", hookName, err)
|
|
}
|
|
|
|
// Try to remove only the beads section (GH#1380)
|
|
newContent, found := removeHookSection(string(content))
|
|
if found {
|
|
remaining := strings.TrimSpace(newContent)
|
|
if remaining == "" || remaining == "#!/usr/bin/env sh" || remaining == "#!/bin/sh" {
|
|
// Only shebang left — remove the file entirely
|
|
if err := os.Remove(hookPath); err != nil {
|
|
return fmt.Errorf("failed to remove %s: %w", hookName, err)
|
|
}
|
|
} else {
|
|
// #nosec G306 -- git hooks must be executable
|
|
if err := os.WriteFile(hookPath, []byte(newContent), 0755); err != nil {
|
|
return fmt.Errorf("failed to write %s: %w", hookName, err)
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
|
|
// No section markers — check if it's a legacy bd hook (remove entire file)
|
|
versionInfo, verr := getHookVersion(hookPath)
|
|
if verr == nil && versionInfo.IsBdHook {
|
|
if err := os.Remove(hookPath); err != nil {
|
|
return fmt.Errorf("failed to remove %s: %w", hookName, err)
|
|
}
|
|
// Restore backup if exists
|
|
backupPath := hookPath + ".backup"
|
|
if _, err := os.Stat(backupPath); err == nil {
|
|
if err := os.Rename(backupPath, hookPath); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to restore backup for %s: %v\n", hookName, err)
|
|
}
|
|
}
|
|
}
|
|
// Not a bd hook at all — leave it alone
|
|
}
|
|
|
|
// Reset beads-managed git config (core.hooksPath, beads.role) now that the
|
|
// hook files themselves are removed. A failure here must not be a
|
|
// scrolling stderr warning — bd hooks uninstall must not report success
|
|
// while beads-managed config is still left behind (GH#4440).
|
|
if err := reset(); err != nil {
|
|
return fmt.Errorf("hook files removed, but failed to reset beads-managed git config: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// resetHooksPathIfBeadsManaged unsets core.hooksPath if it points to a
|
|
// beads-managed hooks directory (.beads/hooks, .beads-hooks, or the resolved
|
|
// out-of-repo <effective .beads>/hooks storage target), and unsets
|
|
// beads.role. beads.role marks a repo as beads-managed independent of
|
|
// core.hooksPath, so it is cleared unconditionally here rather than gated on
|
|
// the hooksPath match — otherwise an uninstall that runs after core.hooksPath
|
|
// was already cleared (e.g. by `bd doctor --fix`) would leave a stale
|
|
// beads.role behind. A key that is already absent is not an error.
|
|
func resetHooksPathIfBeadsManaged() error {
|
|
repoRoot, _ := git.GetMainRepoRoot()
|
|
if repoRoot == "" {
|
|
repoRoot = git.GetRepoRoot()
|
|
}
|
|
if repoRoot == "" {
|
|
return nil // not in a git repo
|
|
}
|
|
|
|
// These checks are defensive. repoRoot and commonDir are resolved
|
|
// independently, and an inherited GIT_DIR can make them name different
|
|
// repositories, so their agreement is intent rather than an invariant.
|
|
// The common-dir pin states that intent: --git-dir addresses the common
|
|
// config through either gitdir, while repoRoot is only the subprocess cwd.
|
|
commonDir, err := git.GetGitCommonDir()
|
|
if err != nil {
|
|
return fmt.Errorf("resolve Git common directory for role reset: %w", err)
|
|
}
|
|
if commonDir == "" {
|
|
return fmt.Errorf("empty Git common directory for role reset")
|
|
}
|
|
return resetHooksPathAt(repoRoot, commonDir, doctor.BeadsManagedStorageHooksDir(),
|
|
gitenv.ScrubRouting(os.Environ()))
|
|
}
|
|
|
|
func resetHooksPathAt(repoRoot, commonDir, storageHooksDir string, configEnv []string) error {
|
|
// beads.role is an authority value, unlike core.hooksPath, so its own
|
|
// commands drop inherited suppression too (see the role pair below).
|
|
// Scrubbing suppression from configEnv rather than os.Environ() leaves a
|
|
// caller's captured environment otherwise intact. Suppression controls are
|
|
// themselves routing keys, so for a configEnv that ScrubRouting already
|
|
// produced the two spellings drop exactly the same entries.
|
|
roleConfigEnv := gitenv.ScrubRoutingAndSuppression(configEnv)
|
|
var failures []string
|
|
|
|
cmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "core.hooksPath")
|
|
cmd.Dir = repoRoot
|
|
cmd.Env = configEnv
|
|
if out, err := cmd.Output(); err == nil {
|
|
hooksPath := strings.TrimSpace(string(out))
|
|
// Matches both relative (legacy) and absolute (GH#2414) beads hooks
|
|
// paths plus the out-of-repo <effective .beads>/hooks directory that
|
|
// `bd hooks install --beads` configures, symlink-resolving the absolute
|
|
// forms. Shared with doctor.CheckHooksPath/FixHooksPath so uninstall and
|
|
// `bd doctor --fix` cannot disagree about what "beads-managed" means.
|
|
if doctor.IsBeadsManagedHooksPath(repoRoot, storageHooksDir, hooksPath) {
|
|
unsetCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--unset", "core.hooksPath")
|
|
unsetCmd.Dir = repoRoot
|
|
unsetCmd.Env = configEnv
|
|
if output, err := unsetCmd.CombinedOutput(); err != nil {
|
|
failures = append(failures, fmt.Sprintf("core.hooksPath: %v (output: %s)", err, strings.TrimSpace(string(output))))
|
|
}
|
|
}
|
|
} else if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
|
|
var diagnostic string
|
|
if ok {
|
|
diagnostic = strings.TrimSpace(string(exit.Stderr))
|
|
}
|
|
failures = append(failures, fmt.Sprintf("read core.hooksPath: %v (output: %s)", err, diagnostic))
|
|
}
|
|
// Exit 1 means the key is absent. Other read failures must remain visible.
|
|
|
|
// Read before unsetting rather than treating git's exit 5 as "already
|
|
// absent". Exit 5 also means "the key has multiple values, refusing an
|
|
// ambiguous unset" — a repo with a duplicated beads.role (bad merge, hand
|
|
// edit) would then report a clean uninstall while leaving the key set,
|
|
// which is the exact failure this is supposed to stop.
|
|
// Keep the selected main/common config, including bare repositories with an
|
|
// external worktree, while dropping routing overrides from both commands.
|
|
// The presence query must use the same local scope as the unset.
|
|
//
|
|
// Both role commands additionally discard the explicit config suppression
|
|
// ScrubRouting keeps: beads.role is an authority value whose absence reads
|
|
// as maintainer, so a suppressed config file would report a clean uninstall
|
|
// while leaving the key set here.
|
|
getRoleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--get", "beads.role")
|
|
getRoleCmd.Dir = repoRoot
|
|
getRoleCmd.Env = roleConfigEnv
|
|
if out, err := getRoleCmd.CombinedOutput(); err == nil {
|
|
roleCmd := exec.Command("git", "--git-dir", commonDir, "config", "--local", "--unset", "beads.role")
|
|
roleCmd.Dir = repoRoot
|
|
roleCmd.Env = roleConfigEnv
|
|
if output, err := roleCmd.CombinedOutput(); err != nil {
|
|
failures = append(failures, fmt.Sprintf("beads.role: %v (output: %s)", err, strings.TrimSpace(string(output))))
|
|
}
|
|
} else if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
|
|
failures = append(failures, fmt.Sprintf("read beads.role: %v (output: %s)", err, strings.TrimSpace(string(out))))
|
|
}
|
|
|
|
if len(failures) > 0 {
|
|
return fmt.Errorf("%s", strings.Join(failures, "; "))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// =============================================================================
|
|
// Hook Implementation Functions (called by thin shims via 'bd hooks run')
|
|
// =============================================================================
|
|
|
|
// runChainedHook runs a .old hook if it exists. Returns the exit code.
|
|
// If the hook doesn't exist, returns 0 (success).
|
|
func runChainedHook(hookName string, args []string) int {
|
|
// Get the hooks directory from common dir (hooks are shared across worktrees)
|
|
hooksDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
return 0 // Not a git repo, nothing to chain
|
|
}
|
|
|
|
oldHookPath := filepath.Join(hooksDir, hookName+".old")
|
|
|
|
// Check if the .old hook exists and is executable
|
|
info, err := os.Stat(oldHookPath)
|
|
if err != nil {
|
|
return 0 // No chained hook
|
|
}
|
|
if info.Mode().Perm()&0111 == 0 {
|
|
return 0 // Not executable
|
|
}
|
|
|
|
// Check if .old is itself a bd hook (shim or inline) - skip to prevent infinite recursion
|
|
// This can happen if user runs `bd hooks install --chain` multiple times,
|
|
// renaming an existing bd hook to .old. See: GH#843, GH#1120
|
|
versionInfo, err := getHookVersion(oldHookPath)
|
|
if err == nil && versionInfo.IsBdHook {
|
|
// Skip execution - .old is a bd hook which would call us again
|
|
return 0
|
|
}
|
|
|
|
// Run the chained hook
|
|
// #nosec G204 -- hookName is from controlled list, path is from git directory
|
|
cmd := exec.Command(oldHookPath, args...)
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
cmd.Stdin = os.Stdin
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
|
return exitErr.ExitCode()
|
|
}
|
|
// Other error - treat as failure
|
|
fmt.Fprintf(os.Stderr, "Warning: chained hook %s failed: %v\n", hookName, err)
|
|
return 1
|
|
}
|
|
|
|
return 0
|
|
}
|
|
|
|
// runPreCommitHook runs chained hooks before commit.
|
|
// Returns 0 on success (or if not applicable).
|
|
func runPreCommitHook() int {
|
|
// Run chained hook first (if exists)
|
|
if exitCode := runChainedHook("pre-commit", nil); exitCode != 0 {
|
|
return exitCode
|
|
}
|
|
|
|
// GH#2489, GH#1863: Export JSONL before commit so issue state lands in
|
|
// the same commit as code changes. maybeAutoExport() skips when
|
|
// BD_GIT_HOOK=1, so we invoke `bd export` as a subprocess instead.
|
|
exportJSONLForCommit()
|
|
|
|
return 0
|
|
}
|
|
|
|
// exportJSONLForCommit exports Dolt issue state to the git-tracked JSONL file
|
|
// when export.auto is enabled. Called from the pre-commit hook so that the
|
|
// exported file can be staged and included in the pending commit.
|
|
//
|
|
// Errors are logged as warnings but never block the commit.
|
|
func exportJSONLForCommit() {
|
|
if !config.GetBool("export.auto") {
|
|
return
|
|
}
|
|
|
|
beadsDir := beads.FindBeadsDir()
|
|
if beadsDir == "" {
|
|
return
|
|
}
|
|
|
|
exportPath := config.GetString("export.path")
|
|
if exportPath == "" {
|
|
exportPath = "issues.jsonl"
|
|
}
|
|
fullPath := filepath.Join(hookJSONLDir(beadsDir), exportPath)
|
|
|
|
// If the export file is staged for deletion (user ran `git rm`), do not
|
|
// re-export or re-stage it. GIT_INDEX_FILE is set during an actual commit,
|
|
// so git-diff-index reads the pending index — where the deletion lives.
|
|
// Without this guard, git add fullPath would convert the staged deletion
|
|
// back to a modification and the file would never be removed from the
|
|
// repo. Reimplements gastownhall/beads#3838 (ckumar1).
|
|
if isExportFileStagedForDeletion(fullPath) {
|
|
debug.Logf("pre-commit: %s staged for deletion — skipping export\n", exportPath)
|
|
return
|
|
}
|
|
|
|
if !preCommitHasStagedBeadsFiles(beadsDir) {
|
|
debug.Logf("pre-commit: skipping JSONL export — no staged .beads paths\n")
|
|
return
|
|
}
|
|
|
|
debug.Logf("pre-commit: exporting JSONL to %s\n", fullPath)
|
|
warnJSONLWithoutDoltRemote("pre-commit auto-export")
|
|
|
|
// The destination directory is not guaranteed to exist: hookJSONLDir can
|
|
// retarget into a worktree that has no .beads yet, and a nested
|
|
// export.path ("exports/issues.jsonl") adds another level. atomicfile
|
|
// does not create parents, so without this every commit would warn and
|
|
// write nothing.
|
|
// 0o750 matches the permissions `bd init` gives a .beads directory.
|
|
if err := os.MkdirAll(filepath.Dir(fullPath), 0o750); err != nil {
|
|
fmt.Fprintf(os.Stderr, "beads: pre-commit export warning: %v\n", err)
|
|
return
|
|
}
|
|
|
|
// Shell out to `bd export` which initializes its own store.
|
|
// Keep BD_GIT_HOOK=1 in the subprocess environment. The explicit export
|
|
// command must run, but its PersistentPostRun auto-export must stay
|
|
// suppressed: maybeAutoExport resolves its own destination straight from
|
|
// beads.FindBeadsDir(), so letting it fire writes the shared primary
|
|
// checkout's JSONL behind this hook's back (GH#6680). It cannot *stage*
|
|
// that file — gitAddFile's cross-worktree guard rejects a target outside
|
|
// the hook's worktree — but the stray write is exactly the unexplained
|
|
// `M .beads/issues.jsonl` users see in the primary checkout.
|
|
//
|
|
// Keeping the variable set also leaves the subprocess's PersistentPostRun
|
|
// auto-backup suppressed (backup_auto.go), matching the parent hook
|
|
// process: the parent bd is already in hook context and skips it, so a
|
|
// pre-commit no longer takes a second backup of the same state.
|
|
//
|
|
// NOTE: we intentionally preserve GIT_DIR et al. in the subprocess env so
|
|
// it retains the hook's selected Git context. The parent stages fullPath
|
|
// after the subprocess returns, using that same context for the
|
|
// cross-worktree guard (GH#3311 part 2).
|
|
// Run from the project root, not .beads/. Embedded Dolt discovery starts
|
|
// from cwd, so cwd=.beads/ can make the export subprocess look for a
|
|
// nested .beads/.beads workspace and warn on every commit (GH#3454).
|
|
cmd := exec.Command("bd", "export", "-o", fullPath)
|
|
cmd.Dir = exportSubprocessDir(beadsDir)
|
|
cmd.Env = hookSubprocessEnv(os.Environ())
|
|
cmd.Stderr = os.Stderr
|
|
if err := cmd.Run(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "beads: pre-commit export warning: %v\n", err)
|
|
return
|
|
}
|
|
|
|
// Stage the exported file if configured. Skip when no-git-ops is set
|
|
// (GH#3314). gitAddFile scrubs the inherited git hook env vars so git
|
|
// rediscovers the repo from cwd, and silently skips when fullPath is
|
|
// outside the hook's worktree. That guard still matters here: hookJSONLDir
|
|
// only retargets the cross-worktree case it can fix, so a .beads/redirect
|
|
// to a shared out-of-repo store, a BEADS_DIR override, or a beads dir
|
|
// above the repository root all still resolve outside this worktree and
|
|
// must not be dropped into the index. See GH#3311.
|
|
if config.GetBool("export.git-add") && !config.GetBool("no-git-ops") {
|
|
if err := gitAddFile(fullPath); err != nil {
|
|
debug.Logf("pre-commit: git add failed: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// hookJSONLDir returns the directory the running git hook should read and
|
|
// write the git-tracked JSONL snapshot in. It is the single destination
|
|
// resolver shared by the pre-commit export writer and the
|
|
// post-merge/post-checkout sync importer, so those two can never disagree
|
|
// about which copy of the file the hook owns.
|
|
//
|
|
// Database discovery and JSONL ownership are separate concerns (GH#6680): a
|
|
// linked worktree has no store of its own, so beads.FindBeadsDir deliberately
|
|
// falls back to the primary checkout's .beads directory, but the JSONL is a
|
|
// tracked file whose contents belong to the worktree being committed.
|
|
//
|
|
// Known asymmetry, deliberately out of scope for a hook fix: the non-hook
|
|
// auto-export lane (maybeAutoExport and its export-state.json throttle key)
|
|
// still resolves straight from beads.FindBeadsDir. It cannot share this
|
|
// resolver — outside a hook there is no GIT_DIR, hookWorkTreeRoot is empty,
|
|
// and this function is the identity. Giving ordinary `bd` commands in a linked
|
|
// worktree ownership of their own JSONL means resolving the worktree from cwd
|
|
// on every command, which changes JSONL ownership globally; that is a product
|
|
// decision rather than a hook fix, and is tracked separately.
|
|
func hookJSONLDir(beadsDir string) string {
|
|
hookRoot := hookWorkTreeRoot()
|
|
primaryRoot := hookLinkedWorktreePrimaryRoot(hookRoot)
|
|
jsonlDir := worktreeJSONLDir(beadsDir, hookRoot, primaryRoot)
|
|
// Log both outcomes. When the verdict goes the "keep beadsDir" way for a
|
|
// topology the user expected this fix to cover, the only other observable
|
|
// is the absence of a change — which is indistinguishable from the hook
|
|
// not running at all.
|
|
debug.Logf("hook: JSONL dir %s (retargeted=%t beadsDir=%s hookRoot=%s primaryRoot=%s)\n",
|
|
jsonlDir, jsonlDir != beadsDir, beadsDir, hookRoot, primaryRoot)
|
|
return jsonlDir
|
|
}
|
|
|
|
// worktreeJSONLDir is the pure gating decision behind hookJSONLDir.
|
|
//
|
|
// The rewrite is deliberately narrow, because hookWorkTreeRoot is non-empty
|
|
// for *every* hook invocation — it returns filepath.Dir(GIT_DIR) for a plain,
|
|
// non-worktree repository too — so it cannot carry this decision alone.
|
|
// beadsDir is retargeted into the committing worktree only when all of:
|
|
//
|
|
// - the hook supplied a worktree root (hookRoot != "");
|
|
// - that worktree is a linked one (primaryRoot != "");
|
|
// - beadsDir is not already inside the committing worktree;
|
|
// - beadsDir lives inside the primary checkout — that is, exporting to it
|
|
// is precisely the cross-worktree write GH#6680 reported.
|
|
//
|
|
// Everything else keeps the discovered directory and so keeps pre-GH#6680
|
|
// behavior: a .beads/redirect to a shared out-of-repo store, a BEADS_DIR
|
|
// override, and a beads dir above the repository root are not another working
|
|
// tree. Retargeting those would both strand the real JSONL and drop a
|
|
// brand-new in-repo copy into the user's commit, and gitAddFile's GH#3311
|
|
// guard already keeps them out of the index.
|
|
//
|
|
// The destination mirrors beadsDir's path *relative to the primary checkout*
|
|
// rather than a hardcoded ".beads" or a bare leaf name, because the relative
|
|
// path is the one the committing worktree actually tracks: a store reached
|
|
// through a .beads/redirect to an in-repo "tools/store" must land at
|
|
// <worktree>/tools/store, not at <worktree>/store, which is a path no commit
|
|
// has ever contained.
|
|
//
|
|
// Which lane reaches that mirroring: the pre-commit export runs only when
|
|
// preCommitHasStagedBeadsFiles sees a staged path under its hardcoded ".beads"
|
|
// pathspec, unchanged from pre-GH#6680. A store that lives outside .beads —
|
|
// "beads-store", "nested/beads-store", an in-repo redirect target — normally
|
|
// stages nothing that gate matches, so on the export lane the mirror is a
|
|
// correctness bound rather than a new capability; the sync lane
|
|
// (importJSONLForSync) has no staged gate and does reach it. The gate blocked
|
|
// exactly the same commits at base, so this is a limit on the fix's reach and
|
|
// not a regression. Read the mirror as "the hook never writes a path the
|
|
// committing worktree does not track", not as "nested stores now auto-export
|
|
// on every commit".
|
|
//
|
|
// One case the gating deliberately does not catch: a <primary>/.beads that is
|
|
// itself a symlink pointing out of the repository. pathInsideDir resolves
|
|
// symlinks on the path's *parent* only (export_auto.go), so such a beadsDir
|
|
// still compares as inside primaryRoot and is retargeted, leaving the real
|
|
// store's JSONL stale — the outcome the .beads/redirect case above exists to
|
|
// prevent. The supported redirect mechanism is unaffected, because
|
|
// FollowRedirect hands back the resolved out-of-repo target whose parent is
|
|
// outside primaryRoot; only a hand-rolled `ln -s` is affected. Closing it
|
|
// means resolving beadsDir itself before both the gating and the lexical Rel
|
|
// below, which also moves the mixed-symlink-form case those two lines
|
|
// currently decline — a behavior change, so the case is named here instead.
|
|
func worktreeJSONLDir(beadsDir, hookRoot, primaryRoot string) string {
|
|
if hookRoot == "" || primaryRoot == "" {
|
|
return beadsDir
|
|
}
|
|
if pathInsideDir(beadsDir, hookRoot) || !pathInsideDir(beadsDir, primaryRoot) {
|
|
return beadsDir
|
|
}
|
|
// pathInsideDir resolves symlinks (on the parent); filepath.Rel is lexical,
|
|
// so the two can still disagree and hand back a path that escapes
|
|
// hookRoot. IsLocal
|
|
// rejects exactly those ("..", an absolute result), and rel == "." means
|
|
// the store *is* the checkout root — too degenerate to mirror. Both
|
|
// decline, which keeps pre-GH#6680 behavior rather than inventing a target.
|
|
rel, err := filepath.Rel(primaryRoot, beadsDir)
|
|
if err != nil || rel == "." || !filepath.IsLocal(rel) {
|
|
return beadsDir
|
|
}
|
|
return filepath.Join(hookRoot, rel)
|
|
}
|
|
|
|
// hookLinkedWorktreePrimaryRoot returns the primary checkout's worktree root
|
|
// when hookRoot is a *linked* git worktree, and "" otherwise: the main
|
|
// checkout, a repository git cannot describe, or a layout whose common git dir
|
|
// is not a conventional "<root>/.git".
|
|
//
|
|
// That last requirement is narrower than internal/beads' probe
|
|
// (worktreeFallbackBeadsDirForRepo), which classifies linked-ness as
|
|
// --git-dir != --git-common-dir and serves a bare-repo-backed worktree by
|
|
// sharing <repo.git>/.beads. The difference is deliberate: this function must
|
|
// name a primary *checkout* to mirror a tracked path out of, and a bare
|
|
// repository has none — <repo.git>/.beads is not inside any working tree, so
|
|
// there is no relative path to carry into the committing worktree. Worktrees
|
|
// of a `git clone --bare` therefore keep writing the shared copy and GH#6680
|
|
// stays unfixed for that layout; where their JSONL should live is a product
|
|
// decision rather than something this hook fix can infer.
|
|
func hookLinkedWorktreePrimaryRoot(hookRoot string) string {
|
|
if hookRoot == "" {
|
|
return ""
|
|
}
|
|
// #nosec G702 - fixed "git" command; args are constant subcommands plus an internal
|
|
// hookRoot derived from the hook's own beads dir, never attacker-controlled input.
|
|
cmd := exec.Command("git", "-C", hookRoot, "rev-parse", "--git-common-dir")
|
|
// Scrub the inherited GIT_* vars so git describes hookRoot itself rather
|
|
// than whatever repository GIT_DIR happens to name.
|
|
cmd.Env = scrubGitHookEnv(os.Environ())
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
debug.Logf("hook: failed to resolve git common dir for %s: %v\n", hookRoot, err)
|
|
return ""
|
|
}
|
|
commonDir := strings.TrimSpace(string(out))
|
|
if commonDir == "" {
|
|
return ""
|
|
}
|
|
if !filepath.IsAbs(commonDir) {
|
|
commonDir = filepath.Join(hookRoot, commonDir)
|
|
}
|
|
if filepath.Base(commonDir) != ".git" {
|
|
return ""
|
|
}
|
|
primaryRoot, err := filepath.Abs(filepath.Dir(commonDir))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
if utils.PathsEqual(primaryRoot, hookRoot) {
|
|
// The hook's worktree is the primary one; nothing to retarget.
|
|
return ""
|
|
}
|
|
return primaryRoot
|
|
}
|
|
|
|
// hookSubprocessEnv builds the environment for the `bd` subprocesses a hook
|
|
// shells out to — `bd export` on the pre-commit lane, `bd import` on the sync
|
|
// lane. It forces BD_GIT_HOOK=1 rather than assuming the caller already
|
|
// exported it: the variable's whole job here is to keep the subprocess's
|
|
// PersistentPostRun auto-export (and auto-backup) suppressed, and a hook
|
|
// entrypoint that had not set it would leave nothing to suppress with. Git
|
|
// routing vars (GIT_DIR et al.) are deliberately preserved — see
|
|
// exportJSONLForCommit.
|
|
//
|
|
// Nothing on either the export or the import path reads BD_GIT_HOOK to decide
|
|
// whether to do its work: its only consumers are maybeAutoExport
|
|
// (export_auto.go), maybeAutoBackup (backup_auto.go), the first-run metrics
|
|
// notice (metrics.go) and terminal color (internal/ui). Setting it therefore
|
|
// suppresses only the post-run writes the hook is doing itself, never the
|
|
// explicit command.
|
|
func hookSubprocessEnv(env []string) []string {
|
|
return append(filterEnv(env, "BD_GIT_HOOK"), "BD_GIT_HOOK=1")
|
|
}
|
|
|
|
// isExportFileStagedForDeletion reports whether the beads export file at
|
|
// fullPath is staged for deletion (the user ran `git rm` on it). When true,
|
|
// exportJSONLForCommit must skip re-exporting and re-staging it: running
|
|
// `git add` on a freshly regenerated file would convert the staged deletion
|
|
// back into a modification, silently reviving a file the user intentionally
|
|
// removed.
|
|
//
|
|
// Unlike preCommitHasStagedBeadsFiles and gitAddFile, this deliberately runs
|
|
// git with the hook's inherited environment intact rather than scrubbing
|
|
// GIT_* vars. GIT_INDEX_FILE is set during an actual commit and points at
|
|
// the pending index — where the staged deletion lives — so scrubbing it
|
|
// here would make git fall back to the on-disk index and miss the
|
|
// deletion. Reimplements gastownhall/beads#3838 (ckumar1).
|
|
//
|
|
// #nosec G702 -- no shell is involved: the binary is the literal "git" and
|
|
// every argument is its own argv element. The only variable argument is the
|
|
// export file's own path, and it sits after the "--" terminator, so git
|
|
// always reads it as a pathspec and never as an option. Annotated on the
|
|
// function rather than on the call so it stays correct however the body
|
|
// addresses that path. Mirrors the annotation on configureHooksPath in
|
|
// init_git_hooks.go.
|
|
func isExportFileStagedForDeletion(fullPath string) bool {
|
|
// The export file's directory is not guaranteed to exist — hookJSONLDir
|
|
// can retarget into a worktree with no .beads yet, and a nested
|
|
// export.path adds another level. exec fails outright on a missing Dir,
|
|
// which would silently drop this guard, so run from the nearest existing
|
|
// ancestor and address the file relative to it. When the directory does
|
|
// exist this is identical to running in it with the bare file name.
|
|
dir := nearestExistingDir(filepath.Dir(fullPath))
|
|
if dir == "" {
|
|
return false
|
|
}
|
|
rel, err := filepath.Rel(dir, fullPath)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
checkCmd := exec.Command("git", "diff", "--cached", "--diff-filter=D", "--name-only", "--", rel)
|
|
checkCmd.Dir = dir
|
|
out, _ := checkCmd.Output()
|
|
return len(out) > 0
|
|
}
|
|
|
|
// nearestExistingDir walks up from dir to the first existing directory,
|
|
// returning "" if it reaches the filesystem root without finding one.
|
|
func nearestExistingDir(dir string) string {
|
|
for {
|
|
if info, err := os.Stat(dir); err == nil && info.IsDir() {
|
|
return dir
|
|
}
|
|
parent := filepath.Dir(dir)
|
|
if parent == dir {
|
|
return ""
|
|
}
|
|
dir = parent
|
|
}
|
|
}
|
|
|
|
func preCommitHasStagedBeadsFiles(beadsDir string) bool {
|
|
cmdDir := exportSubprocessDir(beadsDir)
|
|
if hookRoot := hookWorkTreeRoot(); hookRoot != "" {
|
|
cmdDir = hookRoot
|
|
}
|
|
cmd := exec.Command("git", "diff", "--cached", "--name-only", "--", ".beads")
|
|
cmd.Dir = cmdDir
|
|
cmd.Env = scrubGitHookEnv(os.Environ())
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
debug.Logf("pre-commit: failed to inspect staged .beads paths: %v\n", err)
|
|
return false
|
|
}
|
|
return strings.TrimSpace(string(out)) != ""
|
|
}
|
|
|
|
func exportSubprocessDir(beadsDir string) string {
|
|
return filepath.Dir(beadsDir)
|
|
}
|
|
|
|
// syncImportJSONLPath returns the JSONL path used by the legacy git-hook sync
|
|
// import path. Existing projects may have customized export.path before
|
|
// import.path existed, so keep importing from export.path unless import.path is
|
|
// explicitly configured.
|
|
//
|
|
// jsonlDir is the hook-resolved JSONL directory (hookJSONLDir), which is not
|
|
// always the discovered beads dir: in a linked worktree the sync hook must
|
|
// import the copy `git pull` just refreshed in this worktree — the same copy
|
|
// the pre-commit hook exports — not the primary checkout's (GH#6680).
|
|
func syncImportJSONLPath(jsonlDir string) string {
|
|
if config.GetValueSource("import.path") == config.SourceDefault {
|
|
exportPath := config.GetString("export.path")
|
|
if exportPath != "" {
|
|
return filepath.Join(jsonlDir, exportPath)
|
|
}
|
|
}
|
|
return configuredImportJSONLPath(jsonlDir)
|
|
}
|
|
|
|
// importJSONLForSync imports JSONL into Dolt after a git
|
|
// pull/merge/branch-checkout only for legacy projects with no Dolt remote.
|
|
// When sync.remote is configured, Dolt remains the source of truth and JSONL
|
|
// import is skipped because upsert-only import cannot reconcile stale exports.
|
|
//
|
|
// Errors are logged as warnings but never block the merge/checkout. The
|
|
// import is upsert; running it on an unchanged JSONL is a no-op (bd
|
|
// import returns "Error 1105: nothing to commit", which we tolerate).
|
|
//
|
|
// JSONL ownership on this lane, the decision GH#6680's fix makes here: the
|
|
// *source file* follows the committing worktree (hookJSONLDir below), while
|
|
// the *store* it feeds stays beads.FindBeadsDir()'s — the primary checkout's,
|
|
// shared by every linked worktree. The asymmetry is deliberate. git has just
|
|
// rewritten this worktree's copy of the tracked JSONL, so that is the only
|
|
// copy describing the pull/merge/checkout being imported; the primary's copy
|
|
// is some other branch's state. The consequence is that a linked worktree on
|
|
// a feature branch can introduce that branch's rows into the shared store.
|
|
// That is forward-only, not a rollback: the import never deletes, and it
|
|
// rewrites an existing row only when updated_at is strictly newer — a guard
|
|
// auto-import paths cannot switch off, since --allow-stale is settable only
|
|
// on an explicit `bd import` (import_shared.go). Narrower still, the
|
|
// resolveSyncRemote check above confines the whole lane to legacy projects
|
|
// with no Dolt remote.
|
|
//
|
|
// See GH#3729.
|
|
func importJSONLForSync(reason string) {
|
|
if !config.GetBool("import.auto") {
|
|
return
|
|
}
|
|
if resolveSyncRemote() != "" {
|
|
debug.Logf("%s: skipping JSONL import because sync.remote is configured\n", reason)
|
|
return
|
|
}
|
|
|
|
beadsDir := beads.FindBeadsDir()
|
|
if beadsDir == "" {
|
|
return
|
|
}
|
|
|
|
fullPath := syncImportJSONLPath(hookJSONLDir(beadsDir))
|
|
|
|
if info, err := os.Stat(fullPath); err != nil || info.Size() == 0 {
|
|
return
|
|
}
|
|
|
|
debug.Logf("%s: importing JSONL from %s\n", reason, fullPath)
|
|
warnJSONLWithoutDoltRemote(reason + " JSONL import")
|
|
|
|
// Shell out to `bd import` — same pattern as exportJSONLForCommit,
|
|
// including BD_GIT_HOOK=1. No import path consults that variable, so
|
|
// clearing it suppressed nothing the import needs; all it did was let the
|
|
// subprocess's PersistentPostRun auto-export fire, and that export
|
|
// re-resolves its destination from beads.FindBeadsDir() — the *primary*
|
|
// checkout's JSONL. Harmless while this hook read the primary's copy too,
|
|
// but the source above is now the committing worktree's, so an unsuppressed
|
|
// post-run export would write one worktree's branch state over another
|
|
// checkout's tracked file: GH#6680's second symptom, from the fix for its
|
|
// first. Keeping the marker also suppresses the subprocess's auto-backup,
|
|
// matching the export lane (hookSubprocessEnv).
|
|
cmd := exec.Command("bd", "import", "--quiet", fullPath)
|
|
cmd.Dir = exportSubprocessDir(beadsDir)
|
|
cmd.Env = hookSubprocessEnv(os.Environ())
|
|
|
|
out, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
return
|
|
}
|
|
// Tolerate the no-op case: when JSONL matches Dolt exactly, bd import
|
|
// produces "nothing to commit" from the underlying Dolt commit. That
|
|
// is success for our purposes.
|
|
if strings.Contains(string(out), "nothing to commit") {
|
|
return
|
|
}
|
|
fmt.Fprintf(os.Stderr, "beads: %s import warning: %v\n%s", reason, err, out)
|
|
}
|
|
|
|
func warnJSONLWithoutDoltRemote(reason string) {
|
|
if config.GetBool("no-git-ops") || resolveSyncRemote() != "" || !isGitRepo() {
|
|
return
|
|
}
|
|
fmt.Fprintf(os.Stderr, "beads: %s warning: no Dolt remote configured.\n", reason)
|
|
fmt.Fprintln(os.Stderr, "beads: .beads/issues.jsonl is an export, not cross-machine sync or source of truth.")
|
|
if originURL, err := gitOriginGetURL(); err == nil && originURL != "" {
|
|
fmt.Fprintf(os.Stderr, "beads: repair: bd dolt remote add origin %s && bd dolt push\n", normalizeRemoteURL(originURL))
|
|
return
|
|
}
|
|
fmt.Fprintln(os.Stderr, "beads: repair: add a git origin, then run 'bd dolt remote add origin <git-remote-url>' and 'bd dolt push'.")
|
|
}
|
|
|
|
// filterEnv returns a copy of env with entries matching the given key removed.
|
|
func filterEnv(env []string, key string) []string {
|
|
return filterEnvForOS(env, key, hookEnvGOOS)
|
|
}
|
|
|
|
func filterEnvForOS(env []string, key, goos string) []string {
|
|
return execenv.WithoutForOS(env, goos, key)
|
|
}
|
|
|
|
// runPostMergeHook runs chained hooks after merge, then runs the legacy
|
|
// JSONL import fallback only when no Dolt remote is configured. See GH#3729.
|
|
//
|
|
// Returns 0 on success (or if not applicable).
|
|
//
|
|
//nolint:unparam // Always returns 0 by design - warnings don't block merges
|
|
func runPostMergeHook() int {
|
|
// Run chained hook first (if exists)
|
|
if exitCode := runChainedHook("post-merge", nil); exitCode != 0 {
|
|
return exitCode
|
|
}
|
|
importJSONLForSync("post-merge")
|
|
return 0
|
|
}
|
|
|
|
// runPrePushHook runs chained hooks before push.
|
|
// Returns 0 to allow push, non-zero to block.
|
|
func runPrePushHook(args []string) int {
|
|
// Run chained hook first (if exists)
|
|
if exitCode := runChainedHook("pre-push", args); exitCode != 0 {
|
|
return exitCode
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// runPostCheckoutHook runs chained hooks after branch checkout, then runs
|
|
// the legacy JSONL import fallback when the checkout was a branch switch
|
|
// (flag=1) and no Dolt remote is configured. File-mode checkouts (flag=0)
|
|
// are skipped to avoid spurious imports on `git checkout -- <file>`. See GH#3729.
|
|
//
|
|
// args: [previous-HEAD, new-HEAD, flag] where flag=1 for branch checkout
|
|
// Returns 0 on success (or if not applicable).
|
|
//
|
|
//nolint:unparam // Always returns 0 by design - warnings don't block checkouts
|
|
func runPostCheckoutHook(args []string) int {
|
|
// Run chained hook first (if exists)
|
|
if exitCode := runChainedHook("post-checkout", args); exitCode != 0 {
|
|
return exitCode
|
|
}
|
|
if len(args) >= 3 && args[2] == "1" {
|
|
importJSONLForSync("post-checkout")
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// runPrepareCommitMsgHook adds agent identity trailers to commit messages.
|
|
// args: [commit-msg-file, source, sha1]
|
|
// Returns 0 on success (or if not applicable), non-zero on error.
|
|
//
|
|
//nolint:unparam // Always returns 0 by design - we don't block commits
|
|
func runPrepareCommitMsgHook(args []string) int {
|
|
// Run chained hook first (if exists)
|
|
if exitCode := runChainedHook("prepare-commit-msg", args); exitCode != 0 {
|
|
return exitCode
|
|
}
|
|
|
|
if len(args) < 1 {
|
|
return 0 // No message file provided
|
|
}
|
|
|
|
msgFile := args[0]
|
|
source := ""
|
|
if len(args) >= 2 {
|
|
source = args[1]
|
|
}
|
|
|
|
// Skip for merge commits (they already have their own format)
|
|
if source == "merge" {
|
|
return 0
|
|
}
|
|
|
|
// Detect actor context from BD_ACTOR env var
|
|
actor := os.Getenv("BD_ACTOR")
|
|
if actor == "" {
|
|
return 0 // Not in agent context, nothing to add
|
|
}
|
|
|
|
// Read current message
|
|
content, err := os.ReadFile(msgFile) // #nosec G304 -- path from git
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not read commit message: %v\n", err)
|
|
return 0
|
|
}
|
|
|
|
// Check if trailer already present (avoid duplicates on amend)
|
|
for _, line := range strings.Split(string(content), "\n") {
|
|
if strings.HasPrefix(line, "Executed-By:") {
|
|
return 0
|
|
}
|
|
}
|
|
|
|
// Append Executed-By trailer
|
|
msg := strings.TrimRight(string(content), "\n\r\t ")
|
|
var sb strings.Builder
|
|
sb.WriteString(msg)
|
|
sb.WriteString("\n\n")
|
|
sb.WriteString(fmt.Sprintf("Executed-By: %s\n", actor))
|
|
|
|
// Write back
|
|
if err := os.WriteFile(msgFile, []byte(sb.String()), 0600); err != nil { // Restrict permissions per gosec G306
|
|
fmt.Fprintf(os.Stderr, "Warning: could not write commit message: %v\n", err)
|
|
}
|
|
|
|
return 0
|
|
}
|
|
|
|
// =============================================================================
|
|
// Hook Helper Functions
|
|
// =============================================================================
|
|
|
|
// isRebaseInProgress checks if a rebase is in progress.
|
|
func isRebaseInProgress() bool {
|
|
if _, err := os.Stat(".git/rebase-merge"); err == nil {
|
|
return true
|
|
}
|
|
if _, err := os.Stat(".git/rebase-apply"); err == nil {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
var hooksRunCmd = &cobra.Command{
|
|
Use: "run <hook-name> [args...]",
|
|
Short: "Execute a git hook (called by thin shims)",
|
|
Long: `Execute the logic for a git hook. This command is typically called by
|
|
thin shim scripts installed in .git/hooks/.
|
|
|
|
Supported hooks:
|
|
- pre-commit: Run chained hooks before commit
|
|
- post-merge: Run chained hooks after pull/merge
|
|
- pre-push: Run chained hooks before push
|
|
- post-checkout: Run chained hooks after branch checkout
|
|
- prepare-commit-msg: Add agent identity trailers for forensics
|
|
|
|
The thin shim keeps delegated hook logic in sync with the installed bd
|
|
version. Upgrading bd updates that delegated behavior. To adopt changes to the
|
|
shim's generated shell policy, refresh it with 'bd hooks install'.`,
|
|
Args: cobra.MinimumNArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("hooks-run")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
_ = os.Setenv("BD_GIT_HOOK", "1")
|
|
ui.DisableColors()
|
|
|
|
hookName := args[0]
|
|
hookArgs := args[1:]
|
|
|
|
var exitCode int
|
|
switch hookName {
|
|
case "pre-commit":
|
|
exitCode = runPreCommitHook()
|
|
case "post-merge":
|
|
exitCode = runPostMergeHook()
|
|
case "pre-push":
|
|
exitCode = runPrePushHook(hookArgs)
|
|
case "post-checkout":
|
|
exitCode = runPostCheckoutHook(hookArgs)
|
|
case "prepare-commit-msg":
|
|
exitCode = runPrepareCommitMsgHook(hookArgs)
|
|
default:
|
|
return HandleError("unknown hook: %s", hookName)
|
|
}
|
|
|
|
if exitCode != 0 {
|
|
return &exitError{Code: exitCode}
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
hooksInstallCmd.Flags().Bool("force", false, "No-op, kept for compatibility (section markers always preserve non-bd content)")
|
|
hooksInstallCmd.Flags().Bool("shared", false, "Install hooks to .beads-hooks/ (versioned) instead of .git/hooks/")
|
|
hooksInstallCmd.Flags().Bool("chain", false, "No-op, kept for compatibility (existing hook content always runs alongside the bd section)")
|
|
hooksInstallCmd.Flags().Bool("beads", false, "Install hooks to .beads/hooks/ (recommended for Dolt backend)")
|
|
|
|
hooksCmd.AddCommand(hooksInstallCmd)
|
|
hooksCmd.AddCommand(hooksUninstallCmd)
|
|
hooksCmd.AddCommand(hooksListCmd)
|
|
hooksCmd.AddCommand(hooksRunCmd)
|
|
|
|
rootCmd.AddCommand(hooksCmd)
|
|
}
|