Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(uninstall): list and remove the post-commit hook that init installs (#2655)

Amanf7a443558e97
diff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.py
index d0981063e..eccf411e4 100644
--- a/packages/cli/src/repowise/cli/hooks.py
+++ b/packages/cli/src/repowise/cli/hooks.py
@@ -197,6 +197,41 @@ def _hooks_dir(repo_path: Path) -> Path | None:
return root / ".git" / "hooks"
+def removal_blocked_reason(repo_path: Path, hooks_dir: Path) -> str | None:
+ """Why the hook at *hooks_dir* must not be removed from *repo_path*, or ``None``.
+
+ Two shapes, both about a hooks directory that outlives this one repo.
+
+ A linked git worktree stores no hooks of its own: ``_hooks_dir`` follows
+ ``--git-path``, which resolves through the worktree's common dir straight
+ to the main checkout's ``.git/hooks``. Removing the hook from a worktree
+ would remove the one hook every other worktree (including the main
+ checkout) also runs on their own commits.
+
+ A global ``core.hooksPath`` (husky, lefthook, a user dotfile) is the same
+ problem at machine scope: the directory is shared across every repo that
+ points at it, and ``uninstall`` is deliberately scoped to one repo (unlike
+ ``repowise hook uninstall``, whose whole job is the hooks command).
+ """
+ from repowise.cli.worktree import detect_worktree_base
+
+ base = detect_worktree_base(repo_path)
+ if base is not None:
+ return f"this is a worktree; the hook lives in the main checkout at {base}"
+
+ root = _git_root(repo_path)
+ if root is not None:
+ try:
+ hooks_dir.resolve().relative_to(root.resolve())
+ return None
+ except (OSError, ValueError):
+ pass
+ return (
+ "core.hooksPath points outside this repo; removing the hook here "
+ "would remove it for every repo that shares it"
+ )
+
+
def _is_shell_hook(content: str) -> bool:
"""Whether an existing hook file can take an appended POSIX sh block.
@@ -477,7 +512,10 @@ def _remove_block(repo_path: Path, hook_name: str, start: str, end: str) -> str:
if not hook_path.exists():
return f"no {hook_name} hook found"
- content = hook_path.read_text(encoding="utf-8")
+ try:
+ content = hook_path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as exc:
+ return f"could not read {hook_name} hook: {exc}"
if start not in content:
return f"repowise hook not found in {hook_name}"
@@ -513,7 +551,10 @@ def _block_status(repo_path: Path, hook_name: str, start: str) -> str:
if not hook_path.exists():
return "not installed"
- content = hook_path.read_text(encoding="utf-8")
+ try:
+ content = hook_path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return "unreadable"
if start in content:
pending = husky_pending_reason(hook_path.parent)
state = "installed" if _is_executable(hook_path) else "installed but not executable"
diff --git a/packages/cli/src/repowise/cli/uninstall/inventory.py b/packages/cli/src/repowise/cli/uninstall/inventory.py
index c15b4089c..6bd7f9397 100644
--- a/packages/cli/src/repowise/cli/uninstall/inventory.py
+++ b/packages/cli/src/repowise/cli/uninstall/inventory.py
@@ -361,6 +361,46 @@ def _repo_file_items(repo_path: Path) -> list[Item]:
return items
+def _hook_item(repo_path: Path) -> Item | None:
+ """The post-commit auto-sync hook, as one row in ``REPO_FILES``.
+
+ Grouped with the generated blocks rather than given its own group, per
+ repo instructions: the hook only runs ``repowise update``, which is
+ useless once the index is gone, so there is no real case for keeping the
+ hook while removing the index. ``None`` when there is no repository to
+ look in, the same as every other group falls silent rather than raising.
+ """
+ from repowise.cli import hooks
+
+ hooks_dir = hooks._hooks_dir(repo_path)
+ if hooks_dir is None:
+ return None
+ hook_path = hooks_dir / "post-commit"
+ outcome = hooks.status(repo_path)
+ if outcome == "unreadable":
+ # The hook file is there but not one this command can safely parse
+ # (binary, wrong encoding). Listed and refused, not skipped: silently
+ # reporting "not found" would hide the fact that something is at this
+ # path, and guessing at its content to decide removal is worse.
+ return Item(
+ group=Group.REPO_FILES,
+ path=hook_path,
+ label="post-commit auto-sync hook",
+ exists=True,
+ size=_size_of(hook_path),
+ blocked="the hook file could not be read (binary or non-UTF-8 content)",
+ )
+ installed = outcome.startswith("installed")
+ return Item(
+ group=Group.REPO_FILES,
+ path=hook_path,
+ label="post-commit auto-sync hook",
+ exists=installed,
+ size=_size_of(hook_path) if installed else None,
+ blocked=hooks.removal_blocked_reason(repo_path, hooks_dir) if installed else None,
+ )
+
+
def _global_items() -> list[Item]:
"""``~/.repowise/`` as one row, with the two consequences named.
@@ -453,6 +493,9 @@ def build_plan(repo_path: Path) -> Plan:
plan = Plan(repo_path=repo_path)
plan.items.extend(_agent_items(repo_path))
plan.items.extend(_repo_file_items(repo_path))
+ hook_item = _hook_item(repo_path)
+ if hook_item is not None:
+ plan.items.append(hook_item)
plan.items.append(
Item(
group=Group.INDEX,
diff --git a/packages/cli/src/repowise/cli/uninstall/runner.py b/packages/cli/src/repowise/cli/uninstall/runner.py
index b6e48b24b..5e855a7ea 100644
--- a/packages/cli/src/repowise/cli/uninstall/runner.py
+++ b/packages/cli/src/repowise/cli/uninstall/runner.py
@@ -149,6 +149,7 @@ def _remove_repo_files(repo_path: Path, plan: Plan) -> list[Result]:
from .generated_files import generated_blocks, remove_block
by_path = {item.path: item for item in plan.for_groups(frozenset({Group.REPO_FILES}))}
+ block_paths = {block.path(repo_path) for block in generated_blocks()}
results: list[Result] = []
for block in generated_blocks():
item = by_path.get(block.path(repo_path))
@@ -168,9 +169,52 @@ def _remove_repo_files(repo_path: Path, plan: Plan) -> list[Result]:
results.append(
Result(group=Group.REPO_FILES, path=path, action=action, label=label, reason=reason)
)
+
+ # The post-commit hook is grouped with the generated blocks (its only job
+ # is `repowise update`, useless with no index) but is not one of them:
+ # `generated_blocks()` describes marker-bracketed sections in tracked
+ # files, and the hook lives under `.git/hooks`, outside the working tree.
+ for path, item in by_path.items():
+ if path in block_paths:
+ continue
+ results.append(_remove_hook(repo_path, item))
return results
+def _remove_hook(repo_path: Path, item: Item) -> Result:
+ from repowise.cli import hooks
+
+ if item.blocked:
+ return Result(
+ group=Group.REPO_FILES,
+ path=item.path,
+ action=FileAction.KEPT,
+ label=item.label,
+ reason=item.blocked,
+ )
+ if not item.exists:
+ return Result(
+ group=Group.REPO_FILES, path=item.path, action=FileAction.NOT_FOUND, label=item.label
+ )
+ outcome = hooks.uninstall(repo_path)
+ if outcome.startswith("removed"):
+ reason = "other hook content preserved" if "preserved" in outcome else None
+ return Result(
+ group=Group.REPO_FILES,
+ path=item.path,
+ action=FileAction.REMOVED,
+ label=item.label,
+ reason=reason,
+ )
+ return Result(
+ group=Group.REPO_FILES,
+ path=item.path,
+ action=FileAction.FAILED,
+ label=item.label,
+ reason=outcome,
+ )
+
+
def _is_link(path: Path) -> bool:
"""Symlink or Windows junction.
diff --git a/tests/unit/cli/test_hooks_path_resolution.py b/tests/unit/cli/test_hooks_path_resolution.py
index 0c333b80b..bac0877bf 100644
--- a/tests/unit/cli/test_hooks_path_resolution.py
+++ b/tests/unit/cli/test_hooks_path_resolution.py
@@ -25,6 +25,7 @@ from repowise.cli.hooks import (
_husky_user_hook_dir,
husky_pending_reason,
install,
+ removal_blocked_reason,
status,
uninstall,
)
@@ -191,3 +192,49 @@ def test_falls_back_when_git_unavailable(git_repo, monkeypatch):
monkeypatch.setattr(subprocess, "run", _boom)
assert _hooks_dir(git_repo) == git_repo / ".git" / "hooks"
+
+
+class TestRemovalBlockedReason:
+ """``repowise uninstall`` must not remove a hook shared beyond this repo (#2469)."""
+
+ def test_a_plain_repos_own_hooks_dir_is_not_blocked(self, git_repo):
+ hooks_dir = _hooks_dir(git_repo)
+ assert removal_blocked_reason(git_repo, hooks_dir) is None
+
+ def test_a_global_core_hooks_path_is_blocked(self, git_repo, tmp_path_factory):
+ # A sibling of `git_repo`'s own tmp dir, not a subdirectory of it: the
+ # point under test is a hooks path genuinely outside the repository,
+ # and `git_repo` already *is* the `tmp_path` this test would otherwise
+ # reach for.
+ outside = tmp_path_factory.mktemp("elsewhere")
+ _git("config", "core.hooksPath", str(outside), cwd=git_repo)
+
+ hooks_dir = _hooks_dir(git_repo)
+ reason = removal_blocked_reason(git_repo, hooks_dir)
+
+ assert reason is not None
+ assert "outside this repo" in reason
+
+ def test_a_worktree_is_blocked_and_names_the_main_checkout(self, committed_repo, tmp_path):
+ wt = tmp_path / "wt"
+ _git("worktree", "add", "-b", "feature", str(wt), cwd=committed_repo)
+
+ hooks_dir = _hooks_dir(wt)
+ reason = removal_blocked_reason(wt, hooks_dir)
+
+ assert reason is not None
+ assert str(committed_repo) in reason
+
+ def test_a_repo_local_hooks_path_outside_git_is_not_blocked(self, git_repo):
+ """A repo-local path such as ``.husky`` is not ``.git``, but is still this repo.
+
+ Regression: the first cut compared against ``root / ".git"`` instead of
+ ``root`` itself, so any repo-local ``core.hooksPath`` outside ``.git``
+ (husky's own layout, or a plain ``hooks/`` directory) was reported
+ blocked and left permanently installed.
+ """
+ _git("config", "core.hooksPath", ".husky", cwd=git_repo)
+ (git_repo / ".husky").mkdir()
+
+ hooks_dir = _hooks_dir(git_repo)
+ assert removal_blocked_reason(git_repo, hooks_dir) is None
diff --git a/tests/unit/cli/test_uninstall_cmd.py b/tests/unit/cli/test_uninstall_cmd.py
index 6d4cd63a7..9aca8f0d7 100644
--- a/tests/unit/cli/test_uninstall_cmd.py
+++ b/tests/unit/cli/test_uninstall_cmd.py
@@ -18,6 +18,7 @@ redirect, so neither layer is optional.
from __future__ import annotations
import json
+import subprocess
from pathlib import Path
import pytest
@@ -616,3 +617,105 @@ def test_the_two_agents_md_blocks_are_removed_independently(repo: Path) -> None:
remaining = agents.read_text(encoding="utf-8") if agents.exists() else ""
assert "REPOWISE_AGENTS:START" not in remaining
assert "REPOWISE_DISTILL:START" not in remaining
+
+
+def _git(*args: str, cwd: Path) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+class TestPostCommitHookRemoval:
+ """``repowise uninstall`` must also take the auto-sync hook with it (#2469)."""
+
+ def test_all_removes_the_post_commit_hook(self, repo: Path) -> None:
+ from repowise.cli import hooks
+
+ _git("init", "-q", cwd=repo)
+ assert hooks.install(repo) == "installed"
+
+ result = _invoke(["uninstall", str(repo), "--all"])
+
+ assert result.exit_code == 0
+ assert hooks.status(repo) == "not installed"
+
+ def test_keep_index_also_removes_the_hook(self, repo: Path) -> None:
+ """It is grouped with the generated blocks, not the index (Raghav's call)."""
+ from repowise.cli import hooks
+
+ _git("init", "-q", cwd=repo)
+ assert hooks.install(repo) == "installed"
+
+ _invoke(["uninstall", str(repo), "--keep-index"])
+
+ assert hooks.status(repo) == "not installed"
+ assert (repo / ".repowise" / "wiki.db").exists()
+
+ def test_no_hook_installed_reports_nothing_to_do(self, repo: Path) -> None:
+ _git("init", "-q", cwd=repo)
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ hook_rows = [
+ r for r in payload["results"] if "hook" in r["label"] and r["group"] == "repo-files"
+ ]
+ assert hook_rows and hook_rows[0]["action"] == "not-found"
+
+ def test_a_global_hooks_path_is_blocked_and_named(self, repo: Path) -> None:
+ from repowise.cli import hooks
+
+ _git("init", "-q", cwd=repo)
+ outside = repo.parent / "shared-hooks"
+ outside.mkdir()
+ _git("config", "core.hooksPath", str(outside), cwd=repo)
+ assert hooks.install(repo) == "installed"
+
+ result = _invoke(["uninstall", str(repo), "--all", "--format", "json"])
+ payload = json.loads(result.output)
+
+ assert hooks.status(repo).startswith("installed")
+ hook_row = next(r for r in payload["results"] if "hook" in r["label"])
+ assert hook_row["action"] == "kept"
+ assert "outside this repo" in hook_row["reason"]
+ assert result.exit_code == 3
+
+ def test_a_worktree_hook_is_blocked_and_names_the_main_checkout(
+ self, repo: Path, tmp_path: Path
+ ) -> None:
+ from repowise.cli import hooks
+
+ _git("init", "-q", cwd=repo)
+ (repo / "seed.txt").write_text("seed\n", encoding="utf-8")
+ _git("add", "seed.txt", cwd=repo)
+ _git("-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "seed", cwd=repo)
+ assert hooks.install(repo) == "installed"
+
+ wt = tmp_path / "wt"
+ _git("worktree", "add", "-b", "feature", str(wt), cwd=repo)
+
+ payload = _payload(["uninstall", str(wt), "--all"])
+
+ hook_row = next(r for r in payload["results"] if "hook" in r["label"])
+ assert hook_row["action"] == "kept"
+ assert str(repo) in hook_row["reason"]
+ assert hooks.status(repo).startswith("installed")
+
+ def test_an_unreadable_hook_is_named_rather_than_crashing_the_plan(self, repo: Path) -> None:
+ """Regression: binary/non-UTF-8 hook content used to raise while building the plan.
+
+ `hooks.status` decoded the whole file as UTF-8 with no guard, so a
+ valid executable hook holding arbitrary bytes (or one merely unreadable)
+ took the entire `uninstall` inventory down with it instead of being
+ reported and left alone.
+ """
+ from repowise.cli import hooks
+
+ _git("init", "-q", cwd=repo)
+ hooks_dir = hooks._hooks_dir(repo)
+ hooks_dir.mkdir(parents=True, exist_ok=True)
+ (hooks_dir / "post-commit").write_bytes(b"#!/bin/sh\n\xff\xfe\x00binary garbage")
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ hook_row = next(r for r in payload["results"] if "hook" in r["label"])
+ assert hook_row["action"] == "kept"
+ assert "could not be read" in hook_row["reason"]
+ assert (hooks_dir / "post-commit").exists()