refactor(gc): split the risk plan to clear quality and review findings
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
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
quality, 24 findings: risk_cleanup(repo_roots, request) takes a frozen RiskRequest and splits into _refusal, _git_options, _host_items, _apply and _report; the hardcoded /tmp root is gone, the CLI passes tempfile.gettempdir() (so TMPDIR is honoured); classify, the tmp verdict and the HTTP client split into helpers in the same check order; gc_cmd options split into two adders; default-value fallbacks removed where every path sets the value. Tests: git(), AUTHOR and isolated_root move to tests/support/git_sandbox.py, the plan tests move to tests/unit/pkgmgr/actions/branch/test_gc_plan.py, test_risk_plan.py splits into risk_fixture.py, test_risk_plan.py and test_risk_apply.py. CodeRabbit: with --branch, --apply only plans and deletes the selected git items, docker and scratch items stay out with a warning; a truncated HTTP error body keeps its status and the partial body. | 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | feature/gc-risk-levels | 17 files +946/-788 | 91 % | 4 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % | Evidence: tests/unit + tests/integration with PYTHONPATH=src 904 passed; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0, 3 accepted (scheme-guarded urlopen moved into _send, fixed-argv git in the test helper). Hub review 913e2f2465eda2d9. Refs https://github.com/kevinveenbirkenbach/package-manager/pull/21 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8248a0253
commit
cee58bcef1
17 files changed
+946
-788
No files matched your search
@@ -4,36 +4,16 @@ import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from contextlib import redirect_stdout
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc, gc_forge
|
||||
from pkgmgr.actions.branch import gc
|
||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.cli.commands.branch import handle_branch
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
from pkgmgr.core.credentials.types import NoCredentialsError
|
||||
|
||||
GITHUB_URL = "https://github.com/example/demo.git"
|
||||
AUTHOR = {
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||
}
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=cwd,
|
||||
env={**os.environ, **AUTHOR},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
from tests.support.git_sandbox import git, isolated_root
|
||||
|
||||
|
||||
def docker_available() -> bool:
|
||||
@@ -46,17 +26,7 @@ def docker_available() -> bool:
|
||||
|
||||
class GcFixture:
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
self.root = os.path.realpath(self._tmp.name)
|
||||
self.addCleanup(os.chdir, os.getcwd())
|
||||
os.chdir(self.root)
|
||||
home = os.path.join(self.root, "home")
|
||||
os.makedirs(home)
|
||||
scratch = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
patcher = patch.dict(os.environ, {**scratch, "HOME": home}, clear=True)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.root = isolated_root(self, {})
|
||||
self.origin = os.path.join(self.root, "origin.git")
|
||||
self.repo = os.path.join(self.root, "repo")
|
||||
git(self.root, "init", "--bare", "-b", "main", self.origin)
|
||||
@@ -153,186 +123,6 @@ class GcFixture:
|
||||
|
||||
|
||||
class TestBranchGc(GcFixture, unittest.TestCase):
|
||||
def test_classifies_every_branch(self) -> None:
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["main"].state, "protected")
|
||||
self.assertEqual(items["merged"].state, "merged-clean")
|
||||
self.assertEqual(items["merged"].merged_by, "ancestor")
|
||||
self.assertEqual(
|
||||
items["merged"].actions,
|
||||
["worktree", "local-branch", "remote-branch:origin"],
|
||||
)
|
||||
self.assertTrue(items["merged"].eligible)
|
||||
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
||||
self.assertTrue(items["squashed"].eligible)
|
||||
self.assertEqual(items["fresh"].state, "unmerged")
|
||||
self.assertEqual(items["fresh"].reason, "no own commits")
|
||||
self.assertEqual(items["wip"].state, "unmerged")
|
||||
self.assertEqual(items["wip"].skip, "open-pr #3")
|
||||
self.assertEqual(items["dirty"].state, "dirty")
|
||||
|
||||
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
||||
self._integration_line()
|
||||
before = self._items(self._plan(host_ns=True, cwds={}))
|
||||
self.assertEqual(before["feat"].state, "unmerged")
|
||||
self.assertIsNone(before["feat"].merged_into)
|
||||
|
||||
for ref in ("line", "origin/line"):
|
||||
with self.subTest(ref=ref):
|
||||
items = self._items(
|
||||
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
||||
)
|
||||
self.assertEqual(items["feat"].state, "merged-clean")
|
||||
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
||||
self.assertEqual(items["feat"].merged_into, ref)
|
||||
self.assertTrue(items["feat"].eligible)
|
||||
self.assertEqual(items["line"].state, "protected")
|
||||
self.assertEqual(items["start"].state, "unmerged")
|
||||
self.assertEqual(items["merged"].merged_into, "origin/main")
|
||||
|
||||
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
||||
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
||||
|
||||
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
||||
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
||||
|
||||
def test_sizes_and_min_age(self) -> None:
|
||||
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
||||
self.assertGreater(items["merged"].size_bytes, 0)
|
||||
self.assertIsNone(items["squashed"].size_bytes)
|
||||
self.assertIn("size ", gc._line(items["merged"]))
|
||||
|
||||
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
||||
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
||||
self.assertFalse(young["merged"].eligible)
|
||||
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
||||
self.assertIsNone(old["merged"].skip)
|
||||
|
||||
def test_busy_worktree_is_skipped(self) -> None:
|
||||
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
||||
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
||||
|
||||
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
||||
self.assertFalse(items["merged"].eligible)
|
||||
|
||||
def test_lock_with_live_pid_is_skipped(self) -> None:
|
||||
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
||||
|
||||
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
||||
self._lock("claude agent x (pid 999999999 on host)")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertIsNone(items["locked"].skip)
|
||||
self.assertTrue(items["locked"].eligible)
|
||||
|
||||
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
||||
self._lock("claude agent x (pid 999999999 on host)")
|
||||
items = self._items(self._plan(host_ns=False, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
||||
|
||||
def test_lock_without_pid_is_respected(self) -> None:
|
||||
self._lock("manual hold")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
||||
|
||||
def test_forge_unavailable_skips_everything(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["merged"].skip, "forge unavailable")
|
||||
self.assertIsNone(items["squashed"].merged_by)
|
||||
|
||||
def _github_without_token(self) -> None:
|
||||
git(self.repo, "branch", "local-done", "merged")
|
||||
git(self.repo, "checkout", "-b", "local-wip", "main")
|
||||
self._commit("local-wip")
|
||||
git(self.repo, "checkout", "main")
|
||||
git(self.repo, "branch", "--track", "tracked", "origin/merged")
|
||||
git(self.repo, "push", "origin", "merged:refs/heads/remote-done")
|
||||
git(self.repo, "remote", "set-url", "origin", GITHUB_URL)
|
||||
|
||||
def _cleanup_without_token(self, apply: bool) -> tuple[int, dict]:
|
||||
out = io.StringIO()
|
||||
with (
|
||||
patch.dict(os.environ, {"GIT_ALLOW_PROTOCOL": "file"}),
|
||||
patch.object(gc, "host_pid_namespace", return_value=True),
|
||||
patch.object(gc, "list_compose_containers", return_value=[]),
|
||||
patch.object(gc, "_process_cwds", return_value={}),
|
||||
patch.object(gc, "_docker", return_value=""),
|
||||
patch.object(gc_forge, "TokenResolver") as resolver,
|
||||
patch.object(gc_forge, "HttpClient") as http,
|
||||
redirect_stdout(out),
|
||||
redirect_stderr(io.StringIO()),
|
||||
):
|
||||
resolver.return_value.get_token.side_effect = NoCredentialsError("none")
|
||||
code = gc.cleanup(
|
||||
[self.repo],
|
||||
scope="branch",
|
||||
apply=apply,
|
||||
as_json=True,
|
||||
include=[],
|
||||
exclude=[],
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
)
|
||||
resolver.return_value.get_token.assert_called_once()
|
||||
http.assert_not_called()
|
||||
return code, json.loads(out.getvalue())["repos"][0]
|
||||
|
||||
def test_local_only_merged_branch_needs_no_forge(self) -> None:
|
||||
self._github_without_token()
|
||||
code, plan = self._cleanup_without_token(apply=False)
|
||||
items = {i["branch"]: i for i in plan["items"] if i["branch"]}
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("forge unavailable: no GitHub token (none)", plan["warnings"])
|
||||
self.assertIsNone(items["local-done"]["skip"])
|
||||
self.assertEqual(items["local-done"]["merged_by"], "ancestor")
|
||||
self.assertEqual(items["local-done"]["actions"], ["local-branch"])
|
||||
self.assertEqual(items["remote-done"]["state"], "merged-clean")
|
||||
self.assertEqual(items["tracked"]["state"], "merged-clean")
|
||||
self.assertEqual(items["local-wip"]["state"], "unmerged")
|
||||
for name in ("merged", "remote-done", "tracked", "local-wip", "squashed"):
|
||||
with self.subTest(branch=name):
|
||||
self.assertEqual(items[name]["skip"], "forge unavailable")
|
||||
|
||||
def test_apply_without_token_deletes_only_the_local_only_merged_branch(
|
||||
self,
|
||||
) -> None:
|
||||
self._github_without_token()
|
||||
before = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||
code, plan = self._cleanup_without_token(apply=True)
|
||||
after = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(
|
||||
[(i["branch"], i["result"]) for i in plan["items"] if i["result"]],
|
||||
[("local-done", "done")],
|
||||
)
|
||||
self.assertEqual(before - after, {"refs/heads/local-done"})
|
||||
self.assertEqual(after - before, set())
|
||||
self.assertEqual(
|
||||
git(self.origin, "branch", "--list", "remote-done"), "remote-done"
|
||||
)
|
||||
|
||||
def test_stale_metadata_is_listed_not_pruned(self) -> None:
|
||||
stub = os.path.join(self.repo, ".git", "worktrees", "stub")
|
||||
os.makedirs(stub)
|
||||
open(os.path.join(stub, "commondir"), "w").close()
|
||||
plan = self._plan(host_ns=True, cwds={})
|
||||
|
||||
stale = [i for i in plan.items if i.state == "stale"]
|
||||
self.assertEqual([i.worktree for i in stale], [stub])
|
||||
self.assertTrue(os.path.isdir(stub))
|
||||
|
||||
def test_execute_removes_worktree_and_branches(self) -> None:
|
||||
plan = self._plan(host_ns=True, cwds={})
|
||||
item = self._items(plan)["merged"]
|
||||
|
||||
Reference in new issue
Block a user