refactor(gc): split the risk plan to clear quality and review findings
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
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
@@ -0,0 +1,276 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from datetime import datetime, timezone
|
||||
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, plan
|
||||
from tests.support.git_sandbox import git, isolated_root
|
||||
|
||||
DAY = 86400
|
||||
REAL_RUN = subprocess.run
|
||||
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
|
||||
IMAGES = (
|
||||
(DANGLING_ID, "0", "<none>", "<none>", "1.5GB"),
|
||||
(TAGGED_ID, "0", "app", "old", "200MB"),
|
||||
(USED_ID, "2", "app", "live", "300MB"),
|
||||
)
|
||||
CACHES = (
|
||||
(OLD_CACHE, "false", "265MB", 8, "8 days ago"),
|
||||
(NEW_CACHE, "false", "10kB", 2, "2 days ago"),
|
||||
(BUSY_CACHE, "true", "1GB", 30, "4 weeks ago"),
|
||||
)
|
||||
CONTAINERS = (
|
||||
(
|
||||
BARE_CONTAINER,
|
||||
"exited",
|
||||
"0",
|
||||
"bare",
|
||||
"Exited (0)",
|
||||
"com.docker.compose.project=demo,x=y",
|
||||
),
|
||||
(VOLUME_CONTAINER, "exited", "1", "withvol", "Exited (1)", ""),
|
||||
(RUNNING_CONTAINER, "running", "0", "live", "Up", ""),
|
||||
)
|
||||
VOLUMES = [
|
||||
{
|
||||
"Name": "demo_data",
|
||||
"Links": "0",
|
||||
"Size": "2GB",
|
||||
"Labels": "com.docker.compose.project=demo",
|
||||
},
|
||||
{"Name": "live_data", "Links": "1", "Size": "1GB", "Labels": ""},
|
||||
]
|
||||
OWNERS = {
|
||||
"old-done.log": "done",
|
||||
"old-stopped": "Stopped",
|
||||
"new-done.log": "done",
|
||||
"old-running.log": "running",
|
||||
"checkout": "done",
|
||||
}
|
||||
SCRATCH_FILES = ("old-done.log", "new-done.log", "old-running.log", "old-unknown.log")
|
||||
OLD_SCRATCH = ("old-done.log", "old-stopped", "old-running.log", "old-unknown.log")
|
||||
|
||||
|
||||
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": image_id,
|
||||
"Containers": containers,
|
||||
"Repository": repository,
|
||||
"Tag": tag,
|
||||
"UniqueSize": size,
|
||||
"CreatedAt": stamp(now),
|
||||
}
|
||||
for image_id, containers, repository, tag, size in IMAGES
|
||||
],
|
||||
"BuildCache": [
|
||||
{
|
||||
"ID": cache_id,
|
||||
"InUse": in_use,
|
||||
"Size": size,
|
||||
"LastUsedAt": stamp(now - days * DAY),
|
||||
"LastUsedSince": since,
|
||||
}
|
||||
for cache_id, in_use, size, days, since in CACHES
|
||||
],
|
||||
"Containers": [
|
||||
{
|
||||
"ID": container_id,
|
||||
"State": state,
|
||||
"LocalVolumes": volumes,
|
||||
"Names": names,
|
||||
"Image": "app:live",
|
||||
"Status": status,
|
||||
"Labels": labels,
|
||||
}
|
||||
for container_id, state, volumes, names, status, labels in CONTAINERS
|
||||
],
|
||||
"Volumes": VOLUMES,
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def write(path: str, text: str) -> None:
|
||||
with open(path, "w") as fh:
|
||||
fh.write(text)
|
||||
|
||||
|
||||
class RiskPlanFixture:
|
||||
def setUp(self) -> None:
|
||||
self.root = isolated_root(self, {"GIT_ALLOW_PROTOCOL": "file"})
|
||||
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")]
|
||||
self.host_ns = True
|
||||
self.include: list[str] = []
|
||||
|
||||
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 _commit(self, cwd: str, name: str) -> None:
|
||||
write(os.path.join(cwd, f"{name}.txt"), name)
|
||||
git(cwd, "add", f"{name}.txt")
|
||||
git(cwd, "commit", "-m", name)
|
||||
|
||||
def _branch(self, name: str, *, push: bool, merge: bool = False) -> None:
|
||||
git(self.repo, "checkout", "-b", name, "main")
|
||||
self._commit(self.repo, name)
|
||||
if push:
|
||||
git(self.repo, "push", "origin", name)
|
||||
git(self.repo, "checkout", "main")
|
||||
if merge:
|
||||
git(self.repo, "merge", "--no-ff", "-m", f"merge {name}", name)
|
||||
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")
|
||||
git(self.root, "init", "--bare", "-b", "main", self.origin)
|
||||
git(self.root, "init", "-b", "main", self.repo)
|
||||
git(self.repo, "remote", "add", "origin", self.origin)
|
||||
self._commit(self.repo, "init")
|
||||
git(self.repo, "push", "-u", "origin", "main")
|
||||
self._branch("cherry", push=False)
|
||||
for name in ("done", "stack", "old"):
|
||||
self._branch(name, push=True, merge=True)
|
||||
git(self.repo, "branch", "dirty", "done")
|
||||
self._branch("pushed", push=True)
|
||||
self._branch("wip", push=False)
|
||||
git(self.repo, "cherry-pick", "cherry")
|
||||
git(self.repo, "push", "origin", "main")
|
||||
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}")
|
||||
git(self.repo, "worktree", "add", self.wt[name], name)
|
||||
write(os.path.join(self.wt["dirty"], "untracked.txt"), "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 (*SCRATCH_FILES, "old-stopped", "checkout")
|
||||
}
|
||||
for name in SCRATCH_FILES:
|
||||
write(self.t[name], name)
|
||||
os.makedirs(os.path.join(self.t["old-stopped"], "deep"))
|
||||
write(os.path.join(self.t["old-stopped"], "deep", "x.log"), "x")
|
||||
os.makedirs(self.t["checkout"])
|
||||
write(os.path.join(self.t["checkout"], ".git"), "gitdir: /nowhere\n")
|
||||
for name in (*OLD_SCRATCH, "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[name]: status for name, status in OWNERS.items()}, fh)
|
||||
|
||||
def request(self, level: str, apply: bool) -> plan.RiskRequest:
|
||||
return plan.RiskRequest(
|
||||
level=level,
|
||||
apply=apply,
|
||||
as_json=True,
|
||||
owners_file=self.owners,
|
||||
include=self.include,
|
||||
exclude=[],
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
tmp_root=self.tmp,
|
||||
)
|
||||
|
||||
def run_gc(self, level: str, apply: bool = False) -> 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=self.host_ns),
|
||||
patch.object(plan, "host_pid_namespace", return_value=self.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], self.request(level, apply))
|
||||
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 entry(self, printed: dict, name: str) -> dict:
|
||||
return next(e for e in printed["items"] if e["name"] == name)
|
||||
|
||||
def refs(self, cwd: str) -> str:
|
||||
return git(cwd, "for-each-ref", "--format=%(refname) %(objectname)")
|
||||
Reference in new issue
Block a user