refactor(branch): clear quality round 2 and tighten the held-branch code to Codacy
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

Rename gc_refs.py to held.py, move the local-scope routing back into _actions so _build matches main, split _held_branches into _symref_holds and _state_file_holds, and move the ancestor check of _local_actions into _ancestor_action (Lizard CCN 9 > 8). Docstrings start their summary on the opening line (D212) and end with a blank line (D413). test_gc_held_once drops its parameter defaults, stops cloning test_branch_cleanup_local and calls git through shutil.which (Bandit B607).

Kept on purpose, each contradicts another rule: D406/D407 numpy sections (AGENTS: Args: docstrings), D100 module docstrings (no prose docstrings), B404/B603 on test subprocess calls (silencing needs # nosec, which quality clean.tool-pragma forbids).

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/branch-cleanup-held-once | 4 files +69/-57 | 90 % | 3 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Refs: https://github.com/kevinveenbirkenbach/package-manager/pull/13
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 14:31:00 +00:00
1 parent 39843ab627
commit d94492e306
4 files changed
+67 -55

No files matched your search

+13 -10
View File
@@ -29,7 +29,7 @@ from pkgmgr.core.git.run import (
) )
from .gc_forge import ForgeFacts, fetch_forge_facts from .gc_forge import ForgeFacts, fetch_forge_facts
from .gc_refs import _common_dir, _git_dirs, _held_branches, _symbolic from .held import _common_dir, _git_dirs, _held_branches, _symbolic
from .nofollow import canonical, remove_tree from .nofollow import canonical, remove_tree
Registrations = tuple[str, dict[str, list[str]]] Registrations = tuple[str, dict[str, list[str]]]
@@ -658,7 +658,7 @@ def _build(
tree: Worktree | None, tree: Worktree | None,
snapshot: Snapshot, snapshot: Snapshot,
) -> Item: ) -> Item:
local, remote, cwds, tracking, registrations, held = snapshot local, remote, cwds, tracking = snapshot[:4]
upstream, ahead, behind, gone = tracking.get( upstream, ahead, behind, gone = tracking.get(
branch or "", (None, None, None, False) branch or "", (None, None, None, False)
) )
@@ -752,11 +752,7 @@ def _build(
and (time.time() - item.last_activity) / 3600 < repo.min_age and (time.time() - item.last_activity) / 3600 < repo.min_age
): ):
item.skip = f"younger than {repo.min_age:g} h" item.skip = f"younger than {repo.min_age:g} h"
item.actions = ( item.actions = _actions(repo, item, tree, checkout, dirty, snapshot)
_local_actions(repo, item, tree, held)
if repo.scope == "local"
else _actions(repo, item, tree, checkout, dirty, registrations)
)
if repo.unsafe: if repo.unsafe:
item.actions = [a for a in item.actions if not a.startswith("remote-branch:")] item.actions = [a for a in item.actions if not a.startswith("remote-branch:")]
return item return item
@@ -768,8 +764,11 @@ def _actions(
tree: Worktree | None, tree: Worktree | None,
checkout: bool, checkout: bool,
dirty: int, dirty: int,
registrations: Registrations, snapshot: Snapshot,
) -> list[str]: ) -> list[str]:
if repo.scope == "local":
return _local_actions(repo, item, tree, snapshot[5])
registrations = snapshot[4]
tree_part: list[str] = [] tree_part: list[str] = []
if tree: if tree:
if ( if (
@@ -814,8 +813,7 @@ def _local_actions(
tree: Worktree | None, tree: Worktree | None,
held: Callable[[], dict[str, str]], held: Callable[[], dict[str, str]],
) -> list[str]: ) -> list[str]:
""" """Settle the actions of an item planned with scope `local`.
Settle the actions of an item planned with scope `local`.
Args: Args:
repo: the planned repository; its default and merged-into lines are repo: the planned repository; its default and merged-into lines are
@@ -831,6 +829,7 @@ def _local_actions(
worktree registration, rebase, bisect or symbolic ref holds and whose worktree registration, rebase, bisect or symbolic ref holds and whose
tip is an ancestor of the default or a merged-into line, else tip is an ancestor of the default or a merged-into line, else
nothing; never a worktree, stack or remote action. nothing; never a worktree, stack or remote action.
""" """
if item.state != "merged-clean" or not item.local_sha or tree is not None: if item.state != "merged-clean" or not item.local_sha or tree is not None:
return [] return []
@@ -838,6 +837,10 @@ def _local_actions(
if hold: if hold:
item.skip = item.skip or hold item.skip = item.skip or hold
return [] return []
return _ancestor_action(repo, item)
def _ancestor_action(repo: Repo, item: Item) -> list[str]:
targets = [repo.default, *repo.lines] targets = [repo.default, *repo.lines]
if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets): if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets):
return ["local-branch"] return ["local-branch"]
@@ -21,8 +21,7 @@ def _common_dir(cwd: str) -> str:
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]: def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
""" """List the resolvable refs under a prefix with their symref targets.
List the resolvable refs under a prefix with their symref targets.
Args: Args:
repo_root: main worktree root of the repository. repo_root: main worktree root of the repository.
@@ -33,6 +32,7 @@ def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
Returns: Returns:
Full ref name -> the ref it points to, or "" for a plain ref. Full ref name -> the ref it points to, or "" for a plain ref.
""" """
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix] args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root) out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
@@ -40,8 +40,7 @@ def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]: 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.
Read the branch every worktree's HEAD names, on any ref backend.
Args: Args:
repo_root: main worktree root of the repository. repo_root: main worktree root of the repository.
@@ -53,6 +52,7 @@ def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
Raises: Raises:
GitBaseError: when a HEAD is neither readable nor detached. GitBaseError: when a HEAD is neither readable nor detached.
""" """
heads: dict[str, str] = {} heads: dict[str, str] = {}
for git_dir in git_dirs: for git_dir in git_dirs:
@@ -72,8 +72,7 @@ def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
def _git_dirs(repo_root: str) -> list[str]: def _git_dirs(repo_root: str) -> list[str]:
""" """List the git dirs of every worktree of the repository.
List the git dirs of every worktree of the repository.
Args: Args:
repo_root: main worktree root of the repository. repo_root: main worktree root of the repository.
@@ -81,6 +80,7 @@ def _git_dirs(repo_root: str) -> list[str]:
Returns: Returns:
The git common dir, then each entry of `<common>/worktrees/`, whatever The git common dir, then each entry of `<common>/worktrees/`, whatever
its id and whether `git worktree list` shows it. its id and whether `git worktree list` shows it.
""" """
common = _common_dir(repo_root) common = _common_dir(repo_root)
base = os.path.join(common, "worktrees") base = os.path.join(common, "worktrees")
@@ -89,8 +89,7 @@ def _git_dirs(repo_root: str) -> list[str]:
def _held_branches(repo_root: str) -> dict[str, str]: def _held_branches(repo_root: str) -> dict[str, str]:
""" """Find the local branches that something besides a listed worktree holds.
Find the local branches that something besides a listed worktree holds.
Args: Args:
repo_root: main worktree root of the repository. repo_root: main worktree root of the repository.
@@ -108,9 +107,19 @@ def _held_branches(repo_root: str) -> dict[str, str]:
GitBaseError: when git cannot read a registration, symref or HEAD. GitBaseError: when git cannot read a registration, symref or HEAD.
OSError: when a state file exists but cannot be read. OSError: when a state file exists but cannot be read.
ValueError: when a state file is not UTF-8. ValueError: when a state file is not UTF-8.
""" """
git_dirs = _git_dirs(repo_root) git_dirs = _git_dirs(repo_root)
held: dict[str, str] = {} held: dict[str, str] = {}
_symref_holds(repo_root, git_dirs, held)
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
held.setdefault(branch, reason)
for git_dir in git_dirs:
_state_file_holds(git_dir, held)
return held
def _symref_holds(repo_root: str, git_dirs: list[str], held: dict[str, str]) -> None:
symrefs = _symbolic(repo_root, "refs", git_dirs[0]) symrefs = _symbolic(repo_root, "refs", git_dirs[0])
for git_dir in git_dirs[1:]: for git_dir in git_dirs[1:]:
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items(): for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
@@ -124,19 +133,18 @@ def _held_branches(repo_root: str) -> dict[str, str]:
held.setdefault( held.setdefault(
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}" 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: def _state_file_holds(git_dir: str, held: dict[str, str]) -> None:
for name, operation in HELD_FILES: for name, operation in HELD_FILES:
try: try:
with open(os.path.join(git_dir, name), encoding="utf-8") as fh: with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
lines = fh.read().splitlines() lines = fh.read().splitlines()
except FileNotFoundError: except FileNotFoundError:
continue continue
for line in lines: for line in lines:
ref = line.strip().removeprefix("ref: ") ref = line.strip().removeprefix("ref: ")
if ref.startswith("refs/heads/") or name == "BISECT_START": if ref.startswith("refs/heads/") or name == "BISECT_START":
held.setdefault( held.setdefault(
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}" ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
) )
return held
@@ -13,7 +13,7 @@ from contextlib import contextmanager, redirect_stderr, redirect_stdout
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import patch from unittest.mock import patch
from pkgmgr.actions.branch import gc, gc_forge, gc_refs, tree from pkgmgr.actions.branch import gc, gc_forge, held, tree
from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots
from pkgmgr.cli.parser import create_parser from pkgmgr.cli.parser import create_parser
from pkgmgr.core.credentials.types import NoCredentialsError from pkgmgr.core.credentials.types import NoCredentialsError
@@ -1647,7 +1647,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
def test_failed_head_read_refuses_the_repository(self) -> None: def test_failed_head_read_refuses_the_repository(self) -> None:
heads = self._refs(self.repo, "refs/heads") heads = self._refs(self.repo, "refs/heads")
real = gc_refs._git real = held._git
def timed_out(args: list[str], cwd: str) -> str: def timed_out(args: list[str], cwd: str) -> str:
if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]: if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]:
@@ -1656,7 +1656,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
raise err raise err
return real(args, cwd) return real(args, cwd)
with patch.object(gc_refs, "_git", side_effect=timed_out): with patch.object(held, "_git", side_effect=timed_out):
run = self._cleanup("local", apply=True) run = self._cleanup("local", apply=True)
self.assertEqual(run.code, 2) self.assertEqual(run.code, 2)
@@ -3,6 +3,7 @@ from __future__ import annotations
import io import io
import json import json
import os import os
import shutil
import subprocess import subprocess
import tempfile import tempfile
import unittest import unittest
@@ -19,8 +20,10 @@ AUTHOR = {
} }
MERGED = 12 MERGED = 12
REGISTRATIONS = 40 REGISTRATIONS = 40
GIT = shutil.which("git")
@unittest.skipUnless(GIT, "git builds the repository under test")
class TestHeldBranchesReadOnce(unittest.TestCase): class TestHeldBranchesReadOnce(unittest.TestCase):
def setUp(self) -> None: def setUp(self) -> None:
tmp = tempfile.TemporaryDirectory() tmp = tempfile.TemporaryDirectory()
@@ -39,7 +42,7 @@ class TestHeldBranchesReadOnce(unittest.TestCase):
def git(self, *args: str) -> str: def git(self, *args: str) -> str:
return subprocess.run( return subprocess.run(
["git", "-c", "commit.gpgsign=false", *args], [GIT, "-c", "commit.gpgsign=false", *args],
cwd=self.repo, cwd=self.repo,
env={**os.environ, **AUTHOR}, env={**os.environ, **AUTHOR},
check=True, check=True,
@@ -54,10 +57,8 @@ class TestHeldBranchesReadOnce(unittest.TestCase):
def _shape(self) -> None: def _shape(self) -> None:
origin = os.path.join(self.root, "origin.git") origin = os.path.join(self.root, "origin.git")
subprocess.run( subprocess.run([GIT, "init", "-q", "--bare", "-b", "main", origin], check=True)
["git", "init", "-q", "--bare", "-b", "main", origin], check=True subprocess.run([GIT, "init", "-q", "-b", "main", self.repo], check=True)
)
subprocess.run(["git", "init", "-q", "-b", "main", self.repo], check=True)
self.git("remote", "add", "origin", origin) self.git("remote", "add", "origin", origin)
self._write(os.path.join(self.repo, "c1"), "c1") self._write(os.path.join(self.repo, "c1"), "c1")
self.git("add", "c1") self.git("add", "c1")
@@ -91,7 +92,7 @@ class TestHeldBranchesReadOnce(unittest.TestCase):
) )
self._write(os.path.join(self.repo, ".git", "BISECT_START"), "merged-004\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]: def _run(self, *, cached: bool, apply: bool) -> tuple[dict, int]:
out = io.StringIO() out = io.StringIO()
with ExitStack() as stack: with ExitStack() as stack:
held = stack.enter_context( held = stack.enter_context(
@@ -126,8 +127,8 @@ class TestHeldBranchesReadOnce(unittest.TestCase):
return {i["branch"]: i for i in plan["repos"][0]["items"]} 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: def test_one_read_gives_the_plan_of_one_read_per_branch(self) -> None:
per_branch, old_reads = self._run(cached=False) per_branch, old_reads = self._run(cached=False, apply=False)
once, new_reads = self._run() once, new_reads = self._run(cached=True, apply=False)
self.assertEqual(once, per_branch) self.assertEqual(once, per_branch)
self.assertEqual(new_reads, 1) self.assertEqual(new_reads, 1)
@@ -143,18 +144,18 @@ class TestHeldBranchesReadOnce(unittest.TestCase):
self.assertEqual(deletable, [f"merged-{i:03d}" for i in free]) self.assertEqual(deletable, [f"merged-{i:03d}" for i in free])
def test_branch_held_after_the_plan_is_not_deleted(self) -> None: def test_branch_held_after_the_plan_is_not_deleted(self) -> None:
real = gc._rebuild rebuilt: list[str] = []
changes = [ rebuild = gc._rebuild
lambda: self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005")
]
def late(repo: gc.Repo, item: gc.Item) -> gc.Item: def pin_before_first_recheck(*args: object) -> object:
if changes: if not rebuilt:
changes.pop()() rebuilt.append(
return real(repo, item) self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005")
)
return rebuild(*args)
with patch.object(gc, "_rebuild", side_effect=late): with patch.object(gc, "_rebuild", side_effect=pin_before_first_recheck):
plan, reads = self._run(apply=True) plan, reads = self._run(cached=True, apply=True)
items = self._items(plan) items = self._items(plan)
self.assertGreater(reads, 1) self.assertGreater(reads, 1)