* 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>
439 lines
14 KiB
Go
439 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/internal/git"
|
|
"github.com/steveyegge/beads/internal/gitenv"
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
domaingit "github.com/steveyegge/beads/internal/storage/domain/git"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
// runEmbeddedInitHooks uses the project for Git and the captured storage for hooks.
|
|
func runEmbeddedInitHooks(ctx context.Context, workDir, beadsDir string, skip, quiet bool) {
|
|
if skip {
|
|
return
|
|
}
|
|
gitUC := domain.NewGitUseCase(workDir, domaingit.NewInitGitRepository(workDir))
|
|
isColocated := gitUC.IsColocatedJJGit(ctx)
|
|
if gitUC.IsJujutsuRepo(ctx) && !isColocated {
|
|
if !quiet {
|
|
printJJAliasInstructions()
|
|
}
|
|
return
|
|
}
|
|
if !isColocated && !gitUC.IsGitRepo(ctx) {
|
|
return
|
|
}
|
|
hooks, err := resolveInitHooksContext(workDir, beadsDir)
|
|
if err != nil {
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "\n%s Failed to resolve git hooks: %v\n", ui.RenderWarn("⚠"), err)
|
|
}
|
|
return
|
|
}
|
|
hooksExist := hooks.installed()
|
|
if hooksExist && !hooks.needsUpdate() {
|
|
return
|
|
}
|
|
if hooksExist && !quiet {
|
|
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
|
}
|
|
if isColocated {
|
|
if err := installHooksWithContext(jjHookNames, false, false, false, false, hooks); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
|
fmt.Fprintf(os.Stderr, "You can try again with: %s\n\n", ui.RenderAccent("bd doctor --fix"))
|
|
} else if !quiet {
|
|
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
|
}
|
|
} else {
|
|
if err := installHooksWithContext(managedHookNames, false, false, false, true, hooks); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
|
fmt.Fprintf(os.Stderr, "You can try again with: %s\n\n", ui.RenderAccent("bd hooks install --beads"))
|
|
} else if !quiet {
|
|
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
|
}
|
|
}
|
|
}
|
|
|
|
// preCommitFrameworkPattern matches pre-commit or prek framework hooks.
|
|
// Uses same patterns as hookManagerPatterns in doctor/fix/hooks.go for consistency.
|
|
// Includes all detection patterns: pre-commit run, prek run/hook-impl, config file refs, and pre-commit env vars.
|
|
var preCommitFrameworkPattern = regexp.MustCompile(`(?i)(pre-commit\s+run|prek\s+run|prek\s+hook-impl|\.pre-commit-config|INSTALL_PYTHON|PRE_COMMIT)`)
|
|
|
|
// hooksInstalled checks if bd git hooks are installed
|
|
func hooksInstalled() bool {
|
|
hooksDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return hooksInstalledAt(hooksDir)
|
|
}
|
|
|
|
func hooksInstalledAt(hooksDir string) bool {
|
|
preCommit := filepath.Join(hooksDir, "pre-commit")
|
|
postMerge := filepath.Join(hooksDir, "post-merge")
|
|
|
|
// Check if both hooks exist
|
|
_, err1 := os.Stat(preCommit)
|
|
_, err2 := os.Stat(postMerge)
|
|
|
|
if err1 != nil || err2 != nil {
|
|
return false
|
|
}
|
|
|
|
// Verify they're bd hooks by checking for signature comment or section marker
|
|
// #nosec G304 - controlled path from git directory
|
|
preCommitContent, err := os.ReadFile(preCommit)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
preCommitStr := string(preCommitContent)
|
|
if !strings.Contains(preCommitStr, "bd (beads) pre-commit hook") &&
|
|
!strings.Contains(preCommitStr, hookSectionBeginPrefix) {
|
|
return false
|
|
}
|
|
|
|
// #nosec G304 - controlled path from git directory
|
|
postMergeContent, err := os.ReadFile(postMerge)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
postMergeStr := string(postMergeContent)
|
|
if !strings.Contains(postMergeStr, "bd (beads) post-merge hook") &&
|
|
!strings.Contains(postMergeStr, hookSectionBeginPrefix) {
|
|
return false
|
|
}
|
|
|
|
// Verify hooks are executable
|
|
preCommitInfo, err := os.Stat(preCommit)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if preCommitInfo.Mode().Perm()&0111 == 0 {
|
|
return false // Not executable
|
|
}
|
|
|
|
postMergeInfo, err := os.Stat(postMerge)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if postMergeInfo.Mode().Perm()&0111 == 0 {
|
|
return false // Not executable
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// hooksNeedUpdate checks if installed bd hooks are outdated and need updating.
|
|
// Delegates to CheckGitHooks() which handles version comparison, shim detection,
|
|
// and inline hook detection consistently.
|
|
func hooksNeedUpdate() bool {
|
|
return hookStatusesNeedUpdate(CheckGitHooks())
|
|
}
|
|
|
|
func hookStatusesNeedUpdate(statuses []HookStatus) bool {
|
|
for _, s := range statuses {
|
|
if s.Outdated {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// hookInfo contains information about an existing hook
|
|
type hookInfo struct {
|
|
name string
|
|
path string
|
|
exists bool
|
|
isBdHook bool
|
|
isPreCommitFramework bool // true for pre-commit or prek
|
|
content string
|
|
}
|
|
|
|
// detectExistingHooks scans for existing git hooks
|
|
func detectExistingHooks() []hookInfo {
|
|
hooksDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
hooks := []hookInfo{
|
|
{name: "pre-commit", path: filepath.Join(hooksDir, "pre-commit")},
|
|
{name: "post-merge", path: filepath.Join(hooksDir, "post-merge")},
|
|
{name: "pre-push", path: filepath.Join(hooksDir, "pre-push")},
|
|
}
|
|
|
|
for i := range hooks {
|
|
content, err := os.ReadFile(hooks[i].path)
|
|
if err == nil {
|
|
hooks[i].exists = true
|
|
hooks[i].content = string(content)
|
|
hooks[i].isBdHook = strings.Contains(hooks[i].content, "bd (beads)") ||
|
|
strings.Contains(hooks[i].content, hookSectionBeginPrefix)
|
|
// Only detect pre-commit/prek framework if not a bd hook
|
|
// Use regex for consistency with DetectActiveHookManager patterns
|
|
if !hooks[i].isBdHook {
|
|
hooks[i].isPreCommitFramework = preCommitFrameworkPattern.MatchString(hooks[i].content)
|
|
}
|
|
}
|
|
}
|
|
|
|
return hooks
|
|
}
|
|
|
|
// installGitHooks installs git hooks inline (no external dependencies)
|
|
func installGitHooks() error {
|
|
hooksDir, err := git.GetGitHooksDir()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Ensure hooks directory exists
|
|
if err := os.MkdirAll(hooksDir, 0750); err != nil {
|
|
return fmt.Errorf("failed to create hooks directory: %w", err)
|
|
}
|
|
|
|
// Detect existing hooks
|
|
existingHooks := detectExistingHooks()
|
|
|
|
// Check if any non-bd hooks exist
|
|
hasExistingHooks := false
|
|
for _, hook := range existingHooks {
|
|
if hook.exists && !hook.isBdHook {
|
|
hasExistingHooks = true
|
|
break
|
|
}
|
|
}
|
|
|
|
// Default to chaining with existing hooks (no prompting)
|
|
chainHooks := hasExistingHooks
|
|
if chainHooks {
|
|
// Chain mode - rename existing hooks to .old so they can be called
|
|
for _, hook := range existingHooks {
|
|
if hook.exists && !hook.isBdHook {
|
|
oldPath := hook.path + ".old"
|
|
if err := os.Rename(hook.path, oldPath); err != nil {
|
|
fmt.Fprintf(os.Stderr, "%s Failed to chain with existing %s hook: %v\n", ui.RenderWarn("⚠"), hook.name, err)
|
|
if usesSQLServer() {
|
|
fmt.Fprintf(os.Stderr, "You can resolve this with: %s\n", ui.RenderAccent("bd doctor --fix"))
|
|
}
|
|
continue
|
|
}
|
|
fmt.Printf(" Chained with existing %s hook\n", hook.name)
|
|
}
|
|
}
|
|
}
|
|
|
|
// pre-commit hook
|
|
preCommitPath := filepath.Join(hooksDir, "pre-commit")
|
|
preCommitContent := buildPreCommitHook(chainHooks, existingHooks)
|
|
|
|
// post-merge hook
|
|
postMergePath := filepath.Join(hooksDir, "post-merge")
|
|
postMergeContent := buildPostMergeHook(chainHooks, existingHooks)
|
|
|
|
// Normalize line endings to LF — on Windows/NTFS, Go string literals
|
|
// are fine but concatenated content from other sources may have CRLF.
|
|
// Git hooks with CRLF fail: /usr/bin/env: 'sh\r': No such file or directory
|
|
preCommitContent = strings.ReplaceAll(preCommitContent, "\r\n", "\n")
|
|
postMergeContent = strings.ReplaceAll(postMergeContent, "\r\n", "\n")
|
|
|
|
// Write pre-commit hook (executable scripts need 0700)
|
|
// #nosec G306 - git hooks must be executable
|
|
if err := os.WriteFile(preCommitPath, []byte(preCommitContent), 0700); err != nil {
|
|
return fmt.Errorf("failed to write pre-commit hook: %w", err)
|
|
}
|
|
|
|
// Write post-merge hook (executable scripts need 0700)
|
|
// #nosec G306 - git hooks must be executable
|
|
if err := os.WriteFile(postMergePath, []byte(postMergeContent), 0700); err != nil {
|
|
return fmt.Errorf("failed to write post-merge hook: %w", err)
|
|
}
|
|
|
|
if chainHooks {
|
|
fmt.Printf("%s Chained bd hooks with existing hooks\n", ui.RenderPass("✓"))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// buildPreCommitHook generates the pre-commit hook content using section markers (GH#1380).
|
|
// If chainHooks is true, chained hooks (.old) are called before the beads section.
|
|
func buildPreCommitHook(chainHooks bool, existingHooks []hookInfo) string {
|
|
section := generateHookSection("pre-commit")
|
|
|
|
if chainHooks {
|
|
var existingPreCommit string
|
|
for _, hook := range existingHooks {
|
|
if hook.name == "pre-commit" && hook.exists && !hook.isBdHook {
|
|
existingPreCommit = hook.path + ".old"
|
|
break
|
|
}
|
|
}
|
|
|
|
return "#!/bin/sh\n" +
|
|
"# Run existing hook first\n" +
|
|
"if [ -x \"" + existingPreCommit + "\" ]; then\n" +
|
|
" \"" + existingPreCommit + "\" \"$@\"\n" +
|
|
" EXIT_CODE=$?\n" +
|
|
" if [ $EXIT_CODE -ne 0 ]; then\n" +
|
|
" exit $EXIT_CODE\n" +
|
|
" fi\n" +
|
|
"fi\n\n" +
|
|
section
|
|
}
|
|
|
|
return "#!/bin/sh\n" + section
|
|
}
|
|
|
|
// buildPostMergeHook generates the post-merge hook content using section markers (GH#1380).
|
|
func buildPostMergeHook(chainHooks bool, existingHooks []hookInfo) string {
|
|
section := generateHookSection("post-merge")
|
|
|
|
if chainHooks {
|
|
var existingPostMerge string
|
|
for _, hook := range existingHooks {
|
|
if hook.name == "post-merge" && hook.exists && !hook.isBdHook {
|
|
existingPostMerge = hook.path + ".old"
|
|
break
|
|
}
|
|
}
|
|
|
|
return "#!/bin/sh\n" +
|
|
"# Run existing hook first\n" +
|
|
"if [ -x \"" + existingPostMerge + "\" ]; then\n" +
|
|
" \"" + existingPostMerge + "\" \"$@\"\n" +
|
|
" EXIT_CODE=$?\n" +
|
|
" if [ $EXIT_CODE -ne 0 ]; then\n" +
|
|
" exit $EXIT_CODE\n" +
|
|
" fi\n" +
|
|
"fi\n\n" +
|
|
section
|
|
}
|
|
|
|
return "#!/bin/sh\n" + section
|
|
}
|
|
|
|
// jjHookNames is the shared inventory for standalone and selected init adapters.
|
|
var jjHookNames = []string{"pre-commit", "post-merge"}
|
|
|
|
// installJJHooks installs marker-managed hooks for colocated jujutsu+git repos.
|
|
// This path intentionally avoids .old sidecar chaining and uses the same section
|
|
// injection behavior as regular hook installs.
|
|
func installJJHooks() error {
|
|
return installHooksWithOptions(jjHookNames, false, false, false, false)
|
|
}
|
|
|
|
// buildJJPreCommitHook generates the pre-commit hook for jujutsu repos using section markers (GH#1380).
|
|
func buildJJPreCommitHook(chainHooks bool, existingHooks []hookInfo) string {
|
|
// jj uses the same shim as git — bd hooks run handles the differences internally
|
|
section := generateHookSection("pre-commit")
|
|
|
|
if chainHooks {
|
|
var existingPreCommit string
|
|
for _, hook := range existingHooks {
|
|
if hook.name == "pre-commit" && hook.exists && !hook.isBdHook {
|
|
existingPreCommit = hook.path + ".old"
|
|
break
|
|
}
|
|
}
|
|
|
|
return "#!/bin/sh\n" +
|
|
"# Run existing hook first\n" +
|
|
"if [ -x \"" + existingPreCommit + "\" ]; then\n" +
|
|
" \"" + existingPreCommit + "\" \"$@\"\n" +
|
|
" EXIT_CODE=$?\n" +
|
|
" if [ $EXIT_CODE -ne 0 ]; then\n" +
|
|
" exit $EXIT_CODE\n" +
|
|
" fi\n" +
|
|
"fi\n\n" +
|
|
section
|
|
}
|
|
|
|
return "#!/bin/sh\n" + section
|
|
}
|
|
|
|
// printJJAliasInstructions prints setup instructions for pure jujutsu repos.
|
|
// Since jj doesn't have native hooks yet, users need to set up aliases.
|
|
func printJJAliasInstructions() {
|
|
fmt.Printf("\n%s Jujutsu repository detected (not colocated with git)\n\n", ui.RenderWarn("⚠"))
|
|
fmt.Printf("Jujutsu doesn't support hooks yet. To auto-export beads on push,\n")
|
|
fmt.Printf("add this alias to your jj config (~/.config/jj/config.toml):\n\n")
|
|
fmt.Printf(" %s\n", ui.RenderAccent("[aliases]"))
|
|
fmt.Printf(" %s\n", ui.RenderAccent(`push = ["util", "exec", "--", "sh", "-c", "bd dolt commit && bd dolt push && jj git push \"$@\"", ""]`))
|
|
fmt.Printf("\nThen use %s instead of %s\n\n", ui.RenderAccent("jj push"), ui.RenderAccent("jj git push"))
|
|
fmt.Printf("For more details, see: https://github.com/gastownhall/beads/blob/main/docs/reference/git-integration.md#branchless-workflows-jujutsu--jj\n\n")
|
|
}
|
|
|
|
// initHooksContext keeps the selected Git project separate from Beads storage.
|
|
// Its paths and both environments are captured once; tracking fallback supplies
|
|
// refusal evidence only, never a destination for writing hooks or configuration.
|
|
type initHooksContext struct {
|
|
workDir, beadsDir string
|
|
paths git.HooksContext
|
|
env, inheritedEnv []string
|
|
}
|
|
|
|
func resolveInitHooksContext(workDir, beadsDir string) (*initHooksContext, error) {
|
|
workDir, err := filepath.Abs(workDir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inherited := os.Environ()
|
|
env := gitenv.ScrubRouting(inherited)
|
|
paths, err := git.ResolveHooksContext(workDir, env)
|
|
if err != nil {
|
|
// A repository whose work tree does not resolve -- a bare repository, or
|
|
// a directory such as <repo>/.git that Git answers from -- has no work
|
|
// tree to anchor, but it does have a hooks directory, and bd installed
|
|
// into it before this resolver existed. Resolving that shape here keeps
|
|
// the selected, scrubbed context instead of turning a supported
|
|
// repository into a warning and no install at all. Any other failure is
|
|
// still a failure: the work-tree-less resolver rejects non-repositories
|
|
// and directories inside a work tree.
|
|
workTreeless, workTreelessErr := git.ResolveWorkTreelessHooksContext(workDir, env)
|
|
if workTreelessErr != nil {
|
|
return nil, err
|
|
}
|
|
paths = workTreeless
|
|
}
|
|
if beadsDir != "" && !filepath.IsAbs(beadsDir) {
|
|
beadsDir = filepath.Join(workDir, beadsDir)
|
|
}
|
|
return &initHooksContext{workDir: workDir, beadsDir: beadsDir, paths: paths, env: env, inheritedEnv: inherited}, nil
|
|
}
|
|
|
|
func (c *initHooksContext) installed() bool {
|
|
if c == nil {
|
|
return hooksInstalled()
|
|
}
|
|
return hooksInstalledAt(c.paths.HooksDir)
|
|
}
|
|
|
|
func (c *initHooksContext) needsUpdate() bool {
|
|
if c == nil {
|
|
return hooksNeedUpdate()
|
|
}
|
|
return hookStatusesNeedUpdate(checkGitHooksAt(c.paths.HooksDir))
|
|
}
|
|
|
|
func (c *initHooksContext) configureHooksPath(hooksDir string) error {
|
|
// #nosec G702 -- no shell is involved: the binary is the literal "git" and
|
|
// every path is passed as its own argv element, so neither c.paths.CommonDir
|
|
// nor hooksDir can inject a command. Both reach here from the selected hooks
|
|
// context and are absolute, and this mirrors the pre-existing
|
|
// configureBeadsHooksPath in hooks.go.
|
|
cmd := exec.Command("git", "--git-dir", c.paths.CommonDir, "config", "--local", "core.hooksPath", hooksDir)
|
|
cmd.Dir, cmd.Env = c.workDir, c.env
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
return fmt.Errorf("git config failed: %w (output: %s)", err, string(output))
|
|
}
|
|
return nil
|
|
}
|