diff --git a/src/pkgmgr/actions/branch/gc.py b/src/pkgmgr/actions/branch/gc.py index 3d54fca..77935e9 100644 --- a/src/pkgmgr/actions/branch/gc.py +++ b/src/pkgmgr/actions/branch/gc.py @@ -29,6 +29,7 @@ from pkgmgr.core.git.run import ( ) from .gc_forge import ForgeFacts, fetch_forge_facts +from .gc_refs import _common_dir, _git_dirs, _held_branches, _symbolic from .nofollow import canonical, remove_tree Registrations = tuple[str, dict[str, list[str]]] @@ -71,12 +72,6 @@ NO_REMOTE_DEFAULT = ( ) NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8" DEFAULT_NAMES = ("HEAD", "main", "master") -HELD_FILES = ( - ("rebase-merge/head-name", "rebase in progress"), - ("rebase-merge/update-refs", "rebase in progress"), - ("rebase-apply/head-name", "rebase in progress"), - ("BISECT_START", "bisect in progress"), -) DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$" SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs") WALKED_STORES = ("refs", "reftable", "logs/refs") @@ -265,10 +260,6 @@ def _config_read(args: list[str], cwd: str, view: str) -> str: return run(args, cwd=cwd, scan=True, config_view=view) -def _common_dir(cwd: str) -> str: - return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd) - - def _docker(args: list[str]) -> str: return subprocess.run( ["docker", *args], check=True, capture_output=True, text=True @@ -761,7 +752,11 @@ def _build( and (time.time() - item.last_activity) / 3600 < repo.min_age ): item.skip = f"younger than {repo.min_age:g} h" - item.actions = _actions(repo, item, tree, checkout, dirty, registrations, held) + item.actions = ( + _local_actions(repo, item, tree, held) + if repo.scope == "local" + else _actions(repo, item, tree, checkout, dirty, registrations) + ) if repo.unsafe: item.actions = [a for a in item.actions if not a.startswith("remote-branch:")] return item @@ -774,10 +769,7 @@ def _actions( checkout: bool, dirty: int, registrations: Registrations, - held: Callable[[], dict[str, str]], ) -> list[str]: - if repo.scope == "local": - return _local_actions(repo, item, tree, held) tree_part: list[str] = [] if tree: if ( @@ -922,25 +914,6 @@ def _default_remote(remotes: list[str]) -> str | None: return remotes[0] if len(remotes) == 1 else None -def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]: - """ - List the resolvable refs under a prefix with their symref targets. - - Args: - repo_root: main worktree root of the repository. - prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`. - git_dir: the git common dir (shared refs plus the main worktree's own) - or a `worktrees/` dir whose refs to list, or "" for the refs - as repo_root's worktree sees them. - - Returns: - Full ref name -> the ref it points to, or "" for a plain ref. - """ - args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix] - out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root) - return dict(line.split("\x00", 1) for line in out.splitlines()) - - def _resolve_within(refs: dict[str, str], ref: str) -> str | None: """ Follow a ref's symref chain without leaving a set of refs. @@ -986,109 +959,6 @@ def _remote_default(repo_root: str, remotes: list[str]) -> str | None: return None -def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]: - """ - Read the branch every worktree's HEAD names, on any ref backend. - - Args: - repo_root: main worktree root of the repository. - git_dirs: the git common dir first, then each `worktrees/`. - - Returns: - Branch name -> skip reason, from `git --git-dir= symbolic-ref - HEAD` for each of them, whatever its id. - - Raises: - GitBaseError: when a HEAD is neither readable nor detached. - """ - heads: dict[str, str] = {} - for git_dir in git_dirs: - try: - target = _git( - [f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root - ) - except GitRunError as exc: - if exc.returncode == 1: - continue - raise - if target.startswith("refs/heads/"): - heads.setdefault( - target.removeprefix("refs/heads/"), f"checked out in {git_dir}" - ) - return heads - - -def _git_dirs(repo_root: str) -> list[str]: - """ - List the git dirs of every worktree of the repository. - - Args: - repo_root: main worktree root of the repository. - - Returns: - The git common dir, then each entry of `/worktrees/`, whatever - its id and whether `git worktree list` shows it. - """ - common = _common_dir(repo_root) - base = os.path.join(common, "worktrees") - entries = sorted(os.listdir(base)) if os.path.isdir(base) else [] - return [common, *(os.path.join(base, entry) for entry in entries)] - - -def _held_branches(repo_root: str) -> dict[str, str]: - """ - Find the local branches that something besides a listed worktree holds. - - Args: - repo_root: main worktree root of the repository. - - Returns: - Branch name -> skip reason: a symbolic branch, the branch any symbolic - ref under `refs/` (also a tag or remote-tracking one) or under the - main worktree's or any registration's `refs/worktree/` names, the HEAD - of the main repository and of every `worktrees/` registration, - also one `git worktree list` omits, each rebase-merge and rebase-apply - head-name, an interactive rebase's update-refs and BISECT_START; all - read through the git common dir, whichever worktree repo_root is. - - Raises: - GitBaseError: when git cannot read a registration, symref or HEAD. - OSError: when a state file exists but cannot be read. - ValueError: when a state file is not UTF-8. - """ - git_dirs = _git_dirs(repo_root) - held: dict[str, str] = {} - symrefs = _symbolic(repo_root, "refs", git_dirs[0]) - for git_dir in git_dirs[1:]: - for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items(): - symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target - for ref, target in symrefs.items(): - if target and ref.startswith("refs/heads/"): - held.setdefault( - ref.removeprefix("refs/heads/"), f"symbolic ref to {target}" - ) - if target.startswith("refs/heads/"): - held.setdefault( - target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}" - ) - for branch, reason in _worktree_heads(repo_root, git_dirs).items(): - held.setdefault(branch, reason) - for git_dir in git_dirs: - for name, operation in HELD_FILES: - try: - with open(os.path.join(git_dir, name), encoding="utf-8") as fh: - lines = fh.read().splitlines() - except FileNotFoundError: - continue - for line in lines: - ref = line.strip().removeprefix("ref: ") - if ref.startswith("refs/heads/") or name == "BISECT_START": - held.setdefault( - ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}" - ) - return held - - def _lines( repo_root: str, refs: list[str], remotes: list[str], warnings: list[str] ) -> tuple[dict[str, tuple[str, set[str]]], set[str]]: diff --git a/src/pkgmgr/actions/branch/gc_refs.py b/src/pkgmgr/actions/branch/gc_refs.py new file mode 100644 index 0000000..92f5192 --- /dev/null +++ b/src/pkgmgr/actions/branch/gc_refs.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import os + +from pkgmgr.core.git import GitRunError, run + +HELD_FILES = ( + ("rebase-merge/head-name", "rebase in progress"), + ("rebase-merge/update-refs", "rebase in progress"), + ("rebase-apply/head-name", "rebase in progress"), + ("BISECT_START", "bisect in progress"), +) + + +def _git(args: list[str], cwd: str) -> str: + return run(args, cwd=cwd, scan=True) + + +def _common_dir(cwd: str) -> str: + return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd) + + +def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]: + """ + List the resolvable refs under a prefix with their symref targets. + + Args: + repo_root: main worktree root of the repository. + prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`. + git_dir: the git common dir (shared refs plus the main worktree's own) + or a `worktrees/` dir whose refs to list, or "" for the refs + as repo_root's worktree sees them. + + Returns: + Full ref name -> the ref it points to, or "" for a plain ref. + """ + args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix] + out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root) + return dict(line.split("\x00", 1) for line in out.splitlines()) + + +def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]: + """ + Read the branch every worktree's HEAD names, on any ref backend. + + Args: + repo_root: main worktree root of the repository. + git_dirs: the git common dir first, then each `worktrees/`. + + Returns: + Branch name -> skip reason, from `git --git-dir= symbolic-ref + HEAD` for each of them, whatever its id. + + Raises: + GitBaseError: when a HEAD is neither readable nor detached. + """ + heads: dict[str, str] = {} + for git_dir in git_dirs: + try: + target = _git( + [f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root + ) + except GitRunError as exc: + if exc.returncode == 1: + continue + raise + if target.startswith("refs/heads/"): + heads.setdefault( + target.removeprefix("refs/heads/"), f"checked out in {git_dir}" + ) + return heads + + +def _git_dirs(repo_root: str) -> list[str]: + """ + List the git dirs of every worktree of the repository. + + Args: + repo_root: main worktree root of the repository. + + Returns: + The git common dir, then each entry of `/worktrees/`, whatever + its id and whether `git worktree list` shows it. + """ + common = _common_dir(repo_root) + base = os.path.join(common, "worktrees") + entries = sorted(os.listdir(base)) if os.path.isdir(base) else [] + return [common, *(os.path.join(base, entry) for entry in entries)] + + +def _held_branches(repo_root: str) -> dict[str, str]: + """ + Find the local branches that something besides a listed worktree holds. + + Args: + repo_root: main worktree root of the repository. + + Returns: + Branch name -> skip reason: a symbolic branch, the branch any symbolic + ref under `refs/` (also a tag or remote-tracking one) or under the + main worktree's or any registration's `refs/worktree/` names, the HEAD + of the main repository and of every `worktrees/` registration, + also one `git worktree list` omits, each rebase-merge and rebase-apply + head-name, an interactive rebase's update-refs and BISECT_START; all + read through the git common dir, whichever worktree repo_root is. + + Raises: + GitBaseError: when git cannot read a registration, symref or HEAD. + OSError: when a state file exists but cannot be read. + ValueError: when a state file is not UTF-8. + """ + git_dirs = _git_dirs(repo_root) + held: dict[str, str] = {} + symrefs = _symbolic(repo_root, "refs", git_dirs[0]) + for git_dir in git_dirs[1:]: + for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items(): + symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target + for ref, target in symrefs.items(): + if target and ref.startswith("refs/heads/"): + held.setdefault( + ref.removeprefix("refs/heads/"), f"symbolic ref to {target}" + ) + if target.startswith("refs/heads/"): + held.setdefault( + target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}" + ) + for branch, reason in _worktree_heads(repo_root, git_dirs).items(): + held.setdefault(branch, reason) + for git_dir in git_dirs: + for name, operation in HELD_FILES: + try: + with open(os.path.join(git_dir, name), encoding="utf-8") as fh: + lines = fh.read().splitlines() + except FileNotFoundError: + continue + for line in lines: + ref = line.strip().removeprefix("ref: ") + if ref.startswith("refs/heads/") or name == "BISECT_START": + held.setdefault( + ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}" + ) + return held diff --git a/tests/integration/test_branch_cleanup_local.py b/tests/integration/test_branch_cleanup_local.py index 195cc57..2a3048c 100644 --- a/tests/integration/test_branch_cleanup_local.py +++ b/tests/integration/test_branch_cleanup_local.py @@ -13,7 +13,7 @@ from contextlib import contextmanager, redirect_stderr, redirect_stdout from types import SimpleNamespace from unittest.mock import patch -from pkgmgr.actions.branch import gc, gc_forge, tree +from pkgmgr.actions.branch import gc, gc_forge, gc_refs, tree from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots from pkgmgr.cli.parser import create_parser from pkgmgr.core.credentials.types import NoCredentialsError @@ -489,52 +489,6 @@ class TestBranchCleanupLocal(unittest.TestCase): heads["refs/heads/local-done"], ) - def test_plan_reads_the_held_branches_once_per_repository(self) -> None: - self._set_head() - extra = ("more-a", "more-b", "more-c") - for name in extra: - git(self.repo, "branch", name, "done") - - with patch.object(gc, "_held_branches", wraps=gc._held_branches) as held: - run = self._cleanup("local", apply=False) - - self.assertEqual(held.call_count, 1) - self.assertEqual( - {name for name, i in run.items.items() if i["actions"]}, - {"done", "local-done", *extra}, - ) - - def test_branch_held_after_the_plan_is_not_deleted(self) -> None: - self._set_head() - real = gc._rebuild - changes = [ - lambda: git( - self.repo, "symbolic-ref", "refs/tags/pin", "refs/heads/local-done" - ) - ] - - def late(repo: gc.Repo, item: gc.Item) -> gc.Item: - if changes: - changes.pop()() - return real(repo, item) - - with ( - patch.object(gc, "_held_branches", wraps=gc._held_branches) as held, - patch.object(gc, "_rebuild", side_effect=late), - ): - run = self._cleanup("local", apply=True) - - self.assertEqual(held.call_count, 3) - self.assertEqual( - self._results(run), - { - "done": "done", - "local-done": "skipped: changed since plan " - "(target of symbolic ref refs/tags/pin)", - }, - ) - self.assertIn("refs/heads/local-done", self._refs(self.repo, "refs/heads")) - def test_delete_never_follows_a_symref_made_after_the_check(self) -> None: planned = git(self.repo, "rev-parse", "held-done") @@ -1693,7 +1647,7 @@ class TestBranchCleanupLocal(unittest.TestCase): def test_failed_head_read_refuses_the_repository(self) -> None: heads = self._refs(self.repo, "refs/heads") - real = gc._git + real = gc_refs._git def timed_out(args: list[str], cwd: str) -> str: if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]: @@ -1702,7 +1656,7 @@ class TestBranchCleanupLocal(unittest.TestCase): raise err return real(args, cwd) - with patch.object(gc, "_git", side_effect=timed_out): + with patch.object(gc_refs, "_git", side_effect=timed_out): run = self._cleanup("local", apply=True) self.assertEqual(run.code, 2) diff --git a/tests/unit/pkgmgr/actions/branch/test_gc_held_once.py b/tests/unit/pkgmgr/actions/branch/test_gc_held_once.py new file mode 100644 index 0000000..d5b15f4 --- /dev/null +++ b/tests/unit/pkgmgr/actions/branch/test_gc_held_once.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import io +import json +import os +import subprocess +import tempfile +import unittest +from contextlib import ExitStack, redirect_stderr, redirect_stdout +from unittest.mock import patch + +from pkgmgr.actions.branch import gc + +AUTHOR = { + "GIT_AUTHOR_NAME": "t", + "GIT_AUTHOR_EMAIL": "t@example.org", + "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.org", +} +MERGED = 12 +REGISTRATIONS = 40 + + +class TestHeldBranchesReadOnce(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = os.path.realpath(tmp.name) + self.addCleanup(os.chdir, os.getcwd()) + os.chdir(self.root) + home = os.path.join(self.root, "home") + os.makedirs(home) + clean = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + patcher = patch.dict(os.environ, {**clean, "HOME": home}, clear=True) + patcher.start() + self.addCleanup(patcher.stop) + self.repo = os.path.join(self.root, "repo") + self._shape() + + def git(self, *args: str) -> str: + return subprocess.run( + ["git", "-c", "commit.gpgsign=false", *args], + cwd=self.repo, + env={**os.environ, **AUTHOR}, + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + def _write(self, path: str, text: str) -> None: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + fh.write(text) + + def _shape(self) -> None: + origin = os.path.join(self.root, "origin.git") + subprocess.run( + ["git", "init", "-q", "--bare", "-b", "main", origin], check=True + ) + subprocess.run(["git", "init", "-q", "-b", "main", self.repo], check=True) + self.git("remote", "add", "origin", origin) + self._write(os.path.join(self.repo, "c1"), "c1") + self.git("add", "c1") + self.git("commit", "-q", "-m", "c1") + self.git("checkout", "-q", "-b", "side") + self._write(os.path.join(self.repo, "f1"), "f1") + self.git("add", "f1") + self.git("commit", "-q", "-m", "f1") + f1 = self.git("rev-parse", "HEAD") + self.git("checkout", "-q", "main") + self.git("merge", "-q", "--no-ff", "-m", "m1", "side") + self.git("branch", "-q", "-D", "side") + self.git("push", "-q", "origin", "main") + self.git("fetch", "-q", "origin") + self.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + for index in range(MERGED): + self.git("branch", f"merged-{index:03d}", f1) + self.git("symbolic-ref", "refs/heads/alias", "refs/heads/merged-001") + base = os.path.join(self.repo, ".git", "worktrees") + for index in range(REGISTRATIONS): + reg = os.path.join(base, f"wt{index:03d}") + head = "ref: refs/heads/merged-002\n" if index == 7 else f"{f1}\n" + self._write(os.path.join(reg, "HEAD"), head) + self._write(os.path.join(reg, "commondir"), "../..\n") + self._write( + os.path.join(reg, "gitdir"), f"{self.root}/gone/wt{index:03d}/.git\n" + ) + self._write( + os.path.join(base, "wt011", "rebase-merge", "head-name"), + "refs/heads/merged-003\n", + ) + self._write(os.path.join(self.repo, ".git", "BISECT_START"), "merged-004\n") + + def _run(self, *, cached: bool = True, apply: bool = False) -> tuple[dict, int]: + out = io.StringIO() + with ExitStack() as stack: + held = stack.enter_context( + patch.object(gc, "_held_branches", wraps=gc._held_branches) + ) + if not cached: + stack.enter_context( + patch.object(gc, "cache", side_effect=lambda func: func) + ) + stack.enter_context( + patch.object(gc, "host_pid_namespace", return_value=True) + ) + stack.enter_context(patch.object(gc, "_process_cwds", return_value={})) + stack.enter_context(redirect_stdout(out)) + stack.enter_context(redirect_stderr(io.StringIO())) + code = gc.cleanup( + [self.repo], + scope="local", + apply=apply, + as_json=True, + include=[], + exclude=[], + merged_into=[], + sizes=False, + min_age=None, + hooks={}, + ) + self.assertEqual(code, 0) + return json.loads(out.getvalue()), held.call_count + + def _items(self, plan: dict) -> dict: + return {i["branch"]: i for i in plan["repos"][0]["items"]} + + def test_one_read_gives_the_plan_of_one_read_per_branch(self) -> None: + per_branch, old_reads = self._run(cached=False) + once, new_reads = self._run() + + self.assertEqual(once, per_branch) + self.assertEqual(new_reads, 1) + self.assertGreaterEqual(old_reads, MERGED - 1) + items = self._items(once) + self.assertIn("symbolic ref", items["alias"]["skip"]) + self.assertIn("target of symbolic ref", items["merged-001"]["skip"]) + self.assertIn("checked out in", items["merged-002"]["skip"]) + self.assertIn("rebase in progress", items["merged-003"]["skip"]) + self.assertIn("bisect in progress", items["merged-004"]["skip"]) + deletable = sorted(n for n, i in items.items() if i["actions"]) + free = [0, *range(5, MERGED)] + self.assertEqual(deletable, [f"merged-{i:03d}" for i in free]) + + def test_branch_held_after_the_plan_is_not_deleted(self) -> None: + real = gc._rebuild + changes = [ + lambda: self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005") + ] + + def late(repo: gc.Repo, item: gc.Item) -> gc.Item: + if changes: + changes.pop()() + return real(repo, item) + + with patch.object(gc, "_rebuild", side_effect=late): + plan, reads = self._run(apply=True) + + items = self._items(plan) + self.assertGreater(reads, 1) + self.assertEqual( + items["merged-005"]["result"], + "skipped: changed since plan (target of symbolic ref refs/tags/pin)", + ) + self.assertIn("merged-005", self.git("for-each-ref", "refs/heads")) + + +if __name__ == "__main__": + unittest.main()