fix(hooks): identify the index context behind tracked-file refusals (#6457)
* 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(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 * Identify the Git index behind tracked-hook refusals (saa-cgh.120.13) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(review): repair work-tree-less hook install and the fail-open secret guard Maintainer adoption-review fixes for #6457 (iterations 1 and 2). Blocking: - cmd/bd, internal/git: `bd init` in a repository with no work tree stopped installing hooks and printed "Failed to resolve git hooks". git.ResolveHooksContext requires a work tree and deliberately errors without one, so routing the selected-init path through it lost a capability base had via beads.FindBeadsDir(). Add git.ResolveWorkTreelessHooksContext as the explicit counterpart (empty RepoRoot/MainRepoRoot, relative core.hooksPath anchored to the common directory) and fall back to it, so the install keeps the selected, scrubbed context rather than the inherited one. It keys on "the common directory resolved but the work tree did not", so it covers a bare repository and a cwd inside a repository's own .git alike, and still refuses non-repositories and directories inside a work tree. The `bare` and `git_dir_cwd` rows in the hooks table test pin both shapes and assert the install lands in the selected storage and configures the selected repository. - internal/config: isGitTracked scrubbed Git routing with no fallback, so in a checkout reachable only through legitimate GIT_DIR/GIT_WORK_TREE routing the probe found no repository at all, the guard concluded "untracked", and `bd config set <secret-key>` wrote the credential into a git-tracked config.yaml where base refused. Give it the same two-probe shape as hooks.gitTrackedFileContextWithEnv, with a legitimate-routing test. - internal/config, internal/gitenv, docs: state the GIT_CEILING_DIRECTORIES widening plainly rather than pairing it with a containment clause that is false at every live call site. `-C`/cmd.Dir fixes where discovery starts, not where it stops, so with the ceiling scrubbed the walk can reach a containing repository above cwd; all three gitDirsForRepo call sites pass the process working directory, which need not be a repository root. This mirrors the wording init_proxied_server.go already had, so the tree no longer holds contradictory statements about the same primitive. - cmd/bd/config.go: the policy comment claimed all role commands ignore inherited Git routing. Name the scrubbed paths without asserting a closed set -- `bd config set/get/unset/set-many beads.role`, and the proxied-init role tail, which goes through domain.GitUseCase.BeadsRole/SetBeadsRole and is scrubbed on both of that repository's constructor arms -- and say that a path which does not scrub still goes through the inherited environment: such readers include internal/routing.roleFromGitConfig, RepoContext.Role, doctor.CheckBeadsRole, `bd config show` and init.getBeadsRole; such writers include init.setBeadsRole, `bd init --contributor` and `bd hooks --uninstall`. The earlier wording framed the exception as role *resolution* only, which reads as isolating the write plane when it is not isolated; a quantifier over "every other" reader and writer goes stale in the opposite direction, since set-many and the proxied-init tail are scrubbed, so neither list is exhaustive here. Non-blocking: - Scope the worktrees.md paragraph to the one startup probe that is scrubbed. - Replace normalizeWorktreeGitEnvKey's ToUpper fold with execenv.KeyEqualForOS so one subprocess key identity survives the PR. - Compare beads.role against domain.BeadsRoleConfigKey with strings.ToLower rather than strings.EqualFold, matching execenv.keyIdentityForWindows and git's ASCII-only key folding, and pin it with Beads.Role/BEADS.ROLE rows through GetConfig/SetConfig. - Share the HooksContext workDir anchoring and symlink/case normalization between both resolvers, so no producer of that type emits a spelling the others do not. - Branch the tracked-hook remediation hint on the proof label, so the inherited case points at the routing rather than at `git rm --cached`. - Restore the hook-status gate on the pure-JJ alias hint (base parity). - Note that the boolean tracked-file wrappers are test-only. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(review): reconcile the beads.role scrub with base #6477 on the refreshed base Refreshing onto main511849496pulled incf683435e(#6477), which makes domain/git GetConfig propagate Git's exit error instead of mapping every *exec.ExitError to absence. That collides with this stack's beads.role scrub in both directions, and neither lane's CI could see it: the PR lane builds against a base where #6477's test does not exist, and main's lane never has the PR. Only the merged tree fails (each half passes on its own side alone). The test half is taken byte-identically from stack parent #6464, which already pushed this resolution against the same base commit (head0fe936944). Both PRs target main with every parent still open, so a divergent-but-equivalent fix here would collide in the same file when the stack lands; copying theirs means the two auto-merge. Re-validated and re-mutation-proven here rather than assumed: - TestConfig_ReadFailuresAreNotMissing drops its "invalid_routing_boolean" row, whose poisoned GIT_CONFIG_NOSYSTEM can no longer reach git for beads.role (IsRoutingKeyForOS scrubs the whole GIT_CONFIG* prefix for that key), and gains TestConfig_BeadsRoleScrubsInheritedRoutingEnv, which pins both halves: the role key ignores the poison, and a key outside the scrub (user.name) still surfaces it as exit 128 rather than as an absent key. #6477's read-failure contract for beads.role itself is untouched, still proved by malformed_config through the repository's own config file. - TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted require.NoError with the comment "The existing reader maps Git exit errors to absence" -- the premise #6477 deleted. It now requires the exit-128 error, which is itself the proof that the generic constructor read the *current* caller environment: only that environment can see the planted .gitconfig. Mutation proofs at this head: deleting the beads.role carve-out reds TestConfig_BeadsRoleScrubsInheritedRoutingEnv; reverting #6477's classification reds both that test and captured_home. So neither retargeted fixture is vacuous. Also silence two gosec G702 findings that only appear with this branch present. Unscoped `make ci-pr-lint` at CI's v2.10.1 pin scores 0 on the old base and 0 on current main, 1 on the pre-refresh adopted head (cmd/bd/worktree.go:22) and 2 on the refreshed head (+ cmd/bd/hooks.go:1823). pr.yml scopes golangci-lint to the PR's own diff so it can never report them, but main.yml deliberately sweeps the whole tree, so they would red main's Lint job on the first push after merge. Production reachability is identical on all three trees, so this is taint widening rather than a new call path. Both sinks run a fixed "git" binary with constant subcommands, matching the justification at init_stealth.go:84. cmd/bd/worktree.go is the only file this adds beyond the branch's own 50; #6464 does not touch it, so the annotation cannot collide with the parent either. --------- 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>
This commit is contained in:
parent
cefcabb1e3
commit
6a4b4aa14e
16 changed files with 861 additions and 98 deletions
|
|
@ -1,6 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/cmd/bd/doctor"
|
||||
"github.com/steveyegge/beads/cmd/bd/setup"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
|
|
@ -46,3 +48,29 @@ func newInitFileSystemAdapters(workDir string) domain.BeadsDirFSAdapters {
|
|||
}
|
||||
return adapters
|
||||
}
|
||||
|
||||
// withInitHooks scopes only hook operations; exclude and the other supplied
|
||||
// callbacks keep their existing provider. Empty paths retain isolated callers.
|
||||
func withInitHooks(fs domain.BeadsDirFSUseCase, workDir, beadsDir string) (domain.BeadsDirFSUseCase, *initHooksContext, error) {
|
||||
if workDir == "" {
|
||||
return fs, nil, nil
|
||||
}
|
||||
hooks, err := resolveInitHooksContext(workDir, beadsDir)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return initHooksFileSystem{BeadsDirFSUseCase: fs, hooks: hooks}, hooks, nil
|
||||
}
|
||||
|
||||
type initHooksFileSystem struct {
|
||||
domain.BeadsDirFSUseCase
|
||||
hooks *initHooksContext
|
||||
}
|
||||
|
||||
func (fs initHooksFileSystem) InstallGitHooks(_ context.Context, p domain.HooksInstallParams) error {
|
||||
return installHooksWithContext(p.HookNames, p.Force, p.Shared, p.Chain, p.BeadsHooks, fs.hooks)
|
||||
}
|
||||
|
||||
func (fs initHooksFileSystem) InstallJJHooks(_ context.Context) error {
|
||||
return installHooksWithContext(jjHookNames, false, false, false, false, fs.hooks)
|
||||
}
|
||||
|
|
|
|||
143
cmd/bd/hooks.go
143
cmd/bd/hooks.go
|
|
@ -516,20 +516,21 @@ type HookStatus struct {
|
|||
|
||||
// CheckGitHooks checks the status of bd git hooks in .git/hooks/
|
||||
func CheckGitHooks() []HookStatus {
|
||||
hooks := []string{"pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"}
|
||||
statuses := make([]HookStatus, 0, len(hooks))
|
||||
|
||||
// Get hooks directory from common git dir (hooks are shared across worktrees)
|
||||
hooksDir, err := git.GetGitHooksDir()
|
||||
if err != nil {
|
||||
// Not a git repo - return all hooks as not installed
|
||||
for _, hookName := range hooks {
|
||||
statuses := make([]HookStatus, 0, len(managedHookNames))
|
||||
for _, hookName := range managedHookNames {
|
||||
statuses = append(statuses, HookStatus{Name: hookName, Installed: false})
|
||||
}
|
||||
return statuses
|
||||
}
|
||||
return checkGitHooksAt(hooksDir)
|
||||
}
|
||||
|
||||
for _, hookName := range hooks {
|
||||
func checkGitHooksAt(hooksDir string) []HookStatus {
|
||||
statuses := make([]HookStatus, 0, len(managedHookNames))
|
||||
for _, hookName := range managedHookNames {
|
||||
status := HookStatus{
|
||||
Name: hookName,
|
||||
}
|
||||
|
|
@ -818,6 +819,10 @@ var hooksListCmd = &cobra.Command{
|
|||
// 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) {
|
||||
|
|
@ -841,8 +846,16 @@ func guardHookWritePath(hookPath string, allowTracked bool) error {
|
|||
// 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 isGitTrackedFile(hookPath) && !isBdOwnedHookFile(hookPath) {
|
||||
return fmt.Errorf("%s is tracked by git and not a bd-managed hook; bd will not modify committed files it does not own\nUntrack it (git rm --cached) or move hooks to an untracked directory and re-run", hookPath)
|
||||
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
|
||||
}
|
||||
|
|
@ -861,39 +874,86 @@ func isBdOwnedHookFile(path string) bool {
|
|||
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)
|
||||
inherited := os.Environ()
|
||||
// Check the containing repository first so inherited routing cannot hide a
|
||||
// tracked hook. The fallback preserves bare work trees and trusted config.
|
||||
// Exit 1 is git's "repository reached, path is not tracked" answer and is
|
||||
// final, so the second probe runs only when the scrubbed environment failed
|
||||
// for a configuration reason (no reachable repository) rather than spawning
|
||||
// a second `git ls-files` on every ordinary miss.
|
||||
for _, env := range [][]string{gitenv.ScrubRouting(inherited), inherited} {
|
||||
// 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 {
|
||||
return true
|
||||
if index == 0 {
|
||||
return trackedProofContainingIndex
|
||||
}
|
||||
return trackedProofInheritedIndex
|
||||
}
|
||||
if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 1 {
|
||||
return false
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return false
|
||||
return ""
|
||||
}
|
||||
|
||||
func installHooksWithOptions(hookNames []string, force bool, shared bool, chain bool, beadsHooks bool) error {
|
||||
return installHooksWithContext(hookNames, force, shared, chain, beadsHooks, nil)
|
||||
}
|
||||
|
||||
//nolint:unparam // force and chain kept for CLI flag compatibility; section markers make them no-ops
|
||||
func installHooksWithOptions(hookNames []string, force bool, shared bool, chain bool, beadsHooks bool) error {
|
||||
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")
|
||||
}
|
||||
var hooksDir string
|
||||
if beadsHooks {
|
||||
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 beadsHooks {
|
||||
// Use .beads/hooks/ directory (preferred for Dolt backend)
|
||||
beadsDir := beads.FindBeadsDir()
|
||||
if beadsDir == "" {
|
||||
|
|
@ -932,13 +992,23 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain
|
|||
// 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 {
|
||||
preservePreexistingHooks(hooksDir)
|
||||
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 := guardHookWritePath(filepath.Join(hooksDir, hookName), shared); err != nil {
|
||||
if err := guardHookWritePathWithProbe(filepath.Join(hooksDir, hookName), shared, tracked); err != nil {
|
||||
return fmt.Errorf("refusing to install %s hook: %w", hookName, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1001,8 +1071,12 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain
|
|||
}
|
||||
}
|
||||
|
||||
// Configure git to use the hooks directory
|
||||
if beadsHooks {
|
||||
// Configure git to use the hooks directory after writing, as in ordinary installs.
|
||||
if selected != nil && beadsHooks {
|
||||
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)
|
||||
}
|
||||
|
|
@ -1026,6 +1100,16 @@ func preservePreexistingHooks(targetDir string) {
|
|||
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 {
|
||||
|
|
@ -1037,19 +1121,16 @@ func preservePreexistingHooks(targetDir string) {
|
|||
}
|
||||
|
||||
// If the current dir is already our target, this is a re-install — skip.
|
||||
if absTarget == absCurrent {
|
||||
if utils.PathsEqual(absTarget, absCurrent) {
|
||||
return
|
||||
}
|
||||
|
||||
// If current dir is already a beads-managed directory, skip.
|
||||
repoRoot, _ := git.GetMainRepoRoot()
|
||||
if repoRoot == "" {
|
||||
repoRoot = git.GetRepoRoot()
|
||||
}
|
||||
repoRoot := mainRoot()
|
||||
if repoRoot != "" {
|
||||
absBeadsHooks, _ := filepath.Abs(filepath.Join(repoRoot, ".beads", "hooks"))
|
||||
absSharedHooks, _ := filepath.Abs(filepath.Join(repoRoot, ".beads-hooks"))
|
||||
if absCurrent == absBeadsHooks || absCurrent == absSharedHooks {
|
||||
if utils.PathsEqual(absCurrent, absBeadsHooks) || utils.PathsEqual(absCurrent, absSharedHooks) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
@ -1789,6 +1870,8 @@ 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.
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/gitenv"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) {
|
||||
|
|
@ -51,6 +53,7 @@ func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) {
|
|||
name string
|
||||
env map[string]string
|
||||
}{
|
||||
{"both", map[string]string{"GIT_DIR": filepath.Join(target, ".git"), "GIT_WORK_TREE": target}},
|
||||
{"repository", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git")}},
|
||||
{"worktree", map[string]string{"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy}},
|
||||
{"index", map[string]string{"GIT_INDEX_FILE": filepath.Join(decoy, ".git", "index")}},
|
||||
|
|
@ -60,9 +63,16 @@ func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) {
|
|||
for key, value := range tc.env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
if tc.name == "both" {
|
||||
probe := exec.Command("git", "-C", hooksDir, "ls-files", "--error-unmatch", "--", "pre-commit")
|
||||
out, err := probe.CombinedOutput()
|
||||
require.NoError(t, err, "inherited index must also prove tracking: %s", out)
|
||||
}
|
||||
if !isGitTrackedFile(foreign) {
|
||||
t.Error("inherited routing hid the tracked hook")
|
||||
}
|
||||
require.Equal(t, "containing repository index", gitTrackedFileContext(foreign), "clean proof takes precedence, including when both views track it")
|
||||
require.ErrorContains(t, guardHookWritePath(foreign, false), "tracked by git (containing repository index)")
|
||||
if err := guardHookWritePath(foreign, false); err == nil || !strings.Contains(err.Error(), "tracked by git") {
|
||||
t.Errorf("expected tracked-file refusal, got %v", err)
|
||||
}
|
||||
|
|
@ -78,6 +88,7 @@ func TestGuardHookWritePathIgnoresInheritedGitRouting(t *testing.T) {
|
|||
if isGitTrackedFile(untracked) {
|
||||
t.Error("untracked hook reported as tracked")
|
||||
}
|
||||
require.Empty(t, gitTrackedFileContext(untracked))
|
||||
if err := guardHookWritePath(untracked, false); err != nil {
|
||||
t.Errorf("untracked hook refused: %v", err)
|
||||
}
|
||||
|
|
@ -469,3 +480,81 @@ func TestGuardHookWritePathAllowsFileWhenGitUnavailable(t *testing.T) {
|
|||
t.Fatalf("both tracking errors must retain the untracked policy: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitHooksContextGuardPreservesOwnership(t *testing.T) {
|
||||
for _, name := range []string{"tracked", "bd_owned", "symlink", "captured_fallback"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
selected, _, _, _ := newInitHooksFixture(t)
|
||||
storage := filepath.Join(selected, "local-storage")
|
||||
hooksDir := filepath.Join(storage, "hooks")
|
||||
if name == "captured_fallback" {
|
||||
storage = t.TempDir()
|
||||
hooksDir = filepath.Join(storage, "hooks")
|
||||
}
|
||||
require.NoError(t, os.MkdirAll(hooksDir, 0755))
|
||||
hook := filepath.Join(hooksDir, "pre-commit")
|
||||
content := "#!/bin/sh\necho foreign\n"
|
||||
if name == "bd_owned" {
|
||||
content = "#!/bin/sh\n" + generateHookSection("pre-commit")
|
||||
}
|
||||
if name == "symlink" {
|
||||
target := filepath.Join(t.TempDir(), "foreign hook")
|
||||
require.NoError(t, os.WriteFile(target, []byte(content), 0755))
|
||||
if err := os.Symlink(target, hook); err != nil {
|
||||
t.Skipf("symlink capability unavailable: %v", err)
|
||||
}
|
||||
} else {
|
||||
require.NoError(t, os.WriteFile(hook, []byte(content), 0755))
|
||||
if name == "captured_fallback" {
|
||||
bare := t.TempDir()
|
||||
initExcludeGit(t, bare, "init", "--bare", "--quiet")
|
||||
initExcludeGit(t, storage, "--git-dir", bare, "--work-tree", storage, "add", "hooks/pre-commit")
|
||||
t.Setenv("GIT_DIR", bare)
|
||||
t.Setenv("GIT_WORK_TREE", storage)
|
||||
t.Setenv("GIT_INDEX_FILE", filepath.Join(bare, "index"))
|
||||
} else {
|
||||
initExcludeGit(t, selected, "add", "--force", "--", hook)
|
||||
}
|
||||
}
|
||||
fs, hooks, err := withInitHooks(nil, selected, storage)
|
||||
require.NoError(t, err)
|
||||
if name == "captured_fallback" {
|
||||
require.False(t, isGitTrackedFileWithEnv(hook, hooks.env, hooks.env), "clean view must not supply the proof")
|
||||
require.True(t, isGitTrackedFileWithEnv(hook, hooks.env, hooks.inheritedEnv), "inherited view must prove tracking")
|
||||
}
|
||||
t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), "missing"))
|
||||
err = fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true})
|
||||
if name == "bd_owned" {
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(readInitHooksFile(t, hook)), hookSectionBeginPrefix)
|
||||
} else {
|
||||
want := "tracked by git"
|
||||
if name == "symlink" {
|
||||
want = "symlink"
|
||||
}
|
||||
require.ErrorContains(t, err, want)
|
||||
if name == "captured_fallback" {
|
||||
require.ErrorContains(t, err, "tracked by git (inherited Git index)")
|
||||
// The remediation follows the proof: `git rm --cached` from the
|
||||
// operator's shell aims at whichever index that shell routes to,
|
||||
// so the inherited case has to name clearing the routing instead.
|
||||
require.ErrorContains(t, err, "Clear the inherited Git routing environment and re-run")
|
||||
for _, entry := range hooks.inheritedEnv {
|
||||
if strings.HasPrefix(entry, "GIT_DIR=") {
|
||||
require.NotContains(t, err.Error(), strings.TrimPrefix(entry, "GIT_DIR="))
|
||||
}
|
||||
}
|
||||
} else if name == "tracked" {
|
||||
require.ErrorContains(t, err, "tracked by git (containing repository index)")
|
||||
require.ErrorContains(t, err, "Untrack it (git rm --cached) or move hooks to an untracked directory")
|
||||
require.NotContains(t, err.Error(), "Clear the inherited Git routing environment")
|
||||
}
|
||||
require.Equal(t, content, string(readInitHooksFile(t, hook)))
|
||||
for _, other := range []string{"post-merge", "pre-commit.backup"} {
|
||||
_, err := os.Lstat(filepath.Join(hooksDir, other))
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,10 +4,13 @@ import (
|
|||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConfigureBeadsHooksPath_WorktreeUsesMainRepo(t *testing.T) {
|
||||
|
|
@ -339,3 +342,145 @@ func TestConfigureBeadsHooksPath_NormalRepoUnchanged(t *testing.T) {
|
|||
t.Errorf("core.hooksPath = %q, want %q", hooksPath, expected)
|
||||
}
|
||||
}
|
||||
|
||||
// newInitHooksFixture keeps the selected worktree, ambient repository and
|
||||
// storage physically distinct. Git's default HOME is owned by the parent helper.
|
||||
func newInitHooksFixture(t *testing.T) (selected, decoy, storage, common string) {
|
||||
t.Helper()
|
||||
selected, decoy, exclude, _ := newInitExcludeRepos(t)
|
||||
common = filepath.Dir(filepath.Dir(exclude))
|
||||
storage = filepath.Join(t.TempDir(), "separate storage")
|
||||
require.NoError(t, os.Mkdir(storage, 0755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(decoy, "seed"), []byte("decoy\n"), 0600))
|
||||
initExcludeGit(t, decoy, "add", "seed")
|
||||
initExcludeGit(t, selected, "config", "beads.role", "contributor")
|
||||
t.Setenv("BEADS_DIR", filepath.Join(decoy, ".beads"))
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
t.Setenv("GIT_INDEX_FILE", filepath.Join(decoy, ".git", "index"))
|
||||
git.ResetCaches()
|
||||
t.Cleanup(git.ResetCaches)
|
||||
return selected, decoy, storage, common
|
||||
}
|
||||
|
||||
func readInitHooksFile(t *testing.T, path string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
return data
|
||||
}
|
||||
|
||||
func TestInitHooksPreservesManagedDirectoryAliases(t *testing.T) {
|
||||
for _, managed := range []string{".beads/hooks", ".beads-hooks"} {
|
||||
t.Run(managed, func(t *testing.T) {
|
||||
selected, _, storage, common := newInitHooksFixture(t)
|
||||
root := filepath.Dir(common)
|
||||
source := filepath.Join(root, managed)
|
||||
require.NoError(t, os.MkdirAll(source, 0755))
|
||||
const content = "#!/bin/sh\necho existing managed-directory hook\n"
|
||||
require.NoError(t, os.WriteFile(filepath.Join(source, "post-rewrite"), []byte(content), 0755))
|
||||
alias := filepath.Join(t.TempDir(), "repository alias")
|
||||
if err := os.Symlink(root, alias); err != nil {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skipf("directory symlink capability unavailable: %v", err)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
initExcludeGit(t, selected, "config", "--local", "core.hooksPath", filepath.Join(alias, managed))
|
||||
fs, _, err := withInitHooks(nil, selected, storage)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true}))
|
||||
_, err = os.Stat(filepath.Join(storage, "hooks", "post-rewrite"))
|
||||
require.ErrorIs(t, err, os.ErrNotExist, "an existing managed hooks directory must not be copied through an alias")
|
||||
require.Equal(t, content, string(readInitHooksFile(t, filepath.Join(source, "post-rewrite"))))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitHooksRefusesSharedMode(t *testing.T) {
|
||||
selected, _, storage, common := newInitHooksFixture(t)
|
||||
fs, _, err := withInitHooks(nil, selected, storage)
|
||||
require.NoError(t, err)
|
||||
require.ErrorContains(t, fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, Shared: true}), "shared hooks mode")
|
||||
for _, path := range []string{filepath.Join(storage, "hooks"), filepath.Join(filepath.Dir(common), ".beads-hooks")} {
|
||||
_, err := os.Stat(path)
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitHooksContextPreservesSelectedPaths(t *testing.T) {
|
||||
for _, name := range []string{"foreign", "global", "private", "config_lock"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
selected, decoy, storage, common := newInitHooksFixture(t)
|
||||
current := t.TempDir()
|
||||
const foreign = "#!/bin/sh\necho selected hook\n"
|
||||
for _, hook := range []string{"pre-commit", "post-rewrite"} {
|
||||
require.NoError(t, os.WriteFile(filepath.Join(current, hook), []byte(foreign), 0755))
|
||||
}
|
||||
initExcludeGit(t, selected, "config", "--local", "core.hooksPath", current)
|
||||
if name == "global" {
|
||||
initExcludeGit(t, selected, "config", "--local", "--unset", "core.hooksPath")
|
||||
initExcludeGit(t, selected, "config", "--global", "core.hooksPath", current)
|
||||
}
|
||||
preserved := map[string][]byte{}
|
||||
if name == "private" {
|
||||
initExcludeGit(t, selected, "config", "extensions.worktreeConfig", "true")
|
||||
initExcludeGit(t, selected, "config", "--worktree", "core.hooksPath", current)
|
||||
path := filepath.Join(initExcludeGit(t, selected, "rev-parse", "--absolute-git-dir"), "config.worktree")
|
||||
preserved[path] = readInitHooksFile(t, path)
|
||||
}
|
||||
for _, path := range []string{filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index")} {
|
||||
preserved[path] = readInitHooksFile(t, path)
|
||||
}
|
||||
if name == "global" {
|
||||
path := filepath.Join(os.Getenv("HOME"), ".gitconfig")
|
||||
preserved[path] = readInitHooksFile(t, path)
|
||||
}
|
||||
fs, hooks, err := withInitHooks(nil, selected, storage)
|
||||
require.NoError(t, err)
|
||||
require.False(t, hooks.installed())
|
||||
if name == "config_lock" {
|
||||
require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600))
|
||||
preserved[filepath.Join(common, "config")] = readInitHooksFile(t, filepath.Join(common, "config"))
|
||||
}
|
||||
// Later ambient routing must not rebind the captured hook operation.
|
||||
t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), "missing"))
|
||||
t.Setenv("GIT_CONFIG_COUNT", "1")
|
||||
t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath")
|
||||
t.Setenv("GIT_CONFIG_VALUE_0", filepath.Join(decoy, "wrong hooks"))
|
||||
env := os.Environ()
|
||||
destination := filepath.Join(storage, "hooks")
|
||||
for range 2 {
|
||||
err := fs.InstallGitHooks(t.Context(), domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true})
|
||||
if name == "config_lock" {
|
||||
require.ErrorContains(t, err, "failed to configure git hooks path")
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
got := initExcludeGit(t, selected, "config", "--file", filepath.Join(common, "config"), "--get", "core.hooksPath")
|
||||
gotInfo, err := os.Stat(got)
|
||||
require.NoError(t, err)
|
||||
wantInfo, err := os.Stat(destination)
|
||||
require.NoError(t, err)
|
||||
require.True(t, os.SameFile(gotInfo, wantInfo), "common config must name the installed storage hooks")
|
||||
}
|
||||
installed := string(readInitHooksFile(t, filepath.Join(destination, "pre-commit")))
|
||||
require.Contains(t, installed, foreign)
|
||||
require.Equal(t, 1, strings.Count(installed, hookSectionBeginPrefix))
|
||||
require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(destination, "pre-commit.backup"))))
|
||||
require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(destination, "post-rewrite"))))
|
||||
}
|
||||
for path, before := range preserved {
|
||||
require.Equal(t, before, readInitHooksFile(t, path), "changed %s", path)
|
||||
}
|
||||
for _, hook := range []string{"pre-commit", "post-rewrite"} {
|
||||
require.Equal(t, foreign, string(readInitHooksFile(t, filepath.Join(current, hook))))
|
||||
}
|
||||
if name == "private" {
|
||||
paths, err := git.ResolveHooksContext(selected, hooks.env)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, current, paths.HooksDir, "private override remains effective")
|
||||
}
|
||||
require.Equal(t, env, os.Environ())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,13 @@ package main
|
|||
import (
|
||||
"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/ui"
|
||||
)
|
||||
|
||||
|
|
@ -22,6 +24,10 @@ func hooksInstalled() bool {
|
|||
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")
|
||||
|
||||
|
|
@ -80,7 +86,11 @@ func hooksInstalled() bool {
|
|||
// Delegates to CheckGitHooks() which handles version comparison, shim detection,
|
||||
// and inline hook detection consistently.
|
||||
func hooksNeedUpdate() bool {
|
||||
for _, s := range CheckGitHooks() {
|
||||
return hookStatusesNeedUpdate(CheckGitHooks())
|
||||
}
|
||||
|
||||
func hookStatusesNeedUpdate(statuses []HookStatus) bool {
|
||||
for _, s := range statuses {
|
||||
if s.Outdated {
|
||||
return true
|
||||
}
|
||||
|
|
@ -261,12 +271,13 @@ func buildPostMergeHook(chainHooks bool, existingHooks []hookInfo) string {
|
|||
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 {
|
||||
// jj only needs pre-commit and post-merge hooks
|
||||
jjHookNames := []string{"pre-commit", "post-merge"}
|
||||
return installHooksWithOptions(jjHookNames, false, false, false, false)
|
||||
}
|
||||
|
||||
|
|
@ -310,3 +321,64 @@ func printJJAliasInstructions() {
|
|||
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 {
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -580,33 +580,41 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr
|
|||
}
|
||||
}
|
||||
|
||||
if !in.skipHooks && (!hooksInstalled() || hooksNeedUpdate()) {
|
||||
if hooksInstalled() && !in.quiet {
|
||||
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
||||
}
|
||||
if !in.skipHooks {
|
||||
isJJ := gitUC.IsJujutsuRepo(ctx)
|
||||
isColocated := gitUC.IsColocatedJJGit(ctx)
|
||||
switch {
|
||||
case isJJ && !isColocated:
|
||||
if !in.quiet {
|
||||
// The install arm below took over the hook-status gate that used to
|
||||
// wrap this whole switch. Keep it here too, or a pure-JJ repo with
|
||||
// current hooks starts re-printing the alias hint on every init.
|
||||
if !in.quiet && (!hooksInstalled() || hooksNeedUpdate()) {
|
||||
printJJAliasInstructions()
|
||||
}
|
||||
case isColocated:
|
||||
if err := t.fsUseCase.InstallJJHooks(ctx); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
||||
}
|
||||
default:
|
||||
if isRepo {
|
||||
hooksParams := domain.HooksInstallParams{
|
||||
HookNames: managedHookNames,
|
||||
BeadsHooks: true,
|
||||
case isColocated || isRepo:
|
||||
// Resolve only an eligible Git branch, never skip/pure-JJ/nonrepo paths.
|
||||
hookFS, hooks, err := withInitHooks(t.fsUseCase, t.workDir, t.beadsDir)
|
||||
if err != nil {
|
||||
if !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to resolve git hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
}
|
||||
if err := t.fsUseCase.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
||||
} else if !hooks.installed() || hooks.needsUpdate() {
|
||||
if hooks.installed() && !in.quiet {
|
||||
fmt.Printf(" Updating hooks to version %s...\n", Version)
|
||||
}
|
||||
if isColocated {
|
||||
if err := hookFS.InstallJJHooks(ctx); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err)
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n")
|
||||
}
|
||||
} else {
|
||||
hooksParams := domain.HooksInstallParams{HookNames: managedHookNames, BeadsHooks: true}
|
||||
if err := hookFS.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet {
|
||||
fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err)
|
||||
} else if !in.quiet {
|
||||
fmt.Printf(" Hooks installed to: .beads/hooks/\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -572,3 +572,122 @@ func TestProxiedInitExcludeUsesSelectedDirectory(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxiedInitHooksUseSelectedContext(t *testing.T) {
|
||||
for _, name := range []string{"normal", "missing", "outdated", "current", "skip", "nonrepo", "pure_jj", "colocated", "bare", "git_dir_cwd", "config_lock", "quiet_config_lock"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
selected, decoy, storage, common := newInitHooksFixture(t)
|
||||
// Repository shapes whose common directory resolves while no work tree
|
||||
// does; both must still install, as bd did before the hooks resolver.
|
||||
workTreeless := name == "bare" || name == "git_dir_cwd"
|
||||
if name == "normal" {
|
||||
selected = filepath.Dir(common)
|
||||
}
|
||||
if name == "bare" {
|
||||
selected = t.TempDir()
|
||||
initExcludeGit(t, selected, "init", "--bare", "--quiet")
|
||||
}
|
||||
if name == "git_dir_cwd" {
|
||||
// Standing in a non-bare repository's own .git directory: rev-parse
|
||||
// --git-dir answers, so the repository arm runs, but --show-toplevel
|
||||
// fails and --is-bare-repository reports false.
|
||||
repo := t.TempDir()
|
||||
initExcludeGit(t, repo, "init", "--quiet")
|
||||
selected = filepath.Join(repo, ".git")
|
||||
}
|
||||
current, ambient := t.TempDir(), t.TempDir()
|
||||
initExcludeGit(t, selected, "config", "core.hooksPath", current)
|
||||
initExcludeGit(t, decoy, "config", "core.hooksPath", ambient)
|
||||
writeHooks := func(dir string, outdated bool) {
|
||||
for _, hook := range []string{"pre-commit", "post-merge"} {
|
||||
text := "#!/bin/sh\n" + generateHookSection(hook)
|
||||
if outdated {
|
||||
text = "#!/bin/sh\n# bd (beads) " + hook + " hook\n# Version: obsolete\n"
|
||||
}
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, hook), []byte(text), 0755))
|
||||
}
|
||||
}
|
||||
if name == "current" || name == "outdated" {
|
||||
writeHooks(current, name == "outdated")
|
||||
}
|
||||
if name != "current" {
|
||||
writeHooks(ambient, false)
|
||||
}
|
||||
// Filesystems without executable mode bits retain the existing reinstall policy.
|
||||
currentReady := false
|
||||
if name == "current" {
|
||||
info, err := os.Stat(filepath.Join(current, "pre-commit"))
|
||||
require.NoError(t, err)
|
||||
currentReady = info.Mode().Perm()&0111 != 0
|
||||
if runtime.GOOS != "windows" {
|
||||
require.True(t, currentReady, "POSIX current-status fixture requires executable hooks")
|
||||
}
|
||||
}
|
||||
preserved := map[string][]byte{}
|
||||
for _, path := range []string{filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "index")} {
|
||||
preserved[path] = readInitHooksFile(t, path)
|
||||
}
|
||||
if name == "nonrepo" || name == "pure_jj" {
|
||||
selected = t.TempDir()
|
||||
}
|
||||
if name == "pure_jj" || name == "colocated" {
|
||||
require.NoError(t, os.Mkdir(filepath.Join(selected, ".jj"), 0755))
|
||||
}
|
||||
locked := name == "config_lock" || name == "quiet_config_lock"
|
||||
if locked {
|
||||
require.NoError(t, os.WriteFile(filepath.Join(common, "config.lock"), []byte("owned lock"), 0600))
|
||||
}
|
||||
fs := storagefs.NewFileSystemProvider(selected, newBeadsDirTemplates(), newInitFileSystemAdapters(selected)).BeadsDirFSUseCase()
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("setup-exclude", true, "")
|
||||
in := initProxiedServerInput{skipHooks: name == "skip", quiet: name == "quiet_config_lock", skipAgents: true, nonInteractive: true}
|
||||
env := os.Environ()
|
||||
stderr := captureStderr(t, func() {
|
||||
require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: selected, beadsDir: storage, remoteURL: "file:///unused-hooks-fixture-remote", fsUseCase: fs, gitUC: storagegit.NewGitProvider(selected).GitUseCase()}))
|
||||
})
|
||||
if name == "config_lock" {
|
||||
require.Contains(t, stderr, "Failed to install git hooks")
|
||||
} else if name != "nonrepo" && name != "pure_jj" {
|
||||
require.Empty(t, stderr)
|
||||
}
|
||||
require.NotContains(t, stderr, "Failed to resolve git hooks")
|
||||
wantInstall := name == "normal" || name == "missing" || name == "outdated" || name == "colocated" || workTreeless || locked || (name == "current" && !currentReady)
|
||||
path := filepath.Join(storage, "hooks", "pre-commit")
|
||||
if name == "colocated" {
|
||||
path = filepath.Join(current, "pre-commit")
|
||||
}
|
||||
if wantInstall {
|
||||
require.Contains(t, string(readInitHooksFile(t, path)), hookSectionBeginPrefix)
|
||||
} else {
|
||||
_, err := os.Stat(path)
|
||||
require.ErrorIs(t, err, os.ErrNotExist, "ambient status must not trigger an install")
|
||||
}
|
||||
if workTreeless {
|
||||
// These resolve through the work-tree-less hooks context, so the
|
||||
// install must still land in the selected storage and configure the
|
||||
// selected repository -- not the inherited one this fixture routes to.
|
||||
require.Equal(t, filepath.Join(storage, "hooks"), initExcludeGit(t, selected, "config", "--local", "--get", "core.hooksPath"))
|
||||
}
|
||||
if name != "nonrepo" && name != "pure_jj" {
|
||||
excludeRoot := common
|
||||
if workTreeless {
|
||||
excludeRoot = selected // a work-tree-less selection is its own common directory
|
||||
}
|
||||
exclude := readInitHooksFile(t, filepath.Join(excludeRoot, "info", "exclude"))
|
||||
require.Contains(t, string(exclude), ".beads/", "selected exclude callback lost")
|
||||
}
|
||||
for path, before := range preserved {
|
||||
require.Equal(t, before, readInitHooksFile(t, path), "changed %s", path)
|
||||
}
|
||||
require.Equal(t, env, os.Environ())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitHooksEmptyPathRetainsUseCase(t *testing.T) {
|
||||
supplied := &initTailForkObservation{}
|
||||
fs, hooks, err := withInitHooks(supplied, "", "unused storage")
|
||||
require.NoError(t, err)
|
||||
require.Same(t, supplied, fs)
|
||||
require.Nil(t, hooks)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ func isGitWorktree() bool {
|
|||
// gitRevParse runs git rev-parse with the given flag and returns the trimmed output.
|
||||
// This is a helper for CLI utilities that need git command execution.
|
||||
func gitRevParse(flag string) string {
|
||||
// #nosec G702 - fixed "git" command; flag is a constant rev-parse switch chosen by
|
||||
// the caller in this package, never attacker-controlled input.
|
||||
out, err := exec.Command("git", "rev-parse", flag).Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
|
|
|
|||
|
|
@ -688,12 +688,14 @@ func scrubWorktreeRemovalGitEnvForOS(env []string, goos string) []string {
|
|||
// ScrubRoutingForOS returns a fresh slice, so filtering it in place is safe.
|
||||
result := cleaned[:0]
|
||||
for _, entry := range cleaned {
|
||||
// One shared subprocess key identity: execenv mirrors os/exec's fold, so
|
||||
// this drops exactly the entries a child process would treat as these two
|
||||
// variables -- an independent fold here would diverge from that rule.
|
||||
// ToUpper is not that rule; the two disagree in both directions for
|
||||
// non-ASCII keys on Windows: ToUpper leaves GİT_OPTIONAL_LOCKS unmatched
|
||||
// although Git honors it, and folds GIT_OPTIONAL_LOCKſ onto the literal
|
||||
// although os/exec keeps it distinct.
|
||||
key := worktreeGitEnvKey(entry)
|
||||
// Key identity is the subprocess lookup rule (execenv), not ToUpper.
|
||||
// The two disagree in both directions for non-ASCII keys on Windows:
|
||||
// ToUpper leaves GİT_OPTIONAL_LOCKS unmatched although Git honors it,
|
||||
// and folds GIT_OPTIONAL_LOCKſ onto the literal although os/exec keeps
|
||||
// it distinct.
|
||||
if execenv.KeyEqualForOS(key, "GIT_NO_REPLACE_OBJECTS", goos) ||
|
||||
execenv.KeyEqualForOS(key, "GIT_OPTIONAL_LOCKS", goos) {
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -15,15 +15,21 @@ override discovery with `BEADS_DIR`.
|
|||
Startup *config* discovery — the `rev-parse` probe in `internal/config`'s
|
||||
`gitDirsForRepo`, which locates a linked worktree's shared `.beads` config —
|
||||
scrubs inherited Git routing variables such as `GIT_DIR` and `GIT_WORK_TREE`
|
||||
from its subprocess environment whenever it runs. The scrub is unconditional for
|
||||
that probe, but the probe is a fallback, not a per-command step: it runs only
|
||||
when nothing earlier in startup has already resolved a config path
|
||||
(`internal/config/config.go`), so an ancestor `.beads/config.yaml` or an
|
||||
explicit `BEADS_DIR` short-circuits it. Other startup Git probes still honor
|
||||
inherited routing, including `internal/git`'s process-cached repository context
|
||||
and the `.beads` database discovery probes in `internal/beads`, so those
|
||||
variables can still select which workspace `bd` opens. Clearing those variables
|
||||
from the `bd` process environment applies only to `bd worktree` commands.
|
||||
from its subprocess environment whenever it runs, so a routed environment cannot
|
||||
point that one lookup at another repository. The scrub is unconditional for that
|
||||
probe, but the probe is a fallback, not a per-command step: it runs only when
|
||||
nothing earlier in startup has already resolved a config path
|
||||
(`internal/config/config.go`), so an ancestor `.beads/config.yaml` or an explicit
|
||||
`BEADS_DIR` short-circuits it. It is a single probe, not a general guarantee:
|
||||
other startup Git probes still honor inherited routing, including `internal/git`'s
|
||||
process-cached repository context backing repository-root and hooks-directory
|
||||
lookups and the `.beads` database discovery probes in `internal/beads`, so those
|
||||
variables can still select which workspace `bd` opens. Scrubbing also drops any
|
||||
inherited `GIT_CEILING_DIRECTORIES`, which *widens* upward discovery rather than
|
||||
narrowing it: the explicit working directory fixes where that probe's search
|
||||
starts, not where it stops, so the probe can select a containing parent
|
||||
repository above that directory. Clearing those variables from the `bd` process
|
||||
environment applies only to `bd worktree` commands.
|
||||
|
||||
`GIT_CEILING_DIRECTORIES` is scrubbed along with the redirects. That removes a
|
||||
*bound* rather than a redirect, so discovery from the working directory is
|
||||
|
|
|
|||
|
|
@ -436,7 +436,13 @@ func gitDirsForRepo(repoPath string) (gitDir, commonDir string, ok bool) {
|
|||
cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--git-dir", "--git-common-dir")
|
||||
// repoPath is the authority for this probe. Inherited Git routing such as
|
||||
// GIT_DIR overrides -C and can make startup read another repository's
|
||||
// shared-worktree config before command dispatch has begun.
|
||||
// shared-worktree config before command dispatch has begun. Scrubbing also
|
||||
// drops an inherited GIT_CEILING_DIRECTORIES, which widens rather than
|
||||
// narrows discovery: -C repoPath fixes where the search starts, not where it
|
||||
// stops, so dropping discovery ceilings can select a containing parent
|
||||
// repository above repoPath. That is the intended trade, and it applies here
|
||||
// too -- repoPath is the process working directory, not a proven repository
|
||||
// root.
|
||||
cmd.Env = gitenv.ScrubRouting(os.Environ())
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -129,6 +129,56 @@ func TestSecretGitTrackingIgnoresInheritedGitRouting(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// A checkout reachable only through inherited Git routing is the case a
|
||||
// scrubbed-only probe cannot see at all: it finds no repository, reports
|
||||
// "untracked", and the fail-open guard writes the secret into a tracked
|
||||
// config.yaml. The inherited fallback is what keeps the refusal working there.
|
||||
func TestSecretGitTrackingHonorsLegitimateGitRouting(t *testing.T) {
|
||||
gitDir, work := t.TempDir(), t.TempDir()
|
||||
routedGit := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = work
|
||||
cmd.Env = append(gitenv.ScrubRouting(os.Environ()), "GIT_DIR="+gitDir, "GIT_WORK_TREE="+work)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("routed git %v: %v\n%s", args, err, output)
|
||||
}
|
||||
}
|
||||
routedGit("init", "--quiet")
|
||||
tracked := filepath.Join(work, "config.yaml")
|
||||
untracked := filepath.Join(work, "untracked.yaml")
|
||||
for _, path := range []string{tracked, untracked} {
|
||||
if err := os.WriteFile(path, []byte("json: false\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
routedGit("add", "--", tracked)
|
||||
|
||||
// The work tree holds no .git entry, so the scrubbed probe must fail here.
|
||||
// Without this precondition the inherited fallback could pass vacuously.
|
||||
scrubbed := exec.Command("git", "ls-files", "--error-unmatch", tracked)
|
||||
scrubbed.Dir = work
|
||||
scrubbed.Env = gitenv.ScrubRouting(os.Environ())
|
||||
if scrubbed.Run() == nil {
|
||||
t.Fatal("scrubbed probe already resolves the routed checkout; fixture proves nothing")
|
||||
}
|
||||
|
||||
t.Setenv("GIT_DIR", gitDir)
|
||||
t.Setenv("GIT_WORK_TREE", work)
|
||||
if !isGitTracked(tracked) {
|
||||
t.Error("legitimate routing hid the tracked file from the secret guard")
|
||||
}
|
||||
if isGitTracked(untracked) {
|
||||
t.Error("untracked file reported as tracked")
|
||||
}
|
||||
if err := checkSecretGitTracked(tracked, "linear.api_key"); err == nil || !strings.Contains(err.Error(), "refusing to write secret key") {
|
||||
t.Errorf("tracked secret refusal = %v", err)
|
||||
}
|
||||
if err := checkSecretGitTracked(untracked, "linear.api_key"); err != nil {
|
||||
t.Errorf("untracked secret refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A bare repository whose work tree is named only by GIT_DIR/GIT_WORK_TREE is
|
||||
// invisible to the scrubbed probe — it is reachable through the inherited
|
||||
// routing alone. The secret guard must still refuse a write into the tracked
|
||||
|
|
|
|||
|
|
@ -120,6 +120,30 @@ type HooksContext struct {
|
|||
HooksDir, CommonDir, RepoRoot, MainRepoRoot string
|
||||
}
|
||||
|
||||
// normalizeHooksWorkDir anchors workDir and normalizes its symlinks and case
|
||||
// once. Every HooksContext producer shares it so they cannot drift into emitting
|
||||
// different spellings of the same directory: worktree code string-compares these
|
||||
// paths (GH#880).
|
||||
// The caller-supplied directory must resolve before it can select a repo:
|
||||
// unlike the discovered repoRoot spelling in loadGitContext, it is an input
|
||||
// to Git.
|
||||
func normalizeHooksWorkDir(workDir string) (string, error) {
|
||||
workDir, err := filepath.Abs(workDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// This caller-supplied directory must resolve before it can select a repo.
|
||||
// Unlike the discovered repoRoot spelling, it is an input to Git.
|
||||
workDir, err = filepath.EvalSymlinks(workDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve hooks working directory: %w", err)
|
||||
}
|
||||
if canonical := canonicalizeCase(workDir); canonical != "" {
|
||||
workDir = canonical
|
||||
}
|
||||
return workDir, nil
|
||||
}
|
||||
|
||||
// ResolveHooksContext reads fresh paths without changing the legacy cache.
|
||||
// workDir must be nonempty and is anchored and symlink/case-normalized once;
|
||||
// bare/non-repositories error. Configured absolute hook paths retain their spelling.
|
||||
|
|
@ -132,26 +156,15 @@ type HooksContext struct {
|
|||
//
|
||||
// This is the explicit-context sibling of GetGitHooksDir. It returns a struct
|
||||
// instead of following this file's GetXFrom(startDir) convention because all
|
||||
// four paths must come from one resolution of one directory. The first in-repo
|
||||
// caller arrives with GH#6440, so at this commit only tests exercise the
|
||||
// contract above.
|
||||
// four paths must come from one resolution of one directory.
|
||||
func ResolveHooksContext(workDir string, env []string) (HooksContext, error) {
|
||||
if workDir == "" {
|
||||
return HooksContext{}, fmt.Errorf("hooks context requires a working directory")
|
||||
}
|
||||
workDir, err := filepath.Abs(workDir)
|
||||
workDir, err := normalizeHooksWorkDir(workDir)
|
||||
if err != nil {
|
||||
return HooksContext{}, err
|
||||
}
|
||||
// This caller-supplied directory must resolve before it can select a repo.
|
||||
// Unlike the discovered repoRoot spelling above, it is an input to Git.
|
||||
workDir, err = filepath.EvalSymlinks(workDir)
|
||||
if err != nil {
|
||||
return HooksContext{}, fmt.Errorf("resolve hooks working directory: %w", err)
|
||||
}
|
||||
if canonical := canonicalizeCase(workDir); canonical != "" {
|
||||
workDir = canonical
|
||||
}
|
||||
ctx := loadGitContext(workDir, env)
|
||||
if ctx.err != nil {
|
||||
return HooksContext{}, ctx.err
|
||||
|
|
@ -166,6 +179,58 @@ func ResolveHooksContext(workDir string, env []string) (HooksContext, error) {
|
|||
RepoRoot: ctx.repoRoot, MainRepoRoot: ctx.mainRepoRoot()}, nil
|
||||
}
|
||||
|
||||
// ResolveWorkTreelessHooksContext resolves hook paths for a repository whose
|
||||
// common directory resolves but whose work tree does not: a bare repository, or
|
||||
// a directory such as a repository's own .git that Git answers from while
|
||||
// reporting no work tree. ResolveHooksContext requires one, because it cannot
|
||||
// honor its RepoRoot contract without it; this is the explicit counterpart, so a
|
||||
// caller opts into the weaker shape instead of silently receiving one. RepoRoot
|
||||
// and MainRepoRoot are empty — there is no work-tree root — and a relative
|
||||
// core.hooksPath is anchored to the common directory, which is where Git runs
|
||||
// hooks without a work tree.
|
||||
// It fails for non-repositories and for directories inside a work tree alike, so
|
||||
// callers can use it as a fallback after ResolveHooksContext without widening
|
||||
// that call's failure contract. workDir and env are handled exactly as
|
||||
// ResolveHooksContext handles them, anchoring and normalization included.
|
||||
func ResolveWorkTreelessHooksContext(workDir string, env []string) (HooksContext, error) {
|
||||
if workDir == "" {
|
||||
return HooksContext{}, fmt.Errorf("hooks context requires a working directory")
|
||||
}
|
||||
workDir, err := normalizeHooksWorkDir(workDir)
|
||||
if err != nil {
|
||||
return HooksContext{}, err
|
||||
}
|
||||
probe := exec.Command("git", "rev-parse", "--is-inside-work-tree", "--git-common-dir")
|
||||
probe.Dir, probe.Env = workDir, env
|
||||
output, err := probe.Output()
|
||||
if err != nil {
|
||||
return HooksContext{}, fmt.Errorf("resolve work-tree-less Git repository: %w", err)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
|
||||
if len(lines) < 2 {
|
||||
return HooksContext{}, fmt.Errorf("unexpected git rev-parse output: got %d lines, expected 2", len(lines))
|
||||
}
|
||||
// A work tree resolves here, so ResolveHooksContext's stronger contract is
|
||||
// the one that applies and its error is the one the caller should surface.
|
||||
if strings.TrimSpace(lines[0]) == "true" {
|
||||
return HooksContext{}, fmt.Errorf("%s is inside a Git work tree", workDir)
|
||||
}
|
||||
commonDir, err := absoluteGitPath(workDir, strings.TrimSpace(lines[1]))
|
||||
if err != nil {
|
||||
return HooksContext{}, fmt.Errorf("failed to resolve common dir path: %w", err)
|
||||
}
|
||||
cmd := exec.Command("git", "config", "--get", "core.hooksPath")
|
||||
cmd.Dir, cmd.Env = workDir, env
|
||||
// Without a work tree Git runs hooks in the common directory, so it anchors a
|
||||
// relative core.hooksPath in place of the absent work-tree root.
|
||||
ctx := gitContext{gitDirRaw: commonDir, commonDir: commonDir, repoRoot: commonDir}
|
||||
hooksDir, err := gitHooksDir(cmd, func() (*gitContext, error) { return &ctx, nil })
|
||||
if err != nil {
|
||||
return HooksContext{}, err
|
||||
}
|
||||
return HooksContext{HooksDir: hooksDir, CommonDir: commonDir}, nil
|
||||
}
|
||||
|
||||
// getGitContext returns the cached git context, initializing it if needed.
|
||||
func getGitContext() (*gitContext, error) {
|
||||
gitCtxOnce.Do(initGitContext)
|
||||
|
|
|
|||
|
|
@ -59,7 +59,10 @@ func EntryKey(entry string) string {
|
|||
// repository the caller is standing in, which is the same loss of working-
|
||||
// directory authority. Removing it therefore widens the upward search as well,
|
||||
// so a caller whose working directory is not itself a repository can resolve a
|
||||
// containing one.
|
||||
// containing one. That is the intended trade, and pinning an explicit working
|
||||
// directory does not opt out of it: -C or cmd.Dir fixes where the search
|
||||
// starts, not where it stops, so once the ceiling is gone the walk above that
|
||||
// directory is unbounded.
|
||||
func IsRoutingKeyForOS(key, goos string) bool {
|
||||
keys := routingKeys
|
||||
prefix := "GIT_CONFIG"
|
||||
|
|
|
|||
|
|
@ -129,7 +129,13 @@ func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string,
|
|||
return "", false, fmt.Errorf("git: GetConfig: key must not be empty")
|
||||
}
|
||||
cmd := r.gitCmd(ctx, "config", "--get", key)
|
||||
if key == domain.BeadsRoleConfigKey {
|
||||
// Git config key names are case-insensitive, so match its rule: a caller
|
||||
// spelling "Beads.Role" reads the same key and must take the same
|
||||
// role-authority environment, not slip through on the inherited one. ToLower
|
||||
// rather than EqualFold, following execenv.keyIdentityForWindows: EqualFold
|
||||
// also collapses Unicode near-collisions such as s and ſ, while git folds
|
||||
// ASCII only and rejects beadſ.role as an invalid key.
|
||||
if strings.ToLower(key) == domain.BeadsRoleConfigKey {
|
||||
cmd.Env = r.roleAuthorityEnv()
|
||||
}
|
||||
out, err := cmd.Output()
|
||||
|
|
@ -156,7 +162,10 @@ func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) er
|
|||
return fmt.Errorf("git: SetConfig: key must not be empty")
|
||||
}
|
||||
cmd := r.gitCmd(ctx, "config", key, value)
|
||||
if key == domain.BeadsRoleConfigKey {
|
||||
// Case-insensitive for the same reason as GetConfig, and with the same
|
||||
// ToLower rule: git resolves key names case-insensitively over ASCII, so
|
||||
// every spelling must take the role-authority environment.
|
||||
if strings.ToLower(key) == domain.BeadsRoleConfigKey {
|
||||
cmd.Env = r.roleAuthorityEnv()
|
||||
}
|
||||
out, err := cmd.CombinedOutput()
|
||||
|
|
|
|||
|
|
@ -116,20 +116,40 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() {
|
|||
s.Require().NoError(roleErr)
|
||||
s.False(found)
|
||||
}
|
||||
if tc.name == "invalid_routing_boolean" {
|
||||
// The same poison that fails the read above cannot reach beads.role,
|
||||
// which resolves as absent rather than as a preserved read failure.
|
||||
role, roleFound, roleErr := s.repo.GetConfig(s.Ctx(), "beads.role")
|
||||
s.Require().NoError(roleErr)
|
||||
s.False(roleFound)
|
||||
s.Empty(role)
|
||||
_, _, useCaseErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx())
|
||||
s.Require().NoError(useCaseErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfig_ReadFailuresAreNotMissing's "invalid_routing_boolean" row used to
|
||||
// poison GIT_CONFIG_NOSYSTEM and expect the beads.role read to fail. beads.role
|
||||
// reads now scrub inherited suppression, so that poison never reaches git for
|
||||
// this key; that row therefore reads a key which still inherits it (core.bare)
|
||||
// and asserts the role read's immunity alongside. This test covers the half that
|
||||
// row cannot: under the same poison, the role read returns the value it was
|
||||
// given rather than merely resolving as absent.
|
||||
func (s *testSuite) TestConfig_BeadsRoleScrubsInheritedRoutingEnv() {
|
||||
s.gitInit()
|
||||
s.Require().NoError(s.repo.SetConfig(s.Ctx(), "beads.role", "maintainer"))
|
||||
s.T().Setenv("GIT_CONFIG_NOSYSTEM", "not-a-boolean")
|
||||
|
||||
// beads.role is read with routing scrubbed, so the poisoned value is gone
|
||||
// before git parses its environment.
|
||||
value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role")
|
||||
s.Require().NoError(err)
|
||||
s.True(found)
|
||||
s.Equal("maintainer", value)
|
||||
|
||||
// Keys outside that scrub keep the inherited environment, so the same poison
|
||||
// still surfaces as a read error rather than as an absent key.
|
||||
value, found, err = s.repo.GetConfig(s.Ctx(), "user.name")
|
||||
s.Require().Error(err)
|
||||
s.False(found)
|
||||
s.Empty(value)
|
||||
var exitErr *exec.ExitError
|
||||
s.Require().ErrorAs(err, &exitErr)
|
||||
s.Equal(128, exitErr.ExitCode())
|
||||
}
|
||||
|
||||
// Regression guard: pre-canceled contexts already propagated before the config fix.
|
||||
func (s *testSuite) TestConfig_CancellationIsNotMissing() {
|
||||
ctx, cancel := context.WithCancel(s.Ctx())
|
||||
|
|
@ -402,6 +422,56 @@ func TestRoleConfigIgnoresInheritedGitRouting(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestRoleConfigKeySpellingTakesScrubbedPath pins the case-insensitive key
|
||||
// match. Git resolves config key names case-insensitively, so every spelling of
|
||||
// beads.role must take the scrubbed path; a byte-exact compare would let
|
||||
// "Beads.Role" read and write whichever repository inherited routing selects.
|
||||
func TestRoleConfigKeySpellingTakesScrubbedPath(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
|
||||
t.Setenv(key, "")
|
||||
require.NoError(t, os.Unsetenv(key))
|
||||
}
|
||||
}
|
||||
home := t.TempDir()
|
||||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, home)
|
||||
}
|
||||
runGit := func(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ())
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "fixture git %v: %s", args, out)
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
// The canonical spelling is the control: it takes the scrubbed path under
|
||||
// either comparator, so it proves the fixture routes as intended rather than
|
||||
// the assertions passing vacuously.
|
||||
for _, key := range []string{"beads.role", "Beads.Role", "BEADS.ROLE"} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
target, decoy := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{target, decoy} {
|
||||
runGit(t, dir, "init", "--quiet")
|
||||
}
|
||||
runGit(t, target, "config", "--local", "beads.role", "target-role")
|
||||
runGit(t, decoy, "config", "--local", "beads.role", "decoy-role")
|
||||
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
|
||||
t.Setenv("GIT_WORK_TREE", decoy)
|
||||
repo := NewGitRepository(target)
|
||||
got, found, err := repo.GetConfig(t.Context(), key)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, "target-role", got, "%s read through inherited routing", key)
|
||||
require.NoError(t, repo.SetConfig(t.Context(), key, "written-role"))
|
||||
require.Equal(t, "written-role", runGit(t, target, "config", "--local", "--get", "beads.role"))
|
||||
require.Equal(t, "decoy-role", runGit(t, decoy, "config", "--local", "--get", "beads.role"),
|
||||
"%s write escaped to the inherited repository", key)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) {
|
||||
for _, entry := range os.Environ() {
|
||||
key := gitenv.EntryKey(entry)
|
||||
|
|
@ -473,12 +543,18 @@ func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) {
|
|||
for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} {
|
||||
t.Setenv(key, changedHome)
|
||||
}
|
||||
// gastownhall/beads#6477 made the reader propagate Git's exit
|
||||
// error instead of mapping it to absence, so the generic
|
||||
// constructor now surfaces the changed HOME's broken .gitconfig
|
||||
// rather than reporting the key missing. changedHome is the only
|
||||
// HOME here holding a .gitconfig, so Git's refusal to parse that
|
||||
// file is itself the proof that generic role reads still use the
|
||||
// current caller environment rather than a captured one.
|
||||
role, found, err := inherited.GetConfig(t.Context(), "beads.role")
|
||||
// changedHome is the only HOME here holding a .gitconfig, so Git's
|
||||
// refusal to parse that file is what proves the generic reader used
|
||||
// the current caller environment rather than a captured one. The
|
||||
// reader surfaces such read failures instead of reporting absence.
|
||||
require.Error(t, err, "generic role reads still use the current caller environment")
|
||||
var inheritedExit *exec.ExitError
|
||||
require.ErrorAs(t, err, &inheritedExit)
|
||||
require.Equal(t, 128, inheritedExit.ExitCode())
|
||||
require.ErrorContains(t, err, ".gitconfig")
|
||||
require.False(t, found)
|
||||
require.Empty(t, role)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue