Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(cli): resolve the hooks dir git actually runs, including husky's (#1511)
haibeeb3f8f7732ff41
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.pyindex 525f0ae9d..66442488f 100644--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py@@ -991,10 +991,10 @@ def hook_status(path: str | None, workspace: bool, no_workspace: bool) -> None:for entry in target.ws_config.repos:abs_path = (target.ws_root / entry.path).resolve()result = status(abs_path)- icon = "[green]✓[/green]" if result == "installed" else "[dim]✗[/dim]"+ icon = "[green]✓[/green]" if result.startswith("installed") else "[dim]✗[/dim]"console.print(f" {icon} {entry.alias}: {result}")else:assert target.repo_path is not Noneresult = status(target.repo_path)- icon = "[green]✓[/green]" if result == "installed" else "[dim]✗[/dim]"+ icon = "[green]✓[/green]" if result.startswith("installed") else "[dim]✗[/dim]"console.print(f" {icon} post-commit: {result}")diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.pyindex 40180230d..724e4df2d 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py@@ -205,7 +205,7 @@ def _offer_hook_install_prompts(candidates: list[tuple[Path, str]] = []for i, rp in enumerate(repo_paths):label = aliases[i] if aliases else rp.name- if status(rp) != "installed":+ if not status(rp).startswith("installed"):candidates.append((rp, label))if not candidates:diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.pyindex 51dfca83b..95dd5f2a3 100644--- a/packages/cli/src/repowise/cli/editor_setup.py+++ b/packages/cli/src/repowise/cli/editor_setup.py@@ -92,8 +92,10 @@ def detect_editor_setup_outcome("""Read the ground-truth editor-setup state for the completion panel.Called after registration and the hook offers, so what it reads is final.- Every probe is a cheap local file read and is defensive: a failure degrades- to "not set up" rather than crashing ``init``.+ Every probe is defensive: a failure degrades to "not set up" rather than+ crashing ``init``. All but one are local file reads; the autosync probe+ spawns ``git rev-parse`` once, because ``core.hooksPath`` and worktrees make+ the hooks directory impossible to derive from the repo path alone."""disabled = is_editor_setup_disabled(no_editor_setup)@@ -101,7 +103,7 @@ def detect_editor_setup_outcome(try:from repowise.cli.hooks import status as _hook_status- autosync = _hook_status(repo_path) == "installed"+ autosync = _hook_status(repo_path).startswith("installed")except Exception:passdiff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.pyindex d7b3abd16..65458a65b 100644--- a/packages/cli/src/repowise/cli/hooks.py+++ b/packages/cli/src/repowise/cli/hooks.py@@ -105,6 +105,16 @@ def _hooks_dir(repo_path: Path) -> Path | None:metadata dir — so ``root / ".git" / "hooks"`` is ``NotADirectoryError``territory. Ask git for the real hooks path so both layouts work, and fallback to the ``.git/hooks`` heuristic when git is unavailable or not a repo.++ ``git rev-parse --git-path hooks`` also honours ``core.hooksPath``, which+ husky and lefthook both set. A *global* ``core.hooksPath`` (say+ ``~/.githooks``) resolves outside any repo, so the hook is shared:+ ``status`` then reports installed from every repo, and ``uninstall`` run+ in one repo removes it for all of them. Following the config is still+ correct, because that directory is genuinely where git looks, and the+ hook body is repo-scoped at runtime -- it resolves its own ``$ROOT`` and+ returns early unless ``$ROOT/.repowise`` exists -- so a shared hook is+ inert in repos with no index rather than wrong."""try:result = subprocess.run(@@ -116,9 +126,9 @@ def _hooks_dir(repo_path: Path) -> Path | None:)if result.returncode == 0:p = Path(result.stdout.strip())- if p.is_absolute():- return p- return repo_path / p+ if not p.is_absolute():+ p = repo_path / p+ return _husky_user_hook_dir(p)except Exception:passroot = _git_root(repo_path)@@ -127,6 +137,59 @@ def _hooks_dir(repo_path: Path) -> Path | None:return root / ".git" / "hooks"+def _husky_user_hook_dir(hooks_dir: Path) -> Path:+ """Redirect husky's generated shim directory to its user-hook directory.++ husky points ``core.hooksPath`` at ``.husky/_``, which it regenerates on+ every install and gitignores wholesale (``.husky/_/.gitignore`` is ``*``), so+ a hook written there is deleted by the next ``npm install``. husky's shim+ dispatches to ``.husky/<hook-name>`` one level up, which is the committed,+ durable location.++ Dispatch does not depend on which user hooks already exist. husky writes a+ shim for a fixed list of all 14 git hook names on every install, regardless+ of what is in ``.husky/`` (husky 9.1.7 ``index.js``: the ``l`` array includes+ ``post-commit``, and ``l.forEach`` writes each one unconditionally), and each+ shim sources ``_/h``, which execs ``.husky/<name>`` when that file exists and+ exits 0 when it does not. So a hook written here is picked up immediately+ rather than waiting for the next ``npm install``.++ The exception is a checkout where husky has never run: ``.husky/_`` does not+ exist, ``core.hooksPath`` points at a missing directory, and git therefore+ runs no hooks at all -- husky's own included. Writing to ``.husky/`` is still+ the right destination, since it survives, but nothing fires until husky is+ installed. :func:`husky_pending_reason` reports that so it is visible at+ install time instead of looking like a working hook.+ """+ if hooks_dir.name != "_":+ return hooks_dir+ # Only remap a directory that really is husky's, not any directory named+ # "_". The generated helpers are the strongest signal, but they are absent+ # in a fresh worktree where husky has not been installed yet; there the+ # parent being a ``.husky`` directory is what identifies the layout.+ is_husky = any((hooks_dir / marker).exists() for marker in ("h", "husky.sh"))+ if not (is_husky or hooks_dir.parent.name == ".husky"):+ return hooks_dir+ return hooks_dir.parent+++def husky_pending_reason(hooks_dir: Path) -> str | None:+ """Why a hook in *hooks_dir* will not run yet, or None if it will.++ Only one case: the husky user-hook directory in a checkout where husky has+ not been installed, so ``core.hooksPath`` points at a ``_`` that is not there+ and git runs nothing. Silent in every other layout.+ """+ if hooks_dir.name != ".husky":+ return None+ if (hooks_dir / "_" / "h").exists():+ return None+ return (+ "husky is not set up in this checkout (no .husky/_), so git runs no hooks "+ "here yet -- run your package manager's install to activate it"+ )++def _strip_legacy_block(content: str) -> tuple[str, bool]:"""Remove a pre-marker repowise hook body from *content*.@@ -223,6 +286,11 @@ def install(repo_path: Path) -> str:hooks_dir.mkdir(parents=True, exist_ok=True)hook_path = hooks_dir / "post-commit"+ pending = husky_pending_reason(hooks_dir)++ def _annotate(state: str) -> str:+ return f"{state} ({pending})" if pending else state+migrated_legacy = Falseif hook_path.exists():content = hook_path.read_text(encoding="utf-8")@@ -234,7 +302,7 @@ def install(repo_path: Path) -> str:# Marker block present. Decide whether to leave alone or upgrade.current_block = _HOOK_SCRIPT.rstrip() + "\n"if current_block in content:- return (+ return _annotate("migrated legacy hook" if migrated_legacy else "already installed")content, replaced = _replace_marker_block(content, _HOOK_SCRIPT)@@ -245,8 +313,8 @@ def install(repo_path: Path) -> str:hook_path.stat().st_mode| stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)- return "upgraded"- return "already installed"+ return _annotate("upgraded")+ return _annotate("already installed")# Append to existing hookhook_path.write_text(content.rstrip() + "\n\n" + _HOOK_SCRIPT,@@ -259,7 +327,7 @@ def install(repo_path: Path) -> str:with contextlib.suppress(OSError):hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)- return "installed"+ return _annotate("installed")def uninstall(repo_path: Path) -> str:@@ -313,5 +381,6 @@ def status(repo_path: Path) -> str:content = hook_path.read_text(encoding="utf-8")if _HOOK_MARKER in content:- return "installed"+ pending = husky_pending_reason(hook_path.parent)+ return f"installed ({pending})" if pending else "installed"return "not installed"diff --git a/tests/unit/cli/test_hooks_path_resolution.py b/tests/unit/cli/test_hooks_path_resolution.pynew file mode 100644index 000000000..0c333b80b--- /dev/null+++ b/tests/unit/cli/test_hooks_path_resolution.py@@ -0,0 +1,193 @@+"""Tests for resolving the hooks directory git will actually run.++The installer used to hardcode ``<root>/.git/hooks``, which is wrong in three+layouts that are all common in practice:++* a linked worktree, where ``.git`` is a *file* and ``mkdir`` raised+ ``NotADirectoryError``, killing the command;+* a repo with ``core.hooksPath`` set (husky, lefthook), where git ignores+ ``.git/hooks`` entirely, so the hook installed "successfully" and then never+ ran;+* husky specifically, whose ``core.hooksPath`` points at a generated, gitignored+ ``.husky/_`` that is recreated on every ``npm install``.++Resolution now defers to ``git rev-parse --git-path hooks``.+"""++from __future__ import annotations++import subprocess++import pytest++from repowise.cli.hooks import (+ _hooks_dir,+ _husky_user_hook_dir,+ husky_pending_reason,+ install,+ status,+ uninstall,+)+++def _git(*args: str, cwd) -> subprocess.CompletedProcess:+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def git_repo(tmp_path):+ _git("init", "-q", cwd=tmp_path)+ return tmp_path+++def committed_repo(git_repo):+ """A repo with one commit, so ``git worktree add`` is possible."""+ (git_repo / "seed.txt").write_text("seed\n")+ _git("add", "seed.txt", cwd=git_repo)+ _git(+ "-c",+ "[email protected]",+ "-c",+ "user.name=T",+ "commit",+ "-qm",+ "seed",+ cwd=git_repo,+ )+ return git_repo+++def test_plain_repo_resolves_to_git_hooks(git_repo):+ assert _hooks_dir(git_repo) == git_repo / ".git" / "hooks"+++def test_core_hooks_path_is_honoured(git_repo):+ """A hook written to .git/hooks would never run when hooksPath is set."""+ _git("config", "core.hooksPath", "my-hooks", cwd=git_repo)++ assert _hooks_dir(git_repo) == git_repo / "my-hooks"++ assert install(git_repo) == "installed"+ assert (git_repo / "my-hooks" / "post-commit").exists()+ assert not (git_repo / ".git" / "hooks" / "post-commit").exists()+++def test_absolute_core_hooks_path_is_honoured(git_repo, tmp_path):+ outside = tmp_path / "elsewhere"+ outside.mkdir()+ _git("config", "core.hooksPath", str(outside), cwd=git_repo)++ assert _hooks_dir(git_repo) == outside+++def test_husky_generated_dir_remaps_to_user_hook_dir(git_repo):+ """`.husky/_` is regenerated and gitignored; the durable path is `.husky/`."""+ husky_generated = git_repo / ".husky" / "_"+ husky_generated.mkdir(parents=True)+ (husky_generated / "h").write_text("#!/usr/bin/env sh\n")+ (husky_generated / ".gitignore").write_text("*\n")+ _git("config", "core.hooksPath", ".husky/_", cwd=git_repo)++ assert _hooks_dir(git_repo) == git_repo / ".husky"++ assert install(git_repo) == "installed"+ assert (git_repo / ".husky" / "post-commit").exists()+ # Not in the generated dir, which the next `npm install` would wipe.+ assert not (husky_generated / "post-commit").exists()+++def test_husky_remap_without_generated_helpers(git_repo):+ """A fresh worktree has committed `.husky/` but no generated `_` yet."""+ _git("config", "core.hooksPath", ".husky/_", cwd=git_repo)+ (git_repo / ".husky").mkdir()++ assert _hooks_dir(git_repo) == git_repo / ".husky"+++def test_directory_merely_named_underscore_is_not_remapped(tmp_path):+ """Only husky's layout is special-cased, not any directory called `_`."""+ plain = tmp_path / "hooks" / "_"+ plain.mkdir(parents=True)++ assert _husky_user_hook_dir(plain) == plain+++def test_install_in_linked_worktree_does_not_raise(committed_repo, tmp_path):+ """Regression: `.git` is a file in a worktree, so mkdir raised NotADirectoryError."""+ worktree = tmp_path / "wt"+ _git("worktree", "add", "-q", str(worktree), "-b", "wt-branch", cwd=committed_repo)+ assert (worktree / ".git").is_file()++ assert install(worktree) == "installed"+ assert status(worktree) == "installed"+++def test_install_status_uninstall_agree_on_location(git_repo):+ """All three entry points must resolve the same directory."""+ _git("config", "core.hooksPath", ".husky/_", cwd=git_repo)+ # A fully set-up husky, so the status strings carry no pending-reason suffix.+ generated = git_repo / ".husky" / "_"+ generated.mkdir(parents=True)+ (generated / "h").write_text("#!/usr/bin/env sh\n")++ assert install(git_repo) == "installed"+ assert status(git_repo) == "installed"+ assert uninstall(git_repo) == "removed"+ assert status(git_repo) == "not installed"+++def test_husky_dispatches_without_a_preexisting_user_hook(git_repo):+ """A missing sibling user hook does not stop dispatch.++ husky writes a shim for all 14 hook names on every install regardless of what+ is in ``.husky/``, so ``post-commit`` is dispatched immediately -- there is no+ need to wait for the next ``npm install``.+ """+ generated = git_repo / ".husky" / "_"+ generated.mkdir(parents=True)+ (generated / "h").write_text("#!/usr/bin/env sh\n")+ (generated / "post-commit").write_text('#!/usr/bin/env sh\n. "$(dirname "$0")/h"\n')+ _git("config", "core.hooksPath", ".husky/_", cwd=git_repo)+ # Only pre-commit exists as a user hook; post-commit does not.+ (git_repo / ".husky" / "pre-commit").write_text("npm test\n")++ assert install(git_repo) == "installed"+ assert husky_pending_reason(git_repo / ".husky") is None+ assert status(git_repo) == "installed"+++def test_husky_not_installed_is_reported_not_silent(git_repo):+ """Without husky's generated dir, core.hooksPath points nowhere and git runs nothing.++ The hook still belongs in ``.husky/`` because that survives, but claiming a+ bare "installed" would repeat the very failure this resolver exists to fix.+ """+ _git("config", "core.hooksPath", ".husky/_", cwd=git_repo)+ (git_repo / ".husky").mkdir() # committed dir, but husky never ran++ reason = husky_pending_reason(git_repo / ".husky")+ assert reason is not None+ assert "husky is not set up" in reason++ result = install(git_repo)+ assert result.startswith("installed (")+ assert "no .husky/_" in result+ assert (git_repo / ".husky" / "post-commit").exists()+ assert "husky is not set up" in status(git_repo)+++def test_pending_reason_is_silent_for_non_husky_layouts(git_repo):+ assert husky_pending_reason(git_repo / ".git" / "hooks") is None+ assert husky_pending_reason(git_repo / "my-hooks") is None+++def test_falls_back_when_git_unavailable(git_repo, monkeypatch):+ """Without a usable git binary, keep the historical guess rather than fail."""++ def _boom(*_args, **_kwargs):+ raise OSError("no git")++ monkeypatch.setattr(subprocess, "run", _boom)++ assert _hooks_dir(git_repo) == git_repo / ".git" / "hooks"