refactor(gc): split the risk plan to clear quality and review findings
CI / security-codeql (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
CI / quality (push) Blocked by required conditions
CI / security-codeql (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
CI / quality (push) Blocked by required conditions
quality, 24 findings: risk_cleanup(repo_roots, request) takes a frozen RiskRequest and splits into _refusal, _git_options, _host_items, _apply and _report; the hardcoded /tmp root is gone, the CLI passes tempfile.gettempdir() (so TMPDIR is honoured); classify, the tmp verdict and the HTTP client split into helpers in the same check order; gc_cmd options split into two adders; default-value fallbacks removed where every path sets the value. Tests: git(), AUTHOR and isolated_root move to tests/support/git_sandbox.py, the plan tests move to tests/unit/pkgmgr/actions/branch/test_gc_plan.py, test_risk_plan.py splits into risk_fixture.py, test_risk_plan.py and test_risk_apply.py. CodeRabbit: with --branch, --apply only plans and deletes the selected git items, docker and scratch items stay out with a warning; a truncated HTTP error body keeps its status and the partial body. | 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | feature/gc-risk-levels | 17 files +946/-788 | 91 % | 4 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % | Evidence: tests/unit + tests/integration with PYTHONPATH=src 904 passed; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0, 3 accepted (scheme-guarded urlopen moved into _send, fixed-argv git in the test helper). Hub review 913e2f2465eda2d9. Refs https://github.com/kevinveenbirkenbach/package-manager/pull/21 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8248a0253
commit
cee58bcef1
17 files changed
+933
-775
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
from .levels import LEVELS
|
from .levels import LEVELS
|
||||||
from .plan import risk_cleanup
|
from .plan import RiskRequest, risk_cleanup
|
||||||
|
|
||||||
__all__ = ["LEVELS", "risk_cleanup"]
|
__all__ = ["LEVELS", "RiskRequest", "risk_cleanup"]
|
||||||
@@ -29,7 +29,7 @@ def parse_time(text: object) -> float | None:
|
|||||||
if not match:
|
if not match:
|
||||||
return None
|
return None
|
||||||
clock, fraction, zone = match.groups()
|
clock, fraction, zone = match.groups()
|
||||||
micro = (fraction or "0")[:6].ljust(6, "0")
|
micro = (fraction or "")[:6].ljust(6, "0")
|
||||||
return datetime.strptime(
|
return datetime.strptime(
|
||||||
f"{clock}.{micro} {zone}", "%Y-%m-%d %H:%M:%S.%f %z"
|
f"{clock}.{micro} {zone}", "%Y-%m-%d %H:%M:%S.%f %z"
|
||||||
).timestamp()
|
).timestamp()
|
||||||
|
|||||||
@@ -57,6 +57,10 @@ def classify(repo: Repo, it: Item) -> tuple[str, str]:
|
|||||||
untracked change, whose head is on a remote, without compose stack
|
untracked change, whose head is on a remote, without compose stack
|
||||||
and with nothing but the forge's absence holding it.
|
and with nothing but the forge's absence holding it.
|
||||||
"""
|
"""
|
||||||
|
return _state_verdict(it) or _tree_verdict(repo, it)
|
||||||
|
|
||||||
|
|
||||||
|
def _state_verdict(it: Item) -> tuple[str, str] | None:
|
||||||
if it.state == "protected":
|
if it.state == "protected":
|
||||||
return HIGH, it.reason
|
return HIGH, it.reason
|
||||||
if it.state == "stale":
|
if it.state == "stale":
|
||||||
@@ -71,6 +75,10 @@ def classify(repo: Repo, it: Item) -> tuple[str, str]:
|
|||||||
if it.unpushed:
|
if it.unpushed:
|
||||||
return HIGH, f"{it.reason}; {it.unpushed} commits on no remote"
|
return HIGH, f"{it.reason}; {it.unpushed} commits on no remote"
|
||||||
return MEDIUM, it.reason
|
return MEDIUM, it.reason
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _tree_verdict(repo: Repo, it: Item) -> tuple[str, str]:
|
||||||
if it.merged_by not in LOCAL_PROOF or it.merged_into != repo.default:
|
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}"
|
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)):
|
if it.worktree_state != "clean" or any((it.staged, it.unstaged, it.untracked)):
|
||||||
@@ -151,6 +159,9 @@ def delete_worktree(repo: Repo, it: Item) -> str:
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The result execute settles, or skipped when it changed since the plan.
|
The result execute settles, or skipped when it changed since the plan.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: when execute settles no result.
|
||||||
"""
|
"""
|
||||||
tree_repo = replace(repo, scope="worktree")
|
tree_repo = replace(repo, scope="worktree")
|
||||||
fresh = _rebuild(tree_repo, it)
|
fresh = _rebuild(tree_repo, it)
|
||||||
@@ -158,4 +169,6 @@ def delete_worktree(repo: Repo, it: Item) -> str:
|
|||||||
if risk != LOW or fresh.head != it.head or fresh.worktree != it.worktree:
|
if risk != LOW or fresh.head != it.head or fresh.worktree != it.worktree:
|
||||||
return f"skipped: changed since plan ({reason})"
|
return f"skipped: changed since plan ({reason})"
|
||||||
execute(tree_repo, fresh)
|
execute(tree_repo, fresh)
|
||||||
return fresh.result or "skipped: nothing executed"
|
if fresh.result is None:
|
||||||
|
raise RuntimeError(f"execute settled no result for {it.worktree}")
|
||||||
|
return fresh.result
|
||||||
@@ -4,6 +4,7 @@ import json
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from pkgmgr.actions.branch.gc import (
|
from pkgmgr.actions.branch.gc import (
|
||||||
REFUSAL,
|
REFUSAL,
|
||||||
@@ -18,8 +19,44 @@ from .git_items import delete_worktree, git_items
|
|||||||
from .levels import LEVELS, LOW, rank
|
from .levels import LEVELS, LOW, rank
|
||||||
from .tmp_items import delete_tmp, read_owners, tmp_items
|
from .tmp_items import delete_tmp, read_owners, tmp_items
|
||||||
|
|
||||||
TMP_ROOT = "/tmp"
|
|
||||||
DOCKER_KINDS = ("image", "build-cache", "container")
|
DOCKER_KINDS = ("image", "build-cache", "container")
|
||||||
|
NO_HOST_NS = "process and lock checks unavailable: not in the host PID namespace"
|
||||||
|
INCLUDE_ONLY_GIT = (
|
||||||
|
"--branch selects git items only; docker and scratch items stay out of the plan"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RiskRequest:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
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; when
|
||||||
|
set, docker and scratch items are neither planned nor deleted.
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
def _totals(entries: list[dict]) -> dict:
|
def _totals(entries: list[dict]) -> dict:
|
||||||
@@ -27,7 +64,9 @@ def _totals(entries: list[dict]) -> dict:
|
|||||||
level: {
|
level: {
|
||||||
"count": sum(e["risk"] == level for e in entries),
|
"count": sum(e["risk"] == level for e in entries),
|
||||||
"size_bytes": sum(
|
"size_bytes": sum(
|
||||||
e["size_bytes"] or 0 for e in entries if e["risk"] == level
|
e["size_bytes"]
|
||||||
|
for e in entries
|
||||||
|
if e["risk"] == level and e["size_bytes"] is not None
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
for level in LEVELS
|
for level in LEVELS
|
||||||
@@ -70,78 +109,38 @@ def _delete(
|
|||||||
return f"skipped: {entry['kind']} is never deleted as low"
|
return f"skipped: {entry['kind']} is never deleted as low"
|
||||||
|
|
||||||
|
|
||||||
def risk_cleanup(
|
def _refusal(request: RiskRequest, host_ns: bool) -> str | None:
|
||||||
repo_roots: list[str],
|
if request.apply and request.level != LOW:
|
||||||
*,
|
return "Refusing: --apply removes only low items; use --risk low"
|
||||||
level: str,
|
if request.apply and not host_ns:
|
||||||
apply: bool,
|
return REFUSAL
|
||||||
as_json: bool,
|
return None
|
||||||
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.
|
def _git_options(request: RiskRequest) -> dict:
|
||||||
"""
|
return {
|
||||||
if level not in LEVELS:
|
"merged_into": request.merged_into,
|
||||||
raise ValueError(f"unknown risk {level!r}")
|
"sizes": request.sizes,
|
||||||
if apply and level != LOW:
|
"min_age": request.min_age,
|
||||||
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,
|
"activity": False,
|
||||||
"hooks": hooks,
|
"hooks": request.hooks,
|
||||||
}
|
}
|
||||||
planned = git_items(repo_roots, include, exclude, options)
|
|
||||||
if planned is None:
|
|
||||||
return 2
|
def _host_items(
|
||||||
git, warnings, _ = planned
|
request: RiskRequest, owners: dict[str, str], now: float, host_ns: bool
|
||||||
|
) -> tuple[list[dict], list[str]]:
|
||||||
|
notes = [] if host_ns else [NO_HOST_NS]
|
||||||
|
if request.include:
|
||||||
|
return [], [*notes, INCLUDE_ONLY_GIT]
|
||||||
docker, docker_warnings = docker_items(now)
|
docker, docker_warnings = docker_items(now)
|
||||||
scratch = tmp_items(tmp_root, owners, now, _process_cwds() if host_ns else {})
|
cwds = _process_cwds() if host_ns else {}
|
||||||
entries = [*(entry for _, _, entry in git), *docker, *scratch]
|
scratch = tmp_items(request.tmp_root, owners, now, cwds)
|
||||||
if not host_ns:
|
return [*docker, *scratch], [*notes, *docker_warnings]
|
||||||
warnings.append(
|
|
||||||
"process and lock checks unavailable: not in the host PID namespace"
|
|
||||||
)
|
def _apply(entries: list[dict], git: list, owners: dict[str, str], now: float) -> None:
|
||||||
git_by_name = {(e["repo"], e["name"]): (repo, it) for repo, it, e in git}
|
git_by_name = {(e["repo"], e["name"]): (repo, it) for repo, it, e in git}
|
||||||
if apply:
|
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
if entry["risk"] == LOW:
|
if entry["risk"] == LOW:
|
||||||
entry["result"] = _delete(entry, git_by_name, owners, now)
|
entry["result"] = _delete(entry, git_by_name, owners, now)
|
||||||
@@ -149,14 +148,61 @@ def risk_cleanup(
|
|||||||
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
|
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _report(
|
||||||
|
request: RiskRequest,
|
||||||
|
host_ns: bool,
|
||||||
|
now: float,
|
||||||
|
entries: list[dict],
|
||||||
|
warnings: list[str],
|
||||||
|
) -> int:
|
||||||
plan = {
|
plan = {
|
||||||
"host_pid_namespace": host_ns,
|
"host_pid_namespace": host_ns,
|
||||||
"risk": level,
|
"risk": request.level,
|
||||||
"generated_at": now,
|
"generated_at": now,
|
||||||
"totals": _totals(entries),
|
"totals": _totals(entries),
|
||||||
"items": [e for e in entries if rank(e["risk"]) <= rank(level)],
|
"items": [e for e in entries if rank(e["risk"]) <= rank(request.level)],
|
||||||
"warnings": [*warnings, *docker_warnings],
|
"warnings": warnings,
|
||||||
}
|
}
|
||||||
print(json.dumps(plan, indent=2) if as_json else _render(plan))
|
print(json.dumps(plan, indent=2) if request.as_json else _render(plan))
|
||||||
failed = any((e["result"] or "").startswith("failed") for e in entries)
|
failed = any((e["result"] or "").startswith("failed") for e in entries)
|
||||||
return 1 if failed else 0
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
def risk_cleanup(repo_roots: list[str], request: RiskRequest) -> int:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo_roots: main worktree roots of the repositories to scan.
|
||||||
|
request: what to plan, print and apply.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
2 when refused, 1 when an applied item failed, else 0.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: for a level outside LEVELS.
|
||||||
|
"""
|
||||||
|
if request.level not in LEVELS:
|
||||||
|
raise ValueError(f"unknown risk {request.level!r}")
|
||||||
|
host_ns = host_pid_namespace()
|
||||||
|
refusal = _refusal(request, host_ns)
|
||||||
|
if refusal:
|
||||||
|
print(refusal, file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
owners = read_owners(request.owners_file)
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
print(f"Refusing: owner file: {_describe(exc)}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
now = time.time()
|
||||||
|
planned = git_items(
|
||||||
|
repo_roots, request.include, request.exclude, _git_options(request)
|
||||||
|
)
|
||||||
|
if planned is None:
|
||||||
|
return 2
|
||||||
|
git, git_warnings, _ = planned
|
||||||
|
host, host_warnings = _host_items(request, owners, now, host_ns)
|
||||||
|
entries = [*(entry for _, _, entry in git), *host]
|
||||||
|
if request.apply:
|
||||||
|
_apply(entries, git, owners, now)
|
||||||
|
return _report(request, host_ns, now, entries, [*git_warnings, *host_warnings])
|
||||||
@@ -6,7 +6,7 @@ import stat
|
|||||||
|
|
||||||
from pkgmgr.actions.branch.gc import _busy
|
from pkgmgr.actions.branch.gc import _busy
|
||||||
from pkgmgr.actions.branch.nofollow import canonical, remove_tree
|
from pkgmgr.actions.branch.nofollow import canonical, remove_tree
|
||||||
from pkgmgr.actions.gc.report.walk import walk
|
from pkgmgr.actions.gc.report.walk import TreeStats, walk
|
||||||
|
|
||||||
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
|
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
|
||||||
|
|
||||||
@@ -36,28 +36,43 @@ def read_owners(path: str | None) -> dict[str, str]:
|
|||||||
return {os.path.abspath(k): v.lower() for k, v in data.items()}
|
return {os.path.abspath(k): v.lower() for k, v in data.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def _measure(path: str, st: os.stat_result) -> tuple[TreeStats | None, int, float]:
|
||||||
|
if not stat.S_ISDIR(st.st_mode):
|
||||||
|
return None, st.st_blocks * 512, st.st_mtime
|
||||||
|
stats = walk(path)
|
||||||
|
return stats, stats.size_bytes, max(stats.newest_mtime, st.st_mtime)
|
||||||
|
|
||||||
|
|
||||||
|
def _held(
|
||||||
|
path: str, stats: TreeStats | None, status: str | None, cwds: dict
|
||||||
|
) -> tuple[str, str] | None:
|
||||||
|
if stats is not None and os.path.lexists(os.path.join(path, ".git")):
|
||||||
|
return HIGH, "holds a git checkout: remove it as a worktree"
|
||||||
|
if status is not None and status not in ENDED:
|
||||||
|
return HIGH, f"owner task is {status}"
|
||||||
|
if stats is not None and (stats.foreign_entries or stats.unreadable):
|
||||||
|
return MEDIUM, "holds foreign or unreadable entries"
|
||||||
|
busy = _busy(cwds, path) if stats is not None else None
|
||||||
|
if busy:
|
||||||
|
return MEDIUM, busy
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _settled(status: str | None, age: float) -> tuple[str, str]:
|
||||||
|
if age <= TMP_AGE_S:
|
||||||
|
return MEDIUM, "changed within 24 h"
|
||||||
|
if status is None:
|
||||||
|
return MEDIUM, "no owner task known"
|
||||||
|
return LOW, f"owner task {status}, unchanged for 24 h"
|
||||||
|
|
||||||
|
|
||||||
def _verdict(
|
def _verdict(
|
||||||
path: str, st: os.stat_result, owners: dict[str, str], now: float, cwds: dict
|
path: str, st: os.stat_result, owners: dict[str, str], now: float, cwds: dict
|
||||||
) -> tuple[str, str, int, float]:
|
) -> tuple[str, str, int, float]:
|
||||||
is_dir = stat.S_ISDIR(st.st_mode)
|
stats, size, newest = _measure(path, st)
|
||||||
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)
|
status = owners.get(path)
|
||||||
if is_dir and os.path.lexists(os.path.join(path, ".git")):
|
risk, reason = _held(path, stats, status, cwds) or _settled(status, now - newest)
|
||||||
return HIGH, "holds a git checkout: remove it as a worktree", size, newest
|
return risk, reason, 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(
|
def tmp_items(
|
||||||
|
|||||||
@@ -3,10 +3,11 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
from pkgmgr.actions.branch.gc import main_repo_root
|
from pkgmgr.actions.branch.gc import main_repo_root
|
||||||
from pkgmgr.actions.gc.report import disk_report, render_text
|
from pkgmgr.actions.gc.report import disk_report, render_text
|
||||||
from pkgmgr.actions.gc.risk import risk_cleanup
|
from pkgmgr.actions.gc.risk import RiskRequest, risk_cleanup
|
||||||
from pkgmgr.actions.worktree.flow_actions import (
|
from pkgmgr.actions.worktree.flow_actions import (
|
||||||
worktree_flow_clear,
|
worktree_flow_clear,
|
||||||
worktree_flow_set,
|
worktree_flow_set,
|
||||||
@@ -119,23 +120,25 @@ def handle_worktree(args, ctx: CLIContext) -> None:
|
|||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|
||||||
|
|
||||||
def handle_gc(args, ctx: CLIContext) -> None:
|
def _risk_request(args, ctx: CLIContext) -> RiskRequest:
|
||||||
if args.risk:
|
return RiskRequest(
|
||||||
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,
|
level=args.risk,
|
||||||
apply=args.apply,
|
apply=args.apply,
|
||||||
as_json=args.json,
|
as_json=args.json,
|
||||||
owners_file=args.owners,
|
owners_file=args.owners,
|
||||||
hooks=pinned_hooks(ctx),
|
hooks=pinned_hooks(ctx),
|
||||||
min_age=args.min_age,
|
min_age=args.min_age,
|
||||||
|
tmp_root=tempfile.gettempdir(),
|
||||||
**scan_options(args),
|
**scan_options(args),
|
||||||
)
|
)
|
||||||
)
|
|
||||||
|
|
||||||
|
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), _risk_request(args, ctx)))
|
||||||
if args.owners:
|
if args.owners:
|
||||||
print("--owners only with --risk", file=sys.stderr)
|
print("--owners only with --risk", file=sys.stderr)
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
|||||||
add_apply_options(gc)
|
add_apply_options(gc)
|
||||||
add_scan_options(gc)
|
add_scan_options(gc)
|
||||||
add_min_age_option(gc)
|
add_min_age_option(gc)
|
||||||
|
_add_report_options(gc)
|
||||||
|
_add_risk_options(gc)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_report_options(gc: argparse.ArgumentParser) -> None:
|
||||||
gc.add_argument(
|
gc.add_argument(
|
||||||
"--report",
|
"--report",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -46,6 +51,9 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="With --report: also read `docker system df`",
|
help="With --report: also read `docker system df`",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_risk_options(gc: argparse.ArgumentParser) -> None:
|
||||||
gc.add_argument(
|
gc.add_argument(
|
||||||
"--risk",
|
"--risk",
|
||||||
choices=LEVELS,
|
choices=LEVELS,
|
||||||
@@ -53,7 +61,8 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
|||||||
"Plan branches, worktrees, docker volumes, unused images, idle build "
|
"Plan branches, worktrees, docker volumes, unused images, idle build "
|
||||||
"cache, stopped containers and /tmp entries with a risk class each "
|
"cache, stopped containers and /tmp entries with a risk class each "
|
||||||
"and print the items up to RISK; --apply removes exactly the low "
|
"and print the items up to RISK; --apply removes exactly the low "
|
||||||
"items of that plan and needs --risk low"
|
"items of that plan and needs --risk low; with --branch only the "
|
||||||
|
"matching git items are planned"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
gc.add_argument(
|
gc.add_argument(
|
||||||
|
|||||||
@@ -50,7 +50,9 @@ class HttpClient:
|
|||||||
req = urllib.request.Request(url=url, data=data, method=method.upper())
|
req = urllib.request.Request(url=url, data=data, method=method.upper())
|
||||||
for k, v in final_headers.items():
|
for k, v in final_headers.items():
|
||||||
req.add_header(k, v)
|
req.add_header(k, v)
|
||||||
|
return self._send(req)
|
||||||
|
|
||||||
|
def _send(self, req: urllib.request.Request) -> HttpResponse:
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(
|
with urllib.request.urlopen(
|
||||||
req,
|
req,
|
||||||
@@ -58,22 +60,32 @@ class HttpClient:
|
|||||||
context=ssl.create_default_context(),
|
context=ssl.create_default_context(),
|
||||||
) as resp:
|
) as resp:
|
||||||
raw = resp.read().decode("utf-8", errors="replace")
|
raw = resp.read().decode("utf-8", errors="replace")
|
||||||
|
return HttpResponse(
|
||||||
parsed: dict[str, Any] | None = None
|
status=int(resp.status), text=raw, json=_json_object(raw)
|
||||||
if raw:
|
)
|
||||||
try:
|
|
||||||
loaded = json.loads(raw)
|
|
||||||
parsed = loaded if isinstance(loaded, dict) else None
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
parsed = None
|
|
||||||
|
|
||||||
return HttpResponse(status=int(resp.status), text=raw, json=parsed)
|
|
||||||
except urllib.error.HTTPError as exc:
|
except urllib.error.HTTPError as exc:
|
||||||
try:
|
raise HttpError(
|
||||||
body = exc.read().decode("utf-8", errors="replace")
|
status=int(exc.code), message=str(exc), body=_error_body(exc)
|
||||||
except (OSError, ValueError):
|
) from exc
|
||||||
body = ""
|
|
||||||
raise HttpError(status=int(exc.code), message=str(exc), body=body) from exc
|
|
||||||
except (OSError, http.client.HTTPException) as exc:
|
except (OSError, http.client.HTTPException) as exc:
|
||||||
message = str(exc) or type(exc).__name__
|
message = str(exc) or type(exc).__name__
|
||||||
raise HttpError(status=0, message=message, body="") from exc
|
raise HttpError(status=0, message=message, body="") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _json_object(raw: str) -> dict[str, Any] | None:
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
loaded = json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return loaded if isinstance(loaded, dict) else None
|
||||||
|
|
||||||
|
|
||||||
|
def _error_body(exc: urllib.error.HTTPError) -> str:
|
||||||
|
try:
|
||||||
|
return exc.read().decode("utf-8", errors="replace")
|
||||||
|
except http.client.IncompleteRead as truncated:
|
||||||
|
return truncated.partial.decode("utf-8", errors="replace")
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return ""
|
||||||
@@ -4,36 +4,16 @@ import io
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
|
||||||
import unittest
|
import unittest
|
||||||
from contextlib import redirect_stderr, redirect_stdout
|
from contextlib import redirect_stdout
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from pkgmgr.actions.branch import gc, gc_forge
|
from pkgmgr.actions.branch import gc
|
||||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||||
from pkgmgr.cli.commands.branch import handle_branch
|
from pkgmgr.cli.commands.branch import handle_branch
|
||||||
from pkgmgr.cli.parser import create_parser
|
from pkgmgr.cli.parser import create_parser
|
||||||
from pkgmgr.core.credentials.types import NoCredentialsError
|
from tests.support.git_sandbox import git, isolated_root
|
||||||
|
|
||||||
GITHUB_URL = "https://github.com/example/demo.git"
|
|
||||||
AUTHOR = {
|
|
||||||
"GIT_AUTHOR_NAME": "t",
|
|
||||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
|
||||||
"GIT_COMMITTER_NAME": "t",
|
|
||||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def git(cwd: str, *args: str) -> str:
|
|
||||||
return subprocess.run(
|
|
||||||
["git", "-c", "commit.gpgsign=false", *args],
|
|
||||||
cwd=cwd,
|
|
||||||
env={**os.environ, **AUTHOR},
|
|
||||||
check=True,
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
).stdout.strip()
|
|
||||||
|
|
||||||
|
|
||||||
def docker_available() -> bool:
|
def docker_available() -> bool:
|
||||||
@@ -46,17 +26,7 @@ def docker_available() -> bool:
|
|||||||
|
|
||||||
class GcFixture:
|
class GcFixture:
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
self._tmp = tempfile.TemporaryDirectory()
|
self.root = isolated_root(self, {})
|
||||||
self.addCleanup(self._tmp.cleanup)
|
|
||||||
self.root = os.path.realpath(self._tmp.name)
|
|
||||||
self.addCleanup(os.chdir, os.getcwd())
|
|
||||||
os.chdir(self.root)
|
|
||||||
home = os.path.join(self.root, "home")
|
|
||||||
os.makedirs(home)
|
|
||||||
scratch = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
|
||||||
patcher = patch.dict(os.environ, {**scratch, "HOME": home}, clear=True)
|
|
||||||
patcher.start()
|
|
||||||
self.addCleanup(patcher.stop)
|
|
||||||
self.origin = os.path.join(self.root, "origin.git")
|
self.origin = os.path.join(self.root, "origin.git")
|
||||||
self.repo = os.path.join(self.root, "repo")
|
self.repo = os.path.join(self.root, "repo")
|
||||||
git(self.root, "init", "--bare", "-b", "main", self.origin)
|
git(self.root, "init", "--bare", "-b", "main", self.origin)
|
||||||
@@ -153,186 +123,6 @@ class GcFixture:
|
|||||||
|
|
||||||
|
|
||||||
class TestBranchGc(GcFixture, unittest.TestCase):
|
class TestBranchGc(GcFixture, unittest.TestCase):
|
||||||
def test_classifies_every_branch(self) -> None:
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["main"].state, "protected")
|
|
||||||
self.assertEqual(items["merged"].state, "merged-clean")
|
|
||||||
self.assertEqual(items["merged"].merged_by, "ancestor")
|
|
||||||
self.assertEqual(
|
|
||||||
items["merged"].actions,
|
|
||||||
["worktree", "local-branch", "remote-branch:origin"],
|
|
||||||
)
|
|
||||||
self.assertTrue(items["merged"].eligible)
|
|
||||||
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
|
||||||
self.assertTrue(items["squashed"].eligible)
|
|
||||||
self.assertEqual(items["fresh"].state, "unmerged")
|
|
||||||
self.assertEqual(items["fresh"].reason, "no own commits")
|
|
||||||
self.assertEqual(items["wip"].state, "unmerged")
|
|
||||||
self.assertEqual(items["wip"].skip, "open-pr #3")
|
|
||||||
self.assertEqual(items["dirty"].state, "dirty")
|
|
||||||
|
|
||||||
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
|
||||||
self._integration_line()
|
|
||||||
before = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
self.assertEqual(before["feat"].state, "unmerged")
|
|
||||||
self.assertIsNone(before["feat"].merged_into)
|
|
||||||
|
|
||||||
for ref in ("line", "origin/line"):
|
|
||||||
with self.subTest(ref=ref):
|
|
||||||
items = self._items(
|
|
||||||
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
|
||||||
)
|
|
||||||
self.assertEqual(items["feat"].state, "merged-clean")
|
|
||||||
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
|
||||||
self.assertEqual(items["feat"].merged_into, ref)
|
|
||||||
self.assertTrue(items["feat"].eligible)
|
|
||||||
self.assertEqual(items["line"].state, "protected")
|
|
||||||
self.assertEqual(items["start"].state, "unmerged")
|
|
||||||
self.assertEqual(items["merged"].merged_into, "origin/main")
|
|
||||||
|
|
||||||
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
|
||||||
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
|
||||||
|
|
||||||
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
|
||||||
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
|
||||||
|
|
||||||
def test_sizes_and_min_age(self) -> None:
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
|
||||||
self.assertGreater(items["merged"].size_bytes, 0)
|
|
||||||
self.assertIsNone(items["squashed"].size_bytes)
|
|
||||||
self.assertIn("size ", gc._line(items["merged"]))
|
|
||||||
|
|
||||||
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
|
||||||
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
|
||||||
self.assertFalse(young["merged"].eligible)
|
|
||||||
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
|
||||||
self.assertIsNone(old["merged"].skip)
|
|
||||||
|
|
||||||
def test_busy_worktree_is_skipped(self) -> None:
|
|
||||||
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
|
||||||
|
|
||||||
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
|
||||||
self.assertFalse(items["merged"].eligible)
|
|
||||||
|
|
||||||
def test_lock_with_live_pid_is_skipped(self) -> None:
|
|
||||||
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
|
||||||
|
|
||||||
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
|
||||||
self._lock("claude agent x (pid 999999999 on host)")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertIsNone(items["locked"].skip)
|
|
||||||
self.assertTrue(items["locked"].eligible)
|
|
||||||
|
|
||||||
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
|
||||||
self._lock("claude agent x (pid 999999999 on host)")
|
|
||||||
items = self._items(self._plan(host_ns=False, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
|
||||||
|
|
||||||
def test_lock_without_pid_is_respected(self) -> None:
|
|
||||||
self._lock("manual hold")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
|
||||||
|
|
||||||
def test_forge_unavailable_skips_everything(self) -> None:
|
|
||||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["merged"].skip, "forge unavailable")
|
|
||||||
self.assertIsNone(items["squashed"].merged_by)
|
|
||||||
|
|
||||||
def _github_without_token(self) -> None:
|
|
||||||
git(self.repo, "branch", "local-done", "merged")
|
|
||||||
git(self.repo, "checkout", "-b", "local-wip", "main")
|
|
||||||
self._commit("local-wip")
|
|
||||||
git(self.repo, "checkout", "main")
|
|
||||||
git(self.repo, "branch", "--track", "tracked", "origin/merged")
|
|
||||||
git(self.repo, "push", "origin", "merged:refs/heads/remote-done")
|
|
||||||
git(self.repo, "remote", "set-url", "origin", GITHUB_URL)
|
|
||||||
|
|
||||||
def _cleanup_without_token(self, apply: bool) -> tuple[int, dict]:
|
|
||||||
out = io.StringIO()
|
|
||||||
with (
|
|
||||||
patch.dict(os.environ, {"GIT_ALLOW_PROTOCOL": "file"}),
|
|
||||||
patch.object(gc, "host_pid_namespace", return_value=True),
|
|
||||||
patch.object(gc, "list_compose_containers", return_value=[]),
|
|
||||||
patch.object(gc, "_process_cwds", return_value={}),
|
|
||||||
patch.object(gc, "_docker", return_value=""),
|
|
||||||
patch.object(gc_forge, "TokenResolver") as resolver,
|
|
||||||
patch.object(gc_forge, "HttpClient") as http,
|
|
||||||
redirect_stdout(out),
|
|
||||||
redirect_stderr(io.StringIO()),
|
|
||||||
):
|
|
||||||
resolver.return_value.get_token.side_effect = NoCredentialsError("none")
|
|
||||||
code = gc.cleanup(
|
|
||||||
[self.repo],
|
|
||||||
scope="branch",
|
|
||||||
apply=apply,
|
|
||||||
as_json=True,
|
|
||||||
include=[],
|
|
||||||
exclude=[],
|
|
||||||
merged_into=[],
|
|
||||||
sizes=False,
|
|
||||||
min_age=None,
|
|
||||||
hooks={},
|
|
||||||
)
|
|
||||||
resolver.return_value.get_token.assert_called_once()
|
|
||||||
http.assert_not_called()
|
|
||||||
return code, json.loads(out.getvalue())["repos"][0]
|
|
||||||
|
|
||||||
def test_local_only_merged_branch_needs_no_forge(self) -> None:
|
|
||||||
self._github_without_token()
|
|
||||||
code, plan = self._cleanup_without_token(apply=False)
|
|
||||||
items = {i["branch"]: i for i in plan["items"] if i["branch"]}
|
|
||||||
|
|
||||||
self.assertEqual(code, 0)
|
|
||||||
self.assertIn("forge unavailable: no GitHub token (none)", plan["warnings"])
|
|
||||||
self.assertIsNone(items["local-done"]["skip"])
|
|
||||||
self.assertEqual(items["local-done"]["merged_by"], "ancestor")
|
|
||||||
self.assertEqual(items["local-done"]["actions"], ["local-branch"])
|
|
||||||
self.assertEqual(items["remote-done"]["state"], "merged-clean")
|
|
||||||
self.assertEqual(items["tracked"]["state"], "merged-clean")
|
|
||||||
self.assertEqual(items["local-wip"]["state"], "unmerged")
|
|
||||||
for name in ("merged", "remote-done", "tracked", "local-wip", "squashed"):
|
|
||||||
with self.subTest(branch=name):
|
|
||||||
self.assertEqual(items[name]["skip"], "forge unavailable")
|
|
||||||
|
|
||||||
def test_apply_without_token_deletes_only_the_local_only_merged_branch(
|
|
||||||
self,
|
|
||||||
) -> None:
|
|
||||||
self._github_without_token()
|
|
||||||
before = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
|
||||||
code, plan = self._cleanup_without_token(apply=True)
|
|
||||||
after = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
|
||||||
|
|
||||||
self.assertEqual(code, 0)
|
|
||||||
self.assertEqual(
|
|
||||||
[(i["branch"], i["result"]) for i in plan["items"] if i["result"]],
|
|
||||||
[("local-done", "done")],
|
|
||||||
)
|
|
||||||
self.assertEqual(before - after, {"refs/heads/local-done"})
|
|
||||||
self.assertEqual(after - before, set())
|
|
||||||
self.assertEqual(
|
|
||||||
git(self.origin, "branch", "--list", "remote-done"), "remote-done"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_stale_metadata_is_listed_not_pruned(self) -> None:
|
|
||||||
stub = os.path.join(self.repo, ".git", "worktrees", "stub")
|
|
||||||
os.makedirs(stub)
|
|
||||||
open(os.path.join(stub, "commondir"), "w").close()
|
|
||||||
plan = self._plan(host_ns=True, cwds={})
|
|
||||||
|
|
||||||
stale = [i for i in plan.items if i.state == "stale"]
|
|
||||||
self.assertEqual([i.worktree for i in stale], [stub])
|
|
||||||
self.assertTrue(os.path.isdir(stub))
|
|
||||||
|
|
||||||
def test_execute_removes_worktree_and_branches(self) -> None:
|
def test_execute_removes_worktree_and_branches(self) -> None:
|
||||||
plan = self._plan(host_ns=True, cwds={})
|
plan = self._plan(host_ns=True, cwds={})
|
||||||
item = self._items(plan)["merged"]
|
item = self._items(plan)["merged"]
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,59 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
AUTHOR = {
|
||||||
|
"GIT_AUTHOR_NAME": "t",
|
||||||
|
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||||
|
"GIT_COMMITTER_NAME": "t",
|
||||||
|
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def git(cwd: str, *args: str) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
cwd: the repository to run in.
|
||||||
|
args: the git arguments; signing stays off and AUTHOR applies.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The stripped standard output.
|
||||||
|
"""
|
||||||
|
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 isolated_root(case: unittest.TestCase, env: dict[str, str]) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
case: the test whose cleanups remove the directory and restore the
|
||||||
|
working directory and environment.
|
||||||
|
env: variables set over the environment, from which every GIT_*
|
||||||
|
variable is dropped.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The realpath of a fresh temporary directory, now the working
|
||||||
|
directory, whose empty `home` child is HOME.
|
||||||
|
"""
|
||||||
|
scratch = tempfile.TemporaryDirectory()
|
||||||
|
case.addCleanup(scratch.cleanup)
|
||||||
|
root = os.path.realpath(scratch.name)
|
||||||
|
case.addCleanup(os.chdir, os.getcwd())
|
||||||
|
os.chdir(root)
|
||||||
|
home = os.path.join(root, "home")
|
||||||
|
os.makedirs(home)
|
||||||
|
kept = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||||
|
environ = patch.dict(os.environ, {**kept, **env, "HOME": home}, clear=True)
|
||||||
|
environ.start()
|
||||||
|
case.addCleanup(environ.stop)
|
||||||
|
return root
|
||||||
@@ -4,20 +4,14 @@ import io
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import tempfile
|
|
||||||
import unittest
|
import unittest
|
||||||
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from pkgmgr.actions.branch import gc
|
from pkgmgr.actions.branch import gc
|
||||||
from pkgmgr.core.git import run
|
from pkgmgr.core.git import run
|
||||||
|
from tests.support.git_sandbox import AUTHOR, isolated_root
|
||||||
|
|
||||||
AUTHOR = {
|
|
||||||
"GIT_AUTHOR_NAME": "t",
|
|
||||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
|
||||||
"GIT_COMMITTER_NAME": "t",
|
|
||||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
|
||||||
}
|
|
||||||
MERGED = 12
|
MERGED = 12
|
||||||
REGISTRATIONS = 40
|
REGISTRATIONS = 40
|
||||||
|
|
||||||
@@ -25,17 +19,7 @@ REGISTRATIONS = 40
|
|||||||
@unittest.skipUnless(shutil.which("git"), "git builds the repository under test")
|
@unittest.skipUnless(shutil.which("git"), "git builds the repository under test")
|
||||||
class TestHeldBranchesReadOnce(unittest.TestCase):
|
class TestHeldBranchesReadOnce(unittest.TestCase):
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
tmp = tempfile.TemporaryDirectory()
|
self.root = isolated_root(self, AUTHOR)
|
||||||
self.addCleanup(tmp.cleanup)
|
|
||||||
self.root = os.path.realpath(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_")}
|
|
||||||
patcher = patch.dict(os.environ, {**clean, **AUTHOR, "HOME": home}, clear=True)
|
|
||||||
patcher.start()
|
|
||||||
self.addCleanup(patcher.stop)
|
|
||||||
self.repo = os.path.join(self.root, "repo")
|
self.repo = os.path.join(self.root, "repo")
|
||||||
self._shape()
|
self._shape()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from contextlib import redirect_stderr, redirect_stdout
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch import gc, gc_forge
|
||||||
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||||
|
from pkgmgr.core.credentials.types import NoCredentialsError
|
||||||
|
from tests.integration.test_branch_gc import GcFixture
|
||||||
|
from tests.support.git_sandbox import git
|
||||||
|
|
||||||
|
GITHUB_URL = "https://github.com/example/demo.git"
|
||||||
|
|
||||||
|
|
||||||
|
class TestBranchGcPlan(GcFixture, unittest.TestCase):
|
||||||
|
def test_classifies_every_branch(self) -> None:
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["main"].state, "protected")
|
||||||
|
self.assertEqual(items["merged"].state, "merged-clean")
|
||||||
|
self.assertEqual(items["merged"].merged_by, "ancestor")
|
||||||
|
self.assertEqual(
|
||||||
|
items["merged"].actions,
|
||||||
|
["worktree", "local-branch", "remote-branch:origin"],
|
||||||
|
)
|
||||||
|
self.assertTrue(items["merged"].eligible)
|
||||||
|
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
||||||
|
self.assertTrue(items["squashed"].eligible)
|
||||||
|
self.assertEqual(items["fresh"].state, "unmerged")
|
||||||
|
self.assertEqual(items["fresh"].reason, "no own commits")
|
||||||
|
self.assertEqual(items["wip"].state, "unmerged")
|
||||||
|
self.assertEqual(items["wip"].skip, "open-pr #3")
|
||||||
|
self.assertEqual(items["dirty"].state, "dirty")
|
||||||
|
|
||||||
|
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
||||||
|
self._integration_line()
|
||||||
|
before = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
self.assertEqual(before["feat"].state, "unmerged")
|
||||||
|
self.assertIsNone(before["feat"].merged_into)
|
||||||
|
|
||||||
|
for ref in ("line", "origin/line"):
|
||||||
|
with self.subTest(ref=ref):
|
||||||
|
items = self._items(
|
||||||
|
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
||||||
|
)
|
||||||
|
self.assertEqual(items["feat"].state, "merged-clean")
|
||||||
|
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
||||||
|
self.assertEqual(items["feat"].merged_into, ref)
|
||||||
|
self.assertTrue(items["feat"].eligible)
|
||||||
|
self.assertEqual(items["line"].state, "protected")
|
||||||
|
self.assertEqual(items["start"].state, "unmerged")
|
||||||
|
self.assertEqual(items["merged"].merged_into, "origin/main")
|
||||||
|
|
||||||
|
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
||||||
|
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
||||||
|
|
||||||
|
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
||||||
|
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
||||||
|
|
||||||
|
def test_sizes_and_min_age(self) -> None:
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
||||||
|
self.assertGreater(items["merged"].size_bytes, 0)
|
||||||
|
self.assertIsNone(items["squashed"].size_bytes)
|
||||||
|
self.assertIn("size ", gc._line(items["merged"]))
|
||||||
|
|
||||||
|
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
||||||
|
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
||||||
|
self.assertFalse(young["merged"].eligible)
|
||||||
|
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
||||||
|
self.assertIsNone(old["merged"].skip)
|
||||||
|
|
||||||
|
def test_busy_worktree_is_skipped(self) -> None:
|
||||||
|
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
||||||
|
|
||||||
|
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
||||||
|
self.assertFalse(items["merged"].eligible)
|
||||||
|
|
||||||
|
def test_lock_with_live_pid_is_skipped(self) -> None:
|
||||||
|
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
||||||
|
|
||||||
|
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
||||||
|
self._lock("claude agent x (pid 999999999 on host)")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertIsNone(items["locked"].skip)
|
||||||
|
self.assertTrue(items["locked"].eligible)
|
||||||
|
|
||||||
|
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
||||||
|
self._lock("claude agent x (pid 999999999 on host)")
|
||||||
|
items = self._items(self._plan(host_ns=False, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
||||||
|
|
||||||
|
def test_lock_without_pid_is_respected(self) -> None:
|
||||||
|
self._lock("manual hold")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
||||||
|
|
||||||
|
def test_forge_unavailable_skips_everything(self) -> None:
|
||||||
|
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["merged"].skip, "forge unavailable")
|
||||||
|
self.assertIsNone(items["squashed"].merged_by)
|
||||||
|
|
||||||
|
def _github_without_token(self) -> None:
|
||||||
|
git(self.repo, "branch", "local-done", "merged")
|
||||||
|
git(self.repo, "checkout", "-b", "local-wip", "main")
|
||||||
|
self._commit("local-wip")
|
||||||
|
git(self.repo, "checkout", "main")
|
||||||
|
git(self.repo, "branch", "--track", "tracked", "origin/merged")
|
||||||
|
git(self.repo, "push", "origin", "merged:refs/heads/remote-done")
|
||||||
|
git(self.repo, "remote", "set-url", "origin", GITHUB_URL)
|
||||||
|
|
||||||
|
def _cleanup_without_token(self, apply: bool) -> tuple[int, dict]:
|
||||||
|
out = io.StringIO()
|
||||||
|
with (
|
||||||
|
patch.dict(os.environ, {"GIT_ALLOW_PROTOCOL": "file"}),
|
||||||
|
patch.object(gc, "host_pid_namespace", return_value=True),
|
||||||
|
patch.object(gc, "list_compose_containers", return_value=[]),
|
||||||
|
patch.object(gc, "_process_cwds", return_value={}),
|
||||||
|
patch.object(gc, "_docker", return_value=""),
|
||||||
|
patch.object(gc_forge, "TokenResolver") as resolver,
|
||||||
|
patch.object(gc_forge, "HttpClient") as http,
|
||||||
|
redirect_stdout(out),
|
||||||
|
redirect_stderr(io.StringIO()),
|
||||||
|
):
|
||||||
|
resolver.return_value.get_token.side_effect = NoCredentialsError("none")
|
||||||
|
code = gc.cleanup(
|
||||||
|
[self.repo],
|
||||||
|
scope="branch",
|
||||||
|
apply=apply,
|
||||||
|
as_json=True,
|
||||||
|
include=[],
|
||||||
|
exclude=[],
|
||||||
|
merged_into=[],
|
||||||
|
sizes=False,
|
||||||
|
min_age=None,
|
||||||
|
hooks={},
|
||||||
|
)
|
||||||
|
resolver.return_value.get_token.assert_called_once()
|
||||||
|
http.assert_not_called()
|
||||||
|
return code, json.loads(out.getvalue())["repos"][0]
|
||||||
|
|
||||||
|
def test_local_only_merged_branch_needs_no_forge(self) -> None:
|
||||||
|
self._github_without_token()
|
||||||
|
code, plan = self._cleanup_without_token(apply=False)
|
||||||
|
items = {i["branch"]: i for i in plan["items"] if i["branch"]}
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertIn("forge unavailable: no GitHub token (none)", plan["warnings"])
|
||||||
|
self.assertIsNone(items["local-done"]["skip"])
|
||||||
|
self.assertEqual(items["local-done"]["merged_by"], "ancestor")
|
||||||
|
self.assertEqual(items["local-done"]["actions"], ["local-branch"])
|
||||||
|
self.assertEqual(items["remote-done"]["state"], "merged-clean")
|
||||||
|
self.assertEqual(items["tracked"]["state"], "merged-clean")
|
||||||
|
self.assertEqual(items["local-wip"]["state"], "unmerged")
|
||||||
|
for name in ("merged", "remote-done", "tracked", "local-wip", "squashed"):
|
||||||
|
with self.subTest(branch=name):
|
||||||
|
self.assertEqual(items[name]["skip"], "forge unavailable")
|
||||||
|
|
||||||
|
def test_apply_without_token_deletes_only_the_local_only_merged_branch(
|
||||||
|
self,
|
||||||
|
) -> None:
|
||||||
|
self._github_without_token()
|
||||||
|
before = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||||
|
code, plan = self._cleanup_without_token(apply=True)
|
||||||
|
after = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertEqual(
|
||||||
|
[(i["branch"], i["result"]) for i in plan["items"] if i["result"]],
|
||||||
|
[("local-done", "done")],
|
||||||
|
)
|
||||||
|
self.assertEqual(before - after, {"refs/heads/local-done"})
|
||||||
|
self.assertEqual(after - before, set())
|
||||||
|
self.assertEqual(
|
||||||
|
git(self.origin, "branch", "--list", "remote-done"), "remote-done"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stale_metadata_is_listed_not_pruned(self) -> None:
|
||||||
|
stub = os.path.join(self.repo, ".git", "worktrees", "stub")
|
||||||
|
os.makedirs(stub)
|
||||||
|
open(os.path.join(stub, "commondir"), "w").close()
|
||||||
|
plan = self._plan(host_ns=True, cwds={})
|
||||||
|
|
||||||
|
stale = [i for i in plan.items if i.state == "stale"]
|
||||||
|
self.assertEqual([i.worktree for i in stale], [stub])
|
||||||
|
self.assertTrue(os.path.isdir(stub))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -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)")
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.gc.risk import git_items, plan
|
||||||
|
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||||
|
BARE_CONTAINER,
|
||||||
|
DANGLING_ID,
|
||||||
|
OLD_CACHE,
|
||||||
|
RiskPlanFixture,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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_branch_filter_applies_to_its_git_items_only(self) -> None:
|
||||||
|
tmp_before = sorted(os.listdir(self.tmp))
|
||||||
|
self.include = ["done"]
|
||||||
|
|
||||||
|
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertEqual(
|
||||||
|
[(e["name"], e["result"]) for e in printed["items"]],
|
||||||
|
[(self.wt["done"], "done")],
|
||||||
|
)
|
||||||
|
self.assertIn(plan.INCLUDE_ONLY_GIT, printed["warnings"])
|
||||||
|
self.assertEqual(self.docker.calls, [])
|
||||||
|
self.assertEqual(sorted(os.listdir(self.tmp)), tmp_before)
|
||||||
|
for name in ("dirty", "stack", "pushed", "wip", "cherry"):
|
||||||
|
self.assertTrue(os.path.isdir(self.wt[name]), name)
|
||||||
|
|
||||||
|
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 = self.entry(printed, 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()
|
||||||
|
self.host_ns = host_ns
|
||||||
|
code, printed, err = self.run_gc(level=level, apply=True)
|
||||||
|
|
||||||
|
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"]))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,343 +1,29 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import io
|
import io
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
|
||||||
import unittest
|
import unittest
|
||||||
from contextlib import redirect_stderr, redirect_stdout
|
from contextlib import redirect_stderr
|
||||||
from datetime import datetime, timezone
|
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from pkgmgr.actions.branch import gc
|
|
||||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||||
from pkgmgr.actions.gc.risk import docker_items, git_items, plan
|
from pkgmgr.actions.gc.risk import plan
|
||||||
from pkgmgr.cli.commands.worktree import handle_gc
|
from pkgmgr.cli.commands.worktree import handle_gc
|
||||||
from pkgmgr.cli.parser import create_parser
|
from pkgmgr.cli.parser import create_parser
|
||||||
|
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||||
DAY = 86400
|
BARE_CONTAINER,
|
||||||
REAL_RUN = subprocess.run
|
BUSY_CACHE,
|
||||||
AUTHOR = {
|
DANGLING_ID,
|
||||||
"GIT_AUTHOR_NAME": "t",
|
NEW_CACHE,
|
||||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
OLD_CACHE,
|
||||||
"GIT_COMMITTER_NAME": "t",
|
RUNNING_CONTAINER,
|
||||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
TAGGED_ID,
|
||||||
}
|
USED_ID,
|
||||||
DANGLING_ID = "sha256:" + "d" * 64
|
VOLUME_CONTAINER,
|
||||||
TAGGED_ID = "sha256:" + "a" * 64
|
RiskPlanFixture,
|
||||||
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):
|
class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
||||||
@@ -359,16 +45,16 @@ class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
|||||||
for name, risk in expected.items():
|
for name, risk in expected.items():
|
||||||
with self.subTest(name=name):
|
with self.subTest(name=name):
|
||||||
self.assertEqual(risks[name], risk)
|
self.assertEqual(risks[name], risk)
|
||||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
done = self.entry(printed, self.wt["done"])
|
||||||
self.assertEqual(done["steps"], ["worktree"])
|
self.assertEqual(done["steps"], ["worktree"])
|
||||||
self.assertEqual(done["pr"], "none")
|
self.assertEqual(done["pr"], "none")
|
||||||
cherry = next(e for e in printed["items"] if e["name"] == self.wt["cherry"])
|
cherry = self.entry(printed, self.wt["cherry"])
|
||||||
self.assertEqual(cherry["reason"], "head is on no remote")
|
self.assertEqual(cherry["reason"], "head is on no remote")
|
||||||
|
|
||||||
def test_local_proof_needs_no_forge(self) -> None:
|
def test_local_proof_needs_no_forge(self) -> None:
|
||||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||||
_, printed, _ = self.run_gc(level="high")
|
_, printed, _ = self.run_gc(level="high")
|
||||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
done = self.entry(printed, self.wt["done"])
|
||||||
|
|
||||||
self.assertEqual(done["risk"], "low")
|
self.assertEqual(done["risk"], "low")
|
||||||
self.assertEqual(done["pr"], "unknown")
|
self.assertEqual(done["pr"], "unknown")
|
||||||
@@ -377,7 +63,7 @@ class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
|||||||
def test_open_pull_request_is_not_low(self) -> None:
|
def test_open_pull_request_is_not_low(self) -> None:
|
||||||
self.forge = ForgeFacts(open_heads={"done": 9})
|
self.forge = ForgeFacts(open_heads={"done": 9})
|
||||||
_, printed, _ = self.run_gc(level="high")
|
_, printed, _ = self.run_gc(level="high")
|
||||||
done = next(e for e in printed["items"] if e["name"] == self.wt["done"])
|
done = self.entry(printed, self.wt["done"])
|
||||||
|
|
||||||
self.assertEqual((done["risk"], done["pr"]), ("medium", "open #9"))
|
self.assertEqual((done["risk"], done["pr"]), ("medium", "open #9"))
|
||||||
|
|
||||||
@@ -395,12 +81,12 @@ class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
|||||||
self.assertEqual(risks["live_data"], "high")
|
self.assertEqual(risks["live_data"], "high")
|
||||||
for absent in (USED_ID, BUSY_CACHE, RUNNING_CONTAINER):
|
for absent in (USED_ID, BUSY_CACHE, RUNNING_CONTAINER):
|
||||||
self.assertNotIn(absent, risks)
|
self.assertNotIn(absent, risks)
|
||||||
volume = next(e for e in printed["items"] if e["name"] == "demo_data")
|
volume = self.entry(printed, "demo_data")
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
(volume["compose_project"], volume["links"], volume["size_bytes"]),
|
(volume["compose_project"], volume["links"], volume["size_bytes"]),
|
||||||
("demo", 0, 2 * 10**9),
|
("demo", 0, 2 * 10**9),
|
||||||
)
|
)
|
||||||
image = next(e for e in printed["items"] if e["name"] == DANGLING_ID)
|
image = self.entry(printed, DANGLING_ID)
|
||||||
self.assertEqual(image["size_bytes"], 1_500_000_000)
|
self.assertEqual(image["size_bytes"], 1_500_000_000)
|
||||||
|
|
||||||
def test_tmp_rules(self) -> None:
|
def test_tmp_rules(self) -> None:
|
||||||
@@ -434,91 +120,6 @@ class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
|||||||
self.assertEqual(printed["totals"]["low"]["count"], 6)
|
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):
|
class TestRiskCli(unittest.TestCase):
|
||||||
def _gc(self, *argv: str) -> tuple[int, object]:
|
def _gc(self, *argv: str) -> tuple[int, object]:
|
||||||
args = create_parser("test").parse_args(["gc", *argv])
|
args = create_parser("test").parse_args(["gc", *argv])
|
||||||
@@ -550,16 +151,19 @@ class TestRiskCli(unittest.TestCase):
|
|||||||
self.assertEqual(code, 0)
|
self.assertEqual(code, 0)
|
||||||
run.assert_called_once_with(
|
run.assert_called_once_with(
|
||||||
["/r"],
|
["/r"],
|
||||||
|
plan.RiskRequest(
|
||||||
level="low",
|
level="low",
|
||||||
apply=True,
|
apply=True,
|
||||||
as_json=True,
|
as_json=True,
|
||||||
owners_file="/o.json",
|
owners_file="/o.json",
|
||||||
hooks={},
|
|
||||||
min_age=None,
|
|
||||||
include=[],
|
include=[],
|
||||||
exclude=[],
|
exclude=[],
|
||||||
merged_into=["origin/main"],
|
merged_into=["origin/main"],
|
||||||
sizes=True,
|
sizes=True,
|
||||||
|
min_age=None,
|
||||||
|
hooks={},
|
||||||
|
tmp_root=tempfile.gettempdir(),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_cli_refuses_risk_with_report(self) -> None:
|
def test_cli_refuses_risk_with_report(self) -> None:
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
|||||||
import http.client
|
import http.client
|
||||||
import io
|
import io
|
||||||
import unittest
|
import unittest
|
||||||
|
import urllib.error
|
||||||
|
from typing import NoReturn
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from pkgmgr.actions.branch import gc_forge
|
from pkgmgr.actions.branch import gc_forge
|
||||||
@@ -30,7 +32,32 @@ def truncated_response(*_args, **_kwargs) -> http.client.HTTPResponse:
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
class TruncatedBody(io.BytesIO):
|
||||||
|
def read(self, *_args) -> bytes:
|
||||||
|
raise http.client.IncompleteRead(b'{"message": "Bad', 64)
|
||||||
|
|
||||||
|
|
||||||
|
def truncated_error(*_args, **_kwargs) -> NoReturn:
|
||||||
|
raise urllib.error.HTTPError(
|
||||||
|
"https://example.org/x",
|
||||||
|
502,
|
||||||
|
"Bad Gateway",
|
||||||
|
http.client.HTTPMessage(),
|
||||||
|
TruncatedBody(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestTruncatedResponse(unittest.TestCase):
|
class TestTruncatedResponse(unittest.TestCase):
|
||||||
|
def test_truncated_error_body_keeps_status_and_partial_body(self) -> None:
|
||||||
|
with (
|
||||||
|
patch("urllib.request.urlopen", side_effect=truncated_error),
|
||||||
|
self.assertRaises(HttpError) as caught,
|
||||||
|
):
|
||||||
|
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||||
|
|
||||||
|
self.assertEqual(caught.exception.status, 502)
|
||||||
|
self.assertEqual(caught.exception.body, '{"message": "Bad')
|
||||||
|
|
||||||
def test_incomplete_read_becomes_http_error(self) -> None:
|
def test_incomplete_read_becomes_http_error(self) -> None:
|
||||||
with (
|
with (
|
||||||
patch("urllib.request.urlopen", side_effect=truncated_response),
|
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||||
|
|||||||
Reference in new issue
Block a user