feat(gc): plan deterministic cleanups by risk level and owner
CI / quality (push) Skipped
CI / lint-docker (push) Blocked by required conditions
CI / security-codeql (push) Blocked by required conditions
CodeQL Advanced / Check security (none, actions) (push) Blocked by required conditions
CodeQL Advanced / Check security (none, python) (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
Test Units / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
Test Code Integration / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
Test OS Containers / test-env-virtual (arch) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (centos) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (debian) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (fedora) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (ubuntu) (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
Test End-To-End / test-e2e (arch) (push) Blocked by required conditions
Test End-To-End / test-e2e (centos) (push) Blocked by required conditions
Test End-To-End / test-e2e (debian) (push) Blocked by required conditions
Test End-To-End / test-e2e (fedora) (push) Blocked by required conditions
Test End-To-End / test-e2e (ubuntu) (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
Test Virgin User / test-virgin-user (arch) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (centos) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (debian) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (fedora) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (ubuntu) (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (arch) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (centos) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (debian) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (fedora) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (ubuntu) (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
ShellCheck / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
Ruff (Python code sniffer) / lint-python (push) Blocked by required conditions
Docker Linter / Lint Dockerfile (push) Blocked by required conditions
CI / quality (push) Skipped
CI / lint-docker (push) Blocked by required conditions
CI / security-codeql (push) Blocked by required conditions
CodeQL Advanced / Check security (none, actions) (push) Blocked by required conditions
CodeQL Advanced / Check security (none, python) (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
Test Units / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
Test Code Integration / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
Test OS Containers / test-env-virtual (arch) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (centos) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (debian) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (fedora) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (ubuntu) (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
Test End-To-End / test-e2e (arch) (push) Blocked by required conditions
Test End-To-End / test-e2e (centos) (push) Blocked by required conditions
Test End-To-End / test-e2e (debian) (push) Blocked by required conditions
Test End-To-End / test-e2e (fedora) (push) Blocked by required conditions
Test End-To-End / test-e2e (ubuntu) (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
Test Virgin User / test-virgin-user (arch) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (centos) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (debian) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (fedora) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (ubuntu) (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (arch) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (centos) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (debian) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (fedora) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (ubuntu) (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
ShellCheck / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
Ruff (Python code sniffer) / lint-python (push) Blocked by required conditions
Docker Linter / Lint Dockerfile (push) Blocked by required conditions
pkgmgr gc --risk low|medium|high [--owners FILE] [--apply] classifies Docker images, build cache, containers, volumes, /tmp entries, worktrees and branches into low, medium and high risk with owner and reason and prints the plan up to the picked level; --apply removes only the low items of that plan and refuses any other level. _merged_by asks local git first (line, then patch) and the forge pr number last, so the label of a merged branch no longer depends on whether GitHub answers. Forge facts use a 10 s request timeout and a 60 s paging budget and degrade to unavailable on a failed or truncated answer. HttpClient refuses every URL scheme except http and https before urlopen. Rebuilt on main after PR 14; the held-once part of the earlier draft is dropped because main carries it. | 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | feature/gc-risk-levels | 16 files +1493/-12 | 90 % | 5 % | – | – | 100 % | 86 | ✅ 90/5, tokens and velocity <= 100, security 100 % | Evidence: 129 tests passed, 18 subtests (branch, gc risk, remote_provisioning, test_branch_gc, test_error_path_degradation), ruff clean, MEDUSA 100 % critical 0. Break 5 %: largest new surface; a slow forge now degrades to unavailable after 60 s. Operator review df0f4fbe (re-card of 0b5c15ba). Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0a3badfd63
commit
b8248a0253
16 files changed
+1493
-12
No files matched your search
@@ -0,0 +1,53 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
|
||||
SHA = "a" * 40
|
||||
|
||||
|
||||
def _repo(merged_heads: dict[str, int]) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
first_parent=set(),
|
||||
default="origin/main",
|
||||
repo="/repo",
|
||||
forge=SimpleNamespace(merged_heads=merged_heads),
|
||||
)
|
||||
|
||||
|
||||
class TestMergedByOrder(unittest.TestCase):
|
||||
def _merged_by(self, *, line, patch_merged, merged_heads):
|
||||
with (
|
||||
patch.object(gc, "_is_ancestor", return_value=False),
|
||||
patch.object(gc, "_in_line", return_value=line),
|
||||
patch.object(gc, "_patch_merged", return_value=patch_merged),
|
||||
):
|
||||
return gc._merged_by(_repo(merged_heads), SHA)
|
||||
|
||||
def test_line_wins_over_forge(self):
|
||||
self.assertEqual(
|
||||
self._merged_by(line="release", patch_merged=False, merged_heads={SHA: 7}),
|
||||
"line:release",
|
||||
)
|
||||
|
||||
def test_patch_wins_over_forge(self):
|
||||
self.assertEqual(
|
||||
self._merged_by(line=None, patch_merged=True, merged_heads={SHA: 7}),
|
||||
"patch",
|
||||
)
|
||||
|
||||
def test_forge_only_when_git_has_no_evidence(self):
|
||||
self.assertEqual(
|
||||
self._merged_by(line=None, patch_merged=False, merged_heads={SHA: 7}),
|
||||
"pr#7",
|
||||
)
|
||||
|
||||
def test_unmerged_without_any_evidence(self):
|
||||
self.assertIsNone(
|
||||
self._merged_by(line=None, patch_merged=False, merged_heads={})
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Whitespace-only changes.
@@ -0,0 +1,573 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.actions.gc.risk import docker_items, git_items, plan
|
||||
from pkgmgr.cli.commands.worktree import handle_gc
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
|
||||
DAY = 86400
|
||||
REAL_RUN = subprocess.run
|
||||
AUTHOR = {
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||
}
|
||||
DANGLING_ID = "sha256:" + "d" * 64
|
||||
TAGGED_ID = "sha256:" + "a" * 64
|
||||
USED_ID = "sha256:" + "u" * 64
|
||||
OLD_CACHE = "oldcache0000000000000000a"
|
||||
NEW_CACHE = "newcache0000000000000000b"
|
||||
BUSY_CACHE = "busycache000000000000000c"
|
||||
BARE_CONTAINER = "c" * 64
|
||||
VOLUME_CONTAINER = "v" * 64
|
||||
RUNNING_CONTAINER = "r" * 64
|
||||
|
||||
|
||||
def stamp(epoch: float) -> str:
|
||||
moment = datetime.fromtimestamp(epoch, tz=timezone.utc)
|
||||
return moment.strftime("%Y-%m-%d %H:%M:%S.%f") + "123 +0000 UTC"
|
||||
|
||||
|
||||
def docker_df(now: float) -> dict:
|
||||
return {
|
||||
"Images": [
|
||||
{
|
||||
"ID": DANGLING_ID,
|
||||
"Containers": "0",
|
||||
"Repository": "<none>",
|
||||
"Tag": "<none>",
|
||||
"UniqueSize": "1.5GB",
|
||||
"CreatedAt": stamp(now),
|
||||
},
|
||||
{
|
||||
"ID": TAGGED_ID,
|
||||
"Containers": "0",
|
||||
"Repository": "app",
|
||||
"Tag": "old",
|
||||
"UniqueSize": "200MB",
|
||||
"CreatedAt": stamp(now),
|
||||
},
|
||||
{
|
||||
"ID": USED_ID,
|
||||
"Containers": "2",
|
||||
"Repository": "app",
|
||||
"Tag": "live",
|
||||
"UniqueSize": "300MB",
|
||||
"CreatedAt": stamp(now),
|
||||
},
|
||||
],
|
||||
"BuildCache": [
|
||||
{
|
||||
"ID": OLD_CACHE,
|
||||
"InUse": "false",
|
||||
"Size": "265MB",
|
||||
"LastUsedAt": stamp(now - 8 * DAY),
|
||||
"LastUsedSince": "8 days ago",
|
||||
},
|
||||
{
|
||||
"ID": NEW_CACHE,
|
||||
"InUse": "false",
|
||||
"Size": "10kB",
|
||||
"LastUsedAt": stamp(now - 2 * DAY),
|
||||
"LastUsedSince": "2 days ago",
|
||||
},
|
||||
{
|
||||
"ID": BUSY_CACHE,
|
||||
"InUse": "true",
|
||||
"Size": "1GB",
|
||||
"LastUsedAt": stamp(now - 30 * DAY),
|
||||
"LastUsedSince": "4 weeks ago",
|
||||
},
|
||||
],
|
||||
"Containers": [
|
||||
{
|
||||
"ID": BARE_CONTAINER,
|
||||
"State": "exited",
|
||||
"LocalVolumes": "0",
|
||||
"Names": "bare",
|
||||
"Image": "app:live",
|
||||
"Status": "Exited (0)",
|
||||
"Labels": "com.docker.compose.project=demo,x=y",
|
||||
},
|
||||
{
|
||||
"ID": VOLUME_CONTAINER,
|
||||
"State": "exited",
|
||||
"LocalVolumes": "1",
|
||||
"Names": "withvol",
|
||||
"Image": "app:live",
|
||||
"Status": "Exited (1)",
|
||||
"Labels": "",
|
||||
},
|
||||
{
|
||||
"ID": RUNNING_CONTAINER,
|
||||
"State": "running",
|
||||
"LocalVolumes": "0",
|
||||
"Names": "live",
|
||||
"Image": "app:live",
|
||||
"Status": "Up",
|
||||
"Labels": "",
|
||||
},
|
||||
],
|
||||
"Volumes": [
|
||||
{
|
||||
"Name": "demo_data",
|
||||
"Links": "0",
|
||||
"Size": "2GB",
|
||||
"Labels": "com.docker.compose.project=demo",
|
||||
},
|
||||
{"Name": "live_data", "Links": "1", "Size": "1GB", "Labels": ""},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class FakeDocker:
|
||||
def __init__(self, now: float) -> None:
|
||||
self.calls: list[list[str]] = []
|
||||
self.df = json.dumps(docker_df(now))
|
||||
|
||||
def __call__(self, args: list[str]) -> str:
|
||||
self.calls.append(list(args))
|
||||
if args == docker_items.DF_VERBOSE:
|
||||
return self.df
|
||||
if args == docker_items.DANGLING:
|
||||
return DANGLING_ID + "\n"
|
||||
return ""
|
||||
|
||||
def writes(self) -> list[list[str]]:
|
||||
reads = (docker_items.DF_VERBOSE, docker_items.DANGLING)
|
||||
return [call for call in self.calls if call not in reads]
|
||||
|
||||
|
||||
def inside(path: str, root: str) -> bool:
|
||||
return path == root or path.startswith(root + os.sep)
|
||||
|
||||
|
||||
class RiskPlanFixture:
|
||||
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)
|
||||
clean = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
env = {**clean, "HOME": home, "GIT_ALLOW_PROTOCOL": "file"}
|
||||
self._start(patch.dict(os.environ, env, clear=True))
|
||||
self.commands: list[list[str]] = []
|
||||
self._start(patch("subprocess.run", self._guarded_run))
|
||||
self._repos()
|
||||
self._scratch()
|
||||
self.now = time.time()
|
||||
self.docker = FakeDocker(self.now)
|
||||
self.forge = ForgeFacts()
|
||||
self.containers = [gc.Container("stackproj", self.wt["stack"], "img")]
|
||||
|
||||
def _start(self, patcher) -> None:
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def _guarded_run(self, cmd, *args, **kwargs):
|
||||
argv = [str(part) for part in cmd]
|
||||
self.commands.append(argv)
|
||||
if os.path.basename(argv[0]) not in ("git", "du"):
|
||||
raise AssertionError(f"unexpected command outside the mocks: {argv}")
|
||||
cwd = os.path.realpath(kwargs.get("cwd") or os.getcwd())
|
||||
for path in [cwd, *(a for a in argv[1:] if a.startswith("/"))]:
|
||||
if not inside(os.path.realpath(path), self.root):
|
||||
raise AssertionError(f"{argv} reaches {path} outside {self.root}")
|
||||
return REAL_RUN(cmd, *args, **kwargs)
|
||||
|
||||
def git(self, 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()
|
||||
|
||||
def _commit(self, cwd: str, name: str) -> None:
|
||||
with open(os.path.join(cwd, f"{name}.txt"), "w") as fh:
|
||||
fh.write(name)
|
||||
self.git(cwd, "add", f"{name}.txt")
|
||||
self.git(cwd, "commit", "-m", name)
|
||||
|
||||
def _branch(self, name: str, push: bool = True, merge: bool = False) -> None:
|
||||
self.git(self.repo, "checkout", "-b", name, "main")
|
||||
self._commit(self.repo, name)
|
||||
if push:
|
||||
self.git(self.repo, "push", "origin", name)
|
||||
self.git(self.repo, "checkout", "main")
|
||||
if merge:
|
||||
self.git(self.repo, "merge", "--no-ff", "-m", f"merge {name}", name)
|
||||
self.git(self.repo, "push", "origin", "main")
|
||||
|
||||
def _repos(self) -> None:
|
||||
self.origin = os.path.join(self.root, "origin.git")
|
||||
self.repo = os.path.join(self.root, "repo")
|
||||
self.git(self.root, "init", "--bare", "-b", "main", self.origin)
|
||||
self.git(self.root, "init", "-b", "main", self.repo)
|
||||
self.git(self.repo, "remote", "add", "origin", self.origin)
|
||||
self._commit(self.repo, "init")
|
||||
self.git(self.repo, "push", "-u", "origin", "main")
|
||||
self._branch("cherry", push=False)
|
||||
for name in ("done", "stack", "old"):
|
||||
self._branch(name, merge=True)
|
||||
self.git(self.repo, "branch", "dirty", "done")
|
||||
self._branch("pushed")
|
||||
self._branch("wip", push=False)
|
||||
self.git(self.repo, "cherry-pick", "cherry")
|
||||
self.git(self.repo, "push", "origin", "main")
|
||||
self.git(self.repo, "remote", "set-head", "origin", "main")
|
||||
self.wt = {}
|
||||
for name in ("done", "dirty", "stack", "pushed", "wip", "cherry"):
|
||||
self.wt[name] = os.path.join(self.root, f"wt-{name}")
|
||||
self.git(self.repo, "worktree", "add", self.wt[name], name)
|
||||
with open(os.path.join(self.wt["dirty"], "untracked.txt"), "w") as fh:
|
||||
fh.write("x")
|
||||
|
||||
def _old(self, path: str) -> None:
|
||||
old = time.time() - 2 * DAY
|
||||
for base, dirs, files in os.walk(path):
|
||||
for name in [*dirs, *files]:
|
||||
os.utime(os.path.join(base, name), (old, old))
|
||||
os.utime(path, (old, old))
|
||||
|
||||
def _scratch(self) -> None:
|
||||
self.tmp = os.path.join(self.root, "scratch")
|
||||
os.makedirs(self.tmp)
|
||||
self.t = {
|
||||
name: os.path.join(self.tmp, name)
|
||||
for name in (
|
||||
"old-done.log",
|
||||
"old-stopped",
|
||||
"new-done.log",
|
||||
"old-running.log",
|
||||
"old-unknown.log",
|
||||
"checkout",
|
||||
)
|
||||
}
|
||||
for name in (
|
||||
"old-done.log",
|
||||
"new-done.log",
|
||||
"old-running.log",
|
||||
"old-unknown.log",
|
||||
):
|
||||
with open(self.t[name], "w") as fh:
|
||||
fh.write(name)
|
||||
os.makedirs(os.path.join(self.t["old-stopped"], "deep"))
|
||||
with open(os.path.join(self.t["old-stopped"], "deep", "x.log"), "w") as fh:
|
||||
fh.write("x")
|
||||
os.makedirs(self.t["checkout"])
|
||||
with open(os.path.join(self.t["checkout"], ".git"), "w") as fh:
|
||||
fh.write("gitdir: /nowhere\n")
|
||||
for name in (
|
||||
"old-done.log",
|
||||
"old-stopped",
|
||||
"old-running.log",
|
||||
"old-unknown.log",
|
||||
"checkout",
|
||||
):
|
||||
self._old(self.t[name])
|
||||
os.symlink(self.t["old-done.log"], os.path.join(self.tmp, "link"))
|
||||
self.owners = os.path.join(self.root, "owners.json")
|
||||
with open(self.owners, "w") as fh:
|
||||
json.dump(
|
||||
{
|
||||
self.t["old-done.log"]: "done",
|
||||
self.t["old-stopped"]: "Stopped",
|
||||
self.t["new-done.log"]: "done",
|
||||
self.t["old-running.log"]: "running",
|
||||
self.t["checkout"]: "done",
|
||||
},
|
||||
fh,
|
||||
)
|
||||
|
||||
def run_gc(
|
||||
self, level: str = "low", apply: bool = False, host_ns: bool = True
|
||||
) -> tuple[int, dict, str]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
no_gc_docker = AssertionError("gc must not call docker for low items")
|
||||
with (
|
||||
patch.object(gc, "host_pid_namespace", return_value=host_ns),
|
||||
patch.object(plan, "host_pid_namespace", return_value=host_ns),
|
||||
patch.object(gc, "_process_cwds", return_value={}),
|
||||
patch.object(plan, "_process_cwds", return_value={}),
|
||||
patch.object(gc, "list_compose_containers", return_value=self.containers),
|
||||
patch.object(gc, "fetch_forge_facts", return_value=self.forge),
|
||||
patch.object(gc, "_docker", side_effect=no_gc_docker),
|
||||
patch.object(docker_items, "_docker", side_effect=self.docker),
|
||||
redirect_stdout(out),
|
||||
redirect_stderr(err),
|
||||
):
|
||||
code = plan.risk_cleanup(
|
||||
[self.repo],
|
||||
level=level,
|
||||
apply=apply,
|
||||
as_json=True,
|
||||
owners_file=self.owners,
|
||||
include=[],
|
||||
exclude=[],
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
tmp_root=self.tmp,
|
||||
)
|
||||
printed = json.loads(out.getvalue()) if out.getvalue().strip() else {}
|
||||
return code, printed, err.getvalue()
|
||||
|
||||
def risks(self, printed: dict) -> dict[str, str]:
|
||||
return {entry["name"]: entry["risk"] for entry in printed["items"]}
|
||||
|
||||
def refs(self, cwd: str) -> str:
|
||||
return self.git(cwd, "for-each-ref", "--format=%(refname) %(objectname)")
|
||||
|
||||
|
||||
class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
||||
def test_git_rules(self) -> None:
|
||||
code, printed, _ = self.run_gc(level="high")
|
||||
risks = self.risks(printed)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
expected = {
|
||||
self.wt["done"]: "low",
|
||||
self.wt["dirty"]: "high",
|
||||
self.wt["wip"]: "high",
|
||||
self.wt["pushed"]: "medium",
|
||||
self.wt["stack"]: "medium",
|
||||
self.wt["cherry"]: "medium",
|
||||
"old": "medium",
|
||||
"main": "high",
|
||||
}
|
||||
for name, risk in expected.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(risks[name], risk)
|
||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
||||
self.assertEqual(done["steps"], ["worktree"])
|
||||
self.assertEqual(done["pr"], "none")
|
||||
cherry = next(e for e in printed["items"] if e["name"] == self.wt["cherry"])
|
||||
self.assertEqual(cherry["reason"], "head is on no remote")
|
||||
|
||||
def test_local_proof_needs_no_forge(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
||||
|
||||
self.assertEqual(done["risk"], "low")
|
||||
self.assertEqual(done["pr"], "unknown")
|
||||
self.assertEqual(done["skip"], "forge unavailable")
|
||||
|
||||
def test_open_pull_request_is_not_low(self) -> None:
|
||||
self.forge = ForgeFacts(open_heads={"done": 9})
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
||||
|
||||
self.assertEqual((done["risk"], done["pr"]), ("medium", "open #9"))
|
||||
|
||||
def test_docker_rules(self) -> None:
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
risks = self.risks(printed)
|
||||
|
||||
self.assertEqual(risks[DANGLING_ID], "low")
|
||||
self.assertEqual(risks[TAGGED_ID], "medium")
|
||||
self.assertEqual(risks[OLD_CACHE], "low")
|
||||
self.assertEqual(risks[NEW_CACHE], "medium")
|
||||
self.assertEqual(risks[BARE_CONTAINER], "low")
|
||||
self.assertEqual(risks[VOLUME_CONTAINER], "medium")
|
||||
self.assertEqual(risks["demo_data"], "medium")
|
||||
self.assertEqual(risks["live_data"], "high")
|
||||
for absent in (USED_ID, BUSY_CACHE, RUNNING_CONTAINER):
|
||||
self.assertNotIn(absent, risks)
|
||||
volume = next(e for e in printed["items"] if e["name"] == "demo_data")
|
||||
self.assertEqual(
|
||||
(volume["compose_project"], volume["links"], volume["size_bytes"]),
|
||||
("demo", 0, 2 * 10**9),
|
||||
)
|
||||
image = next(e for e in printed["items"] if e["name"] == DANGLING_ID)
|
||||
self.assertEqual(image["size_bytes"], 1_500_000_000)
|
||||
|
||||
def test_tmp_rules(self) -> None:
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
risks = self.risks(printed)
|
||||
|
||||
self.assertEqual(risks[self.t["old-done.log"]], "low")
|
||||
self.assertEqual(risks[self.t["old-stopped"]], "low")
|
||||
self.assertEqual(risks[self.t["new-done.log"]], "medium")
|
||||
self.assertEqual(risks[self.t["old-unknown.log"]], "medium")
|
||||
self.assertEqual(risks[self.t["old-running.log"]], "high")
|
||||
self.assertEqual(risks[self.t["checkout"]], "high")
|
||||
self.assertNotIn(os.path.join(self.tmp, "link"), risks)
|
||||
|
||||
def test_risk_low_plan_lists_only_low_items(self) -> None:
|
||||
_, printed, _ = self.run_gc(level="low")
|
||||
|
||||
self.assertEqual(
|
||||
sorted(self.risks(printed)),
|
||||
sorted(
|
||||
[
|
||||
self.wt["done"],
|
||||
DANGLING_ID,
|
||||
OLD_CACHE,
|
||||
BARE_CONTAINER,
|
||||
self.t["old-done.log"],
|
||||
self.t["old-stopped"],
|
||||
]
|
||||
),
|
||||
)
|
||||
self.assertEqual(printed["totals"]["low"]["count"], 6)
|
||||
|
||||
|
||||
class TestApplyLow(RiskPlanFixture, unittest.TestCase):
|
||||
def test_apply_deletes_exactly_the_low_items(self) -> None:
|
||||
repo_refs, origin_refs = self.refs(self.repo), self.refs(self.origin)
|
||||
tmp_before = set(os.listdir(self.tmp))
|
||||
_, low_plan, _ = self.run_gc(level="low")
|
||||
self.docker.calls.clear()
|
||||
self.commands.clear()
|
||||
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(sorted(self.risks(printed)), sorted(self.risks(low_plan)))
|
||||
self.assertEqual({e["result"] for e in printed["items"]}, {"done"})
|
||||
self.assertFalse(os.path.exists(self.wt["done"]))
|
||||
for name in ("dirty", "stack", "pushed", "wip", "cherry"):
|
||||
self.assertTrue(os.path.isdir(self.wt[name]), name)
|
||||
self.assertEqual(self.refs(self.repo), repo_refs)
|
||||
self.assertEqual(self.refs(self.origin), origin_refs)
|
||||
self.assertEqual(
|
||||
tmp_before - set(os.listdir(self.tmp)), {"old-done.log", "old-stopped"}
|
||||
)
|
||||
self.assertEqual(
|
||||
self.docker.writes(),
|
||||
[
|
||||
["image", "rm", DANGLING_ID],
|
||||
[
|
||||
"builder",
|
||||
"prune",
|
||||
"--force",
|
||||
"--filter",
|
||||
f"id={OLD_CACHE}",
|
||||
"--filter",
|
||||
"until=168h",
|
||||
],
|
||||
["container", "rm", BARE_CONTAINER],
|
||||
],
|
||||
)
|
||||
for argv in self.commands:
|
||||
self.assertFalse({"push", "-D", "update-ref"} & set(argv), argv)
|
||||
|
||||
def test_worktree_changed_after_plan_is_skipped(self) -> None:
|
||||
real_rebuild = git_items._rebuild
|
||||
|
||||
def dirty_then_rebuild(repo, item):
|
||||
with open(os.path.join(self.wt["done"], "late.txt"), "w") as fh:
|
||||
fh.write("late")
|
||||
return real_rebuild(repo, item)
|
||||
|
||||
with patch.object(git_items, "_rebuild", side_effect=dirty_then_rebuild):
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(done["result"].startswith("skipped: changed since plan"))
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.wt["done"], "late.txt")))
|
||||
|
||||
def test_negative_control_refusals_delete_nothing(self) -> None:
|
||||
repo_refs = self.refs(self.repo)
|
||||
tmp_before = sorted(os.listdir(self.tmp))
|
||||
for level, host_ns in (("medium", True), ("high", True), ("low", False)):
|
||||
with self.subTest(level=level, host_ns=host_ns):
|
||||
self.docker.calls.clear()
|
||||
code, printed, err = self.run_gc(
|
||||
level=level, apply=True, host_ns=host_ns
|
||||
)
|
||||
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(printed, {})
|
||||
self.assertIn("Refusing", err)
|
||||
self.assertEqual(self.docker.calls, [])
|
||||
self.assertTrue(os.path.isdir(self.wt["done"]))
|
||||
self.assertEqual(self.refs(self.repo), repo_refs)
|
||||
self.assertEqual(sorted(os.listdir(self.tmp)), tmp_before)
|
||||
|
||||
def test_bad_owner_file_is_refused(self) -> None:
|
||||
with open(self.owners, "w") as fh:
|
||||
fh.write("[1, 2]")
|
||||
code, printed, err = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual((code, printed), (2, {}))
|
||||
self.assertIn("owner file", err)
|
||||
self.assertTrue(os.path.isdir(self.wt["done"]))
|
||||
self.assertTrue(os.path.isfile(self.t["old-done.log"]))
|
||||
|
||||
|
||||
class TestRiskCli(unittest.TestCase):
|
||||
def _gc(self, *argv: str) -> tuple[int, object]:
|
||||
args = create_parser("test").parse_args(["gc", *argv])
|
||||
ctx = SimpleNamespace(config_merged={"worktree_hooks": {}, "repositories": []})
|
||||
with (
|
||||
patch("pkgmgr.cli.commands.worktree.scan_repo_roots", return_value=["/r"]),
|
||||
patch("pkgmgr.cli.commands.worktree.risk_cleanup", return_value=0) as run,
|
||||
patch("pkgmgr.cli.commands.worktree.run_cleanup") as legacy,
|
||||
redirect_stderr(io.StringIO()),
|
||||
self.assertRaises(SystemExit) as stop,
|
||||
):
|
||||
handle_gc(args, ctx)
|
||||
legacy.assert_not_called()
|
||||
return stop.exception.code, run
|
||||
|
||||
def test_cli_forwards_risk_flags(self) -> None:
|
||||
code, run = self._gc(
|
||||
"--risk",
|
||||
"low",
|
||||
"--apply",
|
||||
"--json",
|
||||
"--owners",
|
||||
"/o.json",
|
||||
"--merged-into",
|
||||
"origin/main",
|
||||
"--sizes",
|
||||
)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
run.assert_called_once_with(
|
||||
["/r"],
|
||||
level="low",
|
||||
apply=True,
|
||||
as_json=True,
|
||||
owners_file="/o.json",
|
||||
hooks={},
|
||||
min_age=None,
|
||||
include=[],
|
||||
exclude=[],
|
||||
merged_into=["origin/main"],
|
||||
sizes=True,
|
||||
)
|
||||
|
||||
def test_cli_refuses_risk_with_report(self) -> None:
|
||||
code, run = self._gc("--risk", "low", "--report")
|
||||
|
||||
self.assertEqual(code, 2)
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,92 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import io
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc_forge
|
||||
from pkgmgr.core.remote_provisioning.http.client import HttpClient
|
||||
from pkgmgr.core.remote_provisioning.http.errors import HttpError
|
||||
|
||||
TRUNCATED = (
|
||||
b"HTTP/1.1 200 OK\r\nContent-Length: 4096\r\n"
|
||||
b"Content-Type: application/json\r\n\r\n"
|
||||
b'[{"number": 1, "merged_at": null'
|
||||
)
|
||||
|
||||
|
||||
class TruncatedSocket:
|
||||
def __init__(self, payload: bytes) -> None:
|
||||
self._file = io.BytesIO(payload)
|
||||
|
||||
def makefile(self, *_args, **_kwargs):
|
||||
return self._file
|
||||
|
||||
|
||||
def truncated_response(*_args, **_kwargs) -> http.client.HTTPResponse:
|
||||
response = http.client.HTTPResponse(TruncatedSocket(TRUNCATED))
|
||||
response.begin()
|
||||
return response
|
||||
|
||||
|
||||
class TestTruncatedResponse(unittest.TestCase):
|
||||
def test_incomplete_read_becomes_http_error(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||
|
||||
self.assertEqual(caught.exception.status, 0)
|
||||
self.assertIn("IncompleteRead", str(caught.exception))
|
||||
|
||||
def test_read_timeout_becomes_http_error(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen", side_effect=TimeoutError()),
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||
|
||||
self.assertEqual(str(caught.exception), "TimeoutError")
|
||||
|
||||
def test_non_http_scheme_is_refused_before_any_request(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen") as urlopen,
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "file:///etc/passwd")
|
||||
|
||||
urlopen.assert_not_called()
|
||||
self.assertIn("unsupported URL scheme 'file'", str(caught.exception))
|
||||
|
||||
def test_forge_facts_degrade_to_unavailable_instead_of_crashing(self) -> None:
|
||||
with patch("urllib.request.urlopen", side_effect=truncated_response):
|
||||
facts = gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||
|
||||
self.assertIn("GitHub API failed for owner/repo", facts.unavailable)
|
||||
self.assertEqual((facts.merged_heads, facts.open_heads), ({}, {}))
|
||||
|
||||
def test_forge_budget_stops_paging(self) -> None:
|
||||
with (
|
||||
patch.object(gc_forge, "BUDGET_S", -1),
|
||||
patch("urllib.request.urlopen") as urlopen,
|
||||
):
|
||||
facts = gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||
|
||||
urlopen.assert_not_called()
|
||||
self.assertIn("budget", facts.unavailable)
|
||||
|
||||
def test_forge_requests_use_the_short_timeout(self) -> None:
|
||||
with (
|
||||
patch.object(gc_forge, "HttpClient", wraps=HttpClient) as client,
|
||||
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||
):
|
||||
gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||
|
||||
client.assert_called_once_with(timeout_s=gc_forge.TIMEOUT_S)
|
||||
self.assertLessEqual(gc_forge.TIMEOUT_S, 10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user