Compare commits

...
Author SHA1 Message Date
Kevin Veen-BirkenbachandClaude Opus 5.5 236649cbdf fix(gc): fail docker deletes on revalidation errors and read the mount table byte-safe
CodeQL Advanced / Check security (none, actions) (push) Waiting to run
Test Units / test-unit (push) Waiting to run
Test Code Integration / test-integration (push) Waiting to run
CI / test-integration (push) Waiting to run
Test OS Containers / test-env-virtual (arch) (push) Waiting to run
CI / test-env-virtual (push) Waiting to run
Test OS Containers / test-env-virtual (centos) (push) Waiting to run
CI / test-env-nix (push) Waiting to run
CI / test-virgin-user (push) Waiting to run
Test OS Containers / test-env-virtual (ubuntu) (push) Waiting to run
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Waiting to run
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Waiting to run
Test End-To-End / test-e2e (centos) (push) Waiting to run
Test End-To-End / test-e2e (debian) (push) Waiting to run
Test End-To-End / test-e2e (fedora) (push) Waiting to run
Test End-To-End / test-e2e (ubuntu) (push) Waiting to run
Test Virgin User / test-virgin-user (arch) (push) Waiting to run
Test Virgin User / test-virgin-user (fedora) (push) Waiting to run
Test Virgin User / test-virgin-user (ubuntu) (push) Waiting to run
Test Virgin Root / test-virgin-root (arch) (push) Waiting to run
Test Virgin Root / test-virgin-root (debian) (push) Waiting to run
Test Virgin Root / test-virgin-root (ubuntu) (push) Waiting to run
ShellCheck / lint-shell (push) Waiting to run
CI / quality (push) Skipped
CI / lint-python (push) Failing after 0s
CI / security-codeql (push) Waiting to run
CodeQL Advanced / Check security (none, python) (push) Waiting to run
CI / test-unit (push) Waiting to run
Test OS Containers / test-env-virtual (debian) (push) Waiting to run
CI / test-e2e (push) Waiting to run
Test OS Containers / test-env-virtual (fedora) (push) Waiting to run
CI / test-virgin-root (push) Waiting to run
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Waiting to run
CI / lint-shell (push) Waiting to run
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Waiting to run
CI / lint-docker (push) Waiting to run
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Waiting to run
Test End-To-End / test-e2e (arch) (push) Waiting to run
Test Virgin User / test-virgin-user (centos) (push) Waiting to run
Test Virgin Root / test-virgin-root (centos) (push) Waiting to run
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
Docker Linter / Lint Dockerfile (push) Waiting to run
Test Virgin User / test-virgin-user (debian) (push) Waiting to run
Test Virgin Root / test-virgin-root (fedora) (push) Waiting to run
CodeRabbit on PR 21: an unreadable docker after the plan was reported as a skip and the run exited 0, and a non-UTF-8 mount path in /proc/self/mountinfo aborted the plan. A revalidation warning now fails the item; the mount table is read with surrogateescape.

PR: https://github.com/kevinveenbirkenbach/package-manager/pull/21
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:29:00 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 43a3f9f73d fix(gc): let worktree holds beat the forge skip, read the mount table and recheck docker before deletes
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
CodeRabbit architecture review on PR 21: a forge-unavailable skip hid lock, busy, checkout and age holds from the risk plan; a mount at a scratch candidate or a same-device bind mount went unseen; containers and build cache were removed without a fresh check. Tree holds now win over the forge skip and the age check also runs under it, scratch items read /proc/self/mountinfo, and docker items are planned again before each delete.

PR: https://github.com/kevinveenbirkenbach/package-manager/pull/21
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:38:08 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 babc977cfe fix(gc): recheck owner status and mounts before scratch deletes
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
CodeRabbit on PR 21: the scratch delete trusted the owner status read at plan time, and walk skipped mounts below a scratch directory that rmtree would cross. The owner file is now read again before every scratch delete; walk counts entries on another filesystem and a counted mount keeps the item above low.

PR: https://github.com/kevinveenbirkenbach/package-manager/pull/21
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:23:17 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 4c603a0087 test(git-sandbox): share origin_and_repo setup across gc fixtures
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
quality/check on PR 21 flagged 4 clean.clones findings: the same bare origin, repo and init commit setup in test_branch_gc.py and risk_fixture.py. Both now call one helper in tests/support/git_sandbox.py.

PR: https://github.com/kevinveenbirkenbach/package-manager/pull/21
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:46:47 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 cee58bcef1 refactor(gc): split the risk plan to clear quality and review findings
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
quality, 24 findings: risk_cleanup(repo_roots, request) takes a frozen RiskRequest and splits into _refusal, _git_options, _host_items, _apply and _report; the hardcoded /tmp root is gone, the CLI passes tempfile.gettempdir() (so TMPDIR is honoured); classify, the tmp verdict and the HTTP client split into helpers in the same check order; gc_cmd options split into two adders; default-value fallbacks removed where every path sets the value. Tests: git(), AUTHOR and isolated_root move to tests/support/git_sandbox.py, the plan tests move to tests/unit/pkgmgr/actions/branch/test_gc_plan.py, test_risk_plan.py splits into risk_fixture.py, test_risk_plan.py and test_risk_apply.py. CodeRabbit: with --branch, --apply only plans and deletes the selected git items, docker and scratch items stay out with a warning; a truncated HTTP error body keeps its status and the partial body.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| feature/gc-risk-levels | 17 files +946/-788 | 91 % | 4 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration with PYTHONPATH=src 904 passed; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0, 3 accepted (scheme-guarded urlopen moved into _send, fixed-argv git in the test helper). Hub review 913e2f2465eda2d9.

