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

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:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-30 19:46:58 +00:00
1 parent 0a3badfd63
commit b8248a0253
16 files changed
+1493 -12

No files matched your search

+4 -4
View File
@@ -466,13 +466,13 @@ def _in_line(repo: Repo, sha: str) -> str | None:
def _merged_by(repo: Repo, sha: str) -> str | None:
if sha not in repo.first_parent and _is_ancestor(sha, repo.default, repo.repo):
return "ancestor"
number = repo.forge.merged_heads.get(sha)
if number:
return f"pr#{number}"
line = _in_line(repo, sha)
if line:
return f"line:{line}"
return "patch" if _patch_merged(repo, sha) else None
if _patch_merged(repo, sha):
return "patch"
number = repo.forge.merged_heads.get(sha)
return f"pr#{number}" if number else None
def _patch_merged(repo: Repo, sha: str) -> bool:
+17 -6
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import time
from dataclasses import dataclass, field
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
@@ -12,6 +13,8 @@ from pkgmgr.core.remote_provisioning.http.errors import HttpError
GITHUB_HOST = "github.com"
GITHUB_API = "https://api.github.com"
PAGE_SIZE = 100
TIMEOUT_S = 10
BUDGET_S = 60
@dataclass
@@ -46,10 +49,14 @@ def github_slugs(remote_urls: dict[str, str]) -> list[tuple[str, str]]:
return slugs
def _pages(http: HttpClient, headers: dict[str, str], url: str) -> list[dict]:
def _pages(
http: HttpClient, headers: dict[str, str], url: str, deadline: float
) -> list[dict]:
items: list[dict] = []
page = 1
while True:
if time.monotonic() > deadline:
raise HttpError(status=0, message=f"budget of {BUDGET_S}s exceeded")
resp = http.request_json(
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
)
@@ -94,7 +101,8 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
The facts, or facts whose unavailable names the failing repository.
"""
facts = ForgeFacts()
http = HttpClient(timeout_s=30)
http = HttpClient(timeout_s=TIMEOUT_S)
deadline = time.monotonic() + BUDGET_S
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
@@ -103,14 +111,17 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
for owner, name in slugs:
base = f"{GITHUB_API}/repos/{owner}/{name}"
try:
for pr in _pages(http, headers, f"{base}/pulls?state=all"):
for pr in _pages(http, headers, f"{base}/pulls?state=all", deadline):
if pr["merged_at"]:
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
elif pr["state"] == "open":
facts.open_heads[pr["head"]["ref"]] = pr["number"]
for branch in _pages(http, headers, f"{base}/branches?protected=true"):
for branch in _pages(
http, headers, f"{base}/branches?protected=true", deadline
):
facts.protected.add(branch["name"])
except (HttpError, ValueError, KeyError, TypeError) as exc:
facts.unavailable = f"GitHub API failed for {owner}/{name}: {exc}"
return facts
return ForgeFacts(
unavailable=f"GitHub API failed for {owner}/{name}: {exc}"
)
return facts
+4
View File
@@ -0,0 +1,4 @@
from .levels import LEVELS
from .plan import risk_cleanup
__all__ = ["LEVELS", "risk_cleanup"]
+196
View File
@@ -0,0 +1,196 @@
from __future__ import annotations
import json
import re
import subprocess
from datetime import datetime
from pkgmgr.actions.branch.gc import COMPOSE_PROJECT, _describe, _docker
from .levels import DAY_S, HIGH, IDLE_DAYS, LOW, MEDIUM, item
DF_VERBOSE = ["system", "df", "--verbose", "--format", "{{json .}}"]
DANGLING = ["image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true"]
STOPPED = ("exited", "dead")
UNITS = {"": 1, "k": 10**3, "m": 10**6, "g": 10**9, "t": 10**12, "p": 10**15}
SIZE = re.compile(r"([0-9.]+)\s*([kKmMgGtTpP]?)B")
STAMP = re.compile(r"(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:\.(\d+))? ([+-]\d{4})")
def parse_size(text: object) -> int | None:
match = SIZE.fullmatch(str(text or "").strip())
if not match:
return None
return int(float(match.group(1)) * UNITS[match.group(2).lower()])
def parse_time(text: object) -> float | None:
match = STAMP.match(str(text or "").strip())
if not match:
return None
clock, fraction, zone = match.groups()
micro = (fraction or "0")[:6].ljust(6, "0")
return datetime.strptime(
f"{clock}.{micro} {zone}", "%Y-%m-%d %H:%M:%S.%f %z"
).timestamp()
def _project(labels: object) -> str | None:
for pair in str(labels or "").split(","):
key, _, value = pair.partition("=")
if key == COMPOSE_PROJECT:
return value
return None
def _volumes(rows: list[dict]) -> list[dict]:
items = []
for row in rows:
links = int(row["Links"]) if str(row.get("Links")).isdigit() else None
unused = links == 0
items.append(
item(
"volume",
str(row["Name"]),
MEDIUM if unused else HIGH,
"unused volume: its data is lost"
if unused
else "volume in use by a container",
size_bytes=parse_size(row.get("Size")),
compose_project=_project(row.get("Labels")),
links=links,
)
)
return items
def _images(rows: list[dict], dangling: set[str]) -> list[dict]:
items = []
for row in rows:
if str(row.get("Containers")) != "0":
continue
loose = row["ID"] in dangling
items.append(
item(
"image",
str(row["ID"]),
LOW if loose else MEDIUM,
"dangling image without containers" if loose else "unused tagged image",
size_bytes=parse_size(row.get("UniqueSize")),
repository=row.get("Repository"),
tag=row.get("Tag"),
created_at=row.get("CreatedAt"),
)
)
return items
def _cache(rows: list[dict], now: float) -> list[dict]:
items = []
for row in rows:
if str(row.get("InUse")).lower() != "false":
continue
used = parse_time(row.get("LastUsedAt")) or parse_time(row.get("CreatedAt"))
idle = used is not None and now - used > IDLE_DAYS * DAY_S
items.append(
item(
"build-cache",
str(row["ID"]),
LOW if idle else MEDIUM,
f"build cache idle > {IDLE_DAYS} days"
if idle
else f"build cache used within {IDLE_DAYS} days",
size_bytes=parse_size(row.get("Size")),
last_used_since=row.get("LastUsedSince"),
last_used_at=used,
shared=str(row.get("Shared")).lower() == "true",
)
)
return items
def _containers(rows: list[dict]) -> list[dict]:
items = []
for row in rows:
if row.get("State") not in STOPPED:
continue
volumes = str(row.get("LocalVolumes"))
bare = volumes == "0"
items.append(
item(
"container",
str(row["ID"]),
LOW if bare else MEDIUM,
"stopped container without volumes"
if bare
else f"stopped container with {volumes} local volumes",
names=row.get("Names"),
image=row.get("Image"),
compose_project=_project(row.get("Labels")),
status=row.get("Status"),
)
)
return items
def docker_items(now: float) -> tuple[list[dict], list[str]]:
"""
Args:
now: epoch seconds the build cache idle time is measured against.
Returns:
Every volume, unused image, idle build cache record and stopped
container with its risk, read without changing anything, and
warnings when docker is missing, fails or prints no JSON.
"""
try:
data = json.loads(_docker(DF_VERBOSE))
dangling = set(_docker(DANGLING).split())
except FileNotFoundError:
return [], ["docker unavailable: not installed"]
except subprocess.CalledProcessError as exc:
return [], [f"docker unavailable: {_describe(exc)}"]
except ValueError:
return [], ["docker system df --verbose: output is not JSON"]
return [
*_volumes(data.get("Volumes") or []),
*_images(data.get("Images") or [], dangling),
*_cache(data.get("BuildCache") or [], now),
*_containers(data.get("Containers") or []),
], []
def delete_docker(entry: dict) -> str:
"""
Args:
entry: a low image, build-cache or container item of the plan.
Returns:
done, or skipped with the reason: an image no longer dangling right
before its delete, or a kind that is never low.
Raises:
subprocess.CalledProcessError: when docker refuses the delete.
"""
name = entry["name"]
if entry["kind"] == "image":
if name not in set(_docker(DANGLING).split()):
return "skipped: no longer dangling"
_docker(["image", "rm", name])
elif entry["kind"] == "build-cache":
_docker(
[
"builder",
"prune",
"--force",
"--filter",
f"id={name}",
"--filter",
f"until={IDLE_DAYS * 24}h",
]
)
elif entry["kind"] == "container":
_docker(["container", "rm", name])
else:
return f"skipped: {entry['kind']} is never deleted as low"
return "done"
+161
View File
@@ -0,0 +1,161 @@
from __future__ import annotations
from dataclasses import replace
from pkgmgr.actions.branch.gc import (
Item,
Repo,
_git,
_rebuild,
execute,
prepare,
)
from pkgmgr.actions.worktree.hooks import FINI_HOOK
from .levels import HIGH, LOW, MEDIUM, item
LOCAL_PROOF = ("ancestor", "patch")
FORGE_UNAVAILABLE = "forge unavailable"
TREE_STEPS = (f"hook:{FINI_HOOK}", "worktree")
def _pushed(repo: Repo, head: str | None) -> bool:
if not head:
return False
count = _git(["rev-list", "--count", head, "--not", "--remotes"], repo.repo)
return count == "0"
def pr_state(repo: Repo, it: Item) -> str:
"""
Args:
repo: the planned repository with its forge facts.
it: one of its items.
Returns:
unknown when the forge was not read, else open #N, merged #N or none.
"""
if repo.forge.unavailable:
return "unknown"
number = repo.forge.open_heads.get(it.branch) if it.branch else None
if number:
return f"open #{number}"
shas = [it.local_sha, it.head, *it.remotes.values()]
merged = [repo.forge.merged_heads[s] for s in shas if s in repo.forge.merged_heads]
return f"merged #{merged[0]}" if merged else "none"
def classify(repo: Repo, it: Item) -> tuple[str, str]:
"""
Args:
repo: the planned repository.
it: one of its items, planned with scope `all` or `worktree`.
Returns:
The risk and why. Low only for a linked worktree merged into the
default branch by ancestry or patch id, without staged, unstaged or
untracked change, whose head is on a remote, without compose stack
and with nothing but the forge's absence holding it.
"""
if it.state == "protected":
return HIGH, it.reason
if it.state == "stale":
return MEDIUM, "stale worktree metadata"
if it.state == "dirty":
return HIGH, it.reason
if it.worktree is None:
if it.state == "merged-clean":
return MEDIUM, f"merged branch ({it.reason}): branches are never low"
return HIGH, it.reason
if it.state != "merged-clean":
if it.unpushed:
return HIGH, f"{it.reason}; {it.unpushed} commits on no remote"
return MEDIUM, it.reason
if it.merged_by not in LOCAL_PROOF or it.merged_into != repo.default:
return MEDIUM, f"merged by {it.merged_by}, not locally into {repo.default}"
if it.worktree_state != "clean" or any((it.staged, it.unstaged, it.untracked)):
return HIGH, "worktree has changes"
if it.compose_projects:
return MEDIUM, f"compose stack {', '.join(it.compose_projects)}"
if it.skip not in (None, FORGE_UNAVAILABLE):
return MEDIUM, it.skip
if "worktree" not in it.actions:
return MEDIUM, "no worktree removal planned"
if not _pushed(repo, it.head):
return MEDIUM, "head is on no remote"
return LOW, f"merged into {repo.default} by {it.merged_by}, clean, pushed"
def _entry(repo: Repo, it: Item) -> dict:
risk, reason = classify(repo, it)
linked = it.worktree is not None and it.worktree != repo.repo
kind = "stale" if it.state == "stale" else "worktree" if linked else "branch"
return item(
kind,
it.worktree if linked or not it.branch else it.branch,
risk,
reason,
size_bytes=it.size_bytes,
repo=repo.repo,
branch=it.branch,
head=it.head,
state=it.state,
merged_by=it.merged_by,
merged_into=it.merged_into,
staged=it.staged,
unstaged=it.unstaged,
untracked=it.untracked,
compose_projects=it.compose_projects,
pr=pr_state(repo, it),
skip=it.skip,
steps=[a for a in it.actions if a in TREE_STEPS] if risk == LOW else [],
)
def git_items(
repo_roots: list[str], include: list[str], exclude: list[str], options: dict
) -> tuple[list[tuple[Repo, Item, dict]], list[str], bool] | None:
"""
Args:
repo_roots: main worktree roots of the repositories to scan, each
planned with scope `all`.
include: only items whose branch or worktree path matches one of these.
exclude: drop items whose branch or worktree path matches one of these.
options: the plan_repo keyword options but scope.
Returns:
(repository, item, plan entry) per chosen item, the warnings and
whether this runs in the host PID namespace; None for an unknown
include.
"""
prepared = prepare(repo_roots, include, exclude, {**options, "scope": "all"})
if prepared is None:
return None
repos, host_ns, chosen = prepared
warnings = [f"{repo.repo}: {w}" for repo in repos for w in repo.warnings]
entries = [
(repo, it, _entry(repo, it))
for repo in repos
for it in repo.items
if chosen(it)
]
return entries, warnings, host_ns
def delete_worktree(repo: Repo, it: Item) -> str:
"""
Args:
repo: the planned repository.
it: the low worktree item as planned; planned again with scope
`worktree`, so its branch stays, and removed only while low.
Returns:
The result execute settles, or skipped when it changed since the plan.
"""
tree_repo = replace(repo, scope="worktree")
fresh = _rebuild(tree_repo, it)
risk, reason = classify(tree_repo, fresh)
if risk != LOW or fresh.head != it.head or fresh.worktree != it.worktree:
return f"skipped: changed since plan ({reason})"
execute(tree_repo, fresh)
return fresh.result or "skipped: nothing executed"
+36
View File
@@ -0,0 +1,36 @@
from __future__ import annotations
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
LEVELS = (LOW, MEDIUM, HIGH)
DAY_S = 86400
IDLE_DAYS = 7
TMP_AGE_S = DAY_S
def rank(level: str) -> int:
return LEVELS.index(level)
def item(kind: str, name: str, risk: str, reason: str, **facts: object) -> dict:
"""
Args:
kind: worktree, branch, stale, image, build-cache, container, volume or tmp.
name: what the item deletes: a path, branch, docker id or volume name.
risk: one of LEVELS.
reason: why the item has that risk.
facts: kind-specific fields; size_bytes is read by the totals.
Returns:
One plan item; result stays None until an apply sets it.
"""
return {
"kind": kind,
"name": name,
"risk": risk,
"reason": reason,
"size_bytes": None,
**facts,
"result": None,
}
+162
View File
@@ -0,0 +1,162 @@
from __future__ import annotations
import json
import subprocess
import sys
import time
from pkgmgr.actions.branch.gc import (
REFUSAL,
_describe,
_process_cwds,
host_pid_namespace,
human_size,
)
from .docker_items import delete_docker, docker_items
from .git_items import delete_worktree, git_items
from .levels import LEVELS, LOW, rank
from .tmp_items import delete_tmp, read_owners, tmp_items
TMP_ROOT = "/tmp"
DOCKER_KINDS = ("image", "build-cache", "container")
def _totals(entries: list[dict]) -> dict:
return {
level: {
"count": sum(e["risk"] == level for e in entries),
"size_bytes": sum(
e["size_bytes"] or 0 for e in entries if e["risk"] == level
),
}
for level in LEVELS
}
def _render(plan: dict) -> str:
lines = [f"== gc plan (risk up to {plan['risk']})"]
for entry in plan["items"]:
size = "-" if entry["size_bytes"] is None else human_size(entry["size_bytes"])
line = (
f"{entry['risk'].upper():<6} {entry['kind']:<11} {size:>8} "
f"{entry['name']} {entry['reason']}"
)
lines.append(f"{line} -> {entry['result']}" if entry["result"] else line)
lines += [
f"TOTAL {level}: {t['count']} items, {human_size(t['size_bytes'])}"
for level, t in plan["totals"].items()
]
lines += [f"WARN {warning}" for warning in plan["warnings"]]
return "\n".join(lines)
def _delete(
entry: dict,
git_by_name: dict,
owners: dict[str, str],
now: float,
) -> str:
try:
if entry["kind"] in DOCKER_KINDS:
return delete_docker(entry)
if entry["kind"] == "tmp":
return delete_tmp(entry, owners, now, _process_cwds())
if entry["kind"] == "worktree":
repo, it = git_by_name[(entry["repo"], entry["name"])]
return delete_worktree(repo, it)
except (subprocess.CalledProcessError, OSError, RuntimeError, ValueError) as exc:
return f"failed: {_describe(exc)}"
return f"skipped: {entry['kind']} is never deleted as low"
def risk_cleanup(
repo_roots: list[str],
*,
level: str,
apply: bool,
as_json: bool,
owners_file: str | None,
include: list[str],
exclude: list[str],
merged_into: list[str],
sizes: bool,
min_age: float | None,
hooks: dict[str, dict[str, list[str]]],
tmp_root: str = TMP_ROOT,
) -> int:
"""
Args:
repo_roots: main worktree roots of the repositories to scan.
level: print the git, docker and scratch items up to this risk;
apply needs `low`.
apply: delete exactly the low items of the same plan, each
re-checked right before.
as_json: print the plan as JSON instead of text lines.
owners_file: optional JSON object of scratch path -> task status.
include: only git items whose branch or worktree path matches.
exclude: drop git items whose branch or worktree path matches.
merged_into: integration lines (refs) that also count as merged.
sizes: measure each worktree's disk usage into the plan.
min_age: skip git items younger than this many hours.
hooks: pinned hooks by managed repository root realpath.
tmp_root: the scratch directory whose direct children are listed.
Returns:
2 when refused, 1 when an applied item failed, else 0.
"""
if level not in LEVELS:
raise ValueError(f"unknown risk {level!r}")
if apply and level != LOW:
print(
"Refusing: --apply removes only low items; use --risk low", file=sys.stderr
)
return 2
host_ns = host_pid_namespace()
if apply and not host_ns:
print(REFUSAL, file=sys.stderr)
return 2
try:
owners = read_owners(owners_file)
except (OSError, ValueError) as exc:
print(f"Refusing: owner file: {_describe(exc)}", file=sys.stderr)
return 2
now = time.time()
options = {
"merged_into": merged_into,
"sizes": sizes,
"min_age": min_age,
"activity": False,
"hooks": hooks,
}
planned = git_items(repo_roots, include, exclude, options)
if planned is None:
return 2
git, warnings, _ = planned
docker, docker_warnings = docker_items(now)
scratch = tmp_items(tmp_root, owners, now, _process_cwds() if host_ns else {})
entries = [*(entry for _, _, entry in git), *docker, *scratch]
if not host_ns:
warnings.append(
"process and lock checks unavailable: not in the host PID namespace"
)
git_by_name = {(e["repo"], e["name"]): (repo, it) for repo, it, e in git}
if apply:
for entry in entries:
if entry["risk"] == LOW:
entry["result"] = _delete(entry, git_by_name, owners, now)
print(
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
file=sys.stderr,
)
plan = {
"host_pid_namespace": host_ns,
"risk": level,
"generated_at": now,
"totals": _totals(entries),
"items": [e for e in entries if rank(e["risk"]) <= rank(level)],
"warnings": [*warnings, *docker_warnings],
}
print(json.dumps(plan, indent=2) if as_json else _render(plan))
failed = any((e["result"] or "").startswith("failed") for e in entries)
return 1 if failed else 0
+141
View File
@@ -0,0 +1,141 @@
from __future__ import annotations
import json
import os
import stat
from pkgmgr.actions.branch.gc import _busy
from pkgmgr.actions.branch.nofollow import canonical, remove_tree
from pkgmgr.actions.gc.report.walk import walk
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
ENDED = ("done", "stopped")
def read_owners(path: str | None) -> dict[str, str]:
"""
Args:
path: a JSON object of absolute path -> task status, or None.
Returns:
Normalised absolute path -> lower-case status; empty without a file.
Raises:
OSError: when the file cannot be read.
ValueError: when it is not such a JSON object.
"""
if not path:
return {}
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, dict) or not all(
isinstance(k, str) and isinstance(v, str) for k, v in data.items()
):
raise ValueError(f"{path}: expected a JSON object of path -> status")
return {os.path.abspath(k): v.lower() for k, v in data.items()}
def _verdict(
path: str, st: os.stat_result, owners: dict[str, str], now: float, cwds: dict
) -> tuple[str, str, int, float]:
is_dir = stat.S_ISDIR(st.st_mode)
stats = walk(path) if is_dir else None
size = stats.size_bytes if stats else st.st_blocks * 512
newest = max(stats.newest_mtime, st.st_mtime) if stats else st.st_mtime
status = owners.get(path)
if is_dir and os.path.lexists(os.path.join(path, ".git")):
return HIGH, "holds a git checkout: remove it as a worktree", size, newest
if status is not None and status not in ENDED:
return HIGH, f"owner task is {status}", size, newest
if stats and (stats.foreign_entries or stats.unreadable):
return MEDIUM, "holds foreign or unreadable entries", size, newest
busy = _busy(cwds, path) if is_dir else None
if busy:
return MEDIUM, busy, size, newest
if now - newest <= TMP_AGE_S:
return MEDIUM, "changed within 24 h", size, newest
if status is None:
return MEDIUM, "no owner task known", size, newest
return LOW, f"owner task {status}, unchanged for 24 h", size, newest
def tmp_items(
root: str, owners: dict[str, str], now: float, cwds: dict[int, str]
) -> list[dict]:
"""
Args:
root: the scratch directory, /tmp on a host; only its direct
children the current user owns are listed.
owners: absolute path -> task status from read_owners.
now: epoch seconds the 24 h age is measured against.
cwds: pid -> working directory of the host's processes.
Returns:
One item per regular file or directory, never a symlink, socket or
foreign entry: low only when its owner task is done or stopped and
nothing in it changed for 24 h.
"""
items = []
base = os.path.realpath(root)
try:
names = sorted(os.listdir(base))
except OSError:
return []
for name in names:
path = os.path.join(base, name)
try:
st = os.lstat(path)
except OSError:
continue
if st.st_uid != os.getuid() or not (
stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)
):
continue
risk, reason, size, newest = _verdict(path, st, owners, now, cwds)
items.append(
item(
"tmp",
path,
risk,
reason,
size_bytes=size,
newest_mtime=newest,
owner_status=owners.get(path),
)
)
return items
def delete_tmp(
entry: dict, owners: dict[str, str], now: float, cwds: dict[int, str]
) -> str:
"""
Args:
entry: a low tmp item of the plan, deleted only while still low.
owners: as tmp_items takes them.
now: as tmp_items takes it.
cwds: as tmp_items takes them, read again before the delete.
Returns:
The result: done, or skipped with the reason.
Raises:
OSError: when the delete fails.
"""
path = entry["name"]
if not canonical(path):
return "skipped: path is not canonical"
st = os.lstat(path)
if st.st_uid != os.getuid():
return "skipped: no longer owned by this user"
risk, reason, _, _ = _verdict(path, st, owners, now, cwds)
if risk != LOW:
return f"skipped: changed since plan ({reason})"
if stat.S_ISDIR(st.st_mode):
remove_tree(path)
elif stat.S_ISREG(st.st_mode):
os.unlink(path)
else:
return "skipped: no longer a file or directory"
return "done"
+20
View File
@@ -6,6 +6,7 @@ import sys
from pkgmgr.actions.branch.gc import main_repo_root
from pkgmgr.actions.gc.report import disk_report, render_text
from pkgmgr.actions.gc.risk import risk_cleanup
from pkgmgr.actions.worktree.flow_actions import (
worktree_flow_clear,
worktree_flow_set,
@@ -119,6 +120,25 @@ def handle_worktree(args, ctx: CLIContext) -> None:
def handle_gc(args, ctx: CLIContext) -> None:
if args.risk:
if args.report:
print("--risk cannot be combined with --report", file=sys.stderr)
sys.exit(2)
sys.exit(
risk_cleanup(
scan_repo_roots(args, ctx),
level=args.risk,
apply=args.apply,
as_json=args.json,
owners_file=args.owners,
hooks=pinned_hooks(ctx),
min_age=args.min_age,
**scan_options(args),
)
)
if args.owners:
print("--owners only with --risk", file=sys.stderr)
sys.exit(2)
if not args.report:
run_cleanup(args, ctx, "all")
if args.apply:
+21
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
import argparse
from pkgmgr.actions.gc.risk.levels import LEVELS
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
@@ -44,3 +46,22 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
action="store_true",
help="With --report: also read `docker system df`",
)
gc.add_argument(
"--risk",
choices=LEVELS,
help=(
"Plan branches, worktrees, docker volumes, unused images, idle build "
"cache, stopped containers and /tmp entries with a risk class each "
"and print the items up to RISK; --apply removes exactly the low "
"items of that plan and needs --risk low"
),
)
gc.add_argument(
"--owners",
metavar="FILE",
help=(
"With --risk: JSON object of /tmp path -> owner task status; only "
"an entry whose task is done or stopped and that is unchanged for "
"24 h is low"
),
)
@@ -1,15 +1,19 @@
# src/pkgmgr/core/remote_provisioning/http/client.py
from __future__ import annotations
import http.client
import json
import ssl
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Any
from .errors import HttpError
ALLOWED_SCHEMES = frozenset({"http", "https"})
@dataclass(frozen=True)
class HttpResponse:
@@ -31,6 +35,11 @@ class HttpClient:
headers: dict[str, str] | None = None,
payload: dict[str, Any] | None = None,
) -> HttpResponse:
scheme = urllib.parse.urlsplit(url).scheme
if scheme not in ALLOWED_SCHEMES:
raise HttpError(
status=0, message=f"unsupported URL scheme {scheme!r}", body=""
)
data: bytes | None = None
final_headers: dict[str, str] = dict(headers or {})
@@ -65,5 +74,6 @@ class HttpClient:
except (OSError, ValueError):
body = ""
raise HttpError(status=int(exc.code), message=str(exc), body=body) from exc
except urllib.error.URLError as exc:
raise HttpError(status=0, message=str(exc), body="") from exc
except (OSError, http.client.HTTPException) as exc:
message = str(exc) or type(exc).__name__
raise HttpError(status=0, message=message, body="") from exc
+1
View File
@@ -264,6 +264,7 @@ class TestBranchGc(GcFixture, unittest.TestCase):
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),
@@ -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()