refactor(branch): move the held-branch reader to gc_refs and the held-once tests to a unit module
CI / security-codeql (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
CI / quality (push) Blocked by required conditions

The quality gate's ratchet flagged PR 13: gc.py and test_branch_cleanup_local.py grew past their already-oversized base length, and _actions gained a seventh parameter. The held-branch reader (_held_branches, _worktree_heads, _git_dirs, _symbolic, _common_dir, HELD_FILES) moves unchanged into gc_refs.py, so gc.py shrinks below its base; scope local is routed in _build, so _actions keeps six parameters; the held-once tests move into tests/unit/pkgmgr/actions/branch/test_gc_held_once.py and test_branch_cleanup_local.py is back to main plus one patch target. Mutating git calls stay on gc._git, so the gc.run spies still see them.

🎯 Fix: 90 %
💥 Break: 4 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-28 11:52:58 +00:00
1 parent 5e08847286
commit 39843ab627
4 files changed
+320 -185

No files matched your search

+3 -49
View File
@@ -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)
@@ -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()