Refs https://github.com/kevinveenbirkenbach/package-manager/pull/21

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:57:50 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 b8248a0253 feat(gc): plan deterministic cleanups by risk level and owner
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
Test End-To-End / test-e2e (ubuntu) (push) Canceled after 0s
Test End-To-End / test-e2e (fedora) (push) Canceled after 0s
Test End-To-End / test-e2e (debian) (push) Canceled after 0s
Test End-To-End / test-e2e (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / quality (push) Skipped
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Canceled after 0s
Test End-To-End / test-e2e (arch) (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / lint-python (push) Failing after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
Test Virgin User / test-virgin-user (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
pkgmgr gc --risk low|medium|high [--owners FILE] [--apply] classifies Docker images, build cache, containers, volumes, /tmp entries, worktrees and branches into low, medium and high risk with owner and reason and prints the plan up to the picked level; --apply removes only the low items of that plan and refuses any other level. _merged_by asks local git first (line, then patch) and the forge pr number last, so the label of a merged branch no longer depends on whether GitHub answers. Forge facts use a 10 s request timeout and a 60 s paging budget and degrade to unavailable on a failed or truncated answer. HttpClient refuses every URL scheme except http and https before urlopen. Rebuilt on main after PR 14; the held-once part of the earlier draft is dropped because main carries it.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| feature/gc-risk-levels | 16 files +1493/-12 | 90 % | 5 % | – | – | 100 % | 86 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: 129 tests passed, 18 subtests (branch, gc risk, remote_provisioning, test_branch_gc, test_error_path_degradation), ruff clean, MEDUSA 100 % critical 0. Break 5 %: largest new surface; a slow forge now degrades to unavailable after 60 s. Operator review df0f4fbe (re-card of 0b5c15ba).
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:46:58 +00:00
Kevin Veen-Birkenbach 0a3badfd63 Merge pull request #14 from kevinveenbirkenbach/fix/branch-cleanup-held-once-codacy
fix(branch): close the Codacy issues of the held-once read
2026-11-29 22:25:22 +01:00
Kevin Veen-BirkenbachandClaude Opus 5.5 1361fb9314 fix(branch): close the Codacy issues of the held-once read
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
Test End-To-End / test-e2e (ubuntu) (push) Canceled after 0s
Test End-To-End / test-e2e (fedora) (push) Canceled after 0s
Test End-To-End / test-e2e (debian) (push) Canceled after 0s
Test End-To-End / test-e2e (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / lint-python (push) Failing after 0s
CI / quality (push) Skipped
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Canceled after 0s
Test End-To-End / test-e2e (arch) (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
Test Virgin User / test-virgin-user (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
Codacy reports 27 new issues on PR 13. The pydocstyle ones (D213/D406/D407) ask for numpy sections with the summary on line two, which contradicts the Args: docstrings of AGENTS.md and the quality clean.comment rule; the five docstrings on the private helpers of held.py and gc.py go, which also clears the clean.comment findings behind the red quality/check. The Bandit and Opengrep subprocess findings go with the test running git through pkgmgr.core.git.run instead of its own subprocess calls.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/branch-cleanup-held-once-codacy | 3 files +6/-89 | 93 % | 1 % | – | – | 100 % | 92 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Refs https://github.com/kevinveenbirkenbach/package-manager/pull/13

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 15:19:01 +00:00
Kevin Veen-Birkenbach 2c70837d00 Merge pull request #13 from kevinveenbirkenbach/fix/branch-cleanup-held-once
perf(branch): read the held branches once per cleanup plan
2026-11-29 16:03:20 +01:00
Kevin Veen-Birkenbach 83297dab67 Merge pull request #12 from kevinveenbirkenbach/fix/release-cwd
fix(release): release the cwd checkout and refuse tracked changes
2026-11-29 16:00:09 +01:00
Kevin Veen-Birkenbach bd32cf9fab Merge pull request #10 from kevinveenbirkenbach/dependabot/github_actions/docker/login-action-4.8.0
build(deps): bump docker/login-action from 4.6.0 to 4.8.0
2026-11-29 15:59:46 +01:00
Kevin Veen-Birkenbach eff95a8003 Merge pull request #9 from kevinveenbirkenbach/update_flake_lock_action
chore(deps): update flake.lock
2026-11-29 15:59:24 +01:00
Kevin Veen-BirkenbachandClaude Opus 5.5 d94492e306 refactor(branch): clear quality round 2 and tighten the held-branch code to Codacy
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
Test End-To-End / test-e2e (ubuntu) (push) Canceled after 0s
Test End-To-End / test-e2e (fedora) (push) Canceled after 0s
Test End-To-End / test-e2e (debian) (push) Canceled after 0s
Test End-To-End / test-e2e (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / quality (push) Skipped
CI / lint-python (push) Failing after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Canceled after 0s
Test End-To-End / test-e2e (arch) (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test Virgin User / test-virgin-user (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
Rename gc_refs.py to held.py, move the local-scope routing back into _actions so _build matches main, split _held_branches into _symref_holds and _state_file_holds, and move the ancestor check of _local_actions into _ancestor_action (Lizard CCN 9 > 8). Docstrings start their summary on the opening line (D212) and end with a blank line (D413). test_gc_held_once drops its parameter defaults, stops cloning test_branch_cleanup_local and calls git through shutil.which (Bandit B607).

Kept on purpose, each contradicts another rule: D406/D407 numpy sections (AGENTS: Args: docstrings), D100 module docstrings (no prose docstrings), B404/B603 on test subprocess calls (silencing needs # nosec, which quality clean.tool-pragma forbids).

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/branch-cleanup-held-once | 4 files +69/-57 | 90 % | 3 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Refs: https://github.com/kevinveenbirkenbach/package-manager/pull/13
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:31:00 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 28ff2f7a8e refactor(release): tighten the release-at-cwd code to Codacy
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
The docstrings of _at_cwd_checkout, release_at_cwd and has_explicit_selection end with a blank line after their last section (pydocstyle D413). TestReleaseCwdCheckout calls git through shutil.which and skips without git (Bandit B607).

Kept on purpose, each contradicts another rule: D205/D212/D415 want a summary sentence (AGENTS allows docstrings only as parameter docs), D406/D407 numpy sections (AGENTS: Args: docstrings), B404/B603 on test subprocess calls (silencing needs # nosec, which quality clean.tool-pragma forbids).

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/release-cwd | 3 files +8/-1 | 90 % | 2 % | – | – | 100 % | 88 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Refs: https://github.com/kevinveenbirkenbach/package-manager/pull/12
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:29:25 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 0917ceffdb refactor(release): keep the cwd checkout out of dispatch and reuse the test module
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
The quality gate's differential check flagged PR 12: dispatch_command grew in length and complexity, tests/integration gained a 37th item and the new test module cloned test_push_mirror_leases' setup. The cwd-checkout step moves into release_at_cwd in the release command, has_explicit_selection moves next to get_selected_repos, and the four cwd tests move into test_release_publish_hook.py with an env-based git identity. Behaviour unchanged.

🎯 Fix: 90 %
💥 Break: 3 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 87
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:54:19 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 39843ab627 refactor(branch): move the held-branch reader to gc_refs and the held-once tests to a unit module
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
The quality gate's ratchet flagged PR 13: gc.py and test_branch_cleanup_local.py grew past their already-oversized base length, and _actions gained a seventh parameter. The held-branch reader (_held_branches, _worktree_heads, _git_dirs, _symbolic, _common_dir, HELD_FILES) moves unchanged into gc_refs.py, so gc.py shrinks below its base; scope local is routed in _build, so _actions keeps six parameters; the held-once tests move into tests/unit/pkgmgr/actions/branch/test_gc_held_once.py and test_branch_cleanup_local.py is back to main plus one patch target. Mutating git calls stay on gc._git, so the gc.run spies still see them.

🎯 Fix: 90 %
💥 Break: 4 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:52:58 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 5e08847286 Merge origin/main into fix/branch-cleanup-held-once
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
Test End-To-End / test-e2e (ubuntu) (push) Canceled after 0s
Test End-To-End / test-e2e (fedora) (push) Canceled after 0s
Test End-To-End / test-e2e (debian) (push) Canceled after 0s
Test End-To-End / test-e2e (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / quality (push) Skipped
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Canceled after 0s
Test End-To-End / test-e2e (arch) (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / lint-python (push) Failing after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
Test Virgin User / test-virgin-user (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
Brings the 11-14 held-branches fix (e017af0) up to main 895ec2f; clean merge, no conflicts. test_branch_cleanup_local passes 76/76 on the merge and both new tests fail on the unfixed main on the held-branches read count.

🎯 Fix: 90 %
💥 Break: 3 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 87
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:35:52 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 b06b33ff57 fix(release): release the cwd checkout and refuse tracked changes
CI / test-env-virtual (push) Blocked by required conditions
Test OS Containers / test-env-virtual (arch) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (centos) (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Blocked by required conditions
Test End-To-End / test-e2e (centos) (push) Blocked by required conditions
Test End-To-End / test-e2e (debian) (push) Blocked by required conditions
Test End-To-End / test-e2e (fedora) (push) Blocked by required conditions
Test End-To-End / test-e2e (ubuntu) (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
Test Virgin User / test-virgin-user (arch) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (fedora) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (ubuntu) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (arch) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (debian) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (ubuntu) (push) Blocked by required conditions
ShellCheck / lint-shell (push) Blocked by required conditions
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
CI / test-virgin-root (push) Blocked by required conditions
CI / quality (push) Skipped
Test OS Containers / test-env-virtual (debian) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (fedora) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
Test End-To-End / test-e2e (arch) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (centos) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (centos) (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
Ruff (Python code sniffer) / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
Docker Linter / Lint Dockerfile (push) Blocked by required conditions
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test Virgin User / test-virgin-user (debian) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (fedora) (push) Blocked by required conditions
A release started from a nested clone (for example .worktrees/release-x) matched the configured main checkout by cwd prefix, so pkgmgr chdir'd into the main checkout and its commit -a swept that checkout's unfinished tracked edits into the release commit. Implicit selection for release now uses the cwd's git toplevel, an explicit identifier keeps the configured directory, and ensure_clean_and_synced refuses a tree with tracked changes before any sync or version bump.

🎯 fix 92 % · 💥 break 3 % · 💸 tokens – · ⏱️ velocity – · 🛡️ security 100 % · 🏆 score 89

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 21:20:26 +00:00
Kevin Veen-Birkenbach 895ec2f0d4 Merge pull request #11 from kevinveenbirkenbach/chore/quality-reusable-gate
ci: run ruff and the quality gate from infinito-nexus/quality
2026-11-25 22:26:22 +01:00
Kevin Veen-BirkenbachandClaude Opus 5.5 d34c3f3772 ci: pin the quality workflows to v0.2.0
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
Both reusable quality workflows move from quality main ed91a38 to the v0.2.0 release commit 003eed6, pinned by sha with the version comment that Dependabot's github-actions updates. job.workflow_sha resolves to the same commit, so the tool versions follow this one pin.

🎯 Fix: 93 %
💥 Break: 2 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 91
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:47:11 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 2b18deede8 ci: call the quality gate from ci.yml to keep the workflow folder at 15 files
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
The gate's first run on PR #11 found one new finding, clean.folder-items on .github/workflows (16 items). The gate's call moves into ci.yml as the job quality, which runs only on pull requests and pushes to main, so the folder keeps the 15 files main has.

🎯 Fix: 90 %
💥 Break: 3 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 87
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 19:53:16 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 1707cc0192 ci: run quality's gate and take ruff from the quality flake
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
Test End-To-End / test-e2e (ubuntu) (push) Canceled after 0s
Test End-To-End / test-e2e (fedora) (push) Canceled after 0s
Test End-To-End / test-e2e (debian) (push) Canceled after 0s
Test End-To-End / test-e2e (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / lint-python (push) Failing after 0s
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Canceled after 0s
Test End-To-End / test-e2e (arch) (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
Test Virgin User / test-virgin-user (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
lint-python now runs ruff through quality's reusable tool workflow, so its version comes from quality's flake.lock instead of the latest pip release, and a new workflow runs quality's differential gate on pull requests and pushes to main. Both pin one quality commit by their uses: line only.

🎯 Fix: 85 %
💥 Break: 4 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 82
🚦 Gate: ⛔ fix 85 % < 90

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 19:13:25 +00:00
github-actions[bot] d416fc79e9 flake.lock: Update
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/afbbf77' (2026-02-21)
  → 'github:NixOS/nixpkgs/b6018f8' (2026-06-30)
2026-11-16 05:26:18 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 e017af0cd1 perf(branch): read the held branches once per cleanup plan
branch cleanup --local reads the held-branches map lazily once per snapshot instead of once per item, so a plan reads it once and every apply-time re-check still reads it fresh; a branch held after the plan is still skipped. On a scratch repository with 60 merged branches and 101 git dirs the plan drops from 27.1 s to 2.3 s with a byte-identical JSON plan. Tests run once after the merge (operator order 2026-11-14).

🎯 Fix: 85 %
💥 Break: 3 %
💸 Tokens: 10 %
⏱️ Velocity: 5 %
🛡️ Security: 100 %
🏆 Score: 100
🚦 Gate: ⛔ fix 85 % < 90

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:39:37 +00:00
dependabot[bot] 9421f69ea9 build(deps): bump docker/login-action from 4.6.0 to 4.8.0
Bumps [docker/login-action](https://github.com/docker/login-action) from 4.6.0 to 4.8.0.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/dbcb813823bdd20940b903addbd779551569679f...8aa5831fb8d48d8f76594c7ddde61ae58019f550)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 00:16:23 +00:00
35 changed files with 2554 additions and 458 deletions

No files matched your search

+6
View File
@@ -71,3 +71,9 @@ jobs:
contents: read
security-events: write
uses: ./.github/workflows/lint-docker.yml
quality:
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
permissions:
contents: read
uses: infinito-nexus/quality/.github/workflows/quality.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
+4 -16
View File
@@ -8,19 +8,7 @@ permissions:
jobs:
lint-python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install ruff
run: pip install ruff
- name: Run ruff
run: |
ruff check src tests
uses: infinito-nexus/quality/.github/workflows/tool.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
with:
tool: ruff
args: check src tests
+2 -2
View File
@@ -64,7 +64,7 @@ jobs:
use: true
- name: Login to GHCR
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
with:
registry: ghcr.io
username: ${{ github.actor }}
@@ -106,7 +106,7 @@ jobs:
use: true
- name: Login to GHCR
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
with:
registry: ghcr.io
username: ${{ github.actor }}
Generated
+3 -3
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1771714954,
"narHash": "sha256-nhZJPnBavtu40/L2aqpljrfUNb2rxmWTmSjK2c9UKds=",
"lastModified": 1782847189,
"narHash": "sha256-twXPFqFsrrY5r28Zh7Homgcp2gUMBgQ6WDS98Q/3xFI=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "afbbf774e2087c3d734266c22f96fca2e78d3620",
"rev": "b6018f87da91d19d0ab4cf979885689b469cdd41",
"type": "github"
},
"original": {
+40 -176
View File
@@ -8,6 +8,7 @@ import sys
import time
from collections.abc import Callable
from dataclasses import asdict, dataclass, field
from functools import cache
from graphlib import CycleError, TopologicalSorter
from pkgmgr.actions.worktree.hooks import FINI_HOOK, hook_command, run_hook
@@ -28,6 +29,7 @@ from pkgmgr.core.git.run import (
)
from .gc_forge import ForgeFacts, fetch_forge_facts
from .held import _common_dir, _git_dirs, _held_branches, _symbolic
from .nofollow import canonical, remove_tree
Registrations = tuple[str, dict[str, list[str]]]
@@ -37,6 +39,7 @@ Snapshot = tuple[
dict[int, str],
dict[str, tuple[str | None, int | None, int | None, bool]],
Registrations,
Callable[[], dict[str, str]],
]
# PROC_PID_INIT_INO: only the initial PID namespace sees every process of the host.
@@ -62,6 +65,7 @@ REFUSAL = (
)
SCOPES = ("worktree", "branch", "all", "purge", "local")
NOT_LINKED = "not a linked worktree of this repository"
FORGE_UNAVAILABLE = "forge unavailable"
NO_REMOTE_DEFAULT = (
"refused: no remote-tracking default (origin, else the only remote: "
"refs/remotes/<remote>/HEAD, main or master, resolving inside "
@@ -69,12 +73,6 @@ NO_REMOTE_DEFAULT = (
)
NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8"
DEFAULT_NAMES = ("HEAD", "main", "master")
HELD_FILES = (
("rebase-merge/head-name", "rebase in progress"),
("rebase-merge/update-refs", "rebase in progress"),
("rebase-apply/head-name", "rebase in progress"),
("BISECT_START", "bisect in progress"),
)
DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$"
SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs")
WALKED_STORES = ("refs", "reftable", "logs/refs")
@@ -263,10 +261,6 @@ def _config_read(args: list[str], cwd: str, view: str) -> str:
return run(args, cwd=cwd, scan=True, config_view=view)
def _common_dir(cwd: str) -> str:
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
def _docker(args: list[str]) -> str:
return subprocess.run(
["docker", *args], check=True, capture_output=True, text=True
@@ -473,13 +467,13 @@ def _in_line(repo: Repo, sha: str) -> str | None:
def _merged_by(repo: Repo, sha: str) -> str | None:
if sha not in repo.first_parent and _is_ancestor(sha, repo.default, repo.repo):
return "ancestor"
number = repo.forge.merged_heads.get(sha)
if number:
return f"pr#{number}"
line = _in_line(repo, sha)
if line:
return f"line:{line}"
return "patch" if _patch_merged(repo, sha) else None
if _patch_merged(repo, sha):
return "patch"
number = repo.forge.merged_heads.get(sha)
return f"pr#{number}" if number else None
def _patch_merged(repo: Repo, sha: str) -> bool:
@@ -525,24 +519,22 @@ def human_size(size: int) -> str:
return f"{value / 1024:.1f}T"
def _needs_forge(item: Item, tree: Worktree | None) -> bool:
def _forge_skip(repo: Repo, item: Item, tree: Worktree | None) -> str | None:
"""
Whether deciding the item needs the forge's PR and protection facts.
Args:
repo: the planned repository with its forge facts.
item: the classified item.
tree: the worktree holding its branch, or None.
Returns:
False only for a branch that no worktree holds, without upstream and
remote branch, merged into the default by ancestry; True otherwise.
FORGE_UNAVAILABLE when the forge was not read, except for a branch that
no worktree holds, without upstream and remote branch, merged into the
default by ancestry; None otherwise.
"""
return not (
tree is None
and item.merged_by == "ancestor"
and item.upstream is None
and not item.remotes
)
if not repo.forge.unavailable:
return None
local = tree is None and item.upstream is None and not item.remotes
return None if local and item.merged_by == "ancestor" else FORGE_UNAVAILABLE
def _skip(
@@ -555,10 +547,9 @@ def _skip(
number = repo.forge.open_heads.get(item.branch) if item.branch else None
if number:
return f"open-pr #{number}"
if repo.forge.unavailable and _needs_forge(item, tree):
return "forge unavailable"
forge = _forge_skip(repo, item, tree)
if tree is None:
return None
return forge
if tree.main:
return "checked out in main worktree"
if repo.scope == "local":
@@ -583,7 +574,7 @@ def _skip(
lock = _lock_skip(tree.locked, repo.host_ns)
if lock:
return lock
return _busy(cwds, tree.path)
return _busy(cwds, tree.path) or forge
def _remote_refusal(unsafe: list[str], item: Item) -> str | None:
@@ -665,7 +656,7 @@ def _build(
tree: Worktree | None,
snapshot: Snapshot,
) -> Item:
local, remote, cwds, tracking, registrations = snapshot
local, remote, cwds, tracking = snapshot[:4]
upstream, ahead, behind, gone = tracking.get(
branch or "", (None, None, None, False)
)
@@ -753,13 +744,13 @@ def _build(
)
item.skip = _skip(repo, item, tree, checkout, cwds)
if (
item.skip is None
item.skip in (None, FORGE_UNAVAILABLE)
and repo.min_age is not None
and item.last_activity
and (time.time() - item.last_activity) / 3600 < repo.min_age
):
item.skip = f"younger than {repo.min_age:g} h"
item.actions = _actions(repo, item, tree, checkout, dirty, registrations)
item.actions = _actions(repo, item, tree, checkout, dirty, snapshot)
if repo.unsafe:
item.actions = [a for a in item.actions if not a.startswith("remote-branch:")]
return item
@@ -771,10 +762,11 @@ def _actions(
tree: Worktree | None,
checkout: bool,
dirty: int,
registrations: Registrations,
snapshot: Snapshot,
) -> list[str]:
if repo.scope == "local":
return _local_actions(repo, item, tree)
return _local_actions(repo, item, tree, snapshot[5])
registrations = snapshot[4]
tree_part: list[str] = []
if tree:
if (
@@ -813,29 +805,22 @@ def _actions(
return actions
def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]:
"""
Settle the actions of an item planned with scope `local`.
Args:
repo: the planned repository; its default and merged-into lines are
the refs the branch tip must be an ancestor of.
item: the classified item; a merged-clean one whose tip is an
ancestor of none of them gets that as its skip.
tree: the worktree holding its branch, or None.
Returns:
`local-branch` for a merged-clean local branch that no worktree,
worktree registration, rebase, bisect or symbolic ref holds and whose
tip is an ancestor of the default or a merged-into line, else
nothing; never a worktree, stack or remote action.
"""
def _local_actions(
repo: Repo,
item: Item,
tree: Worktree | None,
held: Callable[[], dict[str, str]],
) -> list[str]:
if item.state != "merged-clean" or not item.local_sha or tree is not None:
return []
held = _held_branches(repo.repo).get(item.branch)
if held:
item.skip = item.skip or held
hold = held().get(item.branch)
if hold:
item.skip = item.skip or hold
return []
return _ancestor_action(repo, item)
def _ancestor_action(repo: Repo, item: Item) -> list[str]:
targets = [repo.default, *repo.lines]
if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets):
return ["local-branch"]
@@ -854,6 +839,7 @@ def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
cwds,
tracking,
_registrations(repo.repo),
cache(lambda: _held_branches(repo.repo)),
)
@@ -911,25 +897,6 @@ def _default_remote(remotes: list[str]) -> str | None:
return remotes[0] if len(remotes) == 1 else None
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
"""
List the resolvable refs under a prefix with their symref targets.
Args:
repo_root: main worktree root of the repository.
prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`.
git_dir: the git common dir (shared refs plus the main worktree's own)
or a `worktrees/<id>` dir whose refs to list, or "" for the refs
as repo_root's worktree sees them.
Returns:
Full ref name -> the ref it points to, or "" for a plain ref.
"""
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
return dict(line.split("\x00", 1) for line in out.splitlines())
def _resolve_within(refs: dict[str, str], ref: str) -> str | None:
"""
Follow a ref's symref chain without leaving a set of refs.
@@ -975,109 +942,6 @@ def _remote_default(repo_root: str, remotes: list[str]) -> str | None:
return None
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
"""
Read the branch every worktree's HEAD names, on any ref backend.
Args:
repo_root: main worktree root of the repository.
git_dirs: the git common dir first, then each `worktrees/<id>`.
Returns:
Branch name -> skip reason, from `git --git-dir=<dir> symbolic-ref
HEAD` for each of them, whatever its id.
Raises:
GitBaseError: when a HEAD is neither readable nor detached.
"""
heads: dict[str, str] = {}
for git_dir in git_dirs:
try:
target = _git(
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
)
except GitRunError as exc:
if exc.returncode == 1:
continue
raise
if target.startswith("refs/heads/"):
heads.setdefault(
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
)
return heads
def _git_dirs(repo_root: str) -> list[str]:
"""
List the git dirs of every worktree of the repository.
Args:
repo_root: main worktree root of the repository.
Returns:
The git common dir, then each entry of `<common>/worktrees/`, whatever
its id and whether `git worktree list` shows it.
"""
common = _common_dir(repo_root)
base = os.path.join(common, "worktrees")
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
return [common, *(os.path.join(base, entry) for entry in entries)]
def _held_branches(repo_root: str) -> dict[str, str]:
"""
Find the local branches that something besides a listed worktree holds.
Args:
repo_root: main worktree root of the repository.
Returns:
Branch name -> skip reason: a symbolic branch, the branch any symbolic
ref under `refs/` (also a tag or remote-tracking one) or under the
main worktree's or any registration's `refs/worktree/` names, the HEAD
of the main repository and of every `worktrees/<id>` registration,
also one `git worktree list` omits, each rebase-merge and rebase-apply
head-name, an interactive rebase's update-refs and BISECT_START; all
read through the git common dir, whichever worktree repo_root is.
Raises:
GitBaseError: when git cannot read a registration, symref or HEAD.
OSError: when a state file exists but cannot be read.
ValueError: when a state file is not UTF-8.
"""
git_dirs = _git_dirs(repo_root)
held: dict[str, str] = {}
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
for git_dir in git_dirs[1:]:
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
for ref, target in symrefs.items():
if target and ref.startswith("refs/heads/"):
held.setdefault(
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
)
if target.startswith("refs/heads/"):
held.setdefault(
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
)
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
held.setdefault(branch, reason)
for git_dir in git_dirs:
for name, operation in HELD_FILES:
try:
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
continue
for line in lines:
ref = line.strip().removeprefix("ref: ")
if ref.startswith("refs/heads/") or name == "BISECT_START":
held.setdefault(
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
)
return held
def _lines(
repo_root: str, refs: list[str], remotes: list[str], warnings: list[str]
) -> tuple[dict[str, tuple[str, set[str]]], set[str]]:
+17 -6
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import time
from dataclasses import dataclass, field
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
@@ -12,6 +13,8 @@ from pkgmgr.core.remote_provisioning.http.errors import HttpError
GITHUB_HOST = "github.com"
GITHUB_API = "https://api.github.com"
PAGE_SIZE = 100
TIMEOUT_S = 10
BUDGET_S = 60
@dataclass
@@ -46,10 +49,14 @@ def github_slugs(remote_urls: dict[str, str]) -> list[tuple[str, str]]:
return slugs
def _pages(http: HttpClient, headers: dict[str, str], url: str) -> list[dict]:
def _pages(
http: HttpClient, headers: dict[str, str], url: str, deadline: float
) -> list[dict]:
items: list[dict] = []
page = 1
while True:
if time.monotonic() > deadline:
raise HttpError(status=0, message=f"budget of {BUDGET_S}s exceeded")
resp = http.request_json(
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
)
@@ -94,7 +101,8 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
The facts, or facts whose unavailable names the failing repository.
"""
facts = ForgeFacts()
http = HttpClient(timeout_s=30)
http = HttpClient(timeout_s=TIMEOUT_S)
deadline = time.monotonic() + BUDGET_S
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
@@ -103,14 +111,17 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
for owner, name in slugs:
base = f"{GITHUB_API}/repos/{owner}/{name}"
try:
for pr in _pages(http, headers, f"{base}/pulls?state=all"):
for pr in _pages(http, headers, f"{base}/pulls?state=all", deadline):
if pr["merged_at"]:
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
elif pr["state"] == "open":
facts.open_heads[pr["head"]["ref"]] = pr["number"]
for branch in _pages(http, headers, f"{base}/branches?protected=true"):
for branch in _pages(
http, headers, f"{base}/branches?protected=true", deadline
):
facts.protected.add(branch["name"])
except (HttpError, ValueError, KeyError, TypeError) as exc:
facts.unavailable = f"GitHub API failed for {owner}/{name}: {exc}"
return facts
return ForgeFacts(
unavailable=f"GitHub API failed for {owner}/{name}: {exc}"
)
return facts
+93
View File
@@ -0,0 +1,93 @@
from __future__ import annotations
import os
from pkgmgr.core.git import GitRunError, run
HELD_FILES = (
("rebase-merge/head-name", "rebase in progress"),
("rebase-merge/update-refs", "rebase in progress"),
("rebase-apply/head-name", "rebase in progress"),
("BISECT_START", "bisect in progress"),
)
def _git(args: list[str], cwd: str) -> str:
return run(args, cwd=cwd, scan=True)
def _common_dir(cwd: str) -> str:
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
return dict(line.split("\x00", 1) for line in out.splitlines())
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
heads: dict[str, str] = {}
for git_dir in git_dirs:
try:
target = _git(
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
)
except GitRunError as exc:
if exc.returncode == 1:
continue
raise
if target.startswith("refs/heads/"):
heads.setdefault(
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
)
return heads
def _git_dirs(repo_root: str) -> list[str]:
common = _common_dir(repo_root)
base = os.path.join(common, "worktrees")
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
return [common, *(os.path.join(base, entry) for entry in entries)]
def _held_branches(repo_root: str) -> dict[str, str]:
git_dirs = _git_dirs(repo_root)
held: dict[str, str] = {}
_symref_holds(repo_root, git_dirs, held)
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
held.setdefault(branch, reason)
for git_dir in git_dirs:
_state_file_holds(git_dir, held)
return held
def _symref_holds(repo_root: str, git_dirs: list[str], held: dict[str, str]) -> None:
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
for git_dir in git_dirs[1:]:
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
for ref, target in symrefs.items():
if target and ref.startswith("refs/heads/"):
held.setdefault(
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
)
if target.startswith("refs/heads/"):
held.setdefault(
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
)
def _state_file_holds(git_dir: str, held: dict[str, str]) -> None:
for name, operation in HELD_FILES:
try:
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
continue
for line in lines:
ref = line.strip().removeprefix("ref: ")
if ref.startswith("refs/heads/") or name == "BISECT_START":
held.setdefault(
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
)
+4
View File
@@ -0,0 +1,4 @@
from .levels import LEVELS
from .plan import RiskRequest, risk_cleanup
__all__ = ["LEVELS", "RiskRequest", "risk_cleanup"]
+204
View File
@@ -0,0 +1,204 @@
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, now: float) -> str:
"""
Args:
entry: a low image, build-cache or container item of the plan.
now: as docker_items takes it.
Returns:
done, or skipped with the reason: an item that docker no longer
lists as low right before its delete, or a kind that is never low.
Raises:
subprocess.CalledProcessError: when docker refuses the delete.
RuntimeError: when docker cannot be read again before the delete.
"""
name = entry["name"]
fresh, warnings = docker_items(now)
if warnings:
raise RuntimeError(f"revalidation failed: {'; '.join(warnings)}")
if not any(
i["kind"] == entry["kind"] and i["name"] == name and i["risk"] == LOW
for i in fresh
):
return "skipped: changed since plan"
if entry["kind"] == "image":
_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"
+174
View File
@@ -0,0 +1,174 @@
from __future__ import annotations
from dataclasses import replace
from pkgmgr.actions.branch.gc import (
FORGE_UNAVAILABLE,
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")
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
+36
View File
@@ -0,0 +1,36 @@
from __future__ import annotations
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
LEVELS = (LOW, MEDIUM, HIGH)
DAY_S = 86400
IDLE_DAYS = 7
TMP_AGE_S = DAY_S
def rank(level: str) -> int:
return LEVELS.index(level)
def item(kind: str, name: str, risk: str, reason: str, **facts: object) -> dict:
"""
Args:
kind: worktree, branch, stale, image, build-cache, container, volume or tmp.
name: what the item deletes: a path, branch, docker id or volume name.
risk: one of LEVELS.
reason: why the item has that risk.
facts: kind-specific fields; size_bytes is read by the totals.
Returns:
One plan item; result stays None until an apply sets it.
"""
return {
"kind": kind,
"name": name,
"risk": risk,
"reason": reason,
"size_bytes": None,
**facts,
"result": None,
}
+212
View File
@@ -0,0 +1,212 @@
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_file: str | None,
now: float,
) -> str:
try:
if entry["kind"] in DOCKER_KINDS:
return delete_docker(entry, now)
if entry["kind"] == "tmp":
return delete_tmp(
entry, read_owners(owners_file), 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_file: str | None, 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_file, 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, request.owners_file, now)
return _report(request, host_ns, now, entries, [*git_warnings, *host_warnings])
+179
View File
@@ -0,0 +1,179 @@
from __future__ import annotations
import json
import os
import re
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")
MOUNTINFO = "/proc/self/mountinfo"
OCTAL = re.compile(r"\\([0-7]{3})")
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 _mount_hold(path: str) -> tuple[str, str] | None:
try:
with open(MOUNTINFO, encoding="utf-8", errors="surrogateescape") as fh:
points = [OCTAL.sub(_char, line.split()[4]) for line in fh]
except (OSError, IndexError):
return MEDIUM, "mount table unreadable"
if any(p == path or p.startswith(path + os.sep) for p in points):
return MEDIUM, "is or holds a mount point"
return None
def _char(match: re.Match) -> str:
return chr(int(match.group(1), 8))
def _contents(path: str, stats: TreeStats, cwds: dict) -> tuple[str, str] | None:
if stats.foreign_entries or stats.unreadable:
return MEDIUM, "holds foreign or unreadable entries"
busy = _busy(cwds, path)
return (MEDIUM, busy) if busy else None
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}"
mounted = _mount_hold(path)
if mounted:
return mounted
return _contents(path, stats, cwds) if stats is not None else 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"
+12
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from pkgmgr.core.git import run
from pkgmgr.core.git.commands import (
fetch,
pull_ff_only,
@@ -14,7 +15,18 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
Always run a pull BEFORE modifying anything.
Uses --ff-only to avoid creating merge commits automatically.
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()
if not upstream:
print("[INFO] No upstream configured for current branch. Skipping pull.")
+2 -1
View File
@@ -6,7 +6,7 @@ from .config import handle_config
from .make import handle_make
from .mirror import handle_mirror_command
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 .review import handle_review
from .tools import handle_tools_command
@@ -29,4 +29,5 @@ __all__ = [
"handle_tools_command",
"handle_version",
"handle_worktree",
"release_at_cwd",
]
+35
View File
@@ -7,12 +7,47 @@ from typing import Any
from pkgmgr.actions.publish import publish as run_publish
from pkgmgr.actions.release import release as run_release
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.identifier import get_repo_identifier
from pkgmgr.core.repository.selected import has_explicit_selection
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(
args,
ctx: CLIContext,
+23
View File
@@ -3,9 +3,11 @@ from __future__ import annotations
import json
import os
import sys
import tempfile
from pkgmgr.actions.branch.gc import main_repo_root
from pkgmgr.actions.gc.report import disk_report, render_text
from pkgmgr.actions.gc.risk import RiskRequest, risk_cleanup
from pkgmgr.actions.worktree.flow_actions import (
worktree_flow_clear,
worktree_flow_set,
@@ -118,7 +120,28 @@ def handle_worktree(args, ctx: CLIContext) -> None:
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:
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:
run_cleanup(args, ctx, "all")
if args.apply:
+4 -14
View File
@@ -14,27 +14,17 @@ from pkgmgr.cli.commands import (
handle_make,
handle_mirror_command,
handle_publish,
handle_release,
handle_repos_command,
handle_review,
handle_tools_command,
handle_version,
handle_worktree,
release_at_cwd,
)
from pkgmgr.cli.context import CLIContext
from pkgmgr.cli.proxy import maybe_handle_proxy
from pkgmgr.core.repository.dir import get_repo_dir
from pkgmgr.core.repository.selected import get_selected_repos
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", "")
)
from pkgmgr.core.repository.selected import get_selected_repos, has_explicit_selection
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:
selected = (
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:
@@ -143,7 +133,7 @@ def dispatch_command(args, ctx: CLIContext) -> None:
return
if args.command == "release":
handle_release(args, ctx, selected)
release_at_cwd(args, ctx, selected)
return
if args.command == "publish":
+30
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
import argparse
from pkgmgr.actions.gc.risk.levels import LEVELS
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
@@ -16,6 +18,11 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
add_apply_options(gc)
add_scan_options(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(
"--report",
action="store_true",
@@ -44,3 +51,26 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
action="store_true",
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
from __future__ import annotations
import http.client
import json
import ssl
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Any
from .errors import HttpError
ALLOWED_SCHEMES = frozenset({"http", "https"})
@dataclass(frozen=True)
class HttpResponse:
@@ -31,6 +35,11 @@ class HttpClient:
headers: dict[str, str] | None = None,
payload: dict[str, Any] | None = None,
) -> HttpResponse:
scheme = urllib.parse.urlsplit(url).scheme
if scheme not in ALLOWED_SCHEMES:
raise HttpError(
status=0, message=f"unsupported URL scheme {scheme!r}", body=""
)
data: bytes | None = None
final_headers: dict[str, str] = dict(headers or {})
@@ -41,7 +50,9 @@ class HttpClient:
req = urllib.request.Request(url=url, data=data, method=method.upper())
for k, v in final_headers.items():
req.add_header(k, v)
return self._send(req)
def _send(self, req: urllib.request.Request) -> HttpResponse:
try:
with urllib.request.urlopen(
req,
@@ -49,21 +60,32 @@ class HttpClient:
context=ssl.create_default_context(),
) as resp:
raw = resp.read().decode("utf-8", errors="replace")
parsed: dict[str, Any] | None = None
if raw:
try:
loaded = json.loads(raw)
parsed = loaded if isinstance(loaded, dict) else None
except json.JSONDecodeError:
parsed = None
return HttpResponse(status=int(resp.status), text=raw, json=parsed)
return HttpResponse(
status=int(resp.status), text=raw, json=_json_object(raw)
)
except urllib.error.HTTPError as exc:
try:
body = exc.read().decode("utf-8", errors="replace")
except (OSError, ValueError):
body = ""
raise HttpError(status=int(exc.code), message=str(exc), body=body) from exc
except urllib.error.URLError as exc:
raise HttpError(status=0, message=str(exc), body="") from exc
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
def _json_object(raw: str) -> dict[str, Any] | None:
if not raw:
return None
try:
loaded = json.loads(raw)
except json.JSONDecodeError:
return None
return loaded if isinstance(loaded, dict) else None
def _error_body(exc: urllib.error.HTTPError) -> str:
try:
return exc.read().decode("utf-8", errors="replace")
except http.client.IncompleteRead as truncated:
return truncated.partial.decode("utf-8", errors="replace")
except (OSError, ValueError):
return ""
+19
View File
@@ -136,6 +136,25 @@ def _maybe_filter_ignored(args, repos: list[Repository]) -> list[Repository]:
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]:
"""
Compute the list of repositories selected by CLI arguments.
@@ -13,7 +13,7 @@ from contextlib import contextmanager, redirect_stderr, redirect_stdout
from types import SimpleNamespace
from unittest.mock import patch
from pkgmgr.actions.branch import gc, gc_forge, tree
from pkgmgr.actions.branch import gc, gc_forge, held, tree
from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots
from pkgmgr.cli.parser import create_parser
from pkgmgr.core.credentials.types import NoCredentialsError
@@ -1647,7 +1647,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
def test_failed_head_read_refuses_the_repository(self) -> None:
heads = self._refs(self.repo, "refs/heads")
real = gc._git
real = held._git
def timed_out(args: list[str], cwd: str) -> str:
if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]:
@@ -1656,7 +1656,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
raise err
return real(args, cwd)
with patch.object(gc, "_git", side_effect=timed_out):
with patch.object(held, "_git", side_effect=timed_out):
run = self._cleanup("local", apply=True)
self.assertEqual(run.code, 2)
+5 -220
View File
@@ -4,36 +4,16 @@ import io
import json
import os
import subprocess
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from contextlib import redirect_stdout
from types import SimpleNamespace
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.cli.commands.branch import handle_branch
from pkgmgr.cli.parser import create_parser
from pkgmgr.core.credentials.types import NoCredentialsError
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()
from tests.support.git_sandbox import git, isolated_root, origin_and_repo
def docker_available() -> bool:
@@ -46,24 +26,8 @@ def docker_available() -> bool:
class GcFixture:
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.root = os.path.realpath(self._tmp.name)
self.addCleanup(os.chdir, os.getcwd())
os.chdir(self.root)
home = os.path.join(self.root, "home")
os.makedirs(home)
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.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("init")
git(self.repo, "push", "-u", "origin", "main")
self.root = isolated_root(self, {})
self.origin, self.repo = origin_and_repo(self.root)
self._branch_with_commit("merged")
git(self.repo, "merge", "--no-ff", "-m", "merge merged", "merged")
@@ -153,185 +117,6 @@ class GcFixture:
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:
plan = self._plan(host_ns=True, cwds={})
item = self._items(plan)["merged"]
@@ -1,10 +1,21 @@
from __future__ import annotations
import io
import os
import shutil
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from types import SimpleNamespace
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):
def _ctx(self) -> SimpleNamespace:
@@ -65,5 +76,90 @@ class TestIntegrationReleasePublishHook(unittest.TestCase):
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__":
unittest.main()
View File
Whitespace-only changes.
+81
View File
@@ -0,0 +1,81 @@
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 origin_and_repo(root: str) -> tuple[str, str]:
"""
Args:
root: the directory that holds both repositories.
Returns:
The paths of the bare `origin.git` and of `repo`, whose `main`
tracks origin and carries one pushed commit adding `init.txt`.
"""
origin = os.path.join(root, "origin.git")
repo = os.path.join(root, "repo")
git(root, "init", "--bare", "-b", "main", origin)
git(root, "init", "-b", "main", repo)
git(repo, "remote", "add", "origin", origin)
with open(os.path.join(repo, "init.txt"), "w") as fh:
fh.write("init")
git(repo, "add", "init.txt")
git(repo, "commit", "-m", "init")
git(repo, "push", "-u", "origin", "main")
return origin, repo
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
@@ -0,0 +1,146 @@
from __future__ import annotations
import io
import json
import os
import shutil
import unittest
from contextlib import ExitStack, redirect_stderr, redirect_stdout
from unittest.mock import patch
from pkgmgr.actions.branch import gc
from pkgmgr.core.git import run
from tests.support.git_sandbox import AUTHOR, isolated_root
MERGED = 12
REGISTRATIONS = 40
@unittest.skipUnless(shutil.which("git"), "git builds the repository under test")
class TestHeldBranchesReadOnce(unittest.TestCase):
def setUp(self) -> None:
self.root = isolated_root(self, AUTHOR)
self.repo = os.path.join(self.root, "repo")
self._shape()
def git(self, *args: str) -> str:
return run(["-c", "commit.gpgsign=false", *args], cwd=self.repo)
def _write(self, path: str, text: str) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
def _shape(self) -> None:
origin = os.path.join(self.root, "origin.git")
run(["init", "-q", "--bare", "-b", "main", origin], cwd=self.root)
run(["init", "-q", "-b", "main", self.repo], cwd=self.root)
self.git("remote", "add", "origin", origin)
self._write(os.path.join(self.repo, "c1"), "c1")
self.git("add", "c1")
self.git("commit", "-q", "-m", "c1")
self.git("checkout", "-q", "-b", "side")
self._write(os.path.join(self.repo, "f1"), "f1")
self.git("add", "f1")
self.git("commit", "-q", "-m", "f1")
f1 = self.git("rev-parse", "HEAD")
self.git("checkout", "-q", "main")
self.git("merge", "-q", "--no-ff", "-m", "m1", "side")
self.git("branch", "-q", "-D", "side")
self.git("push", "-q", "origin", "main")
self.git("fetch", "-q", "origin")
self.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
for index in range(MERGED):
self.git("branch", f"merged-{index:03d}", f1)
self.git("symbolic-ref", "refs/heads/alias", "refs/heads/merged-001")
base = os.path.join(self.repo, ".git", "worktrees")
for index in range(REGISTRATIONS):
reg = os.path.join(base, f"wt{index:03d}")
head = "ref: refs/heads/merged-002\n" if index == 7 else f"{f1}\n"
self._write(os.path.join(reg, "HEAD"), head)
self._write(os.path.join(reg, "commondir"), "../..\n")
self._write(
os.path.join(reg, "gitdir"), f"{self.root}/gone/wt{index:03d}/.git\n"
)
self._write(
os.path.join(base, "wt011", "rebase-merge", "head-name"),
"refs/heads/merged-003\n",
)
self._write(os.path.join(self.repo, ".git", "BISECT_START"), "merged-004\n")
def _run(self, *, cached: bool, apply: bool) -> tuple[dict, int]:
out = io.StringIO()
with ExitStack() as stack:
held = stack.enter_context(
patch.object(gc, "_held_branches", wraps=gc._held_branches)
)
if not cached:
stack.enter_context(
patch.object(gc, "cache", side_effect=lambda func: func)
)
stack.enter_context(
patch.object(gc, "host_pid_namespace", return_value=True)
)
stack.enter_context(patch.object(gc, "_process_cwds", return_value={}))
stack.enter_context(redirect_stdout(out))
stack.enter_context(redirect_stderr(io.StringIO()))
code = gc.cleanup(
[self.repo],
scope="local",
apply=apply,
as_json=True,
include=[],
exclude=[],
merged_into=[],
sizes=False,
min_age=None,
hooks={},
)
self.assertEqual(code, 0)
return json.loads(out.getvalue()), held.call_count
def _items(self, plan: dict) -> dict:
return {i["branch"]: i for i in plan["repos"][0]["items"]}
def test_one_read_gives_the_plan_of_one_read_per_branch(self) -> None:
per_branch, old_reads = self._run(cached=False, apply=False)
once, new_reads = self._run(cached=True, apply=False)
self.assertEqual(once, per_branch)
self.assertEqual(new_reads, 1)
self.assertGreaterEqual(old_reads, MERGED - 1)
items = self._items(once)
self.assertIn("symbolic ref", items["alias"]["skip"])
self.assertIn("target of symbolic ref", items["merged-001"]["skip"])
self.assertIn("checked out in", items["merged-002"]["skip"])
self.assertIn("rebase in progress", items["merged-003"]["skip"])
self.assertIn("bisect in progress", items["merged-004"]["skip"])
deletable = sorted(n for n, i in items.items() if i["actions"])
free = [0, *range(5, MERGED)]
self.assertEqual(deletable, [f"merged-{i:03d}" for i in free])
def test_branch_held_after_the_plan_is_not_deleted(self) -> None:
rebuilt: list[str] = []
rebuild = gc._rebuild
def pin_before_first_recheck(*args: object) -> object:
if not rebuilt:
rebuilt.append(
self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005")
)
return rebuild(*args)
with patch.object(gc, "_rebuild", side_effect=pin_before_first_recheck):
plan, reads = self._run(cached=True, apply=True)
items = self._items(plan)
self.assertGreater(reads, 1)
self.assertEqual(
items["merged-005"]["result"],
"skipped: changed since plan (target of symbolic ref refs/tags/pin)",
)
self.assertIn("merged-005", self.git("for-each-ref", "refs/heads"))
if __name__ == "__main__":
unittest.main()
@@ -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,270 @@
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, origin_and_repo
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, self.repo = origin_and_repo(self.root)
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,224 @@
from __future__ import annotations
import json
import os
import unittest
from unittest.mock import patch
from pkgmgr.actions.gc.risk import git_items, plan, tmp_items
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
BARE_CONTAINER,
DANGLING_ID,
OLD_CACHE,
RiskPlanFixture,
write,
)
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"]))
def _after_plan(self, change) -> tuple[int, dict]:
real_apply = plan._apply
def change_then_apply(*args):
change()
return real_apply(*args)
with patch.object(plan, "_apply", side_effect=change_then_apply):
code, printed, _ = self.run_gc(level="low", apply=True)
return code, printed
def test_owner_status_changed_after_plan_keeps_the_scratch(self) -> None:
running = json.dumps({self.t["old-stopped"]: "running"})
code, printed = self._after_plan(lambda: write(self.owners, running))
stopped = self.entry(printed, self.t["old-stopped"])
self.assertEqual(code, 0)
self.assertEqual(
stopped["result"], "skipped: changed since plan (owner task is running)"
)
self.assertTrue(os.path.isdir(self.t["old-stopped"]))
def test_owner_file_gone_after_plan_fails_and_keeps_the_scratch(self) -> None:
code, printed = self._after_plan(lambda: os.unlink(self.owners))
self.assertEqual(code, 1)
for name in ("old-stopped", "old-done.log"):
self.assertTrue(
self.entry(printed, self.t[name])["result"].startswith("failed:"), name
)
self.assertTrue(os.path.lexists(self.t[name]), name)
def test_docker_items_no_longer_low_after_plan_are_kept(self) -> None:
def nothing_low() -> None:
df = json.loads(self.docker.df)
for row in df["Containers"]:
row["LocalVolumes"] = "1"
for row in df["BuildCache"]:
row["InUse"] = "true"
self.docker.df = json.dumps(df)
self.docker.calls.clear()
code, printed = self._after_plan(nothing_low)
changed = {
e["name"]: e["result"]
for e in printed["items"]
if e["kind"] in ("build-cache", "container")
}
self.assertEqual(code, 0)
self.assertEqual(
changed,
dict.fromkeys((OLD_CACHE, BARE_CONTAINER), "skipped: changed since plan"),
)
self.assertEqual(self.docker.writes(), [["image", "rm", DANGLING_ID]])
def test_docker_unreadable_after_plan_fails_and_deletes_nothing(self) -> None:
def docker_gone() -> None:
self.docker.df = "not json"
self.docker.calls.clear()
code, printed = self._after_plan(docker_gone)
results = [
e["result"]
for e in printed["items"]
if e["kind"] in ("image", "build-cache", "container")
]
self.assertEqual(code, 1)
self.assertTrue(results)
for result in results:
self.assertTrue(result.startswith("failed: revalidation failed"), result)
self.assertEqual(self.docker.writes(), [])
def test_non_utf8_mount_elsewhere_keeps_the_plan_working(self) -> None:
table = os.path.join(self.root, "mountinfo")
with open(table, "wb") as fh:
fh.write(b"36 35 98:0 / /mnt/\xff rw - ext4 /dev/x rw\n")
with patch.object(tmp_items, "MOUNTINFO", table):
code, printed, _ = self.run_gc(level="low")
self.assertEqual(code, 0)
self.assertEqual(self.risks(printed).get(self.t["old-stopped"]), "low")
def test_mount_at_or_below_scratch_is_never_low(self) -> None:
stopped = self.t["old-stopped"]
table = os.path.join(self.root, "mountinfo")
for point in (stopped, os.path.join(stopped, "deep"), None):
with self.subTest(point=point):
if point is None:
table_path = os.path.join(self.root, "absent")
else:
escaped = point.replace(" ", "\\040")
write(table, f"36 35 98:0 / {escaped} rw - ext4 /dev/x rw\n")
table_path = table
with patch.object(tmp_items, "MOUNTINFO", table_path):
code, printed, _ = self.run_gc(level="low", apply=True)
self.assertEqual(code, 0)
self.assertNotIn(stopped, self.risks(printed))
self.assertTrue(os.path.isdir(stopped))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,186 @@
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.support.git_sandbox import git
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_forge_absence_never_hides_a_worktree_hold(self) -> None:
self.forge = ForgeFacts(unavailable="no GitHub token")
git(self.repo, "worktree", "lock", "--reason", "kept", self.wt["done"])
_, printed, _ = self.run_gc(level="high")
done = self.entry(printed, self.wt["done"])
self.assertEqual((done["risk"], done["skip"]), ("medium", "lock: kept"))
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
@patch("pkgmgr.actions.release.git_ops.run", return_value="")
class TestEnsureCleanAndSynced(unittest.TestCase):
@patch("pkgmgr.actions.release.git_ops.pull_ff_only")
@patch("pkgmgr.actions.release.git_ops.fetch")
@@ -15,6 +16,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
_mock_run,
) -> None:
mock_get_upstream_ref.return_value = None
@@ -31,6 +33,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
_mock_run,
) -> None:
mock_get_upstream_ref.return_value = "origin/main"
@@ -53,6 +56,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
_mock_run,
) -> None:
mock_get_upstream_ref.return_value = "origin/main"
@@ -66,3 +70,30 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
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()