Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cee58bcef1 | ||
|
|
b8248a0253 | ||
|
|
0a3badfd63 | ||
|
|
2c70837d00 | ||
|
|
83297dab67 | ||
|
|
bd32cf9fab | ||
|
|
eff95a8003 | ||
|
|
28ff2f7a8e | ||
|
|
0917ceffdb | ||
|
|
b06b33ff57 | ||
|
|
d416fc79e9 | ||
|
|
9421f69ea9 |
No files matched your search
@@ -64,7 +64,7 @@ jobs:
|
|||||||
use: true
|
use: true
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
@@ -106,7 +106,7 @@ jobs:
|
|||||||
use: true
|
use: true
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
|
|||||||
Generated
+3
-3
@@ -2,11 +2,11 @@
|
|||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1771714954,
|
"lastModified": 1782847189,
|
||||||
"narHash": "sha256-nhZJPnBavtu40/L2aqpljrfUNb2rxmWTmSjK2c9UKds=",
|
"narHash": "sha256-twXPFqFsrrY5r28Zh7Homgcp2gUMBgQ6WDS98Q/3xFI=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "afbbf774e2087c3d734266c22f96fca2e78d3620",
|
"rev": "b6018f87da91d19d0ab4cf979885689b469cdd41",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -466,13 +466,13 @@ def _in_line(repo: Repo, sha: str) -> str | None:
|
|||||||
def _merged_by(repo: Repo, sha: str) -> str | None:
|
def _merged_by(repo: Repo, sha: str) -> str | None:
|
||||||
if sha not in repo.first_parent and _is_ancestor(sha, repo.default, repo.repo):
|
if sha not in repo.first_parent and _is_ancestor(sha, repo.default, repo.repo):
|
||||||
return "ancestor"
|
return "ancestor"
|
||||||
number = repo.forge.merged_heads.get(sha)
|
|
||||||
if number:
|
|
||||||
return f"pr#{number}"
|
|
||||||
line = _in_line(repo, sha)
|
line = _in_line(repo, sha)
|
||||||
if line:
|
if line:
|
||||||
return f"line:{line}"
|
return f"line:{line}"
|
||||||
return "patch" if _patch_merged(repo, sha) else None
|
if _patch_merged(repo, sha):
|
||||||
|
return "patch"
|
||||||
|
number = repo.forge.merged_heads.get(sha)
|
||||||
|
return f"pr#{number}" if number else None
|
||||||
|
|
||||||
|
|
||||||
def _patch_merged(repo: Repo, sha: str) -> bool:
|
def _patch_merged(repo: Repo, sha: str) -> bool:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import time
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
|
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
|
||||||
@@ -12,6 +13,8 @@ from pkgmgr.core.remote_provisioning.http.errors import HttpError
|
|||||||
GITHUB_HOST = "github.com"
|
GITHUB_HOST = "github.com"
|
||||||
GITHUB_API = "https://api.github.com"
|
GITHUB_API = "https://api.github.com"
|
||||||
PAGE_SIZE = 100
|
PAGE_SIZE = 100
|
||||||
|
TIMEOUT_S = 10
|
||||||
|
BUDGET_S = 60
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -46,10 +49,14 @@ def github_slugs(remote_urls: dict[str, str]) -> list[tuple[str, str]]:
|
|||||||
return slugs
|
return slugs
|
||||||
|
|
||||||
|
|
||||||
def _pages(http: HttpClient, headers: dict[str, str], url: str) -> list[dict]:
|
def _pages(
|
||||||
|
http: HttpClient, headers: dict[str, str], url: str, deadline: float
|
||||||
|
) -> list[dict]:
|
||||||
items: list[dict] = []
|
items: list[dict] = []
|
||||||
page = 1
|
page = 1
|
||||||
while True:
|
while True:
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise HttpError(status=0, message=f"budget of {BUDGET_S}s exceeded")
|
||||||
resp = http.request_json(
|
resp = http.request_json(
|
||||||
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
|
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
|
||||||
)
|
)
|
||||||
@@ -94,7 +101,8 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
|
|||||||
The facts, or facts whose unavailable names the failing repository.
|
The facts, or facts whose unavailable names the failing repository.
|
||||||
"""
|
"""
|
||||||
facts = ForgeFacts()
|
facts = ForgeFacts()
|
||||||
http = HttpClient(timeout_s=30)
|
http = HttpClient(timeout_s=TIMEOUT_S)
|
||||||
|
deadline = time.monotonic() + BUDGET_S
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {token}",
|
"Authorization": f"Bearer {token}",
|
||||||
"Accept": "application/vnd.github+json",
|
"Accept": "application/vnd.github+json",
|
||||||
@@ -103,14 +111,17 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
|
|||||||
for owner, name in slugs:
|
for owner, name in slugs:
|
||||||
base = f"{GITHUB_API}/repos/{owner}/{name}"
|
base = f"{GITHUB_API}/repos/{owner}/{name}"
|
||||||
try:
|
try:
|
||||||
for pr in _pages(http, headers, f"{base}/pulls?state=all"):
|
for pr in _pages(http, headers, f"{base}/pulls?state=all", deadline):
|
||||||
if pr["merged_at"]:
|
if pr["merged_at"]:
|
||||||
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
|
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
|
||||||
elif pr["state"] == "open":
|
elif pr["state"] == "open":
|
||||||
facts.open_heads[pr["head"]["ref"]] = pr["number"]
|
facts.open_heads[pr["head"]["ref"]] = pr["number"]
|
||||||
for branch in _pages(http, headers, f"{base}/branches?protected=true"):
|
for branch in _pages(
|
||||||
|
http, headers, f"{base}/branches?protected=true", deadline
|
||||||
|
):
|
||||||
facts.protected.add(branch["name"])
|
facts.protected.add(branch["name"])
|
||||||
except (HttpError, ValueError, KeyError, TypeError) as exc:
|
except (HttpError, ValueError, KeyError, TypeError) as exc:
|
||||||
facts.unavailable = f"GitHub API failed for {owner}/{name}: {exc}"
|
return ForgeFacts(
|
||||||
return facts
|
unavailable=f"GitHub API failed for {owner}/{name}: {exc}"
|
||||||
|
)
|
||||||
return facts
|
return facts
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
from .levels import LEVELS
|
||||||
|
from .plan import RiskRequest, risk_cleanup
|
||||||
|
|
||||||
|
__all__ = ["LEVELS", "RiskRequest", "risk_cleanup"]
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import COMPOSE_PROJECT, _describe, _docker
|
||||||
|
|
||||||
|
from .levels import DAY_S, HIGH, IDLE_DAYS, LOW, MEDIUM, item
|
||||||
|
|
||||||
|
DF_VERBOSE = ["system", "df", "--verbose", "--format", "{{json .}}"]
|
||||||
|
DANGLING = ["image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true"]
|
||||||
|
STOPPED = ("exited", "dead")
|
||||||
|
UNITS = {"": 1, "k": 10**3, "m": 10**6, "g": 10**9, "t": 10**12, "p": 10**15}
|
||||||
|
SIZE = re.compile(r"([0-9.]+)\s*([kKmMgGtTpP]?)B")
|
||||||
|
STAMP = re.compile(r"(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:\.(\d+))? ([+-]\d{4})")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_size(text: object) -> int | None:
|
||||||
|
match = SIZE.fullmatch(str(text or "").strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
return int(float(match.group(1)) * UNITS[match.group(2).lower()])
|
||||||
|
|
||||||
|
|
||||||
|
def parse_time(text: object) -> float | None:
|
||||||
|
match = STAMP.match(str(text or "").strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
clock, fraction, zone = match.groups()
|
||||||
|
micro = (fraction or "")[:6].ljust(6, "0")
|
||||||
|
return datetime.strptime(
|
||||||
|
f"{clock}.{micro} {zone}", "%Y-%m-%d %H:%M:%S.%f %z"
|
||||||
|
).timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def _project(labels: object) -> str | None:
|
||||||
|
for pair in str(labels or "").split(","):
|
||||||
|
key, _, value = pair.partition("=")
|
||||||
|
if key == COMPOSE_PROJECT:
|
||||||
|
return value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _volumes(rows: list[dict]) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
links = int(row["Links"]) if str(row.get("Links")).isdigit() else None
|
||||||
|
unused = links == 0
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"volume",
|
||||||
|
str(row["Name"]),
|
||||||
|
MEDIUM if unused else HIGH,
|
||||||
|
"unused volume: its data is lost"
|
||||||
|
if unused
|
||||||
|
else "volume in use by a container",
|
||||||
|
size_bytes=parse_size(row.get("Size")),
|
||||||
|
compose_project=_project(row.get("Labels")),
|
||||||
|
links=links,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _images(rows: list[dict], dangling: set[str]) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
if str(row.get("Containers")) != "0":
|
||||||
|
continue
|
||||||
|
loose = row["ID"] in dangling
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"image",
|
||||||
|
str(row["ID"]),
|
||||||
|
LOW if loose else MEDIUM,
|
||||||
|
"dangling image without containers" if loose else "unused tagged image",
|
||||||
|
size_bytes=parse_size(row.get("UniqueSize")),
|
||||||
|
repository=row.get("Repository"),
|
||||||
|
tag=row.get("Tag"),
|
||||||
|
created_at=row.get("CreatedAt"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _cache(rows: list[dict], now: float) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
if str(row.get("InUse")).lower() != "false":
|
||||||
|
continue
|
||||||
|
used = parse_time(row.get("LastUsedAt")) or parse_time(row.get("CreatedAt"))
|
||||||
|
idle = used is not None and now - used > IDLE_DAYS * DAY_S
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"build-cache",
|
||||||
|
str(row["ID"]),
|
||||||
|
LOW if idle else MEDIUM,
|
||||||
|
f"build cache idle > {IDLE_DAYS} days"
|
||||||
|
if idle
|
||||||
|
else f"build cache used within {IDLE_DAYS} days",
|
||||||
|
size_bytes=parse_size(row.get("Size")),
|
||||||
|
last_used_since=row.get("LastUsedSince"),
|
||||||
|
last_used_at=used,
|
||||||
|
shared=str(row.get("Shared")).lower() == "true",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _containers(rows: list[dict]) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
if row.get("State") not in STOPPED:
|
||||||
|
continue
|
||||||
|
volumes = str(row.get("LocalVolumes"))
|
||||||
|
bare = volumes == "0"
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"container",
|
||||||
|
str(row["ID"]),
|
||||||
|
LOW if bare else MEDIUM,
|
||||||
|
"stopped container without volumes"
|
||||||
|
if bare
|
||||||
|
else f"stopped container with {volumes} local volumes",
|
||||||
|
names=row.get("Names"),
|
||||||
|
image=row.get("Image"),
|
||||||
|
compose_project=_project(row.get("Labels")),
|
||||||
|
status=row.get("Status"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def docker_items(now: float) -> tuple[list[dict], list[str]]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
now: epoch seconds the build cache idle time is measured against.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Every volume, unused image, idle build cache record and stopped
|
||||||
|
container with its risk, read without changing anything, and
|
||||||
|
warnings when docker is missing, fails or prints no JSON.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = json.loads(_docker(DF_VERBOSE))
|
||||||
|
dangling = set(_docker(DANGLING).split())
|
||||||
|
except FileNotFoundError:
|
||||||
|
return [], ["docker unavailable: not installed"]
|
||||||
|
except subprocess.CalledProcessError as exc:
|
||||||
|
return [], [f"docker unavailable: {_describe(exc)}"]
|
||||||
|
except ValueError:
|
||||||
|
return [], ["docker system df --verbose: output is not JSON"]
|
||||||
|
return [
|
||||||
|
*_volumes(data.get("Volumes") or []),
|
||||||
|
*_images(data.get("Images") or [], dangling),
|
||||||
|
*_cache(data.get("BuildCache") or [], now),
|
||||||
|
*_containers(data.get("Containers") or []),
|
||||||
|
], []
|
||||||
|
|
||||||
|
|
||||||
|
def delete_docker(entry: dict) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
entry: a low image, build-cache or container item of the plan.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
done, or skipped with the reason: an image no longer dangling right
|
||||||
|
before its delete, or a kind that is never low.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
subprocess.CalledProcessError: when docker refuses the delete.
|
||||||
|
"""
|
||||||
|
name = entry["name"]
|
||||||
|
if entry["kind"] == "image":
|
||||||
|
if name not in set(_docker(DANGLING).split()):
|
||||||
|
return "skipped: no longer dangling"
|
||||||
|
_docker(["image", "rm", name])
|
||||||
|
elif entry["kind"] == "build-cache":
|
||||||
|
_docker(
|
||||||
|
[
|
||||||
|
"builder",
|
||||||
|
"prune",
|
||||||
|
"--force",
|
||||||
|
"--filter",
|
||||||
|
f"id={name}",
|
||||||
|
"--filter",
|
||||||
|
f"until={IDLE_DAYS * 24}h",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
elif entry["kind"] == "container":
|
||||||
|
_docker(["container", "rm", name])
|
||||||
|
else:
|
||||||
|
return f"skipped: {entry['kind']} is never deleted as low"
|
||||||
|
return "done"
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import (
|
||||||
|
Item,
|
||||||
|
Repo,
|
||||||
|
_git,
|
||||||
|
_rebuild,
|
||||||
|
execute,
|
||||||
|
prepare,
|
||||||
|
)
|
||||||
|
from pkgmgr.actions.worktree.hooks import FINI_HOOK
|
||||||
|
|
||||||
|
from .levels import HIGH, LOW, MEDIUM, item
|
||||||
|
|
||||||
|
LOCAL_PROOF = ("ancestor", "patch")
|
||||||
|
FORGE_UNAVAILABLE = "forge unavailable"
|
||||||
|
TREE_STEPS = (f"hook:{FINI_HOOK}", "worktree")
|
||||||
|
|
||||||
|
|
||||||
|
def _pushed(repo: Repo, head: str | None) -> bool:
|
||||||
|
if not head:
|
||||||
|
return False
|
||||||
|
count = _git(["rev-list", "--count", head, "--not", "--remotes"], repo.repo)
|
||||||
|
return count == "0"
|
||||||
|
|
||||||
|
|
||||||
|
def pr_state(repo: Repo, it: Item) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo: the planned repository with its forge facts.
|
||||||
|
it: one of its items.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
unknown when the forge was not read, else open #N, merged #N or none.
|
||||||
|
"""
|
||||||
|
if repo.forge.unavailable:
|
||||||
|
return "unknown"
|
||||||
|
number = repo.forge.open_heads.get(it.branch) if it.branch else None
|
||||||
|
if number:
|
||||||
|
return f"open #{number}"
|
||||||
|
shas = [it.local_sha, it.head, *it.remotes.values()]
|
||||||
|
merged = [repo.forge.merged_heads[s] for s in shas if s in repo.forge.merged_heads]
|
||||||
|
return f"merged #{merged[0]}" if merged else "none"
|
||||||
|
|
||||||
|
|
||||||
|
def classify(repo: Repo, it: Item) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo: the planned repository.
|
||||||
|
it: one of its items, planned with scope `all` or `worktree`.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The risk and why. Low only for a linked worktree merged into the
|
||||||
|
default branch by ancestry or patch id, without staged, unstaged or
|
||||||
|
untracked change, whose head is on a remote, without compose stack
|
||||||
|
and with nothing but the forge's absence holding it.
|
||||||
|
"""
|
||||||
|
return _state_verdict(it) or _tree_verdict(repo, it)
|
||||||
|
|
||||||
|
|
||||||
|
def _state_verdict(it: Item) -> tuple[str, str] | None:
|
||||||
|
if it.state == "protected":
|
||||||
|
return HIGH, it.reason
|
||||||
|
if it.state == "stale":
|
||||||
|
return MEDIUM, "stale worktree metadata"
|
||||||
|
if it.state == "dirty":
|
||||||
|
return HIGH, it.reason
|
||||||
|
if it.worktree is None:
|
||||||
|
if it.state == "merged-clean":
|
||||||
|
return MEDIUM, f"merged branch ({it.reason}): branches are never low"
|
||||||
|
return HIGH, it.reason
|
||||||
|
if it.state != "merged-clean":
|
||||||
|
if it.unpushed:
|
||||||
|
return HIGH, f"{it.reason}; {it.unpushed} commits on no remote"
|
||||||
|
return MEDIUM, it.reason
|
||||||
|
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:
|
||||||
|
return MEDIUM, f"merged by {it.merged_by}, not locally into {repo.default}"
|
||||||
|
if it.worktree_state != "clean" or any((it.staged, it.unstaged, it.untracked)):
|
||||||
|
return HIGH, "worktree has changes"
|
||||||
|
if it.compose_projects:
|
||||||
|
return MEDIUM, f"compose stack {', '.join(it.compose_projects)}"
|
||||||
|
if it.skip not in (None, FORGE_UNAVAILABLE):
|
||||||
|
return MEDIUM, it.skip
|
||||||
|
if "worktree" not in it.actions:
|
||||||
|
return MEDIUM, "no worktree removal planned"
|
||||||
|
if not _pushed(repo, it.head):
|
||||||
|
return MEDIUM, "head is on no remote"
|
||||||
|
return LOW, f"merged into {repo.default} by {it.merged_by}, clean, pushed"
|
||||||
|
|
||||||
|
|
||||||
|
def _entry(repo: Repo, it: Item) -> dict:
|
||||||
|
risk, reason = classify(repo, it)
|
||||||
|
linked = it.worktree is not None and it.worktree != repo.repo
|
||||||
|
kind = "stale" if it.state == "stale" else "worktree" if linked else "branch"
|
||||||
|
return item(
|
||||||
|
kind,
|
||||||
|
it.worktree if linked or not it.branch else it.branch,
|
||||||
|
risk,
|
||||||
|
reason,
|
||||||
|
size_bytes=it.size_bytes,
|
||||||
|
repo=repo.repo,
|
||||||
|
branch=it.branch,
|
||||||
|
head=it.head,
|
||||||
|
state=it.state,
|
||||||
|
merged_by=it.merged_by,
|
||||||
|
merged_into=it.merged_into,
|
||||||
|
staged=it.staged,
|
||||||
|
unstaged=it.unstaged,
|
||||||
|
untracked=it.untracked,
|
||||||
|
compose_projects=it.compose_projects,
|
||||||
|
pr=pr_state(repo, it),
|
||||||
|
skip=it.skip,
|
||||||
|
steps=[a for a in it.actions if a in TREE_STEPS] if risk == LOW else [],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def git_items(
|
||||||
|
repo_roots: list[str], include: list[str], exclude: list[str], options: dict
|
||||||
|
) -> tuple[list[tuple[Repo, Item, dict]], list[str], bool] | None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo_roots: main worktree roots of the repositories to scan, each
|
||||||
|
planned with scope `all`.
|
||||||
|
include: only items whose branch or worktree path matches one of these.
|
||||||
|
exclude: drop items whose branch or worktree path matches one of these.
|
||||||
|
options: the plan_repo keyword options but scope.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(repository, item, plan entry) per chosen item, the warnings and
|
||||||
|
whether this runs in the host PID namespace; None for an unknown
|
||||||
|
include.
|
||||||
|
"""
|
||||||
|
prepared = prepare(repo_roots, include, exclude, {**options, "scope": "all"})
|
||||||
|
if prepared is None:
|
||||||
|
return None
|
||||||
|
repos, host_ns, chosen = prepared
|
||||||
|
warnings = [f"{repo.repo}: {w}" for repo in repos for w in repo.warnings]
|
||||||
|
entries = [
|
||||||
|
(repo, it, _entry(repo, it))
|
||||||
|
for repo in repos
|
||||||
|
for it in repo.items
|
||||||
|
if chosen(it)
|
||||||
|
]
|
||||||
|
return entries, warnings, host_ns
|
||||||
|
|
||||||
|
|
||||||
|
def delete_worktree(repo: Repo, it: Item) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo: the planned repository.
|
||||||
|
it: the low worktree item as planned; planned again with scope
|
||||||
|
`worktree`, so its branch stays, and removed only while low.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The result execute settles, or skipped when it changed since the plan.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: when execute settles no result.
|
||||||
|
"""
|
||||||
|
tree_repo = replace(repo, scope="worktree")
|
||||||
|
fresh = _rebuild(tree_repo, it)
|
||||||
|
risk, reason = classify(tree_repo, fresh)
|
||||||
|
if risk != LOW or fresh.head != it.head or fresh.worktree != it.worktree:
|
||||||
|
return f"skipped: changed since plan ({reason})"
|
||||||
|
execute(tree_repo, fresh)
|
||||||
|
if fresh.result is None:
|
||||||
|
raise RuntimeError(f"execute settled no result for {it.worktree}")
|
||||||
|
return fresh.result
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
LEVELS = (LOW, MEDIUM, HIGH)
|
||||||
|
DAY_S = 86400
|
||||||
|
IDLE_DAYS = 7
|
||||||
|
TMP_AGE_S = DAY_S
|
||||||
|
|
||||||
|
|
||||||
|
def rank(level: str) -> int:
|
||||||
|
return LEVELS.index(level)
|
||||||
|
|
||||||
|
|
||||||
|
def item(kind: str, name: str, risk: str, reason: str, **facts: object) -> dict:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
kind: worktree, branch, stale, image, build-cache, container, volume or tmp.
|
||||||
|
name: what the item deletes: a path, branch, docker id or volume name.
|
||||||
|
risk: one of LEVELS.
|
||||||
|
reason: why the item has that risk.
|
||||||
|
facts: kind-specific fields; size_bytes is read by the totals.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
One plan item; result stays None until an apply sets it.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"kind": kind,
|
||||||
|
"name": name,
|
||||||
|
"risk": risk,
|
||||||
|
"reason": reason,
|
||||||
|
"size_bytes": None,
|
||||||
|
**facts,
|
||||||
|
"result": None,
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import (
|
||||||
|
REFUSAL,
|
||||||
|
_describe,
|
||||||
|
_process_cwds,
|
||||||
|
host_pid_namespace,
|
||||||
|
human_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
from .docker_items import delete_docker, docker_items
|
||||||
|
from .git_items import delete_worktree, git_items
|
||||||
|
from .levels import LEVELS, LOW, rank
|
||||||
|
from .tmp_items import delete_tmp, read_owners, tmp_items
|
||||||
|
|
||||||
|
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:
|
||||||
|
return {
|
||||||
|
level: {
|
||||||
|
"count": sum(e["risk"] == level for e in entries),
|
||||||
|
"size_bytes": sum(
|
||||||
|
e["size_bytes"]
|
||||||
|
for e in entries
|
||||||
|
if e["risk"] == level and e["size_bytes"] is not None
|
||||||
|
),
|
||||||
|
}
|
||||||
|
for level in LEVELS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _render(plan: dict) -> str:
|
||||||
|
lines = [f"== gc plan (risk up to {plan['risk']})"]
|
||||||
|
for entry in plan["items"]:
|
||||||
|
size = "-" if entry["size_bytes"] is None else human_size(entry["size_bytes"])
|
||||||
|
line = (
|
||||||
|
f"{entry['risk'].upper():<6} {entry['kind']:<11} {size:>8} "
|
||||||
|
f"{entry['name']} {entry['reason']}"
|
||||||
|
)
|
||||||
|
lines.append(f"{line} -> {entry['result']}" if entry["result"] else line)
|
||||||
|
lines += [
|
||||||
|
f"TOTAL {level}: {t['count']} items, {human_size(t['size_bytes'])}"
|
||||||
|
for level, t in plan["totals"].items()
|
||||||
|
]
|
||||||
|
lines += [f"WARN {warning}" for warning in plan["warnings"]]
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _delete(
|
||||||
|
entry: dict,
|
||||||
|
git_by_name: dict,
|
||||||
|
owners: dict[str, str],
|
||||||
|
now: float,
|
||||||
|
) -> str:
|
||||||
|
try:
|
||||||
|
if entry["kind"] in DOCKER_KINDS:
|
||||||
|
return delete_docker(entry)
|
||||||
|
if entry["kind"] == "tmp":
|
||||||
|
return delete_tmp(entry, owners, now, _process_cwds())
|
||||||
|
if entry["kind"] == "worktree":
|
||||||
|
repo, it = git_by_name[(entry["repo"], entry["name"])]
|
||||||
|
return delete_worktree(repo, it)
|
||||||
|
except (subprocess.CalledProcessError, OSError, RuntimeError, ValueError) as exc:
|
||||||
|
return f"failed: {_describe(exc)}"
|
||||||
|
return f"skipped: {entry['kind']} is never deleted as low"
|
||||||
|
|
||||||
|
|
||||||
|
def _refusal(request: RiskRequest, host_ns: bool) -> str | None:
|
||||||
|
if request.apply and request.level != LOW:
|
||||||
|
return "Refusing: --apply removes only low items; use --risk low"
|
||||||
|
if request.apply and not host_ns:
|
||||||
|
return REFUSAL
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _git_options(request: RiskRequest) -> dict:
|
||||||
|
return {
|
||||||
|
"merged_into": request.merged_into,
|
||||||
|
"sizes": request.sizes,
|
||||||
|
"min_age": request.min_age,
|
||||||
|
"activity": False,
|
||||||
|
"hooks": request.hooks,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _host_items(
|
||||||
|
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)
|
||||||
|
cwds = _process_cwds() if host_ns else {}
|
||||||
|
scratch = tmp_items(request.tmp_root, owners, now, cwds)
|
||||||
|
return [*docker, *scratch], [*notes, *docker_warnings]
|
||||||
|
|
||||||
|
|
||||||
|
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}
|
||||||
|
for entry in entries:
|
||||||
|
if entry["risk"] == LOW:
|
||||||
|
entry["result"] = _delete(entry, git_by_name, owners, now)
|
||||||
|
print(
|
||||||
|
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _report(
|
||||||
|
request: RiskRequest,
|
||||||
|
host_ns: bool,
|
||||||
|
now: float,
|
||||||
|
entries: list[dict],
|
||||||
|
warnings: list[str],
|
||||||
|
) -> int:
|
||||||
|
plan = {
|
||||||
|
"host_pid_namespace": host_ns,
|
||||||
|
"risk": request.level,
|
||||||
|
"generated_at": now,
|
||||||
|
"totals": _totals(entries),
|
||||||
|
"items": [e for e in entries if rank(e["risk"]) <= rank(request.level)],
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
print(json.dumps(plan, indent=2) if request.as_json else _render(plan))
|
||||||
|
failed = any((e["result"] or "").startswith("failed") for e in entries)
|
||||||
|
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])
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import stat
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import _busy
|
||||||
|
from pkgmgr.actions.branch.nofollow import canonical, remove_tree
|
||||||
|
from pkgmgr.actions.gc.report.walk import TreeStats, walk
|
||||||
|
|
||||||
|
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
|
||||||
|
|
||||||
|
ENDED = ("done", "stopped")
|
||||||
|
|
||||||
|
|
||||||
|
def read_owners(path: str | None) -> dict[str, str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
path: a JSON object of absolute path -> task status, or None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Normalised absolute path -> lower-case status; empty without a file.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OSError: when the file cannot be read.
|
||||||
|
ValueError: when it is not such a JSON object.
|
||||||
|
"""
|
||||||
|
if not path:
|
||||||
|
return {}
|
||||||
|
with open(path, encoding="utf-8") as fh:
|
||||||
|
data = json.load(fh)
|
||||||
|
if not isinstance(data, dict) or not all(
|
||||||
|
isinstance(k, str) and isinstance(v, str) for k, v in data.items()
|
||||||
|
):
|
||||||
|
raise ValueError(f"{path}: expected a JSON object of path -> status")
|
||||||
|
return {os.path.abspath(k): v.lower() for k, v in data.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def _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(
|
||||||
|
path: str, st: os.stat_result, owners: dict[str, str], now: float, cwds: dict
|
||||||
|
) -> tuple[str, str, int, float]:
|
||||||
|
stats, size, newest = _measure(path, st)
|
||||||
|
status = owners.get(path)
|
||||||
|
risk, reason = _held(path, stats, status, cwds) or _settled(status, now - newest)
|
||||||
|
return risk, reason, size, newest
|
||||||
|
|
||||||
|
|
||||||
|
def tmp_items(
|
||||||
|
root: str, owners: dict[str, str], now: float, cwds: dict[int, str]
|
||||||
|
) -> list[dict]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
root: the scratch directory, /tmp on a host; only its direct
|
||||||
|
children the current user owns are listed.
|
||||||
|
owners: absolute path -> task status from read_owners.
|
||||||
|
now: epoch seconds the 24 h age is measured against.
|
||||||
|
cwds: pid -> working directory of the host's processes.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
One item per regular file or directory, never a symlink, socket or
|
||||||
|
foreign entry: low only when its owner task is done or stopped and
|
||||||
|
nothing in it changed for 24 h.
|
||||||
|
"""
|
||||||
|
items = []
|
||||||
|
base = os.path.realpath(root)
|
||||||
|
try:
|
||||||
|
names = sorted(os.listdir(base))
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
for name in names:
|
||||||
|
path = os.path.join(base, name)
|
||||||
|
try:
|
||||||
|
st = os.lstat(path)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
if st.st_uid != os.getuid() or not (
|
||||||
|
stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
risk, reason, size, newest = _verdict(path, st, owners, now, cwds)
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"tmp",
|
||||||
|
path,
|
||||||
|
risk,
|
||||||
|
reason,
|
||||||
|
size_bytes=size,
|
||||||
|
newest_mtime=newest,
|
||||||
|
owner_status=owners.get(path),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def delete_tmp(
|
||||||
|
entry: dict, owners: dict[str, str], now: float, cwds: dict[int, str]
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
entry: a low tmp item of the plan, deleted only while still low.
|
||||||
|
owners: as tmp_items takes them.
|
||||||
|
now: as tmp_items takes it.
|
||||||
|
cwds: as tmp_items takes them, read again before the delete.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The result: done, or skipped with the reason.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OSError: when the delete fails.
|
||||||
|
"""
|
||||||
|
path = entry["name"]
|
||||||
|
if not canonical(path):
|
||||||
|
return "skipped: path is not canonical"
|
||||||
|
st = os.lstat(path)
|
||||||
|
if st.st_uid != os.getuid():
|
||||||
|
return "skipped: no longer owned by this user"
|
||||||
|
risk, reason, _, _ = _verdict(path, st, owners, now, cwds)
|
||||||
|
if risk != LOW:
|
||||||
|
return f"skipped: changed since plan ({reason})"
|
||||||
|
if stat.S_ISDIR(st.st_mode):
|
||||||
|
remove_tree(path)
|
||||||
|
elif stat.S_ISREG(st.st_mode):
|
||||||
|
os.unlink(path)
|
||||||
|
else:
|
||||||
|
return "skipped: no longer a file or directory"
|
||||||
|
return "done"
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pkgmgr.core.git import run
|
||||||
from pkgmgr.core.git.commands import (
|
from pkgmgr.core.git.commands import (
|
||||||
fetch,
|
fetch,
|
||||||
pull_ff_only,
|
pull_ff_only,
|
||||||
@@ -14,7 +15,18 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
|
|||||||
Always run a pull BEFORE modifying anything.
|
Always run a pull BEFORE modifying anything.
|
||||||
Uses --ff-only to avoid creating merge commits automatically.
|
Uses --ff-only to avoid creating merge commits automatically.
|
||||||
If no upstream is configured, we skip.
|
If no upstream is configured, we skip.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: a tracked file is modified; the release commit uses
|
||||||
|
``commit -a`` and would ship it.
|
||||||
"""
|
"""
|
||||||
|
dirty = run(["status", "--porcelain", "--untracked-files=no"])
|
||||||
|
if dirty:
|
||||||
|
raise RuntimeError(
|
||||||
|
"Tracked changes in the release checkout; commit or park them "
|
||||||
|
f"first, the release commit would include them:\n{dirty}"
|
||||||
|
)
|
||||||
|
|
||||||
upstream = get_upstream_ref()
|
upstream = get_upstream_ref()
|
||||||
if not upstream:
|
if not upstream:
|
||||||
print("[INFO] No upstream configured for current branch. Skipping pull.")
|
print("[INFO] No upstream configured for current branch. Skipping pull.")
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from .config import handle_config
|
|||||||
from .make import handle_make
|
from .make import handle_make
|
||||||
from .mirror import handle_mirror_command
|
from .mirror import handle_mirror_command
|
||||||
from .publish import handle_publish
|
from .publish import handle_publish
|
||||||
from .release import handle_release
|
from .release import handle_release, release_at_cwd
|
||||||
from .repos import handle_repos_command
|
from .repos import handle_repos_command
|
||||||
from .review import handle_review
|
from .review import handle_review
|
||||||
from .tools import handle_tools_command
|
from .tools import handle_tools_command
|
||||||
@@ -29,4 +29,5 @@ __all__ = [
|
|||||||
"handle_tools_command",
|
"handle_tools_command",
|
||||||
"handle_version",
|
"handle_version",
|
||||||
"handle_worktree",
|
"handle_worktree",
|
||||||
|
"release_at_cwd",
|
||||||
]
|
]
|
||||||
@@ -7,12 +7,47 @@ from typing import Any
|
|||||||
from pkgmgr.actions.publish import publish as run_publish
|
from pkgmgr.actions.publish import publish as run_publish
|
||||||
from pkgmgr.actions.release import release as run_release
|
from pkgmgr.actions.release import release as run_release
|
||||||
from pkgmgr.cli.context import CLIContext
|
from pkgmgr.cli.context import CLIContext
|
||||||
|
from pkgmgr.core.git import GitRunError, run
|
||||||
from pkgmgr.core.repository.dir import get_repo_dir
|
from pkgmgr.core.repository.dir import get_repo_dir
|
||||||
from pkgmgr.core.repository.identifier import get_repo_identifier
|
from pkgmgr.core.repository.identifier import get_repo_identifier
|
||||||
|
from pkgmgr.core.repository.selected import has_explicit_selection
|
||||||
|
|
||||||
Repository = dict[str, Any]
|
Repository = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _at_cwd_checkout(args, selected: list[Repository]) -> list[Repository]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
args: parsed CLI arguments.
|
||||||
|
selected: the repositories dispatch picked.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
selected unchanged after an explicit selection or outside git; else each
|
||||||
|
repository pointed at the current directory's git toplevel, so a release
|
||||||
|
from a nested clone never commits in the configured main checkout.
|
||||||
|
|
||||||
|
"""
|
||||||
|
if has_explicit_selection(args):
|
||||||
|
return selected
|
||||||
|
try:
|
||||||
|
toplevel = run(["rev-parse", "--show-toplevel"])
|
||||||
|
except GitRunError:
|
||||||
|
return selected
|
||||||
|
return [{**repo, "directory": toplevel} for repo in selected]
|
||||||
|
|
||||||
|
|
||||||
|
def release_at_cwd(args, ctx: CLIContext, selected: list[Repository]) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
args: parsed CLI arguments.
|
||||||
|
ctx: the CLI context.
|
||||||
|
selected: the repositories dispatch picked; without an explicit
|
||||||
|
selection each is released in the current directory's checkout.
|
||||||
|
|
||||||
|
"""
|
||||||
|
handle_release(args, ctx, _at_cwd_checkout(args, selected))
|
||||||
|
|
||||||
|
|
||||||
def handle_release(
|
def handle_release(
|
||||||
args,
|
args,
|
||||||
ctx: CLIContext,
|
ctx: CLIContext,
|
||||||
|
|||||||
@@ -3,9 +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 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,
|
||||||
@@ -118,7 +120,28 @@ def handle_worktree(args, ctx: CLIContext) -> None:
|
|||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|
||||||
|
|
||||||
|
def _risk_request(args, ctx: CLIContext) -> RiskRequest:
|
||||||
|
return RiskRequest(
|
||||||
|
level=args.risk,
|
||||||
|
apply=args.apply,
|
||||||
|
as_json=args.json,
|
||||||
|
owners_file=args.owners,
|
||||||
|
hooks=pinned_hooks(ctx),
|
||||||
|
min_age=args.min_age,
|
||||||
|
tmp_root=tempfile.gettempdir(),
|
||||||
|
**scan_options(args),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def handle_gc(args, ctx: CLIContext) -> None:
|
def handle_gc(args, ctx: CLIContext) -> None:
|
||||||
|
if args.risk:
|
||||||
|
if args.report:
|
||||||
|
print("--risk cannot be combined with --report", file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
|
sys.exit(risk_cleanup(scan_repo_roots(args, ctx), _risk_request(args, ctx)))
|
||||||
|
if args.owners:
|
||||||
|
print("--owners only with --risk", file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
if not args.report:
|
if not args.report:
|
||||||
run_cleanup(args, ctx, "all")
|
run_cleanup(args, ctx, "all")
|
||||||
if args.apply:
|
if args.apply:
|
||||||
|
|||||||
@@ -14,27 +14,17 @@ from pkgmgr.cli.commands import (
|
|||||||
handle_make,
|
handle_make,
|
||||||
handle_mirror_command,
|
handle_mirror_command,
|
||||||
handle_publish,
|
handle_publish,
|
||||||
handle_release,
|
|
||||||
handle_repos_command,
|
handle_repos_command,
|
||||||
handle_review,
|
handle_review,
|
||||||
handle_tools_command,
|
handle_tools_command,
|
||||||
handle_version,
|
handle_version,
|
||||||
handle_worktree,
|
handle_worktree,
|
||||||
|
release_at_cwd,
|
||||||
)
|
)
|
||||||
from pkgmgr.cli.context import CLIContext
|
from pkgmgr.cli.context import CLIContext
|
||||||
from pkgmgr.cli.proxy import maybe_handle_proxy
|
from pkgmgr.cli.proxy import maybe_handle_proxy
|
||||||
from pkgmgr.core.repository.dir import get_repo_dir
|
from pkgmgr.core.repository.dir import get_repo_dir
|
||||||
from pkgmgr.core.repository.selected import get_selected_repos
|
from pkgmgr.core.repository.selected import get_selected_repos, has_explicit_selection
|
||||||
|
|
||||||
|
|
||||||
def _has_explicit_selection(args) -> bool:
|
|
||||||
return bool(
|
|
||||||
getattr(args, "all", False)
|
|
||||||
or getattr(args, "identifiers", [])
|
|
||||||
or getattr(args, "category", [])
|
|
||||||
or getattr(args, "tag", [])
|
|
||||||
or getattr(args, "string", "")
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _select_repo_for_current_directory(ctx: CLIContext) -> list[dict[str, Any]]:
|
def _select_repo_for_current_directory(ctx: CLIContext) -> list[dict[str, Any]]:
|
||||||
@@ -100,7 +90,7 @@ def dispatch_command(args, ctx: CLIContext) -> None:
|
|||||||
if args.command in commands_with_selection:
|
if args.command in commands_with_selection:
|
||||||
selected = (
|
selected = (
|
||||||
get_selected_repos(args, ctx.all_repositories)
|
get_selected_repos(args, ctx.all_repositories)
|
||||||
if _has_explicit_selection(args)
|
if has_explicit_selection(args)
|
||||||
else _select_repo_for_current_directory(ctx)
|
else _select_repo_for_current_directory(ctx)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -143,7 +133,7 @@ def dispatch_command(args, ctx: CLIContext) -> None:
|
|||||||
return
|
return
|
||||||
|
|
||||||
if args.command == "release":
|
if args.command == "release":
|
||||||
handle_release(args, ctx, selected)
|
release_at_cwd(args, ctx, selected)
|
||||||
return
|
return
|
||||||
|
|
||||||
if args.command == "publish":
|
if args.command == "publish":
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
|
from pkgmgr.actions.gc.risk.levels import LEVELS
|
||||||
|
|
||||||
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
|
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
|
||||||
|
|
||||||
|
|
||||||
@@ -16,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",
|
||||||
@@ -44,3 +51,26 @@ 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(
|
||||||
|
"--risk",
|
||||||
|
choices=LEVELS,
|
||||||
|
help=(
|
||||||
|
"Plan branches, worktrees, docker volumes, unused images, idle build "
|
||||||
|
"cache, stopped containers and /tmp entries with a risk class each "
|
||||||
|
"and print the items up to RISK; --apply removes exactly the low "
|
||||||
|
"items of that plan and needs --risk low; with --branch only the "
|
||||||
|
"matching git items are planned"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
gc.add_argument(
|
||||||
|
"--owners",
|
||||||
|
metavar="FILE",
|
||||||
|
help=(
|
||||||
|
"With --risk: JSON object of /tmp path -> owner task status; only "
|
||||||
|
"an entry whose task is done or stopped and that is unchanged for "
|
||||||
|
"24 h is low"
|
||||||
|
),
|
||||||
|
)
|
||||||
@@ -1,15 +1,19 @@
|
|||||||
# src/pkgmgr/core/remote_provisioning/http/client.py
|
# src/pkgmgr/core/remote_provisioning/http/client.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
import json
|
import json
|
||||||
import ssl
|
import ssl
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .errors import HttpError
|
from .errors import HttpError
|
||||||
|
|
||||||
|
ALLOWED_SCHEMES = frozenset({"http", "https"})
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class HttpResponse:
|
class HttpResponse:
|
||||||
@@ -31,6 +35,11 @@ class HttpClient:
|
|||||||
headers: dict[str, str] | None = None,
|
headers: dict[str, str] | None = None,
|
||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
) -> HttpResponse:
|
) -> HttpResponse:
|
||||||
|
scheme = urllib.parse.urlsplit(url).scheme
|
||||||
|
if scheme not in ALLOWED_SCHEMES:
|
||||||
|
raise HttpError(
|
||||||
|
status=0, message=f"unsupported URL scheme {scheme!r}", body=""
|
||||||
|
)
|
||||||
data: bytes | None = None
|
data: bytes | None = None
|
||||||
final_headers: dict[str, str] = dict(headers or {})
|
final_headers: dict[str, str] = dict(headers or {})
|
||||||
|
|
||||||
@@ -41,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,
|
||||||
@@ -49,21 +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(
|
||||||
|
status=int(resp.status), text=raw, json=_json_object(raw)
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
raise HttpError(
|
||||||
|
status=int(exc.code), message=str(exc), body=_error_body(exc)
|
||||||
|
) from exc
|
||||||
|
except (OSError, http.client.HTTPException) as exc:
|
||||||
|
message = str(exc) or type(exc).__name__
|
||||||
|
raise HttpError(status=0, message=message, body="") from exc
|
||||||
|
|
||||||
parsed: dict[str, Any] | None = None
|
|
||||||
if raw:
|
def _json_object(raw: str) -> dict[str, Any] | None:
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
try:
|
try:
|
||||||
loaded = json.loads(raw)
|
loaded = json.loads(raw)
|
||||||
parsed = loaded if isinstance(loaded, dict) else None
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
parsed = None
|
return None
|
||||||
|
return loaded if isinstance(loaded, dict) else None
|
||||||
|
|
||||||
return HttpResponse(status=int(resp.status), text=raw, json=parsed)
|
|
||||||
except urllib.error.HTTPError as exc:
|
def _error_body(exc: urllib.error.HTTPError) -> str:
|
||||||
try:
|
try:
|
||||||
body = exc.read().decode("utf-8", errors="replace")
|
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):
|
except (OSError, ValueError):
|
||||||
body = ""
|
return ""
|
||||||
raise HttpError(status=int(exc.code), message=str(exc), body=body) from exc
|
|
||||||
except urllib.error.URLError as exc:
|
|
||||||
raise HttpError(status=0, message=str(exc), body="") from exc
|
|
||||||
@@ -136,6 +136,25 @@ def _maybe_filter_ignored(args, repos: list[Repository]) -> list[Repository]:
|
|||||||
return filter_ignored(repos)
|
return filter_ignored(repos)
|
||||||
|
|
||||||
|
|
||||||
|
def has_explicit_selection(args) -> bool:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
args: parsed CLI arguments.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True when --all, an identifier, --category, --tag or --string picks
|
||||||
|
the repositories instead of the current directory.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return bool(
|
||||||
|
getattr(args, "all", False)
|
||||||
|
or getattr(args, "identifiers", [])
|
||||||
|
or getattr(args, "category", [])
|
||||||
|
or getattr(args, "tag", [])
|
||||||
|
or getattr(args, "string", "")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_selected_repos(args, all_repositories: list[Repository]) -> list[Repository]:
|
def get_selected_repos(args, all_repositories: list[Repository]) -> list[Repository]:
|
||||||
"""
|
"""
|
||||||
Compute the list of repositories selected by CLI arguments.
|
Compute the list of repositories selected by CLI arguments.
|
||||||
|
|||||||
@@ -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,185 +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_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"]
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
from contextlib import redirect_stdout
|
||||||
|
from pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
|
||||||
|
from pkgmgr.cli.context import CLIContext
|
||||||
|
|
||||||
|
GIT = shutil.which("git")
|
||||||
|
|
||||||
|
|
||||||
class TestIntegrationReleasePublishHook(unittest.TestCase):
|
class TestIntegrationReleasePublishHook(unittest.TestCase):
|
||||||
def _ctx(self) -> SimpleNamespace:
|
def _ctx(self) -> SimpleNamespace:
|
||||||
@@ -65,5 +76,90 @@ class TestIntegrationReleasePublishHook(unittest.TestCase):
|
|||||||
m_publish.assert_not_called()
|
m_publish.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(GIT, "git builds the clones under test")
|
||||||
|
class TestReleaseCwdCheckout(unittest.TestCase):
|
||||||
|
def _sh(self, cwd: str, *argv: str) -> None:
|
||||||
|
subprocess.run([GIT, *argv], cwd=cwd, check=True, capture_output=True)
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self._tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self._tmp.cleanup)
|
||||||
|
base = os.path.realpath(self._tmp.name)
|
||||||
|
identity = {
|
||||||
|
f"GIT_{role}_{field}": value
|
||||||
|
for role in ("AUTHOR", "COMMITTER")
|
||||||
|
for field, value in (("NAME", "t"), ("EMAIL", "t@example.org"))
|
||||||
|
}
|
||||||
|
scrubbed = patch.dict(
|
||||||
|
os.environ,
|
||||||
|
{**identity, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"},
|
||||||
|
)
|
||||||
|
scrubbed.start()
|
||||||
|
self.addCleanup(scrubbed.stop)
|
||||||
|
self.addCleanup(os.chdir, os.getcwd())
|
||||||
|
|
||||||
|
self.main = os.path.join(base, "app")
|
||||||
|
self._sh(base, "init", "-q", "-b", "main", self.main)
|
||||||
|
Path(self.main, "app.py").write_text("v1\n")
|
||||||
|
self._sh(self.main, "add", "app.py")
|
||||||
|
self._sh(self.main, "commit", "-q", "--no-gpg-sign", "-m", "init")
|
||||||
|
self.clone = os.path.join(self.main, ".worktrees", "release")
|
||||||
|
self._sh(base, "clone", "-q", self.main, self.clone)
|
||||||
|
Path(self.main, "app.py").write_text("unfinished work\n")
|
||||||
|
self.ctx = CLIContext(
|
||||||
|
config_merged={},
|
||||||
|
repositories_base_dir=os.path.join(base, "repos"),
|
||||||
|
all_repositories=[
|
||||||
|
{
|
||||||
|
"provider": "github.com",
|
||||||
|
"account": "t",
|
||||||
|
"repository": "app",
|
||||||
|
"directory": self.main,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
binaries_dir=os.path.join(base, "bin"),
|
||||||
|
user_config_path=os.path.join(base, "config.yaml"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _released_in(self, cwd: str, *argv: str) -> str:
|
||||||
|
from pkgmgr.cli.dispatch import dispatch_command
|
||||||
|
from pkgmgr.cli.parser import create_parser
|
||||||
|
|
||||||
|
seen: list[str] = []
|
||||||
|
os.chdir(cwd)
|
||||||
|
args = create_parser("test").parse_args(["release", *argv, "--no-publish"])
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"pkgmgr.cli.commands.release.run_release",
|
||||||
|
side_effect=lambda **_kwargs: seen.append(os.getcwd()),
|
||||||
|
),
|
||||||
|
redirect_stdout(io.StringIO()),
|
||||||
|
):
|
||||||
|
dispatch_command(args, self.ctx)
|
||||||
|
self.assertEqual(len(seen), 1)
|
||||||
|
return seen[0]
|
||||||
|
|
||||||
|
def test_release_from_a_nested_clone_runs_in_the_clone(self) -> None:
|
||||||
|
self.assertEqual(self._released_in(self.clone, "patch"), self.clone)
|
||||||
|
|
||||||
|
def test_explicit_identifier_keeps_the_configured_checkout(self) -> None:
|
||||||
|
self.assertEqual(self._released_in(self.clone, "patch", "app"), self.main)
|
||||||
|
|
||||||
|
def test_tracked_changes_refuse_the_release(self) -> None:
|
||||||
|
os.chdir(self.main)
|
||||||
|
|
||||||
|
with self.assertRaises(RuntimeError) as cm:
|
||||||
|
ensure_clean_and_synced(preview=False)
|
||||||
|
|
||||||
|
self.assertIn("app.py", str(cm.exception))
|
||||||
|
self.assertEqual(Path(self.main, "app.py").read_text(), "unfinished work\n")
|
||||||
|
|
||||||
|
def test_clean_clone_passes_the_check(self) -> None:
|
||||||
|
os.chdir(self.clone)
|
||||||
|
|
||||||
|
with redirect_stdout(io.StringIO()):
|
||||||
|
ensure_clean_and_synced(preview=False)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
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,53 @@
|
|||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch import gc
|
||||||
|
|
||||||
|
SHA = "a" * 40
|
||||||
|
|
||||||
|
|
||||||
|
def _repo(merged_heads: dict[str, int]) -> SimpleNamespace:
|
||||||
|
return SimpleNamespace(
|
||||||
|
first_parent=set(),
|
||||||
|
default="origin/main",
|
||||||
|
repo="/repo",
|
||||||
|
forge=SimpleNamespace(merged_heads=merged_heads),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMergedByOrder(unittest.TestCase):
|
||||||
|
def _merged_by(self, *, line, patch_merged, merged_heads):
|
||||||
|
with (
|
||||||
|
patch.object(gc, "_is_ancestor", return_value=False),
|
||||||
|
patch.object(gc, "_in_line", return_value=line),
|
||||||
|
patch.object(gc, "_patch_merged", return_value=patch_merged),
|
||||||
|
):
|
||||||
|
return gc._merged_by(_repo(merged_heads), SHA)
|
||||||
|
|
||||||
|
def test_line_wins_over_forge(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._merged_by(line="release", patch_merged=False, merged_heads={SHA: 7}),
|
||||||
|
"line:release",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_patch_wins_over_forge(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._merged_by(line=None, patch_merged=True, merged_heads={SHA: 7}),
|
||||||
|
"patch",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_forge_only_when_git_has_no_evidence(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._merged_by(line=None, patch_merged=False, merged_heads={SHA: 7}),
|
||||||
|
"pr#7",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unmerged_without_any_evidence(self):
|
||||||
|
self.assertIsNone(
|
||||||
|
self._merged_by(line=None, patch_merged=False, merged_heads={})
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -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()
|
||||||
Whitespace-only changes.
@@ -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()
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from contextlib import redirect_stderr
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||||
|
from pkgmgr.actions.gc.risk import plan
|
||||||
|
from pkgmgr.cli.commands.worktree import handle_gc
|
||||||
|
from pkgmgr.cli.parser import create_parser
|
||||||
|
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||||
|
BARE_CONTAINER,
|
||||||
|
BUSY_CACHE,
|
||||||
|
DANGLING_ID,
|
||||||
|
NEW_CACHE,
|
||||||
|
OLD_CACHE,
|
||||||
|
RUNNING_CONTAINER,
|
||||||
|
TAGGED_ID,
|
||||||
|
USED_ID,
|
||||||
|
VOLUME_CONTAINER,
|
||||||
|
RiskPlanFixture,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
||||||
|
def test_git_rules(self) -> None:
|
||||||
|
code, printed, _ = self.run_gc(level="high")
|
||||||
|
risks = self.risks(printed)
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
expected = {
|
||||||
|
self.wt["done"]: "low",
|
||||||
|
self.wt["dirty"]: "high",
|
||||||
|
self.wt["wip"]: "high",
|
||||||
|
self.wt["pushed"]: "medium",
|
||||||
|
self.wt["stack"]: "medium",
|
||||||
|
self.wt["cherry"]: "medium",
|
||||||
|
"old": "medium",
|
||||||
|
"main": "high",
|
||||||
|
}
|
||||||
|
for name, risk in expected.items():
|
||||||
|
with self.subTest(name=name):
|
||||||
|
self.assertEqual(risks[name], risk)
|
||||||
|
done = self.entry(printed, self.wt["done"])
|
||||||
|
self.assertEqual(done["steps"], ["worktree"])
|
||||||
|
self.assertEqual(done["pr"], "none")
|
||||||
|
cherry = self.entry(printed, self.wt["cherry"])
|
||||||
|
self.assertEqual(cherry["reason"], "head is on no remote")
|
||||||
|
|
||||||
|
def test_local_proof_needs_no_forge(self) -> None:
|
||||||
|
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||||
|
_, printed, _ = self.run_gc(level="high")
|
||||||
|
done = self.entry(printed, self.wt["done"])
|
||||||
|
|
||||||
|
self.assertEqual(done["risk"], "low")
|
||||||
|
self.assertEqual(done["pr"], "unknown")
|
||||||
|
self.assertEqual(done["skip"], "forge unavailable")
|
||||||
|
|
||||||
|
def test_open_pull_request_is_not_low(self) -> None:
|
||||||
|
self.forge = ForgeFacts(open_heads={"done": 9})
|
||||||
|
_, printed, _ = self.run_gc(level="high")
|
||||||
|
done = self.entry(printed, self.wt["done"])
|
||||||
|
|
||||||
|
self.assertEqual((done["risk"], done["pr"]), ("medium", "open #9"))
|
||||||
|
|
||||||
|
def test_docker_rules(self) -> None:
|
||||||
|
_, printed, _ = self.run_gc(level="high")
|
||||||
|
risks = self.risks(printed)
|
||||||
|
|
||||||
|
self.assertEqual(risks[DANGLING_ID], "low")
|
||||||
|
self.assertEqual(risks[TAGGED_ID], "medium")
|
||||||
|
self.assertEqual(risks[OLD_CACHE], "low")
|
||||||
|
self.assertEqual(risks[NEW_CACHE], "medium")
|
||||||
|
self.assertEqual(risks[BARE_CONTAINER], "low")
|
||||||
|
self.assertEqual(risks[VOLUME_CONTAINER], "medium")
|
||||||
|
self.assertEqual(risks["demo_data"], "medium")
|
||||||
|
self.assertEqual(risks["live_data"], "high")
|
||||||
|
for absent in (USED_ID, BUSY_CACHE, RUNNING_CONTAINER):
|
||||||
|
self.assertNotIn(absent, risks)
|
||||||
|
volume = self.entry(printed, "demo_data")
|
||||||
|
self.assertEqual(
|
||||||
|
(volume["compose_project"], volume["links"], volume["size_bytes"]),
|
||||||
|
("demo", 0, 2 * 10**9),
|
||||||
|
)
|
||||||
|
image = self.entry(printed, DANGLING_ID)
|
||||||
|
self.assertEqual(image["size_bytes"], 1_500_000_000)
|
||||||
|
|
||||||
|
def test_tmp_rules(self) -> None:
|
||||||
|
_, printed, _ = self.run_gc(level="high")
|
||||||
|
risks = self.risks(printed)
|
||||||
|
|
||||||
|
self.assertEqual(risks[self.t["old-done.log"]], "low")
|
||||||
|
self.assertEqual(risks[self.t["old-stopped"]], "low")
|
||||||
|
self.assertEqual(risks[self.t["new-done.log"]], "medium")
|
||||||
|
self.assertEqual(risks[self.t["old-unknown.log"]], "medium")
|
||||||
|
self.assertEqual(risks[self.t["old-running.log"]], "high")
|
||||||
|
self.assertEqual(risks[self.t["checkout"]], "high")
|
||||||
|
self.assertNotIn(os.path.join(self.tmp, "link"), risks)
|
||||||
|
|
||||||
|
def test_risk_low_plan_lists_only_low_items(self) -> None:
|
||||||
|
_, printed, _ = self.run_gc(level="low")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
sorted(self.risks(printed)),
|
||||||
|
sorted(
|
||||||
|
[
|
||||||
|
self.wt["done"],
|
||||||
|
DANGLING_ID,
|
||||||
|
OLD_CACHE,
|
||||||
|
BARE_CONTAINER,
|
||||||
|
self.t["old-done.log"],
|
||||||
|
self.t["old-stopped"],
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.assertEqual(printed["totals"]["low"]["count"], 6)
|
||||||
|
|
||||||
|
|
||||||
|
class TestRiskCli(unittest.TestCase):
|
||||||
|
def _gc(self, *argv: str) -> tuple[int, object]:
|
||||||
|
args = create_parser("test").parse_args(["gc", *argv])
|
||||||
|
ctx = SimpleNamespace(config_merged={"worktree_hooks": {}, "repositories": []})
|
||||||
|
with (
|
||||||
|
patch("pkgmgr.cli.commands.worktree.scan_repo_roots", return_value=["/r"]),
|
||||||
|
patch("pkgmgr.cli.commands.worktree.risk_cleanup", return_value=0) as run,
|
||||||
|
patch("pkgmgr.cli.commands.worktree.run_cleanup") as legacy,
|
||||||
|
redirect_stderr(io.StringIO()),
|
||||||
|
self.assertRaises(SystemExit) as stop,
|
||||||
|
):
|
||||||
|
handle_gc(args, ctx)
|
||||||
|
legacy.assert_not_called()
|
||||||
|
return stop.exception.code, run
|
||||||
|
|
||||||
|
def test_cli_forwards_risk_flags(self) -> None:
|
||||||
|
code, run = self._gc(
|
||||||
|
"--risk",
|
||||||
|
"low",
|
||||||
|
"--apply",
|
||||||
|
"--json",
|
||||||
|
"--owners",
|
||||||
|
"/o.json",
|
||||||
|
"--merged-into",
|
||||||
|
"origin/main",
|
||||||
|
"--sizes",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
run.assert_called_once_with(
|
||||||
|
["/r"],
|
||||||
|
plan.RiskRequest(
|
||||||
|
level="low",
|
||||||
|
apply=True,
|
||||||
|
as_json=True,
|
||||||
|
owners_file="/o.json",
|
||||||
|
include=[],
|
||||||
|
exclude=[],
|
||||||
|
merged_into=["origin/main"],
|
||||||
|
sizes=True,
|
||||||
|
min_age=None,
|
||||||
|
hooks={},
|
||||||
|
tmp_root=tempfile.gettempdir(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_cli_refuses_risk_with_report(self) -> None:
|
||||||
|
code, run = self._gc("--risk", "low", "--report")
|
||||||
|
|
||||||
|
self.assertEqual(code, 2)
|
||||||
|
run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -6,6 +6,7 @@ from unittest.mock import patch
|
|||||||
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
|
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
|
||||||
|
|
||||||
|
|
||||||
|
@patch("pkgmgr.actions.release.git_ops.run", return_value="")
|
||||||
class TestEnsureCleanAndSynced(unittest.TestCase):
|
class TestEnsureCleanAndSynced(unittest.TestCase):
|
||||||
@patch("pkgmgr.actions.release.git_ops.pull_ff_only")
|
@patch("pkgmgr.actions.release.git_ops.pull_ff_only")
|
||||||
@patch("pkgmgr.actions.release.git_ops.fetch")
|
@patch("pkgmgr.actions.release.git_ops.fetch")
|
||||||
@@ -15,6 +16,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
|
|||||||
mock_get_upstream_ref,
|
mock_get_upstream_ref,
|
||||||
mock_fetch,
|
mock_fetch,
|
||||||
mock_pull_ff_only,
|
mock_pull_ff_only,
|
||||||
|
_mock_run,
|
||||||
) -> None:
|
) -> None:
|
||||||
mock_get_upstream_ref.return_value = None
|
mock_get_upstream_ref.return_value = None
|
||||||
|
|
||||||
@@ -31,6 +33,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
|
|||||||
mock_get_upstream_ref,
|
mock_get_upstream_ref,
|
||||||
mock_fetch,
|
mock_fetch,
|
||||||
mock_pull_ff_only,
|
mock_pull_ff_only,
|
||||||
|
_mock_run,
|
||||||
) -> None:
|
) -> None:
|
||||||
mock_get_upstream_ref.return_value = "origin/main"
|
mock_get_upstream_ref.return_value = "origin/main"
|
||||||
|
|
||||||
@@ -53,6 +56,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
|
|||||||
mock_get_upstream_ref,
|
mock_get_upstream_ref,
|
||||||
mock_fetch,
|
mock_fetch,
|
||||||
mock_pull_ff_only,
|
mock_pull_ff_only,
|
||||||
|
_mock_run,
|
||||||
) -> None:
|
) -> None:
|
||||||
mock_get_upstream_ref.return_value = "origin/main"
|
mock_get_upstream_ref.return_value = "origin/main"
|
||||||
|
|
||||||
@@ -66,3 +70,30 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
|
|||||||
preview=False,
|
preview=False,
|
||||||
)
|
)
|
||||||
mock_pull_ff_only.assert_called_once_with(preview=False)
|
mock_pull_ff_only.assert_called_once_with(preview=False)
|
||||||
|
|
||||||
|
@patch("pkgmgr.actions.release.git_ops.pull_ff_only")
|
||||||
|
@patch("pkgmgr.actions.release.git_ops.fetch")
|
||||||
|
@patch("pkgmgr.actions.release.git_ops.get_upstream_ref")
|
||||||
|
def test_tracked_changes_refuse_before_any_sync(
|
||||||
|
self,
|
||||||
|
mock_get_upstream_ref,
|
||||||
|
mock_fetch,
|
||||||
|
mock_pull_ff_only,
|
||||||
|
mock_run,
|
||||||
|
) -> None:
|
||||||
|
mock_run.return_value = " M src/app.py"
|
||||||
|
|
||||||
|
with self.assertRaises(RuntimeError) as cm:
|
||||||
|
ensure_clean_and_synced(preview=True)
|
||||||
|
|
||||||
|
self.assertIn("src/app.py", str(cm.exception))
|
||||||
|
mock_run.assert_called_once_with(
|
||||||
|
["status", "--porcelain", "--untracked-files=no"]
|
||||||
|
)
|
||||||
|
mock_get_upstream_ref.assert_not_called()
|
||||||
|
mock_fetch.assert_not_called()
|
||||||
|
mock_pull_ff_only.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import io
|
||||||
|
import unittest
|
||||||
|
import urllib.error
|
||||||
|
from typing import NoReturn
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch import gc_forge
|
||||||
|
from pkgmgr.core.remote_provisioning.http.client import HttpClient
|
||||||
|
from pkgmgr.core.remote_provisioning.http.errors import HttpError
|
||||||
|
|
||||||
|
TRUNCATED = (
|
||||||
|
b"HTTP/1.1 200 OK\r\nContent-Length: 4096\r\n"
|
||||||
|
b"Content-Type: application/json\r\n\r\n"
|
||||||
|
b'[{"number": 1, "merged_at": null'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TruncatedSocket:
|
||||||
|
def __init__(self, payload: bytes) -> None:
|
||||||
|
self._file = io.BytesIO(payload)
|
||||||
|
|
||||||
|
def makefile(self, *_args, **_kwargs):
|
||||||
|
return self._file
|
||||||
|
|
||||||
|
|
||||||
|
def truncated_response(*_args, **_kwargs) -> http.client.HTTPResponse:
|
||||||
|
response = http.client.HTTPResponse(TruncatedSocket(TRUNCATED))
|
||||||
|
response.begin()
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
class 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):
|
||||||
|
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:
|
||||||
|
with (
|
||||||
|
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||||
|
self.assertRaises(HttpError) as caught,
|
||||||
|
):
|
||||||
|
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||||
|
|
||||||
|
self.assertEqual(caught.exception.status, 0)
|
||||||
|
self.assertIn("IncompleteRead", str(caught.exception))
|
||||||
|
|
||||||
|
def test_read_timeout_becomes_http_error(self) -> None:
|
||||||
|
with (
|
||||||
|
patch("urllib.request.urlopen", side_effect=TimeoutError()),
|
||||||
|
self.assertRaises(HttpError) as caught,
|
||||||
|
):
|
||||||
|
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||||
|
|
||||||
|
self.assertEqual(str(caught.exception), "TimeoutError")
|
||||||
|
|
||||||
|
def test_non_http_scheme_is_refused_before_any_request(self) -> None:
|
||||||
|
with (
|
||||||
|
patch("urllib.request.urlopen") as urlopen,
|
||||||
|
self.assertRaises(HttpError) as caught,
|
||||||
|
):
|
||||||
|
HttpClient(timeout_s=1).request_json("GET", "file:///etc/passwd")
|
||||||
|
|
||||||
|
urlopen.assert_not_called()
|
||||||
|
self.assertIn("unsupported URL scheme 'file'", str(caught.exception))
|
||||||
|
|
||||||
|
def test_forge_facts_degrade_to_unavailable_instead_of_crashing(self) -> None:
|
||||||
|
with patch("urllib.request.urlopen", side_effect=truncated_response):
|
||||||
|
facts = gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||||
|
|
||||||
|
self.assertIn("GitHub API failed for owner/repo", facts.unavailable)
|
||||||
|
self.assertEqual((facts.merged_heads, facts.open_heads), ({}, {}))
|
||||||
|
|
||||||
|
def test_forge_budget_stops_paging(self) -> None:
|
||||||
|
with (
|
||||||
|
patch.object(gc_forge, "BUDGET_S", -1),
|
||||||
|
patch("urllib.request.urlopen") as urlopen,
|
||||||
|
):
|
||||||
|
facts = gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||||
|
|
||||||
|
urlopen.assert_not_called()
|
||||||
|
self.assertIn("budget", facts.unavailable)
|
||||||
|
|
||||||
|
def test_forge_requests_use_the_short_timeout(self) -> None:
|
||||||
|
with (
|
||||||
|
patch.object(gc_forge, "HttpClient", wraps=HttpClient) as client,
|
||||||
|
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||||
|
):
|
||||||
|
gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||||
|
|
||||||
|
client.assert_called_once_with(timeout_s=gc_forge.TIMEOUT_S)
|
||||||
|
self.assertLessEqual(gc_forge.TIMEOUT_S, 10)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user