Compare commits

...
59 Commits
Author SHA1 Message Date
Kevin Veen-Birkenbach 67e110ff92 Release version 2.6.0
Mark stable commit / mark-stable (push) Canceled after 0s
Scorecard supply-chain security / Scorecard analysis (push) Canceled after 0s
2026-12-02 12:08:23 +00:00
Kevin Veen-Birkenbach 11d32c36b6 Merge pull request #24 from kevinveenbirkenbach/fix/scorecard-pins-permissions
fix(ci): pin GitHub actions by SHA, restrict token, add security policy
2026-12-02 12:07:04 +01:00
Kevin Veen-BirkenbachandClaude Opus 5.5 0a98f35492 fix(ci): pin GitHub actions by SHA, restrict token, add security policy
Resolves the open OpenSSF Scorecard code-scanning alerts that a change in this repository can fix:

- PinnedDependencies: every GitHub-owned action is pinned by commit SHA (actions/checkout v7.0.1, github/codeql-action init, analyze and upload-sarif v4.39.5); scorecard.yml carried checkout v7.0.0 under a wrong v4.2.2 comment. Dependabot keeps the pins current.
- TokenPermissions: mark-stable, publish-containers and security-codeql get a top-level contents: read; every job there already declares its own permissions, so no job token changes.
- SecurityPolicy: .github/SECURITY.md with private reporting via GitHub advisories.

Left open on purpose: the job-level write permissions those jobs need, the Dockerfile FROM ${BASE_IMAGE} that scripts/build/base.sh resolves per distro, and the repository-setting checks.

| Fix | Break | Tokens | Velocity | Security | Score |
| --- | --- | --- | --- | --- | --- |
| 93 % | 3 % | 100 % | 100 % | 100 % | 90 |

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:45:19 +00:00
Kevin Veen-Birkenbach 966892f648 Merge pull request #23 from kevinveenbirkenbach/dependabot/github_actions/github-actions-e71a23264e
build(deps): bump the github-actions group with 3 updates
2026-12-02 11:32:22 +01:00
Kevin Veen-Birkenbach 9e01b0fccd Merge pull request #21 from kevinveenbirkenbach/feature/gc-risk-levels
feat(gc): plan deterministic cleanups by risk level and owner
2026-12-02 00:59:33 +01:00
Kevin Veen-BirkenbachandClaude Opus 5.5 236649cbdf fix(gc): fail docker deletes on revalidation errors and read the mount table byte-safe
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / quality (push) Skipped
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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-Birkenbach 42d3d9aa6d Merge pull request #18 from kevinveenbirkenbach/fix/push-trusted-gitdir
fix(push): sign and push from a private bare repository
2026-12-01 10:21:53 +01:00
Kevin Veen-Birkenbach 828d7885d1 Merge pull request #19 from kevinveenbirkenbach/feature/release-expect-tree
feat(release): refuse a release whose HEAD tree is not the audited one
2026-12-01 09:58:17 +01:00
dependabot[bot] 2753076312 build(deps): bump the github-actions group with 3 updates
Bumps the github-actions group with 3 updates: [infinito-nexus/quality/.github/workflows/quality.yml](https://github.com/infinito-nexus/quality), [infinito-nexus/quality/.github/workflows/tool.yml](https://github.com/infinito-nexus/quality) and [ossf/scorecard-action](https://github.com/ossf/scorecard-action).


Updates `infinito-nexus/quality/.github/workflows/quality.yml` from 1.0.0 to 1.2.0
- [Release notes](https://github.com/infinito-nexus/quality/releases)
- [Changelog](https://github.com/infinito-nexus/quality/blob/main/CHANGELOG.md)
- [Commits](https://github.com/infinito-nexus/quality/compare/53d7dfae01de1746e091706f1c817ff3dd7bd257...2eaac6f644eb4c47102bd8cc353635c71af5dab9)

Updates `infinito-nexus/quality/.github/workflows/tool.yml` from 1.0.0 to 1.2.0
- [Release notes](https://github.com/infinito-nexus/quality/releases)
- [Changelog](https://github.com/infinito-nexus/quality/blob/main/CHANGELOG.md)
- [Commits](https://github.com/infinito-nexus/quality/compare/53d7dfae01de1746e091706f1c817ff3dd7bd257...2eaac6f644eb4c47102bd8cc353635c71af5dab9)

Updates `ossf/scorecard-action` from 2.5.0 to 2.6.0
- [Release notes](https://github.com/ossf/scorecard-action/releases)
- [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md)
- [Commits](https://github.com/ossf/scorecard-action/compare/fa7117db83c52d787ae5a89f350999701505d78e...23f22cd43608bae7a1f1fa2603d7314dee9538a5)

---
updated-dependencies:
- dependency-name: infinito-nexus/quality/.github/workflows/quality.yml
  dependency-version: 1.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: infinito-nexus/quality/.github/workflows/tool.yml
  dependency-version: 1.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: ossf/scorecard-action
  dependency-version: 2.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 08:46:43 +00:00
Kevin Veen-Birkenbach 6ba77c4f58 Merge pull request #17 from kevinveenbirkenbach/chore/repository-bot-baseline
chore(github): add the repository bot baseline
2026-12-01 08:40:29 +01:00
Kevin Veen-Birkenbach c0b8be2bff Merge pull request #20 from kevinveenbirkenbach/chore/test-scripts-no-inline
chore(test): run the container test bodies from files instead of inline bash
2026-12-01 08:09:28 +01:00
Kevin Veen-Birkenbach a73f4b5645 Merge pull request #22 from kevinveenbirkenbach/fix/codeql-alerts
fix(security): close the 32 open CodeQL alerts
2026-12-01 07:50:35 +01:00
Kevin Veen-BirkenbachandClaude Opus 5.5 db7532f9b4 fix(push): redact URL credentials and close the review findings of PR 18
quality clean.default-value: trusted_repo passes --object-format only when the checkout sets extensions.objectFormat; _old_tip refuses an unsigned HEAD only when HEAD is in the pushed range, without a .get fallback. CodeRabbit: _config_all reads git config -z --get-all and splits on NUL, so one pushurl value with a newline stays one value and url_allowed rejects it; file_url uses Path.as_uri; redact_urls replaces URL userinfo with *** in the GitRunError text of _tgit_run and in every push.py refusal, failure, preview and status line while the argv given to git is unchanged; fetch_heads splits ls-remote records at the TAB; _track sets and reads the upstream of the validated branch. Tests: the mirror fixture drops GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE, the planted-after-check test asserts the second check ran, and test_push_trusted_review.py covers each fix.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/push-trusted-gitdir | 5 files +173/-22 | 90 % | 5 % | – | – | 100 % | 86 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration with PYTHONPATH=src 860 passed; the 33 fake-SSH push fixture tests fail identically on the previous HEAD in the agent sandbox and pass in PR CI, so PR CI is the proof for the push paths; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0. Hub review f31edb8114253cb6.

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

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:34:02 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 208a8c3ace refactor(release): bundle the options and refuse untracked release inputs
quality, 7 findings: _release_impl and release take one frozen ReleaseOptions (new options.py, exported from pkgmgr.actions.release) and split into small private helpers with a frozen _Prepared carrier; the three _release_impl call paths become one plus dataclasses.replace(preview=True) for the interactive preview. cli/commands/release.py and cli/parser/release_cmd.py split into helpers with arguments in the same order, so the CLI surface is unchanged; test_workflow.py uses one with-block instead of five patch decorators. CodeRabbit: with --expect-tree an existing but untracked release input (pyproject, CHANGELOG.md, flake.nix, PKGBUILD, spec, debian/changelog, Cargo files) aborts before any write; the README says the abort comes before any release file is written and the pull is not reverted.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| feature/release-expect-tree | 13 files +457/-342 | 91 % | 4 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration with PYTHONPATH=src 886 passed; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0. Hub review e12f7e62ce35b6f5.

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

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:33:49 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 cee58bcef1 refactor(gc): split the risk plan to clear quality and review findings
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 / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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 4cb00eec18 chore(test): fold the container scripts to clear the quality findings
quality clean.prefix-groups: env-nix.sh and env-virtual.sh move to scripts/test/container/env/nix.sh and env/virtual.sh; their only callers, scripts/test/test-env-nix.sh and test-env-virtual.sh, are updated. clean.clones: the shared git safe.directory block of e2e.sh and env-nix.sh is one script, scripts/test/container/safe-directory.sh, called at the same spot. clean.comment: parameter lines use the form # Param: NAME ($n) - text. coding.shell-lint SC1091: quality runs shellcheck without -x, so the source directives are shellcheck source=/dev/null like the sibling scripts; the sourcing logic is unchanged.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| chore/test-scripts-no-inline | 7 files +17/-17 | 92 % | 3 % | – | – | 100 % | 89 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: quality check --staged 0 findings, shellcheck --norc clean on all 7 scripts, MEDUSA 100 %, critical 0. The container jobs of PR CI are the proof. Hub review 42b3a76554491026.

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

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:57:43 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 63cd42e273 chore(ci): rename the scorecard workflow and drop the no-op docker updater
quality clean.prefix-groups on .github/workflows: security-scorecard.yml formed a 2-file security-* group with security-codeql.yml; GitHub reads workflows only flat from .github/workflows, so the file is renamed to scorecard.yml (nothing references the old name). CodeRabbit on dependabot.yml: the Dockerfile builds FROM ${BASE_IMAGE} and scripts/build/base.sh follows the base-images latest tags by design, so the docker updater could never propose anything; it is removed, pip and github-actions stay.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| chore/repository-bot-baseline | 2 files +0/-11 | 92 % | 2 % | – | – | 100 % | 90 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: quality check --staged 0 findings, actionlint clean, MEDUSA 100 %, critical 0. Hub review 2a607fb88c18b207.

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

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:57:37 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 52f0d804f6 fix(codeql): clear quality, Codacy and CodeRabbit findings of PR 22
quality clean.clones in test_editor.py: one _edit helper returns what the editor was handed and the kept entry; _buffer reuses it. Codacy D205/D415 vs quality clean.comment on secret_service_token: its only caller is _forge_access, so it becomes private _secret_service_token without a docstring, as in PR 14. CodeRabbit: select_autoescape matches the full suffix and the renderer passes names ending in .j2, so html.j2, htm.j2 and xml.j2 are enabled; new test renders them escaped and README.md.j2 raw.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/codeql-alerts | 4 files +58/-27 | 93 % | 2 % | – | – | 100 % | 91 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration with PYTHONPATH=src 881 passed; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0. Hub review 41be5d7a0b4eec30.

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

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:57:30 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 0f6583ca48 fix(security): close the 32 open CodeQL alerts
Critical #60/#61 untrusted checkout: publish-containers.yml prepare runs for workflow_run only when the triggering run succeeded, was a push and came from this repository; build and merge need prepare, so the guard covers both checkouts. Mark stable commit triggers only on push of v* tags, schedule and workflow_dispatch are unchanged. Medium #55/#56: update-flake-lock.yml pins nix-installer-action v23 and update-flake-lock v29 to commit SHAs. High: secret_service_token returns only the token and raises SecretServiceUnavailable with the same reasons, _forge_access builds the token/reason pair (#62); jinja2 select_autoescape for html/htm/xml only, scaffolding output byte-identical (#29); chmod 0o755 to 0o700 for owner-run scripts in ink.py and 7 test sites; exact URL equality in a mirror probe test. Error #33: raise unittest.SkipTest from exc. Notes: empty-except to contextlib.suppress, one import form per module, unused variable, commented-out code, assertNotIn.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/codeql-alerts | 28 files +92/-81 | 90 % | 3 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration 880 passed, 574 subtests; 2 test_publish_integration failures are identical on a clone without these changes (global tag.gpgsign, sandbox blocks gpg). ruff and actionlint clean, MEDUSA 100 % critical 0 (1 accepted keyword false positive). Operator choice 7589a6f1 (swarm), operator review dcc2f461.
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:19:21 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 b8248a0253 feat(gc): plan deterministic cleanups by risk level and owner
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / 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
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (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
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-BirkenbachandClaude Opus 5.5 6c7ca613fc fix(push): sign and push from a private bare repository
pkgmgr push copies HEAD and tags into a private temporary bare repository and signs (git commit-tree -S) and pushes from there, so the checkout config, hooks, filters, merge drivers, replace refs, bundle URIs, submodule configs and allowed-signers never take part. The checkout is only read via upload-pack and updated by a fetch of the signed commit plus an update-ref guarded by the old HEAD. Push and fetch URLs must be https, ssh or user@host:path. Codacy tightened (D413, Lizard CCN 8, no new defaults, B607 via shutil.which); prose docstrings removed for quality clean.comment.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/push-trusted-gitdir | 4 files +1112/-233 | 90 % | 8 % | – | – | 100 % | 83 | ⛔ break 8 % > 5 |

Evidence: host run 86 tests OK, full unit suite 527 OK, ruff clean, lizard -C 8 clean, MEDUSA 100 % critical 0. Break 8 %: a checkout whose origin fetch URL is a local path or http:// is refused; repository-level http.* and credential.* settings and a GIT_CONFIG_GLOBAL override no longer apply to push. Operator review a41d30aa (re-card of 39022e85).
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:44:39 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 9a9ac39ad4 chore(test): run the container test bodies from files instead of inline bash
No code in code for the container tests (operator denial d8b0c6c8; operator choice 13bec2bf: swarm funnel; fits Quality req 018 clean.embedded-code). The five host scripts no longer embed an in-container script as bash -lc; each runs a file with bash -l: test-unit.sh and test-integration.sh call scripts/test/container/unittest.sh with tests/unit or tests/integration, test-e2e.sh calls container/e2e.sh, test-env-virtual.sh calls container/env-virtual.sh, test-env-nix.sh calls container/env-nix.sh with IMAGE and PKGMGR_DISTRO as arguments. Commands, order, strict-mode lines, env vars, volumes and workdir are unchanged.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| chore/test-scripts-no-inline | 9 files +116/-127 | 90 % | 4 % | – | – | 100 % | 86 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: shellcheck -x clean on all 9 files, no bash -lc block left under scripts/, MEDUSA 100 % critical 0 (2 SC1091 scanner artefacts accepted). Break 4 %: unproven until PR CI runs the containers. Operator review a493a79a (re-card of f877c5dd).
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:44:34 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 29cb898a0a feat(release): refuse a release whose HEAD tree is not the audited one
pkgmgr release --expect-tree TREE closes the window between an external audit and the fetch pkgmgr runs itself, where a push could ship an unaudited tree (Skills request, req 076). git_ops.ensure_head_tree compares git rev-parse HEAD^{tree} with the given sha and raises RuntimeError on mismatch; _release_impl calls it right after ensure_clean_and_synced and before any file write, release() with --retry before retry_release pushes anything. expect_tree is keyword-only without a default and every caller passes it. README section added; the --force help is reworded (MEDUSA EXA004 false positive on the old text).

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| feature/release-expect-tree | 9 files +120/-11 | 93 % | 2 % | – | – | 100 % | 91 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: 45 targeted tests OK (5 new expect-tree tests), full unit suite 521 OK, ruff clean, MEDUSA 100 % critical 0. Break 2 %: an external caller of release() or _release_impl() must now pass expect_tree. Operator review 91234f6d (re-card of f538413a).
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:44:29 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 235a43225b chore(github): add the repository bot baseline
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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 / test-virgin (ubuntu, user) (push) Canceled after 0s
Test Virgin / test-virgin (fedora, user) (push) Canceled after 0s
Test Virgin / test-virgin (arch, user) (push) Canceled after 0s
Test Virgin / test-virgin (arch, root) (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Canceled after 0s
Test End-To-End / test-e2e (arch) (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
Test Virgin / test-virgin (fedora, root) (push) Canceled after 0s
Test Virgin / test-virgin (debian, user) (push) Canceled after 0s
Test Virgin / test-virgin (centos, root) (push) Canceled after 0s
CI / test-virgin (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (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
Test OS Containers / test-env-virtual (fedora) (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 (arch) (push) Canceled after 0s
Test Virgin / test-virgin (ubuntu, root) (push) Canceled after 0s
Test Virgin / test-virgin (debian, root) (push) Canceled after 0s
Test Virgin / test-virgin (centos, user) (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
Quality req 014 (Main 2.0 SECURITE by operator order; Allstar dropped): CODEOWNERS with the owner for every path; dependabot.yml with pip security updates only (open-pull-requests-limit 0, one security group), github-actions and docker weekly grouped version updates, only the existing dependencies label; security-scorecard.yml standalone with pinned actions. Virgin tests without code in code (operator denial d8b0c6c8): the inline bash -lc scripts leave the workflow for scripts/test/virgin/run.sh, root.sh, user.sh and dev.sh, each called with bash -l; test-virgin.yml is one matrix job (mode x distro) whose run step only calls run.sh, matrix values reach the shell through env. test-virgin-user.yml and test-virgin-root.yml are removed, the workflow folder stays at 15 files.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| chore/repository-bot-baseline | 11 files +168/-138 | 90 % | 4 % | – | – | 100 % | 86 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: shellcheck -x clean on the four scripts, actionlint clean on test-virgin.yml, ci.yml and security-scorecard.yml, yamllint clean on dependabot.yml, MEDUSA 100 % critical 0. Break 4 %: virgin rework unproven until PR CI; check names become test-virgin / test-virgin (mode, distro). Operator review 7bed4c46 (re-card of fa241c7b).
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:43:53 +00:00
Kevin Veen-Birkenbach f529139db5 Merge pull request #16 from kevinveenbirkenbach/dependabot/github_actions/infinito-nexus/quality/dot-github/workflows/tool.yml-1.0.0
build(deps): bump infinito-nexus/quality/.github/workflows/tool.yml from 0.2.0 to 1.0.0
2026-11-30 20:11:16 +01:00
Kevin Veen-Birkenbach ed02ad5c02 Merge pull request #15 from kevinveenbirkenbach/dependabot/github_actions/infinito-nexus/quality/dot-github/workflows/quality.yml-1.0.0
build(deps): bump infinito-nexus/quality/.github/workflows/quality.yml from 0.2.0 to 1.0.0
2026-11-30 20:11:13 +01:00
dependabot[bot] db7dc34474 build(deps): bump infinito-nexus/quality/.github/workflows/tool.yml
Bumps [infinito-nexus/quality/.github/workflows/tool.yml](https://github.com/infinito-nexus/quality) from 0.2.0 to 1.0.0.
- [Release notes](https://github.com/infinito-nexus/quality/releases)
- [Changelog](https://github.com/infinito-nexus/quality/blob/main/CHANGELOG.md)
- [Commits](https://github.com/infinito-nexus/quality/compare/003eed66dd51592c3312a7c21ae429abead54d6f...53d7dfae01de1746e091706f1c817ff3dd7bd257)

---
updated-dependencies:
- dependency-name: infinito-nexus/quality/.github/workflows/tool.yml
  dependency-version: 1.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-30 00:41:40 +00:00
dependabot[bot] 832b03c77c build(deps): bump infinito-nexus/quality/.github/workflows/quality.yml
Bumps [infinito-nexus/quality/.github/workflows/quality.yml](https://github.com/infinito-nexus/quality) from 0.2.0 to 1.0.0.
- [Release notes](https://github.com/infinito-nexus/quality/releases)
- [Changelog](https://github.com/infinito-nexus/quality/blob/main/CHANGELOG.md)
- [Commits](https://github.com/infinito-nexus/quality/compare/003eed66dd51592c3312a7c21ae429abead54d6f...53d7dfae01de1746e091706f1c817ff3dd7bd257)

---
updated-dependencies:
- dependency-name: infinito-nexus/quality/.github/workflows/quality.yml
  dependency-version: 1.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-30 00:41:38 +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
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (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
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Failing 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
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / quality (push) Skipped
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (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
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Failing 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 (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 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
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Blocked by required conditions
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 (arch) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (centos) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (fedora) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (ubuntu) (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
Docker Linter / Lint Dockerfile (push) Blocked by required conditions
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-virgin-root (push) Blocked by required conditions
CI / quality (push) Skipped
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 (fedora) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (debian) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (centos) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (fedora) (push) Blocked by required conditions
Ruff (Python code sniffer) / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (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
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (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
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Failing 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
Kevin Veen-BirkenbachandClaude Opus 5.5 d9a8746635 fix(publish): build and upload with pkgmgr's interpreter in a private directory
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 / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
pkgmgr publish ran bare python, so on a PATH without build or twine it
failed even when pkgmgr's own interpreter had both. It now runs every
child with sys.executable, builds with --outdir into a fresh private
temporary directory that is also the working directory of every child,
and uploads only what that build produced: a dist symlink or leftover
artifacts in the repository can no longer reach PyPI, and no build.py or
twine.py in the repository shadows the tools under -m. Child processes
get no PKGMGR_* variable and no PYTHONPATH entry inside the repository,
and twine is pinned to the mirror host with --repository-url and
--non-interactive.

🎯 Fix: 92 %
💥 Break: 5 %
💸 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 17:18:06 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 5151b36250 fix(release): bump a setuptools dynamic attr version in its module
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
pkgmgr release skipped pyproject.toml when [project].dynamic lists version
and [tool.setuptools.dynamic] reads it from a module attribute, so a tag
could move to X.Y.Z while the wheel kept the old version. read_pyproject_version
and update_pyproject_version now resolve the attr module through
[tool.setuptools].package-dir and read or rewrite its version literal; a
module without that literal aborts the release before any file is written.

🎯 Fix: 95 %
💥 Break: 3 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 92
🚦 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 16:26:56 +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
Kevin Veen-Birkenbach 757903fdd5 Release version 2.5.0
Test Units / test-unit (push) Canceled after 0s
Test Code Integration / 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
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
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
Mark stable commit / mark-stable (push) Canceled after 0s
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (centos) (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 (ubuntu) (push) Canceled after 0s
Test Virgin User / test-virgin-user (fedora) (push) Canceled after 0s
Test Virgin User / test-virgin-user (centos) (push) Canceled after 0s
Test Virgin User / test-virgin-user (arch) (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (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 (arch) (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
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
2026-11-13 22:53:12 +00:00
Kevin Veen-Birkenbach c09e44af50 Merge branch 'feature/review-page-icons' into unify/pkgmgr-20261113 2026-11-13 16:13:36 +00:00
Kevin Veen-Birkenbach 791761a239 Merge branch 'feature/branch-cleanup-local' into unify/pkgmgr-20261113 2026-11-13 16:13:35 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 3936125633 fix(branch): cleanup --local keeps branches whose sibling upstream was deleted
A local branch whose upstream sibling was deleted on the remote counted as merged when its tip was reachable from the deleted ref's last known commit, so cleanup --local removed it although git branch -d would refuse. The plan now asks git itself for each candidate, in the same order the delete runs, and skips a branch git would not delete; the README states the rule.

🎯 Fix: 93 %
💥 Break: 3 %
💸 Cost: –
⏱️ Time: –
🛡️ Security: 100 %
🏆 Score: 90
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:10:50 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 0d88c69c51 feat(branch): cleanup --local deletes merged local branches only when git itself would
pkgmgr branch cleanup --local [--apply] [--json] [--merged-into REF]
deletes local branches whose tip is an ancestor of the remote-tracking
default or a --merged-into ref, each with update-ref against the planned
sha. It keeps every branch git branch --delete-merged keeps: symbolic,
checked out or registered in any worktree, under a rebase or bisect,
deleteMerged=false in any worktree, system or global config, and the
local upstream of any branch that stays. Git runs without inherited
GIT_* variables except the ceiling; the keep reads run once with the
caller's config variables and once with the default system and
passwd-home config, so the environment can add keeps but never remove
one. Repositories with symlinked refs, foreign worktree registrations or
unreadable holds are refused with the plan still printed.

MEDUSA: MEDUSA-OUTPUT-SQL-003 at branch_cmd.py:121 accepted after an
independent review: the SQL comment+DELETE regex matched the help text
--merged-into and the git key deleteMerged; no SQL in the change.

🎯 Fix: 92 %
💥 Break: 5 %
💸 Cost: 100 %
⏱️ Time: 100 %
🛡️ Security: 100 %
🏆 Score: 87
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:01:06 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 b0f9395c68 feat(review): icon buttons with labels for expand and collapse
The review page toolbar showed Expand all and Collapse all as text. They are now Bootstrap Icons (arrows-expand, arrows-collapse) inlined as SVG under the page's strict CSP, with title and aria-label carrying the words; the Bootstrap Icons MIT licence ships next to the template as package data. A test checks the labels, the icon classes, no visible text and no external resource.

🎯 Fix: 95 %
💥 Break: 2 %
💸 Cost: 100 %
⏱️ Time: 100 %
🛡️ Security: 100 %
🏆 Score: 93
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:48:19 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 814322f8f5 fix(branch): gc local-only merged branches without a forge token
Without a forge token every gc item was skipped before any local check. _needs_forge now decides which items still need PR and protection facts: a branch no worktree holds, without upstream or remote branch, merged into the default by ancestry is decided locally and removed without the forge. Two integration tests fail on 2.4.0 and assert the HTTP client is never called.

🎯 Fix: 92 %
💥 Break: 4 %
💸 Cost: 100 %
⏱️ Time: 100 %
🛡️ Security: 100 %
🏆 Score: 88
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:11:31 +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
121 changed files with 8288 additions and 1199 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
* @kevinveenbirkenbach
+19
View File
@@ -0,0 +1,19 @@
# Security Policy
## Supported Versions
Only the latest release receives security fixes. Fixes land on `main` and ship
with the next release; the `stable` tag and the published container images
follow the highest released version.
## Reporting a Vulnerability
Please do not report security issues in a public issue or pull request.
Report them privately through either channel:
- GitHub: [report a vulnerability](https://github.com/kevinveenbirkenbach/package-manager/security/advisories/new)
- Email: Kevin Veen-Birkenbach, [kevin@veen.world](mailto:kevin@veen.world), [veen.world](https://veen.world)
Include the affected version, the steps to reproduce, and the impact you
expect.
+9 -7
View File
@@ -5,19 +5,21 @@ updates:
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "00:00"
rebase-strategy: "auto"
open-pull-requests-limit: 0
groups:
pip-security:
applies-to: security-updates
patterns: ["*"]
labels:
- "dependencies"
- "python"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "00:00"
groups:
github-actions:
applies-to: version-updates
patterns: ["*"]
labels:
- "dependencies"
- "ci"
+8 -7
View File
@@ -46,15 +46,10 @@ jobs:
contents: read
uses: ./.github/workflows/test-e2e.yml
test-virgin-user:
test-virgin:
permissions:
contents: read
uses: ./.github/workflows/test-virgin-user.yml
test-virgin-root:
permissions:
contents: read
uses: ./.github/workflows/test-virgin-root.yml
uses: ./.github/workflows/test-virgin.yml
lint-shell:
permissions:
@@ -71,3 +66,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@2eaac6f644eb4c47102bd8cc353635c71af5dab9 # v1.2.0
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
security-events: write
steps:
- name: Checkout code
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Run hadolint (produce SARIF)
id: hadolint
@@ -29,7 +29,7 @@ jobs:
- name: Upload analysis results to GitHub
if: always()
uses: github/codeql-action/upload-sarif@v4
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
sarif_file: hadolint-results.sarif
wait-for-processing: true
+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@2eaac6f644eb4c47102bd8cc353635c71af5dab9 # v1.2.0
with:
tool: ruff
args: check src tests
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
lint-shell:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install ShellCheck
run: sudo apt-get update && sudo apt-get install -y shellcheck
- name: Run ShellCheck
+5 -1
View File
@@ -8,6 +8,10 @@ on:
push:
tags:
- 'v*'
permissions:
contents: read
jobs:
mark-stable:
runs-on: ubuntu-latest
@@ -19,7 +23,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
fetch-tags: true # We need tags and main history for version comparison
+9 -6
View File
@@ -8,9 +8,12 @@ on:
- cron: "0 3 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
prepare:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
if: ${{ github.event_name != 'workflow_run' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) }}
runs-on: ubuntu-latest
permissions:
@@ -21,7 +24,7 @@ jobs:
steps:
- name: Checkout repository (with tags)
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
@@ -54,7 +57,7 @@ jobs:
steps:
- name: Checkout ${{ matrix.release.version }}
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ matrix.release.sha }}
@@ -64,7 +67,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 }}
@@ -96,7 +99,7 @@ jobs:
steps:
- name: Checkout ${{ matrix.release.version }}
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ matrix.release.sha }}
@@ -106,7 +109,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 }}
+41
View File
@@ -0,0 +1,41 @@
name: Scorecard supply-chain security
on:
branch_protection_rule:
schedule:
- cron: '00 00 * * *'
push:
branches: [ "main" ]
concurrency:
group: scorecard-${{ github.repository }}-${{ github.ref_name }}
cancel-in-progress: true
permissions: read-all
jobs:
analysis:
name: Scorecard analysis
runs-on: ubuntu-latest
if: github.event.repository.default_branch == github.ref_name
permissions:
security-events: write
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.6.0
with:
results_file: results.sarif
results_format: sarif
publish_results: true
- name: Upload to code-scanning
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
sarif_file: results.sarif
+6 -3
View File
@@ -3,6 +3,9 @@ name: CodeQL Advanced
on:
workflow_call:
permissions:
contents: read
jobs:
analyze:
name: Check security
@@ -23,10 +26,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
@@ -42,6 +45,6 @@ jobs:
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
category: "/language:${{ matrix.language }}"
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Show Docker version
run: docker version
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Show Docker version
run: docker version
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Show commit SHA
run: git rev-parse HEAD
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Show Docker version
run: docker version
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Show Docker version
run: docker version
-56
View File
@@ -1,56 +0,0 @@
name: Test Virgin Root
on:
workflow_call:
permissions:
contents: read
jobs:
test-virgin-root:
runs-on: ubuntu-latest
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
distro: [arch, debian, ubuntu, fedora, centos]
env:
NIX_CONFIG: |
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Show Docker version
run: docker version
- name: Pull base image (${{ matrix.distro }})
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
- name: Virgin ${{ matrix.distro }} pkgmgr test (root)
run: |
set -euo pipefail
docker run --rm \
-v "$PWD":/opt/src/pkgmgr \
-v pkgmgr_repos:/root/Repositories \
-v pkgmgr_pip_cache:/root/.cache/pip \
-e NIX_CONFIG="${NIX_CONFIG}" \
-w /opt/src/pkgmgr \
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
bash -lc '
set -euo pipefail
git config --global --add safe.directory /opt/src/pkgmgr
make install
make setup
. "$HOME/.venvs/pkgmgr/bin/activate"
pkgmgr update pkgmgr --clone-mode shallow --no-verification
pkgmgr version pkgmgr
echo ">>> Running Nix-based: nix run .#pkgmgr -- version pkgmgr"
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
'
-68
View File
@@ -1,68 +0,0 @@
name: Test Virgin User
on:
workflow_call:
permissions:
contents: read
jobs:
test-virgin-user:
runs-on: ubuntu-latest
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
distro: [arch, debian, ubuntu, fedora, centos]
env:
NIX_CONFIG: |
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Show Docker version
run: docker version
- name: Pull base image (${{ matrix.distro }})
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
- name: Virgin ${{ matrix.distro }} pkgmgr test (user)
run: |
set -euo pipefail
docker run --rm \
-v "$PWD":/opt/src/pkgmgr \
-e NIX_CONFIG="${NIX_CONFIG}" \
-w /opt/src/pkgmgr \
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
bash -lc '
set -euo pipefail
make install
useradd -m dev
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
chmod 0440 /etc/sudoers.d/dev
chown -R dev:dev /opt/src/pkgmgr
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
chown -R dev:dev /nix
chmod 0755 /nix
chmod 1777 /nix/store
sudo -H -u dev env \
HOME=/home/dev \
NIX_CONFIG="$NIX_CONFIG" \
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
bash -lc "
set -euo pipefail
cd /opt/src/pkgmgr
make setup-venv
. \"\$HOME/.venvs/pkgmgr/bin/activate\"
pkgmgr version pkgmgr
export NIX_REMOTE=local
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
"
'
+34
View File
@@ -0,0 +1,34 @@
name: Test Virgin
on:
workflow_call:
permissions:
contents: read
jobs:
test-virgin:
runs-on: ubuntu-latest
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
mode: [user, root]
distro: [arch, debian, ubuntu, fedora, centos]
env:
NIX_CONFIG: |
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
MODE: ${{ matrix.mode }}
DISTRO: ${{ matrix.distro }}
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Show Docker version
run: docker version
- name: Pull base image (${{ matrix.distro }})
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${DISTRO}:latest"
- name: Virgin ${{ matrix.distro }} pkgmgr test (${{ matrix.mode }})
run: bash scripts/test/virgin/run.sh "$MODE" "$DISTRO"
+3 -3
View File
@@ -18,13 +18,13 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@v23
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
- name: Update flake.lock and open a pull request
uses: DeterminateSystems/update-flake-lock@v29
uses: DeterminateSystems/update-flake-lock@da03c0f078bc4b2c37ee4f7e072d34bf8f188bb3 # v29
with:
pr-title: "chore(deps): update flake.lock"
pr-labels: |
+42
View File
@@ -1,5 +1,47 @@
# Changelog
## [2.6.0] - 2026-12-02
Added:
- GC: *gc --risk low* plans and applies cleanups by risk level and owner
- Release: *--expect-tree* refuses a release whose HEAD tree changed
- Security: *.github/SECURITY.md* with private vulnerability reporting
Changed:
- Push: signs and pushes from a private bare repository, not the checkout
- Push: URL credentials are redacted in every error and preview line
- Release: untracked release inputs abort an *--expect-tree* release
- CI: GitHub actions pinned by SHA; workflow tokens default to read-only
Fixed:
- Release: a nested clone releases itself, never the main checkout
- Release: tracked changes are refused before any version bump
- Release: a setuptools dynamic attr version is bumped in its module
- Publish: builds with the pkgmgr interpreter in a private directory
- GC: owner status, mounts and docker state are rechecked before deletes
- GC: worktree holds win over a missing forge token
- Branch: held branches are read once per cleanup plan
- Security: the 32 open CodeQL alerts are closed
Upgrade notes:
- Push refuses an origin whose URL is a local path or plain http
- Push ignores http and credential settings in the repository git config
## [2.5.0] - 2026-11-13
Added:
- Branch: *cleanup --local* deletes merged branches only where git would
- Review: expand and collapse are icon buttons with labels
Fixed:
- GC: merged local-only branches are removed without a forge token
## [2.4.0] - 2026-11-07
Added:
+1
View File
@@ -80,6 +80,7 @@ versioning features it can drive **end-to-end workflows**:
| `pkgmgr worktree flow clear [PATH] [--json]` | Removes the merge flow |
| `pkgmgr worktree cleanup [--apply]` | Removes clean worktrees whose commits are merged or pushed: pinned `worktree-fini` hook, compose stack, checkout; the branch stays |
| `pkgmgr branch cleanup [--apply]` | Removes merged branches that no worktree holds, locally and on the remotes |
| `pkgmgr branch cleanup --local [--apply] [--json] [--merged-into REF]...` | Deletes only local branches whose tip is an ancestor of the remote-tracking default or of a `--merged-into` REF, each with `git update-ref --no-deref -d` against the planned sha and then its `branch.<name>` section in the repository's own config file (`git config --file <git common dir>/config`; a section it cannot remove is noted on the done item), also when the branch has an upstream or remote copy. Every git call of `--local` runs without any inherited `GIT_*` variable but `GIT_CEILING_DIRECTORIES`, which only narrows repository discovery, so a directory below a ceiling is never resolved to the repository above it; only the config reads of `deleteMerged` and of the upstreams run twice, both with the system config: once with the caller's `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_PARAMETERS` and `GIT_CONFIG_COUNT` with its `GIT_CONFIG_KEY_<n>` and `GIT_CONFIG_VALUE_<n>`, once without any of them, without `XDG_CONFIG_HOME` and with `HOME` set to the passwd home, and a branch either read keeps stays, so the environment can add keeps but never remove one. A `--merged-into` REF must name exactly one branch or remote-tracking ref, as `git rev-parse --symbolic-full-name` resolves it, in every scanned repository git can read; `X~0`, `X^0`, `X@{0}`, a sha, a range or an unknown ref stops the run. The default comes from `origin`, or from the only remote when there is no `origin`: the ref `refs/remotes/<remote>/HEAD`, else `main`, else `master` resolves to, every symref step inside `refs/remotes/<remote>/`, so never a local branch or `HEAD`; without one, for example with several remotes and no `origin`, the repository is refused, also under `--merged-into`; so is one whose `refs`, `packed-refs`, `reftable`, `logs` or `logs/refs` is a symlink (git-new-workdir), one with a symlink anywhere below `refs/`, `reftable/` or `logs/refs/` (for example `refs/heads/team` linked to another clone's heads), one whose git dir is neither its git common dir nor directly under `<common>/worktrees/` (a registration moved elsewhere), or one whose git output is not UTF-8. The repository is the one the current directory belongs to, also in a submodule or with a separate git dir; one whose main worktree belongs to another repository (`core.worktree`), whose git dir is neither its git common dir nor directly under `<common>/worktrees/`, or whose path is not UTF-8 is refused with exit 2. Skips a symbolic branch, every branch a symbolic ref anywhere under `refs/` (also a tag or remote-tracking one) or under the main worktree's or any registration's `refs/worktree/` points to, a branch that is itself a `--merged-into` target, a branch a worktree holds or that the HEAD of the main repository or of any `worktrees/<id>` registration names (also one `git worktree list` omits or whose id is no valid ref name, read through `git --git-dir=<dir> symbolic-ref HEAD`, so also under reftable), one a rebase or bisect in any worktree works on, one merged only by patch or PR, and, as `git branch --delete-merged` keeps them, one whose `branch.<name>.deleteMerged` is false in the config of any worktree (also its `config.worktree` or an `includeIf "onbranch:..."` file) or in the system config file, and the local upstream, as git's `%(upstream)` resolves it in any worktree, of any branch that stays, also of one that `--branch` or `--exclude` leaves out, each shown as kept with its reason; these holds are read through the git common dir, whichever worktree is scanned, and a registration, symbolic ref, HEAD or state file they cannot read refuses the repository; when a repository vanishes, moves or stops being readable, or its default or a `--merged-into` target stops resolving mid-run, its later items are skipped with that reason and the plan is still printed. A repository git or the filesystem fails on while planning (for example a dangling `.git` file under `--all`) is refused with that reason and the run goes on. The plan, refused repositories included, is printed (as JSON with `--json`), and the run exits 1 when an item failed, else 2 when a repository was refused, else 0. It stops with a message on stderr, no plan and exit 2 in exactly these cases: without `--all`, the current directory is not inside a git repository, its git dir is neither its git common dir nor directly under `<common>/worktrees/`, its main worktree belongs to another repository (`core.worktree`), or its path or git output is not UTF-8; `--apply` outside the host PID namespace; a `--merged-into` REF refused as above; a `--branch` that matches no item (also one that exists only on a remote). Meant for working clones and their worktrees, not for a bare server repository. Not mirrored from `git branch --delete-merged`: git also keeps a branch whose push would update its own upstream; `--local` does not. A branch is deleted before its planned local upstream; right before each delete its holds and then itLine truncated
| `pkgmgr branch tree [--format json\|yaml] [--output FILE]` | Writes every managed repository's branches and worktrees with their cleanup state, without fetching |
| `pkgmgr gc [--all] [--apply]` | Both cleanups in one pass, for the current repository or every managed one |
| `pkgmgr gc --report [--all] [--root DIR] [--threshold-mb MB] [--docker] [--json]` | Read-only disk inventory: worktree sizes, changes a cleanup would keep, `--root` children, core dumps, docker usage, free space per filesystem |
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": {
+1 -1
View File
@@ -32,7 +32,7 @@
rec {
pkgmgr = pyPkgs.buildPythonApplication {
pname = "package-manager";
version = "2.4.0";
version = "2.6.0";
# Use the git repo as source
src = ./.;
+1 -1
View File
@@ -1,7 +1,7 @@
# Maintainer: Kevin Veen-Birkenbach <info@veen.world>
pkgname=package-manager
pkgver=2.4.0
pkgver=2.6.0
pkgrel=1
pkgdesc="Local-flake wrapper for Kevin's package-manager (Nix-based)."
arch=('any')
+46
View File
@@ -1,3 +1,49 @@
package-manager (2.6.0-1) unstable; urgency=medium
Added:
- GC: *gc --risk low* plans and applies cleanups by risk level and owner
- Release: *--expect-tree* refuses a release whose HEAD tree changed
- Security: *.github/SECURITY.md* with private vulnerability reporting
Changed:
- Push: signs and pushes from a private bare repository, not the checkout
- Push: URL credentials are redacted in every error and preview line
- Release: untracked release inputs abort an *--expect-tree* release
- CI: GitHub actions pinned by SHA; workflow tokens default to read-only
Fixed:
- Release: a nested clone releases itself, never the main checkout
- Release: tracked changes are refused before any version bump
- Release: a setuptools dynamic attr version is bumped in its module
- Publish: builds with the pkgmgr interpreter in a private directory
- GC: owner status, mounts and docker state are rechecked before deletes
- GC: worktree holds win over a missing forge token
- Branch: held branches are read once per cleanup plan
- Security: the 32 open CodeQL alerts are closed
Upgrade notes:
- Push refuses an origin whose URL is a local path or plain http
- Push ignores http and credential settings in the repository git config
-- Kevin Veen-Birkenbach <kevin@veen.world> Wed, 02 Dec 2026 12:08:23 +0000
package-manager (2.5.0-1) unstable; urgency=medium
Added:
- Branch: *cleanup --local* deletes merged branches only where git would
- Review: expand and collapse are icon buttons with labels
Fixed:
- GC: merged local-only branches are removed without a forge token
-- Kevin Veen-Birkenbach <kevin@veen.world> Fri, 13 Nov 2026 22:53:12 +0000
package-manager (2.4.0-1) unstable; urgency=medium
Added:
+41 -1
View File
@@ -1,5 +1,5 @@
Name: package-manager
Version: 2.4.0
Version: 2.6.0
Release: 1%{?dist}
Summary: Wrapper that runs Kevin's package-manager via Nix flake
@@ -74,6 +74,46 @@ echo ">>> package-manager removed. Nix itself was not removed."
/usr/lib/package-manager/
%changelog
* Wed Dec 02 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.6.0-1
- Added:
- - GC: *gc --risk low* plans and applies cleanups by risk level and owner
- - Release: *--expect-tree* refuses a release whose HEAD tree changed
- - Security: *.github/SECURITY.md* with private vulnerability reporting
- Changed:
- - Push: signs and pushes from a private bare repository, not the checkout
- - Push: URL credentials are redacted in every error and preview line
- - Release: untracked release inputs abort an *--expect-tree* release
- - CI: GitHub actions pinned by SHA; workflow tokens default to read-only
- Fixed:
- - Release: a nested clone releases itself, never the main checkout
- - Release: tracked changes are refused before any version bump
- - Release: a setuptools dynamic attr version is bumped in its module
- - Publish: builds with the pkgmgr interpreter in a private directory
- - GC: owner status, mounts and docker state are rechecked before deletes
- - GC: worktree holds win over a missing forge token
- - Branch: held branches are read once per cleanup plan
- - Security: the 32 open CodeQL alerts are closed
- Upgrade notes:
- - Push refuses an origin whose URL is a local path or plain http
- - Push ignores http and credential settings in the repository git config
* Fri Nov 13 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.5.0-1
- Added:
- - Branch: *cleanup --local* deletes merged branches only where git would
- - Review: expand and collapse are icon buttons with labels
- Fixed:
- - GC: merged local-only branches are removed without a forge token
* Sat Nov 07 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.4.0-1
- Added:
+2 -2
View File
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "kpmx"
version = "2.4.0"
version = "2.6.0"
description = "Kevin's package-manager tool (pkgmgr)"
readme = "README.md"
requires-python = ">=3.9"
@@ -52,4 +52,4 @@ include = ["pkgmgr*"]
[tool.setuptools.package-data]
"pkgmgr.config" = ["*.yml", "*.yaml"]
"pkgmgr.actions.review" = ["*.j2"]
"pkgmgr.actions.review" = ["*.j2", "*.LICENSE"]
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -euo pipefail
if [ -f /etc/os-release ]; then
# shellcheck source=/dev/null
. /etc/os-release
fi
echo "Running tests inside distro: ${ID:-unknown}"
if [ -f "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" ]; then
# shellcheck source=/dev/null
. "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh"
fi
if [ -f "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then
# shellcheck source=/dev/null
. "$HOME/.nix-profile/etc/profile.d/nix.sh"
fi
PATH="/nix/var/nix/profiles/default/bin:$HOME/.nix-profile/bin:$PATH"
command -v nix >/dev/null || {
echo "ERROR: nix not found."
exit 1
}
bash scripts/test/container/safe-directory.sh
nix develop .#default --no-write-lock-file -c \
python3 -m unittest discover \
-s /opt/src/pkgmgr/tests/e2e \
-p "$TEST_PATTERN"
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
set -euo pipefail
# Param: IMAGE ($1) - the image name shown in the missing-nix error.
# Param: PKGMGR_DISTRO ($2) - the distro shown in the missing-nix error.
IMAGE="$1"
PKGMGR_DISTRO="$2"
bash scripts/test/container/safe-directory.sh
echo ">>> preflight: nix must exist in image"
if ! command -v nix >/dev/null 2>&1; then
echo "NO_NIX"
echo "ERROR: nix not found in image ${IMAGE} (PKGMGR_DISTRO=${PKGMGR_DISTRO})"
echo "HINT: Ensure Nix is installed during image build for this distro."
exit 1
fi
echo ">>> nix version"
nix --version
if [[ -f /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh ]]; then
# shellcheck source=/dev/null
source /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh
elif [[ -f ./scripts/nix/lib/retry_403.sh ]]; then
# shellcheck source=/dev/null
source ./scripts/nix/lib/retry_403.sh
else
echo "ERROR: retry helper not found: scripts/nix/lib/retry_403.sh"
exit 1
fi
echo ">>> nix flake show"
run_with_github_403_retry nix flake show . --no-write-lock-file >/dev/null
echo ">>> nix build .#default"
run_with_github_403_retry nix build .#default --no-link --no-write-lock-file
echo ">>> nix run .#pkgmgr -- --help"
run_with_github_403_retry nix run .#pkgmgr -- --help --no-write-lock-file
echo ">>> OK: Nix flake-only test succeeded."
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
echo "[test-env-virtual] Installing pkgmgr (distro package)..."
make install
echo "[test-env-virtual] Setting up Python venv..."
make setup-venv
echo "[test-env-virtual] Activating venv..."
# shellcheck source=/dev/null
. "$HOME/.venvs/pkgmgr/bin/activate"
echo "[test-env-virtual] Using pkgmgr from:"
command -v pkgmgr
pkgmgr --help
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
if command -v git >/dev/null 2>&1; then
git config --global --add safe.directory /opt/src/pkgmgr || true
git config --global --add safe.directory /opt/src/pkgmgr/.git || true
git config --global --add safe.directory "*" || true
fi
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -e
# Param: suite ($1) - the test folder to discover, tests/unit or tests/integration.
suite="$1"
git config --global --add safe.directory /opt/src/pkgmgr || true
nix develop .#default --no-write-lock-file -c \
python3 -m unittest discover \
-s "$suite" \
-t /opt/src/pkgmgr \
-p "$TEST_PATTERN"
+1 -45
View File
@@ -14,48 +14,4 @@ docker run --rm \
-e NIX_CONFIG="${NIX_CONFIG}" \
--workdir /opt/src/pkgmgr \
"pkgmgr-${PKGMGR_DISTRO}" \
bash -lc '
set -euo pipefail
# Load distro info
if [ -f /etc/os-release ]; then
. /etc/os-release
fi
echo "Running tests inside distro: ${ID:-unknown}"
# Load Nix environment if available
if [ -f "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" ]; then
. "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh"
fi
if [ -f "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then
. "$HOME/.nix-profile/etc/profile.d/nix.sh"
fi
PATH="/nix/var/nix/profiles/default/bin:$HOME/.nix-profile/bin:$PATH"
command -v nix >/dev/null || {
echo "ERROR: nix not found."
exit 1
}
# Mark the mounted repository as safe to avoid Git ownership errors.
# Newer Git (e.g. on Ubuntu) complains about the gitdir (/opt/src/pkgmgr/.git),
# older versions about the worktree (/opt/src/pkgmgr). Nix turns "." into the
# flake input "git+file:///opt/src/pkgmgr", which then uses Git under the hood.
if command -v git >/dev/null 2>&1; then
# Worktree path
git config --global --add safe.directory /opt/src/pkgmgr || true
# Gitdir path shown in the "dubious ownership" error
git config --global --add safe.directory /opt/src/pkgmgr/.git || true
# Ephemeral CI containers: allow all paths as a last resort
git config --global --add safe.directory "*" || true
fi
# Run the E2E tests inside the Nix development shell
nix develop .#default --no-write-lock-file -c \
python3 -m unittest discover \
-s /opt/src/pkgmgr/tests/e2e \
-p "$TEST_PATTERN"
'
bash -l scripts/test/container/e2e.sh
+1 -45
View File
@@ -16,48 +16,4 @@ docker run --rm \
-e REINSTALL_PKGMGR=1 \
-e NIX_CONFIG="${NIX_CONFIG}" \
"${IMAGE}" \
bash -lc '
set -euo pipefail
if command -v git >/dev/null 2>&1; then
git config --global --add safe.directory /opt/src/pkgmgr || true
git config --global --add safe.directory /opt/src/pkgmgr/.git || true
git config --global --add safe.directory "*" || true
fi
echo ">>> preflight: nix must exist in image"
if ! command -v nix >/dev/null 2>&1; then
echo "NO_NIX"
echo "ERROR: nix not found in image '"${IMAGE}"' (PKGMGR_DISTRO='"${PKGMGR_DISTRO}"')"
echo "HINT: Ensure Nix is installed during image build for this distro."
exit 1
fi
echo ">>> nix version"
nix --version
# ------------------------------------------------------------
# Retry helper for GitHub API rate-limit (HTTP 403)
# ------------------------------------------------------------
if [[ -f /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh ]]; then
# shellcheck source=./scripts/nix/lib/retry_403.sh
source /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh
elif [[ -f ./scripts/nix/lib/retry_403.sh ]]; then
# shellcheck source=./scripts/nix/lib/retry_403.sh
source ./scripts/nix/lib/retry_403.sh
else
echo "ERROR: retry helper not found: scripts/nix/lib/retry_403.sh"
exit 1
fi
echo ">>> nix flake show"
run_with_github_403_retry nix flake show . --no-write-lock-file >/dev/null
echo ">>> nix build .#default"
run_with_github_403_retry nix build .#default --no-link --no-write-lock-file
echo ">>> nix run .#pkgmgr -- --help"
run_with_github_403_retry nix run .#pkgmgr -- --help --no-write-lock-file
echo ">>> OK: Nix flake-only test succeeded."
'
bash -l scripts/test/container/env/nix.sh "${IMAGE}" "${PKGMGR_DISTRO}"
+1 -19
View File
@@ -12,31 +12,13 @@ echo "[test-env-virtual] Inspect image metadata:"
docker image inspect "${IMAGE}" | sed -n '1,40p'
echo
# ------------------------------------------------------------
# Run VENV-based pkgmgr test inside container
# ------------------------------------------------------------
if OUTPUT=$(docker run --rm \
-e REINSTALL_PKGMGR=1 \
-v "$(pwd):/opt/src/pkgmgr" \
-w /opt/src/pkgmgr \
-e NIX_CONFIG="${NIX_CONFIG}" \
"${IMAGE}" \
bash -lc '
set -euo pipefail
echo "[test-env-virtual] Installing pkgmgr (distro package)..."
make install
echo "[test-env-virtual] Setting up Python venv..."
make setup-venv
echo "[test-env-virtual] Activating venv..."
. "$HOME/.venvs/pkgmgr/bin/activate"
echo "[test-env-virtual] Using pkgmgr from:"
command -v pkgmgr
pkgmgr --help
' 2>&1); then
bash -l scripts/test/container/env/virtual.sh 2>&1); then
echo "$OUTPUT"
echo
+1 -9
View File
@@ -14,12 +14,4 @@ docker run --rm \
-e TEST_PATTERN="${TEST_PATTERN}" \
-e NIX_CONFIG="${NIX_CONFIG}" \
"pkgmgr-${PKGMGR_DISTRO}" \
bash -lc '
set -e;
git config --global --add safe.directory /opt/src/pkgmgr || true;
nix develop .#default --no-write-lock-file -c \
python3 -m unittest discover \
-s tests/integration \
-t /opt/src/pkgmgr \
-p "$TEST_PATTERN";
'
bash -l scripts/test/container/unittest.sh tests/integration
+1 -9
View File
@@ -14,12 +14,4 @@ docker run --rm \
-e TEST_PATTERN="${TEST_PATTERN}" \
-e NIX_CONFIG="${NIX_CONFIG}" \
"pkgmgr-${PKGMGR_DISTRO}" \
bash -lc '
set -e;
git config --global --add safe.directory /opt/src/pkgmgr || true;
nix develop .#default --no-write-lock-file -c \
python3 -m unittest discover \
-s tests/unit \
-t /opt/src/pkgmgr \
-p "$TEST_PATTERN";
'
bash -l scripts/test/container/unittest.sh tests/unit
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
cd /opt/src/pkgmgr
make setup-venv
# shellcheck source=/dev/null
. "$HOME/.venvs/pkgmgr/bin/activate"
pkgmgr version pkgmgr
export NIX_REMOTE=local
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
git config --global --add safe.directory /opt/src/pkgmgr
make install
make setup
# shellcheck source=/dev/null
. "$HOME/.venvs/pkgmgr/bin/activate"
pkgmgr update pkgmgr --clone-mode shallow --no-verification
pkgmgr version pkgmgr
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euo pipefail
mode="$1"
distro="$2"
case "$mode" in
root) volumes=(-v pkgmgr_repos:/root/Repositories -v pkgmgr_pip_cache:/root/.cache/pip) ;;
user) volumes=() ;;
*)
echo "usage: $0 root|user <distro>" >&2
exit 2
;;
esac
docker run --rm \
-v "$PWD":/opt/src/pkgmgr \
"${volumes[@]}" \
-e NIX_CONFIG="${NIX_CONFIG}" \
-w /opt/src/pkgmgr \
"ghcr.io/kevinveenbirkenbach/base-${distro}:latest" \
bash -l "scripts/test/virgin/${mode}.sh"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
make install
useradd -m dev
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
chmod 0440 /etc/sudoers.d/dev
chown -R dev:dev /opt/src/pkgmgr
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
chown -R dev:dev /nix
chmod 0755 /nix
chmod 1777 /nix/store
sudo -H -u dev env \
HOME=/home/dev \
NIX_CONFIG="$NIX_CONFIG" \
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
bash -l /opt/src/pkgmgr/scripts/test/virgin/dev.sh
File diff suppressed because it is too large. Load diff
+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}"
)
+19 -14
View File
@@ -50,17 +50,15 @@ def _cache_path(owner: str, name: str) -> str:
return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json")
def secret_service_token() -> tuple[str | None, str | None]:
"""
Read the GitHub token from the Secret Service without unlocking it.
class SecretServiceUnavailable(Exception):
pass
Returns:
(token, None), or (None, why no token is available).
"""
def _secret_service_token() -> str:
try:
import secretstorage
except ImportError:
return None, "secretstorage not installed"
except ImportError as exc:
raise SecretServiceUnavailable("secretstorage not installed") from exc
key = build_keyring_key("github", GITHUB_HOST, None)
try:
connection = secretstorage.dbus_init()
@@ -72,14 +70,21 @@ def secret_service_token() -> tuple[str | None, str | None]:
)
unlocked = [item for item in items if not item.is_locked()]
if not items:
return None, "no GitHub token in the Secret Service"
raise SecretServiceUnavailable("no GitHub token in the Secret Service")
if not unlocked:
return None, "Secret Service locked"
return unlocked[0].get_secret().decode(), None
raise SecretServiceUnavailable("Secret Service locked")
return unlocked[0].get_secret().decode()
finally:
connection.close()
except (secretstorage.exceptions.SecretStorageException, OSError) as exc:
return None, f"Secret Service unavailable: {exc}"
raise SecretServiceUnavailable(f"Secret Service unavailable: {exc}") from exc
def _forge_access() -> tuple[str | None, str | None]:
try:
return _secret_service_token(), None
except SecretServiceUnavailable as exc:
return None, str(exc)
@contextmanager
@@ -315,7 +320,7 @@ def branch_tree(
"""
known = list(dict.fromkeys(os.path.realpath(d) for d in repo_dirs))
orphans = [d for d in _shared_owners(worktrees_root) if d not in known]
token, reason = secret_service_token()
token, reason = _forge_access()
host_ns = gc.host_pid_namespace()
containers = gc.list_compose_containers()
data = {
@@ -357,7 +362,7 @@ def refresh_tree_entry(repo_root: str) -> None:
if not os.path.isfile(path) or not gc.host_pid_namespace():
return
root = os.path.realpath(repo_root)
token, reason = secret_service_token()
token, reason = _forge_access()
fresh = _scan(root, True, token, reason, gc.list_compose_containers(), True)
with _locked(path):
with open(path, encoding="utf-8") as fh:
+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"
-1
View File
@@ -161,7 +161,6 @@ class InstallationPipeline:
else:
repo.pop("command", None)
state = new_state
return
if attempted:
+85 -24
View File
@@ -1,9 +1,9 @@
from __future__ import annotations
import glob
import os
import shutil
import subprocess
import sys
import tempfile
from pkgmgr.actions.mirror.io import read_mirrors_file
from pkgmgr.actions.mirror.types import Repository
@@ -12,20 +12,62 @@ from pkgmgr.core.version.semver import SemVer
from .git_tags import head_semver_tags
from .pypi_url import parse_pypi_project_url
from .types import PyPITarget
UPLOAD_URLS = {
"pypi.org": "https://upload.pypi.org/legacy/",
"test.pypi.org": "https://test.pypi.org/legacy/",
}
def _require_tool(module: str) -> None:
def _child_env(repo_dir: str) -> dict[str, str]:
"""
Args:
repo_dir: absolute path of the repository being published.
Returns:
The environment for build and twine without pkgmgr's own variables,
so no PKGMGR_* token reaches a build backend or an upload, and
without PYTHONPATH entries inside repo_dir, so no repository file
shadows build or twine.
"""
env = {k: v for k, v in os.environ.items() if not k.startswith("PKGMGR_")}
if "PYTHONPATH" in env:
root = os.path.realpath(repo_dir)
kept = [
entry
for entry in env["PYTHONPATH"].split(os.pathsep)
if entry and os.path.commonpath([root, os.path.realpath(entry)]) != root
]
if kept:
env["PYTHONPATH"] = os.pathsep.join(kept)
else:
del env["PYTHONPATH"]
return env
def _require_tool(module: str, cwd: str, env: dict[str, str]) -> None:
"""
Args:
module: the Python module run with -m.
cwd: an empty private directory, so no file of the repository
shadows the module on sys.path.
env: the child environment from _child_env.
"""
try:
subprocess.run(
["python", "-m", module, "--help"],
[sys.executable, "-m", module, "--help"],
cwd=cwd,
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
except Exception as exc:
raise RuntimeError(
f"Required Python module '{module}' is not available. "
f"Install it via: pip install {module}"
f"Required Python module '{module}' is not available to "
f"{sys.executable}. Install it via: "
f"{sys.executable} -m pip install {module}"
) from exc
@@ -66,22 +108,38 @@ def publish(
print("[PREVIEW] Would build and upload to PyPI.")
return
_require_tool("build")
_require_tool("twine")
with tempfile.TemporaryDirectory() as out:
_upload(target, os.path.abspath(repo_dir), out, interactive, allow_prompt)
dist_dir = os.path.join(repo_dir, "dist")
if os.path.isdir(dist_dir):
shutil.rmtree(dist_dir, ignore_errors=True)
print("[INFO] Publish completed.")
def _upload(
target: PyPITarget, repo_dir: str, out: str, interactive: bool, allow_prompt: bool
) -> None:
"""
Args:
target: the PyPI target parsed from the mirror URL.
repo_dir: absolute path of the repository to build.
out: an empty private directory that receives the artifacts and is
the working directory of every child process.
interactive: allow interactive token resolution.
allow_prompt: allow prompting for the token.
"""
env = _child_env(repo_dir)
_require_tool("build", out, env)
_require_tool("twine", out, env)
subprocess.run(
["python", "-m", "build"],
cwd=repo_dir,
[sys.executable, "-m", "build", "--outdir", out, repo_dir],
cwd=out,
env=env,
check=True,
)
artifacts = sorted(glob.glob(os.path.join(dist_dir, "*")))
artifacts = sorted(os.path.join(out, name) for name in os.listdir(out))
if not artifacts:
raise RuntimeError("No build artifacts found in dist/.")
raise RuntimeError("No build artifacts found.")
resolver = TokenResolver()
@@ -98,15 +156,18 @@ def publish(
),
).token
env = dict(os.environ)
env["TWINE_USERNAME"] = "__token__"
env["TWINE_PASSWORD"] = token
subprocess.run(
["python", "-m", "twine", "upload", *artifacts],
cwd=repo_dir,
env=env,
[
sys.executable,
"-m",
"twine",
"upload",
"--non-interactive",
"--repository-url",
UPLOAD_URLS[target.host],
*artifacts,
],
cwd=out,
env={**env, "TWINE_USERNAME": "__token__", "TWINE_PASSWORD": token},
check=True,
)
print("[INFO] Publish completed.")
+17
View File
@@ -131,6 +131,23 @@ When `--close` is enabled:
---
## Audited Tree (`--expect-tree <sha>`)
Pins the release to an audited tree:
- After the pull (`fetch` + `pull --ff-only`) and before any file is written,
`git rev-parse HEAD^{tree}` must equal the given full sha
- Any other tree, also one a push brought in after the audit, aborts the
release with a non-zero exit before any release file is written; the
pull already ran and is not reverted, so HEAD and tracked files may
have moved
- A release input (pyproject, changelogs, flake, packaging or Cargo
files) that exists but is untracked is not part of the audited tree,
so it aborts the release the same way
- With `--retry` the check runs before anything is pushed
---
## Execution Flow (ASCII Diagram)
```
+2 -1
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from .options import ReleaseOptions
from .workflow import release
__all__ = ["release"]
__all__ = ["ReleaseOptions", "release"]
+36 -1
View File
@@ -8,6 +8,36 @@ try:
except ImportError:
import tomli as tomllib # type: ignore
from pkgmgr.core.version.source import dynamic_version_source, version_literal
def update_module_version(
path: str, name: str, new_version: str, preview: bool
) -> None:
"""
Args:
path: the module file that holds the version literal.
name: the attribute assigned the version, e.g. __version__.
new_version: the version to write.
preview: print the change instead of writing it.
Raises:
RuntimeError: the file holds no `name = "..."` literal.
"""
with open(path, encoding="utf-8") as f:
content = f.read()
new_content, count = version_literal(name).subn(
lambda mm: f"{mm.group(1)}{new_version}{mm.group(3)}", content, count=1
)
if count == 0:
raise RuntimeError(f"Missing {name} literal in {path}")
if preview:
print(f"[PREVIEW] Would update {name} in {path} to {new_version}")
return
with open(path, "w", encoding="utf-8") as f:
f.write(new_content)
print(f"Updated {name} in {path} to {new_version}")
def update_pyproject_version(
pyproject_path: str, new_version: str, preview: bool = False
@@ -23,7 +53,12 @@ def update_pyproject_version(
print(f"[WARN] Could not read pyproject.toml: {exc}")
return
project = tomllib.loads(content).get("project")
data = tomllib.loads(content)
project = data.get("project")
source = dynamic_version_source(pyproject_path, data)
if source is not None:
update_module_version(*source, new_version, preview)
return
if project is None or "version" in project.get("dynamic", []):
print("[INFO] pyproject.toml declares no static version, skipping.")
return
+43
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.")
@@ -29,6 +41,37 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
pull_ff_only(preview=preview)
def ensure_head_tree(expected: str | None) -> None:
if expected is None:
return
actual = run(["rev-parse", "HEAD^{tree}"])
if actual != expected:
raise RuntimeError(
f"HEAD tree {actual} is not the expected tree {expected}; "
"refusing to release an unaudited tree"
)
def ensure_inputs_tracked(expected: str | None, files: list[str]) -> None:
"""
Args:
expected: the audited tree sha, or None to skip the check.
files: existing files the release writes or stages.
Raises:
RuntimeError: one of the files is not tracked, so its content is
not part of the audited tree.
"""
if expected is None or not files:
return
untracked = run(["ls-files", "--others", "--", *files])
if untracked:
raise RuntimeError(
f"Release inputs not in the audited tree {expected}:\n{untracked}\n"
"refusing to release unaudited content"
)
def _parse_v_tag(tag: str) -> tuple[int, ...] | None:
"""
Parse tags like 'v1.2.3' into (1, 2, 3).
+29
View File
@@ -0,0 +1,29 @@
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class ReleaseOptions:
"""
Args:
expect_tree: full tree sha HEAD must match after the pull, or None.
pyproject_path: pyproject.toml of the repository to release.
changelog_path: Markdown changelog to extend.
release_type: semver part to bump (major, minor, patch).
message: release message for the changelogs and the tag.
preview: only print what would change.
force: skip the interactive preview and the branch deletion prompt.
close: delete the current branch after the release.
retry: re-deploy the existing HEAD release instead of bumping.
"""
expect_tree: str | None
pyproject_path: str = "pyproject.toml"
changelog_path: str = "CHANGELOG.md"
release_type: str = "patch"
message: str | None = None
preview: bool = False
force: bool = False
close: bool = False
retry: bool = False
+168 -165
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import os
import sys
from dataclasses import dataclass, replace
from pkgmgr.actions.branch import close_branch
from pkgmgr.actions.repository.push import (
@@ -12,7 +13,7 @@ from pkgmgr.actions.repository.push import (
from pkgmgr.core.git import GitRunError
from pkgmgr.core.git.commands import add, commit, tag_annotated
from pkgmgr.core.git.queries import get_current_branch
from pkgmgr.core.repository.paths import resolve_repo_paths
from pkgmgr.core.repository.paths import RepoPaths, resolve_repo_paths
from .files import (
update_cargo_version,
@@ -26,87 +27,91 @@ from .files import (
)
from .git_ops import (
ensure_clean_and_synced,
ensure_head_tree,
ensure_inputs_tracked,
is_highest_version_tag,
update_latest_tag,
)
from .options import ReleaseOptions
from .package_name import resolve_package_name
from .prompts import confirm_proceed_release, should_delete_branch
from .retry import retry_release
from .versioning import bump_semver, determine_current_version
MAIN_BRANCHES = ("main", "master")
CARGO_FILES = ("Cargo.toml", "Cargo.lock")
def _release_impl(
pyproject_path: str = "pyproject.toml",
changelog_path: str = "CHANGELOG.md",
release_type: str = "patch",
message: str | None = None,
preview: bool = False,
close: bool = False,
force: bool = False,
) -> None:
# Determine current branch early
@dataclass(frozen=True)
class _Prepared:
branch: str
version: str
tag: str
tag_message: str
files: list[str]
def _current_branch() -> str:
try:
branch = get_current_branch() or "main"
return get_current_branch() or "main"
except GitRunError:
branch = "main"
print(f"Releasing on branch: {branch}")
return "main"
refuse_unsafe_config(".")
# Pull BEFORE making any modifications
ensure_clean_and_synced(preview=preview)
repo_root = os.path.dirname(os.path.abspath(pyproject_path))
current_ver = determine_current_version(repo_root)
new_ver = bump_semver(current_ver, release_type)
new_ver_str = str(new_ver)
new_tag = new_ver.to_tag(with_prefix=True)
def _existing(files: list[str | None]) -> list[str]:
return [p for p in files if isinstance(p, str) and p and os.path.exists(p)]
mode = "PREVIEW" if preview else "REAL"
print(f"Release mode: {mode}")
print(f"Current version: {current_ver}")
print(f"New version: {new_ver_str} ({release_type})")
paths = resolve_repo_paths(repo_root)
# --- Update versioned files ------------------------------------------------
update_pyproject_version(pyproject_path, new_ver_str, preview=preview)
changelog_message = update_changelog(
changelog_path,
new_ver_str,
message=message,
preview=preview,
def _release_files(
options: ReleaseOptions, paths: RepoPaths, extra: list[str]
) -> list[str]:
return _existing(
[
options.pyproject_path,
options.changelog_path,
paths.flake_nix,
paths.arch_pkgbuild,
paths.rpm_spec,
paths.debian_changelog,
*extra,
]
)
update_flake_version(paths.flake_nix, new_ver_str, preview=preview)
cargo_files = update_cargo_version(repo_root, new_ver_str, preview=preview)
def _next_version(options: ReleaseOptions, repo_root: str):
current_ver = determine_current_version(repo_root)
new_ver = bump_semver(current_ver, options.release_type)
print(f"Release mode: {'PREVIEW' if options.preview else 'REAL'}")
print(f"Current version: {current_ver}")
print(f"New version: {new_ver} ({options.release_type})")
return new_ver
def _update_packaging_versions(paths: RepoPaths, version: str, preview: bool) -> None:
if paths.arch_pkgbuild:
update_pkgbuild_version(paths.arch_pkgbuild, new_ver_str, preview=preview)
update_pkgbuild_version(paths.arch_pkgbuild, version, preview=preview)
else:
print(
"[INFO] No PKGBUILD found (packaging/arch/PKGBUILD or PKGBUILD). Skipping."
)
if paths.rpm_spec:
update_spec_version(paths.rpm_spec, new_ver_str, preview=preview)
update_spec_version(paths.rpm_spec, version, preview=preview)
else:
print("[INFO] No RPM spec file found. Skipping spec version update.")
effective_message: str | None = message
if isinstance(changelog_message, str) and changelog_message.strip():
effective_message = changelog_message.strip()
def _update_packaging_changelogs(
paths: RepoPaths, version: str, message: str | None, preview: bool
) -> None:
package_name = resolve_package_name(paths)
if paths.debian_changelog:
update_debian_changelog(
paths.debian_changelog,
package_name=package_name,
new_version=new_ver_str,
message=effective_message,
new_version=version,
message=message,
preview=preview,
)
else:
@@ -116,152 +121,150 @@ def _release_impl(
update_spec_changelog(
spec_path=paths.rpm_spec,
package_name=package_name,
new_version=new_ver_str,
message=effective_message,
new_version=version,
message=message,
preview=preview,
)
# --- Git commit / tag / push ----------------------------------------------
commit_msg = f"Release version {new_ver_str}"
tag_msg = effective_message or commit_msg
def _update_files(
options: ReleaseOptions, repo_root: str, paths: RepoPaths, version: str
) -> tuple[str | None, list[str]]:
"""
Returns:
The effective release message and the Cargo files that were updated.
"""
preview = options.preview
update_pyproject_version(options.pyproject_path, version, preview=preview)
changelog_message = update_changelog(
options.changelog_path,
version,
message=options.message,
preview=preview,
)
update_flake_version(paths.flake_nix, version, preview=preview)
cargo_files = update_cargo_version(repo_root, version, preview=preview)
_update_packaging_versions(paths, version, preview)
files_to_add = [
pyproject_path,
changelog_path,
paths.flake_nix,
paths.arch_pkgbuild,
paths.rpm_spec,
paths.debian_changelog,
*cargo_files,
]
existing_files = [
p for p in files_to_add if isinstance(p, str) and p and os.path.exists(p)
]
message = options.message
if isinstance(changelog_message, str) and changelog_message.strip():
message = changelog_message.strip()
if preview:
add(existing_files, preview=True)
commit(commit_msg, all=True, preview=True)
sign_unpushed(".", preview=True)
tag_annotated(new_tag, tag_msg, preview=True)
push_branch(".", [], sign=True, refs=(new_tag,), preview=True)
_update_packaging_changelogs(paths, version, message, preview)
return message, cargo_files
if is_highest_version_tag(new_tag):
update_latest_tag(new_tag, preview=True)
def _prepare(options: ReleaseOptions, branch: str) -> _Prepared:
repo_root = os.path.dirname(os.path.abspath(options.pyproject_path))
paths = resolve_repo_paths(repo_root)
cargo_inputs = [os.path.join(repo_root, name) for name in CARGO_FILES]
ensure_inputs_tracked(
options.expect_tree, _release_files(options, paths, cargo_inputs)
)
new_ver = _next_version(options, repo_root)
version = str(new_ver)
message, cargo_files = _update_files(options, repo_root, paths, version)
return _Prepared(
branch=branch,
version=version,
tag=new_ver.to_tag(with_prefix=True),
tag_message=message or f"Release version {version}",
files=_release_files(options, paths, cargo_files),
)
def _commit_tag_push(prepared: _Prepared, preview: bool) -> None:
add(prepared.files, preview=preview)
commit(f"Release version {prepared.version}", all=True, preview=preview)
sign_unpushed(".", preview=preview)
tag_annotated(prepared.tag, prepared.tag_message, preview=preview)
push_branch(".", [], sign=True, refs=(prepared.tag,), preview=preview)
def _finish_preview(prepared: _Prepared, options: ReleaseOptions) -> None:
tag = prepared.tag
if is_highest_version_tag(tag):
update_latest_tag(tag, preview=True)
else:
print(f"[PREVIEW] Skipping 'latest' update (tag {tag} is not the highest).")
branch = prepared.branch
if options.close and branch not in MAIN_BRANCHES:
if options.force:
print(f"[PREVIEW] Would delete branch {branch} (forced).")
else:
print(
f"[PREVIEW] Skipping 'latest' update (tag {new_tag} is not the highest)."
f"[PREVIEW] Would ask whether to delete branch {branch} after release."
)
if close and branch not in ("main", "master"):
if force:
print(f"[PREVIEW] Would delete branch {branch} (forced).")
else:
print(
f"[PREVIEW] Would ask whether to delete branch {branch} after release."
)
return
add(existing_files, preview=False)
commit(commit_msg, all=True, preview=False)
sign_unpushed(".", preview=False)
tag_annotated(new_tag, tag_msg, preview=False)
push_branch(".", [], sign=True, refs=(new_tag,), preview=False)
# Update 'latest' only if this is the highest version tag
def _move_latest(tag: str) -> None:
try:
if is_highest_version_tag(new_tag):
update_latest_tag(new_tag, preview=False)
if is_highest_version_tag(tag):
update_latest_tag(tag, preview=False)
else:
print(
f"[INFO] Skipping 'latest' update (tag {new_tag} is not the highest)."
)
print(f"[INFO] Skipping 'latest' update (tag {tag} is not the highest).")
except GitRunError as exc:
print(f"[WARN] Failed to update floating 'latest' tag for {new_tag}: {exc}")
print(f"[WARN] Failed to update floating 'latest' tag for {tag}: {exc}")
print("'latest' tag was not updated.")
print(f"Release {new_ver_str} completed.")
if close:
if branch in ("main", "master"):
print(
f"[INFO] close=True but current branch is {branch}; skipping branch deletion."
)
return
if not should_delete_branch(force=force):
print(f"[INFO] Branch deletion declined. Keeping branch {branch}.")
return
print(f"[INFO] Deleting branch {branch} after successful release...")
try:
close_branch(name=branch, base_branch="main", cwd=".")
except (RuntimeError, GitRunError) as exc:
print(f"[WARN] Failed to close branch {branch} automatically: {exc}")
def release(
pyproject_path: str = "pyproject.toml",
changelog_path: str = "CHANGELOG.md",
release_type: str = "patch",
message: str | None = None,
preview: bool = False,
force: bool = False,
close: bool = False,
retry: bool = False,
) -> None:
if retry:
retry_release(pyproject_path=pyproject_path, preview=preview)
return
if preview:
_release_impl(
pyproject_path=pyproject_path,
changelog_path=changelog_path,
release_type=release_type,
message=message,
preview=True,
close=close,
force=force,
def _close_released_branch(branch: str, force: bool) -> None:
if branch in MAIN_BRANCHES:
print(
f"[INFO] close=True but current branch is {branch}; skipping branch deletion."
)
return
# If force or non-interactive: no preview+confirmation step
if force or (not sys.stdin.isatty()):
_release_impl(
pyproject_path=pyproject_path,
changelog_path=changelog_path,
release_type=release_type,
message=message,
preview=False,
close=close,
force=force,
)
if not should_delete_branch(force=force):
print(f"[INFO] Branch deletion declined. Keeping branch {branch}.")
return
print(f"[INFO] Deleting branch {branch} after successful release...")
try:
close_branch(name=branch, base_branch="main", cwd=".")
except (RuntimeError, GitRunError) as exc:
print(f"[WARN] Failed to close branch {branch} automatically: {exc}")
def _release_impl(options: ReleaseOptions) -> None:
branch = _current_branch()
print(f"Releasing on branch: {branch}")
refuse_unsafe_config(".")
ensure_clean_and_synced(preview=options.preview)
ensure_head_tree(options.expect_tree)
prepared = _prepare(options, branch)
_commit_tag_push(prepared, options.preview)
if options.preview:
_finish_preview(prepared, options)
return
_move_latest(prepared.tag)
print(f"Release {prepared.version} completed.")
if options.close:
_close_released_branch(branch, options.force)
def release(options: ReleaseOptions) -> None:
if options.retry:
ensure_head_tree(options.expect_tree)
retry_release(pyproject_path=options.pyproject_path, preview=options.preview)
return
if options.preview or options.force or not sys.stdin.isatty():
_release_impl(options)
return
print("[INFO] Running preview before actual release...\n")
_release_impl(
pyproject_path=pyproject_path,
changelog_path=changelog_path,
release_type=release_type,
message=message,
preview=True,
close=close,
force=force,
)
_release_impl(replace(options, preview=True))
if not confirm_proceed_release():
print()
return
print("\n[INFO] Running REAL release...\n")
_release_impl(
pyproject_path=pyproject_path,
changelog_path=changelog_path,
release_type=release_type,
message=message,
preview=False,
close=close,
force=force,
)
_release_impl(options)
+392
View File
@@ -0,0 +1,392 @@
from __future__ import annotations
import os
import re
import shutil
import subprocess
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urlsplit
from pkgmgr.core.git import GitRunError, run
from pkgmgr.core.git.run import DEFAULT_CONFIG, SCAN_FLAGS, _scan_env
PUSH_SCHEMES = ("https", "ssh")
_SCP_URL = re.compile(
r"[A-Za-z0-9_][A-Za-z0-9._-]*@(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:.]+\]):\S+"
)
_URL_USERINFO = re.compile(r"(?<=://)[^/?#\s]*@")
TRUSTED_FLAGS = (
*SCAN_FLAGS,
"-c",
"protocol.allow=never",
*(
arg
for scheme in PUSH_SCHEMES
for arg in ("-c", f"protocol.{scheme}.allow=always")
),
"-c",
"transfer.bundleURI=false",
"-c",
"submodule.recurse=false",
"-c",
"fetch.recurseSubmodules=false",
)
_FILE_PROTOCOL = ("-c", "protocol.file.allow=always")
CHECKOUT_FETCH_FLAGS = (
"-c",
"protocol.allow=never",
*_FILE_PROTOCOL,
"-c",
"fetch.bundleURI=",
"-c",
"transfer.bundleURI=false",
"-c",
"core.alternateRefsCommand=true",
"-c",
"submodule.recurse=false",
"-c",
"fetch.recurseSubmodules=false",
)
class PushRefusedError(RuntimeError):
pass
@dataclass(frozen=True)
class Target:
repo_dir: str
tdir: str
branch: str
head: str
remote: str
fetch_url: str
push_urls: tuple[str, ...]
@property
def branch_ref(self) -> str:
return f"refs/heads/{self.branch}"
def try_git(repo_dir: str, *args: str) -> str | None:
try:
return run(list(args), cwd=repo_dir, scan=True)
except GitRunError:
return None
def _config_all(repo_dir: str, key: str) -> list[str]:
values = try_git(repo_dir, "config", "-z", "--get-all", key)
return values.split("\0")[:-1] if values else []
def file_url(path: str) -> str:
return Path(os.path.abspath(path)).as_uri()
def redact_urls(text: str) -> str:
"""
Args:
text: a diagnostic that may name remote URLs.
Returns:
The text with the userinfo of every scheme URL, which may carry a
password or token, replaced by `***`.
"""
return _URL_USERINFO.sub("***@", text)
def trusted_env(extra: dict[str, str]) -> dict[str, str]:
"""
Args:
extra: variables set on top, e.g. the author of a re-signed commit.
Returns:
The environment of every git call in the temporary repository: no
inherited `GIT_*` variable, the system and passwd-home global config,
no replace objects, prompts and askpass helpers left to that config.
"""
env = _scan_env(False, DEFAULT_CONFIG)
env.pop("GIT_TERMINAL_PROMPT", None)
env.pop("GIT_ASKPASS", None)
return {**env, **extra}
def _tgit_run(tdir: str, args: tuple[str, ...], local: bool) -> bytes:
"""
Args:
tdir: the temporary bare repository.
args: the git arguments.
local: also allow the file protocol, for transfers with the checkout.
Returns:
The raw stdout.
Raises:
GitRunError: git failed.
"""
cmd = [
"git",
f"--git-dir={tdir}",
*TRUSTED_FLAGS,
*(_FILE_PROTOCOL if local else ()),
*args,
]
result = subprocess.run(
cmd,
cwd=tdir,
env=trusted_env({}),
input=b"",
capture_output=True,
check=False,
)
if result.returncode != 0:
raise GitRunError(
redact_urls(
f"Git command failed in {tdir!r}: {' '.join(cmd)}\n"
f"Exit code: {result.returncode}\n"
f"STDERR:\n{os.fsdecode(result.stderr)}"
)
)
return result.stdout
def tgit_bytes(tdir: str, *args: str) -> bytes:
return _tgit_run(tdir, args, False)
def tgit(tdir: str, *args: str) -> str:
return os.fsdecode(_tgit_run(tdir, args, False)).strip()
def tgit_local(tdir: str, *args: str) -> str:
return os.fsdecode(_tgit_run(tdir, args, True)).strip()
def _ttry(tdir: str, *args: str) -> str | None:
try:
return tgit(tdir, *args) or None
except GitRunError:
return None
@contextmanager
def trusted_repo(repo_dir: str) -> Iterator[str]:
tdir = tempfile.mkdtemp(prefix="pkgmgr-push-")
try:
object_format = try_git(repo_dir, "config", "--get", "extensions.objectFormat")
tgit(
tdir,
"init",
"--quiet",
"--bare",
"--template=",
*((f"--object-format={object_format}",) if object_format else ()),
)
yield tdir
finally:
shutil.rmtree(tdir, ignore_errors=True)
def _scheme_url_allowed(url: str) -> bool:
if url.split("://", 1)[0] not in PUSH_SCHEMES:
return False
try:
parts = urlsplit(url)
host = parts.hostname or ""
user = parts.username or ""
except ValueError:
return False
return bool(host) and not host.startswith("-") and not user.startswith("-")
def url_allowed(url: str) -> bool:
if any(ch.isspace() or not ch.isprintable() for ch in url):
return False
if "://" not in url:
return _SCP_URL.fullmatch(url) is not None
return _scheme_url_allowed(url)
def _listed_head(repo_dir: str, tdir: str) -> tuple[str, str]:
symrefs: dict[str, str] = {}
refs: dict[str, str] = {}
listed = tgit_local(tdir, "ls-remote", "--symref", "--", file_url(repo_dir))
for line in listed.splitlines():
value, _, name = line.partition("\t")
if value.startswith("ref: "):
symrefs[name] = value[len("ref: ") :]
else:
refs[name] = value
target = symrefs.get("HEAD", "")
if "HEAD" not in refs or not target.startswith("refs/heads/"):
raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push")
return target[len("refs/heads/") :], refs["HEAD"]
def _push_remote(repo_dir: str, branch: str) -> str:
return (
try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote")
or try_git(repo_dir, "config", "--get", "remote.pushDefault")
or try_git(repo_dir, "config", "--get", f"branch.{branch}.remote")
or "origin"
)
def open_target(repo_dir: str, tdir: str) -> Target:
"""
Args:
repo_dir: the checkout, read through upload-pack and `git config`.
tdir: the temporary bare repository.
Returns:
The checkout's current branch, its HEAD and the push remote's URLs.
Raises:
PushRefusedError: detached HEAD, no URL, or a URL that is not https,
ssh or user@host:path.
"""
branch, head = _listed_head(repo_dir, tdir)
remote = _push_remote(repo_dir, branch)
urls = _config_all(repo_dir, f"remote.{remote}.url")
if not urls:
raise PushRefusedError(f"{repo_dir}: remote {remote} has no URL")
push_urls = tuple(_config_all(repo_dir, f"remote.{remote}.pushurl") or urls)
for url in (urls[0], *push_urls):
if not url_allowed(url):
raise PushRefusedError(
f"{repo_dir}: remote {remote} URL {redact_urls(repr(url))} is not "
"https, ssh or user@host:path; local paths and other transports are "
"not pushed to"
)
return Target(repo_dir, tdir, branch, head, remote, urls[0], push_urls)
def copy_head(target: Target, *, tags: bool) -> None:
tgit_local(
target.tdir,
"fetch",
"--quiet",
"--no-tags",
"--no-write-fetch-head",
"--no-recurse-submodules",
"--",
file_url(target.repo_dir),
target.head,
*(("+refs/tags/*:refs/tags/*",) if tags else ()),
)
def fetch_heads(
target: Target, url: str, names: list[str], prefix: str
) -> dict[str, str]:
wanted = [f"refs/heads/{name}" for name in dict.fromkeys(names)]
listed = tgit(target.tdir, "ls-remote", "--", url, *wanted).splitlines()
present = {ln.partition("\t")[2] for ln in listed} & set(wanted)
if not present:
return {}
tgit(
target.tdir,
"fetch",
"--quiet",
"--no-tags",
"--no-write-fetch-head",
"--no-recurse-submodules",
"--",
url,
*(f"+{ref}:{prefix}/{ref}" for ref in sorted(present)),
)
return {
ref[len("refs/heads/") :]: tgit(
target.tdir, "rev-parse", "--verify", "--quiet", f"{prefix}/{ref}"
)
for ref in present
}
def _upstream_branch(target: Target) -> tuple[str, str] | None:
remote = try_git(
target.repo_dir, "config", "--get", f"branch.{target.branch}.remote"
)
merge = try_git(target.repo_dir, "config", "--get", f"branch.{target.branch}.merge")
if not remote or remote == "." or not (merge or "").startswith("refs/heads/"):
return None
return remote, merge[len("refs/heads/") :]
def _upstream_tip(target: Target) -> tuple[str | None, str | None]:
upstream = _upstream_branch(target)
if upstream is None:
return None, None
remote, name = upstream
if remote == target.remote:
return name, None
urls = _config_all(target.repo_dir, f"remote.{remote}.url")
if not urls or not url_allowed(urls[0]):
return None, None
try:
return None, fetch_heads(target, urls[0], [name], "refs/pkgmgr/upstream").get(
name
)
except GitRunError:
return None, None
def bases(target: Target) -> tuple[str | None, list[str | None]]:
"""
Returns:
The push remote's tip of the branch, and the candidate bases in order:
that tip, the upstream's tip, then the remote's main and master.
"""
upstream_name, upstream_sha = _upstream_tip(target)
names = [
target.branch,
*([upstream_name] if upstream_name else []),
"main",
"master",
]
tips = fetch_heads(target, target.fetch_url, names, "refs/pkgmgr/base")
upstream = tips.get(upstream_name) if upstream_name else upstream_sha
return tips.get(target.branch), [
tips.get(target.branch),
upstream,
tips.get("main"),
tips.get("master"),
]
def unpushed_signatures(
target: Target, candidates: list[str | None]
) -> tuple[str, dict[str, str]]:
"""
Args:
target: the copied checkout.
candidates: bases as `bases` returns them; the first with a merge base wins.
Returns:
The merge base, and the `%G?` signature status of every commit after it.
Raises:
PushRefusedError: no candidate shares history with HEAD.
"""
for tip in candidates:
base = tip and _ttry(target.tdir, "merge-base", target.head, tip)
if base:
lines = tgit(
target.tdir, "log", "--format=%H %G?", f"{base}..{target.head}"
).splitlines()
return base, dict(line.split() for line in lines)
raise PushRefusedError(
f"{target.repo_dir}: no {target.remote}/{target.branch}, no upstream and no "
f"{target.remote}/main or {target.remote}/master to sign against"
)
@@ -7,8 +7,13 @@ from typing import Any
from pkgmgr.core.git.queries import get_repo_root
try:
from jinja2 import Environment, FileSystemLoader, StrictUndefined
except ImportError as exc: # pragma: no cover
from jinja2 import (
Environment,
FileSystemLoader,
StrictUndefined,
select_autoescape,
)
except ImportError as exc: # pragma: no cover
Environment = None # type: ignore
FileSystemLoader = None # type: ignore
StrictUndefined = None # type: ignore
@@ -41,7 +46,18 @@ class TemplateRenderer:
env = Environment(
loader=FileSystemLoader(self.templates_dir),
undefined=StrictUndefined,
autoescape=False,
autoescape=select_autoescape(
enabled_extensions=(
"html",
"htm",
"xml",
"html.j2",
"htm.j2",
"xml.j2",
),
default_for_string=False,
default=False,
),
keep_trailing_newline=True,
)
+299 -201
View File
@@ -1,7 +1,10 @@
from __future__ import annotations
import os
import re
import subprocess
import threading
from dataclasses import dataclass
from typing import Any
from pkgmgr.actions.repository._parallel import (
@@ -9,25 +12,42 @@ from pkgmgr.actions.repository._parallel import (
resolve_repos,
run_on_repos,
)
from pkgmgr.actions.repository._trusted import (
CHECKOUT_FETCH_FLAGS,
TRUSTED_FLAGS,
PushRefusedError,
Target,
bases,
copy_head,
fetch_heads,
file_url,
open_target,
redact_urls,
tgit,
tgit_bytes,
trusted_env,
trusted_repo,
try_git,
unpushed_signatures,
)
from pkgmgr.core.git import GitRunError, run
from pkgmgr.core.git.queries import UNSAFE_CONFIG, local_config
from pkgmgr.core.git.run import SCAN_FLAGS
Repository = dict[str, Any]
# Re-signing opens pinentry; parallel pushes must not ask for the passphrase at once.
_SIGN_LOCK = threading.Lock()
class PushRefusedError(RuntimeError):
"""Raised when a push would ship unsigned commits or overwrite a mirror."""
_AUTHOR = re.compile(rb"(.*?) <([^>]*)> (\d+) ([+-]\d{4})")
def _try_git(repo_dir: str, *args: str) -> str | None:
try:
return run(list(args), cwd=repo_dir)
except GitRunError:
return None
@dataclass(frozen=True)
class _Push:
extra_args: tuple[str, ...]
refs: tuple[str, ...]
rewrite: bool
preview: bool
old_tip: str | None
def refuse_unsafe_config(repo_dir: str) -> None:
@@ -38,9 +58,10 @@ def refuse_unsafe_config(repo_dir: str) -> None:
Raises:
PushRefusedError: the repository's own config, which an agent may have
written, sets a key that makes git run a program or reroute the push.
Filter drivers stay allowed on purpose: git-lfs and git-crypt need
them locally, so a clean filter can still run in the amend's index
refresh, as it did before.
Signing and pushing never read that config, so this is only an early
refusal; filter drivers stay allowed because git-lfs and git-crypt
need them locally.
"""
unsafe = local_config(repo_dir, UNSAFE_CONFIG)
if unsafe:
@@ -50,142 +71,171 @@ def refuse_unsafe_config(repo_dir: str) -> None:
)
def _push_target(repo_dir: str) -> tuple[str, str]:
refuse_unsafe_config(repo_dir)
branch = run(["rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_dir)
if branch == "HEAD":
raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push")
remote = (
_try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote")
or _try_git(repo_dir, "config", "--get", "remote.pushDefault")
or _try_git(repo_dir, "config", "--get", f"branch.{branch}.remote")
or "origin"
)
return branch, remote
def _head_commit(target: Target) -> tuple[list[str], dict[str, str], bytes]:
"""
Args:
target: the copied checkout.
Returns:
The `git commit-tree` arguments that rebuild HEAD (encoding, tree,
parents), its author as environment variables, and its message.
Raises:
PushRefusedError: HEAD has no tree or no parseable author.
"""
fields, message = _commit_fields(target)
author = _AUTHOR.fullmatch((fields.get(b"author") or [b""])[0])
if not fields.get(b"tree") or author is None:
raise PushRefusedError(
f"{target.repo_dir}: cannot parse HEAD {target.head[:10]}"
)
name, email, stamp, zone = (os.fsdecode(part) for part in author.groups())
args = [
"-c",
"i18n.commitEncoding="
+ os.fsdecode((fields.get(b"encoding") or [b"UTF-8"])[0]),
"commit-tree",
os.fsdecode(fields[b"tree"][0]),
*(arg for p in fields.get(b"parent", []) for arg in ("-p", os.fsdecode(p))),
]
env = {
"GIT_AUTHOR_NAME": name,
"GIT_AUTHOR_EMAIL": email,
"GIT_AUTHOR_DATE": f"@{stamp} {zone}",
}
return args, env, message
def _unpushed_signatures(
repo_dir: str, remote: str, branch: str
) -> tuple[str, dict[str, str]]:
for ref in (
f"refs/remotes/{remote}/{branch}",
"@{u}",
f"refs/remotes/{remote}/main",
f"refs/remotes/{remote}/master",
):
base = _try_git(repo_dir, "merge-base", "HEAD", ref)
if base:
lines = run(
["log", "--format=%H %G?", f"{base}..HEAD"], cwd=repo_dir
).splitlines()
return base, dict(line.split() for line in lines)
raise PushRefusedError(
f"{repo_dir}: no {remote}/{branch}, no upstream and no {remote}/main or "
f"{remote}/master to sign against"
def _commit_fields(target: Target) -> tuple[dict[bytes, list[bytes]], bytes]:
header, _, message = tgit_bytes(
target.tdir, "cat-file", "commit", target.head
).partition(b"\n\n")
fields: dict[bytes, list[bytes]] = {}
for line in header.split(b"\n"):
key, _, value = line.partition(b" ")
fields.setdefault(key, []).append(value)
return fields, message
def _sign_head(target: Target) -> str:
args, author, message = _head_commit(target)
cmd = ["git", f"--git-dir={target.tdir}", *TRUSTED_FLAGS, *args, "-S"]
with _SIGN_LOCK:
result = subprocess.run(
cmd,
cwd=target.tdir,
env=trusted_env(author),
input=message,
stdout=subprocess.PIPE,
check=False,
)
signed = os.fsdecode(result.stdout).strip()
if result.returncode != 0 or not signed:
raise PushRefusedError(
f"{target.repo_dir}: signing HEAD {target.head[:10]} failed"
)
tgit(target.tdir, "update-ref", "refs/pkgmgr/signed", signed)
return signed
def _adopt(target: Target, signed: str) -> None:
"""
Args:
target: the checkout and its temporary repository.
signed: the signed commit; fetched into the checkout, then its branch
moves there. That fetch still reads the checkout's config, so
CHECKOUT_FETCH_FLAGS pins every key that would fetch from elsewhere
or run a program, in case the refuse-list check is stale.
Raises:
PushRefusedError: the branch moved away from HEAD while it was signed.
"""
run(
[
*CHECKOUT_FETCH_FLAGS,
"fetch",
"--quiet",
"--no-tags",
"--no-write-fetch-head",
"--no-recurse-submodules",
"--upload-pack=git-upload-pack",
"--",
file_url(target.tdir),
signed,
],
cwd=target.repo_dir,
scan=True,
)
try:
run(
[
"update-ref",
"-m",
"pkgmgr push: sign HEAD",
target.branch_ref,
signed,
target.head,
],
cwd=target.repo_dir,
scan=True,
)
except GitRunError as exc:
raise PushRefusedError(
f"{target.repo_dir}: {target.branch} moved away from {target.head[:10]} "
f"while it was signed; left it where it is, signed {signed[:10]} is dropped"
) from exc
def sign_unpushed(repo_dir: str, *, preview: bool = False) -> None:
"""
Args:
repo_dir: checkout whose current branch is signed.
preview: print the fetch and the amend instead of running them.
preview: read and check as usual, but print the signing instead of doing it.
"""
branch, remote = _push_target(repo_dir)
run(
["fetch", "--quiet", "--no-recurse-submodules", "--", remote],
cwd=repo_dir,
preview=preview,
)
base, signatures = _unpushed_signatures(repo_dir, remote, branch)
head = run(["rev-parse", "HEAD"], cwd=repo_dir)
older = sum(1 for sha, s in signatures.items() if sha != head and s != "G")
if older:
print(
f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of "
f"{repo_dir} stay unsigned: signing them would rewrite history"
)
if signatures.get(head, "G") == "G":
return
if run(
[
*SCAN_FLAGS,
"diff",
"--cached",
"--name-only",
"--no-ext-diff",
"--ignore-submodules=none",
"HEAD",
],
cwd=repo_dir,
):
raise PushRefusedError(f"{repo_dir}: staged changes, cannot sign HEAD")
cmd = [
"git",
*SCAN_FLAGS,
"commit",
"--amend",
"--no-edit",
"--no-verify",
"--allow-empty",
"-S",
]
print(f"[push] Signing HEAD {head[:10]} in {repo_dir}")
if preview:
print(f"[PREVIEW] Would run in {repo_dir!r}: {' '.join(cmd)}")
return
with _SIGN_LOCK:
result = subprocess.run(cmd, cwd=repo_dir, check=False)
if result.returncode != 0:
raise PushRefusedError(f"{repo_dir}: signing HEAD {head[:10]} failed")
def _lease(
repo_dir: str,
url: str,
branch_ref: str,
tracking: str | None,
keep: tuple[str, ...],
preview: bool,
) -> str:
if tracking is not None:
sha = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking) or ""
else:
listed = run(["ls-remote", "--", url, branch_ref], cwd=repo_dir).splitlines()
sha = next(
(ln.split()[0] for ln in listed if ln.split()[1:] == [branch_ref]), ""
)
if sha and not preview:
run(
[
"fetch",
"--quiet",
"--no-tags",
"--no-recurse-submodules",
"--",
url,
branch_ref,
],
cwd=repo_dir,
refuse_unsafe_config(repo_dir)
with trusted_repo(repo_dir) as tdir:
target = open_target(repo_dir, tdir)
copy_head(target, tags=False)
_tip, candidates = bases(target)
base, signatures = unpushed_signatures(target, candidates)
head = target.head
older = sum(1 for sha, s in signatures.items() if sha != head and s != "G")
if older:
print(
f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of "
f"{repo_dir} stay unsigned: signing them would rewrite history"
)
if not sha or preview:
return sha
if signatures.get(head, "G") == "G":
return
print(f"[push] Signing HEAD {head[:10]} in {repo_dir}")
if preview:
print(
f"[PREVIEW] Would re-sign {head[:10]} with git commit-tree -S in a "
f"temporary repository and move {target.branch_ref} of {repo_dir!r} to it"
)
return
_adopt(target, _sign_head(target))
def _refuse_lost(target: Target, url: str, sha: str, keep: tuple[str, ...]) -> None:
lost: set[str] | None = None
for tip in keep:
plus = {
line[2:]
for line in run(["cherry", tip, sha], cwd=repo_dir).splitlines()
for line in tgit(target.tdir, "cherry", tip, sha).splitlines()
if line.startswith("+")
}
lost = plus if lost is None else lost & plus
if lost:
raise PushRefusedError(
f"{url}: {len(lost)} commit(s) exist only there, not overwritten: "
f"{redact_urls(url)}: {len(lost)} commit(s) exist only there, "
"not overwritten: "
f"{' '.join(s[:10] for s in sorted(lost))}; "
"pass --rewrite for a deliberate history rewrite"
)
return sha
def push_branch(
@@ -198,13 +248,6 @@ def push_branch(
preview: bool = False,
) -> None:
"""
Push the current branch to every pushurl of its push remote, each with its own lease.
The fetch URL is leased against the remote-tracking ref, every other
pushurl against its own branch tip; each only after `git cherry` shows it
holds no commit the new tip lacks. A mirror failure is reported after the
others were pushed; a canonical failure stops before any mirror.
Args:
repo_dir: checkout whose current branch is pushed.
extra_args: flags appended to every `git push`.
@@ -213,73 +256,134 @@ def push_branch(
rewrite: replace commits of the old canonical tip; the fetch URL skips
the cherry check, mirrors only refuse commits the old tip never had.
preview: print the pushes instead of running them.
"""
branch, remote = _push_target(repo_dir)
head = run(["rev-parse", "HEAD"], cwd=repo_dir)
if sign:
_base, signatures = _unpushed_signatures(repo_dir, remote, branch)
if not preview and signatures.get(head, "G") != "G":
raise PushRefusedError(
f"{repo_dir}: HEAD {head[:10]} is unsigned; run `pkgmgr push` to sign it"
)
fetch_url = run(["remote", "get-url", "--", remote], cwd=repo_dir)
push_urls = run(
["remote", "get-url", "--push", "--all", "--", remote], cwd=repo_dir
).splitlines()
branch_ref = f"refs/heads/{branch}"
tracking = f"refs/remotes/{remote}/{branch}"
old_tip = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking)
if fetch_url not in push_urls:
print(
f"[push] WARN {remote}: fetch URL is no pushurl; every URL is leased "
"as a mirror, tracking ref and upstream stay untouched"
"""
refuse_unsafe_config(repo_dir)
with trusted_repo(repo_dir) as tdir:
target = open_target(repo_dir, tdir)
copy_head(target, tags=True)
old_tip = _old_tip(target, sign, preview)
plan = _Push(tuple(extra_args), refs, rewrite, preview, old_tip)
if target.fetch_url not in target.push_urls:
print(
f"[push] WARN {target.remote}: fetch URL is no pushurl; every URL is "
"leased as a mirror, tracking ref and upstream stay untouched"
)
failed: list[str] = []
ordered = sorted(target.push_urls, key=lambda u: u != target.fetch_url)
for index, url in enumerate(ordered):
if not _push_url(target, plan, index, url):
failed.append(url)
if failed:
raise PushRefusedError(
f"{repo_dir}: push failed for {redact_urls(', '.join(failed))}"
)
failed: list[str] = []
for url in sorted(push_urls, key=lambda u: u != fetch_url):
if url == fetch_url:
keep: tuple[str, ...] = () if rewrite else (head,)
else:
keep = (head, old_tip) if rewrite and old_tip else (head,)
try:
expect = _lease(
repo_dir,
url,
branch_ref,
tracking if url == fetch_url else None,
keep,
preview,
)
run(
[
"push",
"--follow-tags",
"--no-recurse-submodules",
f"--force-with-lease={branch_ref}:{expect}",
*extra_args,
"--",
url,
branch_ref,
*refs,
],
cwd=repo_dir,
preview=preview,
)
except (GitRunError, PushRefusedError) as exc:
if url == fetch_url:
raise
print(f"[push] FAILED {url}\n{exc}")
failed.append(url)
continue
print(f"[push] {url} <- {branch} {head[:10]}")
if url == fetch_url and not preview:
run(["update-ref", tracking, head], cwd=repo_dir)
if not _try_git(repo_dir, "rev-parse", "--abbrev-ref", "@{u}"):
run(["branch", f"--set-upstream-to={remote}/{branch}"], cwd=repo_dir)
if failed:
raise PushRefusedError(f"{repo_dir}: push failed for {', '.join(failed)}")
def _old_tip(target: Target, sign: bool, preview: bool) -> str | None:
"""
Args:
target: the copied checkout.
sign: also refuse an unpushed, unsigned HEAD.
preview: skip that refusal.
Returns:
The canonical URL's branch tip, or None when it has no such branch.
"""
if not sign:
return fetch_heads(
target, target.fetch_url, [target.branch], "refs/pkgmgr/base"
).get(target.branch)
old_tip, candidates = bases(target)
_base, signatures = unpushed_signatures(target, candidates)
if not preview and target.head in signatures and signatures[target.head] != "G":
raise PushRefusedError(
f"{target.repo_dir}: HEAD {target.head[:10]} is unsigned; "
"run `pkgmgr push` to sign it"
)
return old_tip
def _lease(target: Target, plan: _Push, index: int, url: str) -> str:
if url == target.fetch_url:
return plan.old_tip or ""
tips = fetch_heads(target, url, [target.branch], f"refs/pkgmgr/lease/{index}")
return tips.get(target.branch) or ""
def _keep(target: Target, plan: _Push, canonical: bool) -> tuple[str, ...]:
if canonical:
return () if plan.rewrite else (target.head,)
if plan.rewrite and plan.old_tip:
return (target.head, plan.old_tip)
return (target.head,)
def _push_url(target: Target, plan: _Push, index: int, url: str) -> bool:
"""
Args:
target: the copied checkout.
plan: the push options and the canonical URL's old tip.
index: position of the URL, naming its lease ref.
url: the URL pushed to.
Returns:
False when a mirror failed; the failure is printed.
Raises:
GitRunError, PushRefusedError: the canonical URL failed.
"""
canonical = url == target.fetch_url
try:
expect = _lease(target, plan, index, url)
if expect and not plan.preview:
_refuse_lost(target, url, expect, _keep(target, plan, canonical))
cmd = [
"push",
"--follow-tags",
"--no-recurse-submodules",
"--no-verify",
f"--force-with-lease={target.branch_ref}:{expect}",
*plan.extra_args,
"--",
url,
f"{target.head}:{target.branch_ref}",
*plan.refs,
]
if plan.preview:
print(
f"[PREVIEW] Would run in a temporary copy of {target.repo_dir!r}: "
f"git {redact_urls(' '.join(cmd))}"
)
else:
tgit(target.tdir, *cmd)
except (GitRunError, PushRefusedError) as exc:
if canonical:
raise
print(f"[push] FAILED {redact_urls(url)}\n{exc}")
return False
print(f"[push] {redact_urls(url)} <- {target.branch} {target.head[:10]}")
if canonical and not plan.preview:
_track(target)
return True
def _track(target: Target) -> None:
tracking = f"refs/remotes/{target.remote}/{target.branch}"
run(["update-ref", tracking, target.head], cwd=target.repo_dir, scan=True)
upstream = f"{target.branch}@{{upstream}}"
if not try_git(target.repo_dir, "rev-parse", "--abbrev-ref", upstream):
run(
[
"branch",
f"--set-upstream-to={target.remote}/{target.branch}",
target.branch,
],
cwd=target.repo_dir,
scan=True,
)
def _push_one(
@@ -302,9 +406,6 @@ def push_repo_dirs(
jobs: int = 1,
rewrite: bool = False,
) -> None:
"""
Sign and push each ``(identifier, repo_dir)``, optionally in parallel.
"""
run_on_repos(
repos,
lambda rd: _push_one(rd, extra_args, sign, rewrite, preview),
@@ -323,9 +424,6 @@ def push_in_parallel(
jobs: int = 1,
rewrite: bool = False,
) -> None:
"""
Sign and push each selected repository, optionally in parallel.
"""
push_repo_dirs(
resolve_repos(selected_repos, repositories_base_dir, all_repos),
extra_args,
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019-2024 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+8 -2
View File
@@ -1,5 +1,9 @@
{% set status_letters = {"added": "A", "deleted": "D", "modified": "M", "renamed": "R", "copied": "C", "untracked": "U"} %}
{% set signs = {"add": "+", "del": "-", "ctx": "", "meta": ""} %}
{% set icon_paths = {
"arrows-expand": "M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8M7.646.146a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 1.707V5.5a.5.5 0 0 1-1 0V1.707L6.354 2.854a.5.5 0 1 1-.708-.708zM8 10a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 0 1 .708-.708L7.5 14.293V10.5A.5.5 0 0 1 8 10",
"arrows-collapse": "M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8m7-8a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 1 1 .708-.708L7.5 4.293V.5A.5.5 0 0 1 8 0m-.5 11.707-1.146 1.147a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 11.707V15.5a.5.5 0 0 1-1 0z",
} %}
{% set style %}
:root {
color-scheme: light dark;
@@ -93,6 +97,7 @@ input[type="search"] { width: 260px; max-width: 100%; padding: 5px 10px; border:
input[type="search"]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
button { padding: 5px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--subtle); color: var(--text); font: 500 13px var(--sans); cursor: pointer; }
button:hover { border-color: var(--muted); }
button.icon { display: inline-flex; align-items: center; justify-content: center; padding: 6px 8px; }
main { padding-top: 24px; padding-bottom: 80px; }
.group { margin-bottom: 36px; }
h2 { display: flex; flex-wrap: wrap; align-items: baseline; gap: 12px; margin: 0 0 12px; font-size: 17px; font-weight: 600; }
@@ -187,6 +192,7 @@ details.commit > summary { padding: 10px 14px; }
})();
{% endset %}
{% macro stat(added, removed) %}<span class="stat"><span class="add">+{{ added }}</span><span class="del">&minus;{{ removed }}</span></span>{% endmacro %}
{% macro icon(name) %}<svg class="bi bi-{{ name }}" width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true" focusable="false"><path fill-rule="evenodd" d="{{ icon_paths[name] }}"/></svg>{% endmacro %}
{% macro plural(count, word) %}{{ count }} {{ word }}{{ "" if count == 1 else "s" }}{% endmacro %}
{% macro file_block(file, open) %}
<details class="file" id="{{ file.anchor }}" data-path="{{ file.search }}"{% if open %} open{% endif %}>
@@ -282,8 +288,8 @@ details.commit > summary { padding: 10px 14px; }
<div class="spacer"></div>
<input id="filter" type="search" placeholder="Filter files by path ( / )" autocomplete="off" spellcheck="false" aria-label="Filter files by path">
<span id="filter-count" class="muted"></span>
<button type="button" id="expand-all">Expand all</button>
<button type="button" id="collapse-all">Collapse all</button>
<button type="button" id="expand-all" class="icon" title="Expand all" aria-label="Expand all">{{ icon("arrows-expand") }}</button>
<button type="button" id="collapse-all" class="icon" title="Collapse all" aria-label="Collapse all">{{ icon("arrows-collapse") }}</button>
</div>
</nav>
<main>
+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",
]
+18 -8
View File
@@ -11,7 +11,7 @@ from pkgmgr.actions.branch import (
open_branch,
tree,
)
from pkgmgr.actions.branch.gc import main_repo_root
from pkgmgr.actions.branch.gc import local_repo_root, main_repo_root
from pkgmgr.cli.context import CLIContext
from pkgmgr.core.git.errors import GitBaseError
from pkgmgr.core.repository.dir import get_repo_dir
@@ -60,14 +60,23 @@ def refresh_tree(roots: list[str]) -> None:
print(f"WARN tree file not rewritten for {root}: {exc}", file=sys.stderr)
def scan_repo_roots(args, ctx: CLIContext) -> list[str]:
def scan_repo_roots(args, ctx: CLIContext, local: bool = False) -> list[str]:
"""
Resolve the repositories a scan covers: the current one, or every
pkgmgr-managed one with --all. Exits with 2 outside a repository.
Args:
args: parsed arguments; `all` selects every managed repository.
ctx: CLI context.
local: resolve the current repository as scope `local` does, also in
a submodule or with a separate git dir, refusing a mismatch.
Returns:
The main worktree roots to scan.
"""
if not args.all:
try:
return [main_repo_root(".")]
return [(local_repo_root if local else main_repo_root)(".")]
except GitBaseError as exc:
print(f"Not inside a git repository: {exc}", file=sys.stderr)
sys.exit(2)
@@ -84,7 +93,7 @@ def scan_options(args) -> dict:
def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
roots = scan_repo_roots(args, ctx)
roots = scan_repo_roots(args, ctx, local=scope == "local")
code = cleanup(
roots,
scope=scope,
@@ -94,7 +103,7 @@ def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
hooks=pinned_hooks(ctx),
**scan_options(args),
)
if args.apply:
if args.apply and scope != "local":
refresh_tree(roots)
sys.exit(code)
@@ -107,8 +116,9 @@ def handle_branch(args, ctx: CLIContext) -> None:
- pkgmgr branch open [<name>] [--base <branch>]
- pkgmgr branch close [<name>] [--base <branch>] [--force|-f]
- pkgmgr branch drop [<name>] [--base <branch>] [--force|-f]
- pkgmgr branch cleanup [--apply] [--json] [--all] [--branch N]... [--exclude N]...
[--merged-into REF]... [--sizes] [--min-age HOURS]
- pkgmgr branch cleanup [--apply] [--json] [--local] [--all] [--branch N]...
[--exclude N]... [--merged-into REF]... [--sizes]
[--min-age HOURS]
- pkgmgr branch purge [--all] [--branch N]... [--exclude N]...
[--merged-into REF]... [--sizes] [--min-age HOURS]
- pkgmgr branch tree [--format json|yaml] [--output FILE]
@@ -124,7 +134,7 @@ def handle_branch(args, ctx: CLIContext) -> None:
)
if args.subcommand == "cleanup":
run_cleanup(args, ctx, "branch")
run_cleanup(args, ctx, "local" if args.local else "branch")
if args.subcommand == "purge":
roots = scan_repo_roots(args, ctx)
+112 -56
View File
@@ -5,14 +5,123 @@ import sys
from typing import Any
from pkgmgr.actions.publish import publish as run_publish
from pkgmgr.actions.release import ReleaseOptions
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 _release_options(args) -> ReleaseOptions:
return ReleaseOptions(
pyproject_path="pyproject.toml",
changelog_path="CHANGELOG.md",
release_type=args.release_type or "patch",
message=args.message or None,
preview=getattr(args, "preview", False),
force=getattr(args, "force", False),
close=getattr(args, "close", False),
retry=bool(getattr(args, "retry", False)),
expect_tree=getattr(args, "expect_tree", None),
)
def _resolve_repo_dir(ctx: CLIContext, repo: Repository, identifier: str) -> str | None:
"""
Returns:
The repository's existing directory, or None after a skip warning.
"""
try:
repo_dir = repo.get("directory") or get_repo_dir(
ctx.repositories_base_dir, repo
)
except (AttributeError, KeyError, TypeError) as exc:
print(
f"[WARN] Skipping repository {identifier}: failed to resolve directory: {exc}"
)
return None
if not os.path.isdir(repo_dir):
print(f"[WARN] Skipping repository {identifier}: directory missing.")
return None
return repo_dir
def _release_type_usable(args, identifier: str) -> bool:
retry = bool(getattr(args, "retry", False))
if retry and args.release_type:
print(
f"[WARN] Ignoring release_type '{args.release_type}' for {identifier} — --retry skips version bumps."
)
if not retry and not args.release_type:
print(
f"[WARN] Skipping {identifier}: release_type is required unless --retry is set."
)
return False
return True
def _release_repo(args, repo: Repository, repo_dir: str, identifier: str) -> None:
options = _release_options(args)
action_label = "retry-release" if options.retry else "release"
print(f"[pkgmgr] Running {action_label} for repository {identifier}...")
cwd_before = os.getcwd()
try:
os.chdir(repo_dir)
run_release(options)
if not getattr(args, "no_publish", False):
print(f"[pkgmgr] Running publish for repository {identifier}...")
is_tty = sys.stdin.isatty()
run_publish(
repo=repo,
repo_dir=repo_dir,
preview=options.preview,
interactive=is_tty,
allow_prompt=is_tty,
)
finally:
os.chdir(cwd_before)
def handle_release(
args,
ctx: CLIContext,
@@ -31,60 +140,7 @@ def handle_release(
for repo in selected:
identifier = get_repo_identifier(repo, ctx.all_repositories)
try:
repo_dir = repo.get("directory") or get_repo_dir(
ctx.repositories_base_dir, repo
)
except (AttributeError, KeyError, TypeError) as exc:
print(
f"[WARN] Skipping repository {identifier}: failed to resolve directory: {exc}"
)
repo_dir = _resolve_repo_dir(ctx, repo, identifier)
if repo_dir is None or not _release_type_usable(args, identifier):
continue
if not os.path.isdir(repo_dir):
print(f"[WARN] Skipping repository {identifier}: directory missing.")
continue
retry = bool(getattr(args, "retry", False))
if retry and args.release_type:
print(
f"[WARN] Ignoring release_type '{args.release_type}' for {identifier} — --retry skips version bumps."
)
if not retry and not args.release_type:
print(
f"[WARN] Skipping {identifier}: release_type is required unless --retry is set."
)
continue
action_label = "retry-release" if retry else "release"
print(f"[pkgmgr] Running {action_label} for repository {identifier}...")
cwd_before = os.getcwd()
try:
os.chdir(repo_dir)
run_release(
pyproject_path="pyproject.toml",
changelog_path="CHANGELOG.md",
release_type=args.release_type or "patch",
message=args.message or None,
preview=getattr(args, "preview", False),
force=getattr(args, "force", False),
close=getattr(args, "close", False),
retry=retry,
)
if not getattr(args, "no_publish", False):
print(f"[pkgmgr] Running publish for repository {identifier}...")
is_tty = sys.stdin.isatty()
run_publish(
repo=repo,
repo_dir=repo_dir,
preview=getattr(args, "preview", False),
interactive=is_tty,
allow_prompt=is_tty,
)
finally:
os.chdir(cwd_before)
_release_repo(args, repo, repo_dir, identifier)
+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":
+35
View File
@@ -105,6 +105,41 @@ def add_branch_subparsers(
),
)
add_apply_options(branch_cleanup)
branch_cleanup.add_argument(
"--local",
action="store_true",
help=(
"Delete only local branches whose tip is an ancestor of origin's "
"remote-tracking default (else the only remote's) or a --merged-into "
"REF, against the planned sha; refuse a repository without such a "
"default, one git fails on, one whose holds cannot be read, one "
"whose git dir is neither its common dir nor directly under "
"<common>/worktrees/ and one with a symlink in or below refs, "
"packed-refs, reftable or logs/refs, and still print the plan; skip "
"a symbolic branch, a branch any symbolic ref of any worktree names, "
"a branch a worktree, worktree registration, rebase or bisect holds, "
"a --merged-into target, a branch with branch.<name>.deleteMerged "
"false in any worktree's or the system config and the local "
"upstream of a branch that stays, also of one --branch or --exclude "
"leaves out; "
"run git without inherited GIT_* variables but "
"GIT_CEILING_DIRECTORIES; the keep config reads run once with the "
"caller's GIT_CONFIG_* variables and once with the default system "
"and passwd-home config, and either read's keep counts; read no "
"forge token; "
"never fetch, push, delete a remote branch, run docker or hooks, or "
"refresh the branch tree file; exit 1 when an item failed, else 2 "
"when a repository was refused, else 0; exit 2 without a plan when, "
"without --all, the current directory is in no git repository, its "
"git dir is neither its common dir nor directly under "
"<common>/worktrees/, its main worktree belongs to another "
"repository or its path or git output is not UTF-8, on --apply "
"outside the host PID namespace, on a --merged-into REF that is not "
"exactly one branch or remote-tracking ref (X~0, X^0, X@{0}, a sha), "
"and on a --branch "
"that matches nothing; meant for working clones"
),
)
branch_purge = branch_subparsers.add_parser(
"purge",
+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"
),
)
+32 -17
View File
@@ -5,20 +5,7 @@ import argparse
from .common import add_identifier_arguments
def add_release_subparser(
subparsers: argparse._SubParsersAction,
) -> None:
"""
Register the release command.
"""
release_parser = subparsers.add_parser(
"release",
help=(
"Create a release for repository/ies by incrementing version "
"and updating the changelog."
),
)
def _add_version_arguments(release_parser: argparse.ArgumentParser) -> None:
release_parser.add_argument(
"release_type",
nargs="?",
@@ -36,8 +23,8 @@ def add_release_subparser(
help="Optional release message to add to the changelog and tag.",
)
add_identifier_arguments(release_parser)
def _add_flow_arguments(release_parser: argparse.ArgumentParser) -> None:
release_parser.add_argument(
"--close",
action="store_true",
@@ -52,8 +39,7 @@ def add_release_subparser(
"--force",
action="store_true",
help=(
"Skip the interactive preview+confirmation step and run the "
"release directly."
"Run the release directly, without the interactive preview and its prompt."
),
)
@@ -63,6 +49,19 @@ def add_release_subparser(
help="Do not run publish automatically after a successful release.",
)
def _add_safety_arguments(release_parser: argparse.ArgumentParser) -> None:
release_parser.add_argument(
"--expect-tree",
metavar="TREE",
default=None,
help=(
"Refuse to release unless HEAD's tree (git rev-parse HEAD^{tree}) "
"equals this full sha after the pull and before any file is "
"written; with --retry, before anything is pushed."
),
)
release_parser.add_argument(
"--retry",
action="store_true",
@@ -74,3 +73,19 @@ def add_release_subparser(
"post-tag push or PyPI upload failed mid-flight."
),
)
def add_release_subparser(
subparsers: argparse._SubParsersAction,
) -> None:
release_parser = subparsers.add_parser(
"release",
help=(
"Create a release for repository/ies by incrementing version "
"and updating the changelog."
),
)
_add_version_arguments(release_parser)
add_identifier_arguments(release_parser)
_add_flow_arguments(release_parser)
_add_safety_arguments(release_parser)
+1 -1
View File
@@ -68,7 +68,7 @@ def create_ink(
# Mark local repo scripts as executable if needed
try:
if os.path.realpath(command).startswith(os.path.realpath(repo_dir)):
os.chmod(command, 0o755)
os.chmod(command, 0o700)
except OSError as e:
if not quiet:
print(f"Failed to set permissions on '{command}': {e}")
+87 -6
View File
@@ -1,7 +1,12 @@
from __future__ import annotations
import contextvars
import os
import pwd
import re
import subprocess
from collections.abc import Iterator
from contextlib import contextmanager
from .errors import GitNotRepositoryError, GitRunError
@@ -52,10 +57,20 @@ SCAN_UNSET = (
"GIT_PAGER",
"PAGER",
)
STRICT_KEEP = ("GIT_CEILING_DIRECTORIES",)
CONFIG_READ_KEEP = re.compile(
r"GIT_CONFIG_(GLOBAL|SYSTEM|PARAMETERS|COUNT|KEY_\d+|VALUE_\d+)"
)
CALLER_CONFIG = "caller"
DEFAULT_CONFIG = "default"
CONFIG_VIEWS = (CALLER_CONFIG, DEFAULT_CONFIG)
SCAN_TIMEOUT = 60
# ref and remote names come from repositories an agent may write: one named
# like --output=<path> would otherwise make rev-list create that file
END_OF_OPTIONS = "--end-of-options"
_STRICT_ENV: contextvars.ContextVar[bool] = contextvars.ContextVar(
"pkgmgr_git_strict_env", default=False
)
def _is_not_repo_error(stderr: str) -> bool:
@@ -63,9 +78,61 @@ def _is_not_repo_error(stderr: str) -> bool:
return "not a git repository" in msg
def _scan_env() -> dict[str, str]:
env = {key: value for key, value in os.environ.items() if key not in SCAN_UNSET}
return {**env, **SCAN_ENV}
@contextmanager
def strict_env() -> Iterator[None]:
token = _STRICT_ENV.set(True)
try:
yield
finally:
_STRICT_ENV.reset(token)
def _strict_keeps(key: str, caller: bool) -> bool:
return key in STRICT_KEEP or (
caller and CONFIG_READ_KEEP.fullmatch(key) is not None
)
def _passwd_home() -> str | None:
try:
return pwd.getpwuid(os.getuid()).pw_dir
except KeyError:
return None
def _scan_env(strict: bool = False, view: str | None = None) -> dict[str, str]:
"""
Build the environment of a scan or strict git call.
Args:
strict: drop every inherited `GIT_*` variable but STRICT_KEEP.
view: None, CALLER_CONFIG or DEFAULT_CONFIG, as run takes it.
Returns:
The inherited environment without SCAN_UNSET, plus SCAN_ENV; for a
config view with the system config; for DEFAULT_CONFIG also without
any `GIT_*` but STRICT_KEEP and XDG_CONFIG_HOME, HOME set to the
passwd home (unset without a passwd entry).
"""
caller = view == CALLER_CONFIG
scrub = strict or view == DEFAULT_CONFIG
env = {
key: value
for key, value in os.environ.items()
if key not in SCAN_UNSET
and not (scrub and key.startswith("GIT_") and not _strict_keeps(key, caller))
}
env = {**env, **SCAN_ENV}
if view is None:
return env
del env["GIT_CONFIG_NOSYSTEM"]
if view == DEFAULT_CONFIG:
env.pop("XDG_CONFIG_HOME", None)
env.pop("HOME", None)
home = _passwd_home()
if home:
env["HOME"] = home
return env
def run(
@@ -75,6 +142,7 @@ def run(
preview: bool = False,
scan: bool = False,
input_text: str | None = None,
config_view: str | None = None,
) -> str:
"""
Run a Git command and return its stdout as a stripped string.
@@ -85,9 +153,17 @@ def run(
preview: print the command instead of running it.
scan: read a repository an agent may have written: no fsmonitor, hook,
pager, lazy fetch, replace object, system config or prompt, stdin
closed, a timeout.
closed, a timeout. Inside strict_env() every call, scan or not,
also runs without any inherited `GIT_*` variable but
`GIT_CEILING_DIRECTORIES`, which only narrows discovery.
input_text: text fed to stdin, e.g. for `cat-file --batch-check`;
replaces the closed stdin of scan mode.
config_view: for a pure config read, the config it sees, both with
the system config: CALLER_CONFIG also keeps, inside strict_env(),
`GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_PARAMETERS`,
`GIT_CONFIG_COUNT` and its `GIT_CONFIG_KEY_<n>` and
`GIT_CONFIG_VALUE_<n>`; DEFAULT_CONFIG reads the default system
and passwd-home global config whatever the environment says.
Raises GitRunError (or a subclass) if execution fails or times out.
"""
@@ -98,10 +174,15 @@ def run(
print(f"[PREVIEW] Would run in {cwd!r}: {cmd_str}")
return ""
strict = _STRICT_ENV.get()
hardened: dict = (
{"env": _scan_env(), "stdin": subprocess.DEVNULL, "timeout": SCAN_TIMEOUT}
{
"env": _scan_env(strict, config_view),
"stdin": subprocess.DEVNULL,
"timeout": SCAN_TIMEOUT,
}
if scan
else {}
else ({"env": _scan_env(True, config_view)} if strict else {})
)
if input_text is not None:
hardened.pop("stdin", None)
@@ -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 ""
@@ -1,6 +1,7 @@
# src/pkgmgr/core/remote_provisioning/providers/github.py
from __future__ import annotations
import contextlib
from typing import Any
from ..http.client import HttpClient
@@ -103,7 +104,7 @@ class GitHubProvider(RemoteProvider):
user_url = f"{api}/user/repos"
# Try org first, then fall back to user creation.
try:
with contextlib.suppress(HttpError):
resp = self._http.request_json(
"POST", org_url, headers=self._headers(token), payload=payload
)
@@ -114,8 +115,6 @@ class GitHubProvider(RemoteProvider):
message="Repository created (org).",
url=str(html_url) if html_url else None,
)
except HttpError:
pass
resp = self._http.request_json(
"POST", user_url, headers=self._headers(token), payload=payload
+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.
+2 -3
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import contextlib
import json
import re
import shutil
@@ -127,7 +128,7 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
# Preferred: JSON output
rc, out, _ = _run_nix(["nix", "profile", "list", "--json"])
if rc == 0 and out.strip():
try:
with contextlib.suppress(json.JSONDecodeError, AttributeError):
data = json.loads(out)
elements = data.get("elements") or data.get("items") or {}
if isinstance(elements, dict):
@@ -145,8 +146,6 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
guess = _extract_version_from_store_path(sp)
if guess:
return InstalledVersion(name=name, version=guess)
except (json.JSONDecodeError, AttributeError):
pass
# Fallback: text mode
rc, out, _ = _run_nix(["nix", "profile", "list"])
+59 -5
View File
@@ -1,6 +1,7 @@
# src/pkgmgr/core/version/source.py
from __future__ import annotations
import contextlib
import os
import re
@@ -9,11 +10,59 @@ import yaml
from pkgmgr.core.repository.paths import resolve_repo_paths
def version_literal(name: str) -> re.Pattern[str]:
"""
Args:
name: the module attribute holding the version, e.g. __version__.
Returns:
A pattern whose groups are the assignment up to the opening quote, the
version and the closing quote of `name = "X.Y.Z"`.
"""
return re.compile(rf"""(?m)^(\s*{re.escape(name)}\s*=\s*["'])([^"']+)(["'])""")
def dynamic_version_source(pyproject_path: str, data: dict) -> tuple[str, str] | None:
"""
Args:
pyproject_path: the pyproject.toml file.
data: its parsed content.
Returns:
(module file, attribute name) that setuptools reads the version from
when [project].dynamic lists version and [tool.setuptools.dynamic]
sets version = {attr = "pkg.module.NAME"}, with
[tool.setuptools].package-dir applied; None otherwise.
"""
project = data.get("project") or {}
if "version" not in project.get("dynamic", []):
return None
setuptools = (data.get("tool") or {}).get("setuptools") or {}
attr = ((setuptools.get("dynamic") or {}).get("version") or {}).get("attr")
if not isinstance(attr, str) or "." not in attr:
return None
module, _, name = attr.rpartition(".")
parts = module.split(".")
dirs = setuptools.get("package-dir") or {}
if parts[0] in dirs:
base = os.path.join(dirs[parts[0]], *parts[1:])
else:
base = os.path.join(dirs.get("", ""), *parts)
root = os.path.dirname(os.path.abspath(pyproject_path))
for candidate in (f"{base}.py", os.path.join(base, "__init__.py")):
path = os.path.join(root, candidate)
if os.path.isfile(path):
return path, name
return None
def read_pyproject_version(repo_dir: str) -> str | None:
"""
Read the version from pyproject.toml in repo_dir, if present.
Expects a PEP 621-style [project] table with a 'version' field.
Expects a PEP 621-style [project] table with a 'version' field, or a
dynamic version that setuptools reads from a module attribute
(dynamic_version_source()).
"""
paths = resolve_repo_paths(repo_dir)
path = paths.pyproject_toml
@@ -30,7 +79,14 @@ def read_pyproject_version(repo_dir: str) -> str | None:
data = tomllib.load(f)
project = data.get("project") or {}
version = project.get("version")
return str(version).strip() if version else None
if version:
return str(version).strip()
source = dynamic_version_source(path, data)
if source is None:
return None
with open(source[0], encoding="utf-8") as f:
match = version_literal(source[1]).search(f.read())
return match.group(2).strip() if match else None
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
return None
@@ -204,14 +260,12 @@ def read_ansible_galaxy_version(repo_dir: str) -> str | None:
"""
galaxy_yml = os.path.join(repo_dir, "galaxy.yml")
if os.path.isfile(galaxy_yml):
try:
with contextlib.suppress(OSError, UnicodeDecodeError, yaml.YAMLError):
with open(galaxy_yml, encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
version = data.get("version")
if isinstance(version, str) and version.strip():
return version.strip()
except (OSError, UnicodeDecodeError, yaml.YAMLError):
pass
meta_yml = os.path.join(repo_dir, "meta", "main.yml")
if os.path.isfile(meta_yml):
+8 -8
View File
@@ -74,17 +74,17 @@ class TestIntegrationReleaseCommand(unittest.TestCase):
self._run_pkgmgr(["release", "patch", "--preview"])
mock_run_release.assert_called_once()
_args, kwargs = mock_run_release.call_args
options = mock_run_release.call_args.args[0]
# CLI wiring
self.assertEqual(kwargs.get("release_type"), "patch")
self.assertEqual(options.release_type, "patch")
self.assertTrue(
kwargs.get("preview"),
options.preview,
"preview should be True when --preview is used",
)
# Default: no --close → close=False
self.assertFalse(
kwargs.get("close"),
options.close,
"close must be False when --close is not given",
)
@@ -116,17 +116,17 @@ class TestIntegrationReleaseCommand(unittest.TestCase):
self._run_pkgmgr(["release", "minor", "--preview", "--close"])
mock_run_release.assert_called_once()
_args, kwargs = mock_run_release.call_args
options = mock_run_release.call_args.args[0]
# CLI wiring
self.assertEqual(kwargs.get("release_type"), "minor")
self.assertEqual(options.release_type, "minor")
self.assertTrue(
kwargs.get("preview"),
options.preview,
"preview should be True when --preview is used",
)
# With --close → close=True
self.assertTrue(
kwargs.get("close"),
options.close,
"close must be True when --close is given",
)
File diff suppressed because it is too large. Load diff
+4 -138
View File
@@ -4,7 +4,6 @@ import io
import json
import os
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from types import SimpleNamespace
@@ -14,25 +13,7 @@ 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
GIT_ENV = {
**os.environ,
"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=GIT_ENV,
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:
@@ -45,15 +26,8 @@ def docker_available() -> bool:
class GcFixture:
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.root = os.path.realpath(self._tmp.name)
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")
@@ -81,9 +55,6 @@ class GcFixture:
merged_heads={self.squashed_sha: 7}, open_heads={"wip": 3}
)
def tearDown(self) -> None:
self._tmp.cleanup()
def _commit(self, name: str) -> None:
with open(os.path.join(self.repo, f"{name}.txt"), "w") as fh:
fh.write(name)
@@ -146,111 +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 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"]
@@ -453,7 +319,7 @@ class TestBranchGc(GcFixture, unittest.TestCase):
hook = os.path.join(self.repo, ".git", "hooks", "reference-transaction")
with open(hook, "w") as fh:
fh.write(f"#!/bin/sh\ntouch {marker}\n")
os.chmod(hook, 0o755)
os.chmod(hook, 0o700)
plan = self._plan(host_ns=True, cwds={})
item = self._items(plan)["merged"]
+4 -4
View File
@@ -110,7 +110,7 @@ class TestBranchTree(unittest.TestCase):
patch.object(gc, "_process_cwds", return_value={}),
patch.object(
tree,
"secret_service_token",
"_forge_access",
return_value=(None, "Secret Service locked"),
),
]
@@ -389,7 +389,7 @@ class TestBranchTree(unittest.TestCase):
open_heads={},
)
with (
patch.object(tree, "secret_service_token", return_value=("t0ken", None)),
patch.object(tree, "_forge_access", return_value=("t0ken", None)),
patch.object(tree, "facts_with_token", return_value=facts) as live,
):
first = self._by_branch(self._entry())
@@ -408,7 +408,7 @@ class TestBranchTree(unittest.TestCase):
(False, "Secret Service locked"),
)
self.assertEqual(data["repos"][0]["forge"], "cached")
with patch.object(tree, "secret_service_token", return_value=("t0ken", None)):
with patch.object(tree, "_forge_access", return_value=("t0ken", None)):
self.assertTrue(json.loads(self._tree())["delete_ready"])
def test_an_unwritable_cache_keeps_the_scan_and_names_it(self) -> None:
@@ -417,7 +417,7 @@ class TestBranchTree(unittest.TestCase):
self._write(self.root, "cache-is-a-file", "")
with (
patch.dict(os.environ, {"XDG_CACHE_HOME": blocker}),
patch.object(tree, "secret_service_token", return_value=("t0ken", None)),
patch.object(tree, "_forge_access", return_value=("t0ken", None)),
patch.object(tree, "facts_with_token", return_value=ForgeFacts()),
):
entry = self._entry()
+1 -1
View File
@@ -22,7 +22,7 @@ class TestBranchTreeFlow(GcFixture, unittest.TestCase):
patch.object(gc, "host_pid_namespace", return_value=True),
patch.object(gc, "list_compose_containers", return_value=[]),
patch.object(gc, "_process_cwds", return_value={}),
patch.object(tree, "secret_service_token", return_value=(None, "locked")),
patch.object(tree, "_forge_access", return_value=(None, "locked")),
):
patcher.start()
self.addCleanup(patcher.stop)
@@ -164,7 +164,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
self.assertIsNone(get_installed_python_version("kpmx"))
def test_non_json_nix_profile_output_falls_back_to_text_mode(self) -> None:
import pkgmgr.core.version.installed as mod
from pkgmgr.core.version import installed as mod
with (
patch.object(mod.shutil, "which", return_value="/usr/bin/nix"),
@@ -173,7 +173,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
self.assertIsNone(mod.get_installed_nix_profile_version("pkgmgr"))
def test_json_list_instead_of_object_is_tolerated(self) -> None:
import pkgmgr.core.version.installed as mod
from pkgmgr.core.version import installed as mod
# Valid JSON, wrong shape: data.get() raises AttributeError on a list.
with (
@@ -566,7 +566,7 @@ class TestReleaseFileWriteDegradation(unittest.TestCase):
self.assertIn("Could not read spec file for changelog update", buf.getvalue())
def test_unwritable_spec_changelog_is_reported(self) -> None:
import pkgmgr.actions.release.files.rpm_changelog as mod
from pkgmgr.actions.release.files import rpm_changelog as mod
path = _write(
os.path.join(self.dir, "pkg.spec"),
+1 -2
View File
@@ -4,7 +4,6 @@ import unittest
from unittest.mock import patch
import pkgmgr.actions.install as install_module
from pkgmgr.actions.install import install_repos
from pkgmgr.actions.install.installers.base import BaseInstaller
@@ -141,7 +140,7 @@ class TestInstallReposIntegration(unittest.TestCase):
old_installers = install_module.INSTALLERS
install_module.INSTALLERS = [DummyInstaller()]
try:
install_repos(
install_module.install_repos(
selected_repos=selected_repos,
repositories_base_dir=tmp_base,
bin_dir=tmp_bin,
@@ -129,7 +129,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
]
def probe_side_effect(url: str, cwd: str = "."):
if "github.com" in url:
if url == "git@github.com:alice/repo.git":
# show "empty repo reachable" note; setup_cmd prints [OK] and does not print reason for ok
return (
True,
@@ -180,7 +180,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
]
def probe_side_effect(url: str, cwd: str = "."):
if "github.com" in url:
if url == "git@github.com:alice/repo.git":
return True, ""
return False, "(exit 128) fatal: Could not read from remote repository."
+101 -40
View File
@@ -6,10 +6,11 @@ import shutil
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from contextlib import redirect_stdout, suppress
from pathlib import Path
from unittest.mock import patch
from pkgmgr.actions.release.options import ReleaseOptions
from pkgmgr.actions.release.retry import retry_release
from pkgmgr.actions.release.workflow import _release_impl
from pkgmgr.actions.repository.push import (
@@ -21,50 +22,94 @@ from pkgmgr.cli.context import CLIContext
from pkgmgr.cli.parser import create_parser
from pkgmgr.cli.proxy import maybe_handle_proxy
_REAL_RUN = subprocess.run
GIT = shutil.which("git")
SSH_KEYGEN = shutil.which("ssh-keygen")
def git(cwd: str, *args: str) -> str:
return subprocess.run(
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
return _REAL_RUN(
[GIT, *args], cwd=cwd, check=True, capture_output=True, text=True
).stdout.strip()
@unittest.skipUnless(shutil.which("ssh-keygen"), "ssh-keygen signs the commits")
class TestPushMirrorLeases(unittest.TestCase):
def keygen(path: Path) -> None:
_REAL_RUN(
[SSH_KEYGEN, "-q", "-t", "ed25519", "-N", "", "-f", str(path)],
check=True,
)
def ssh_url(path: str) -> str:
return f"t@localhost:{path}"
@unittest.skipUnless(GIT and SSH_KEYGEN, "git and ssh-keygen sign the commits")
class SignedRemotesCase(unittest.TestCase):
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
root = Path(os.path.realpath(self._tmp.name))
self.root = str(root)
key = root / "key"
subprocess.run(
["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
check=True,
)
self.key = root / "key"
keygen(self.key)
(root / "allowed").write_text(f"t@example.org {(root / 'key.pub').read_text()}")
(root / "gitconfig").write_text(
self.gitconfig = root / ".gitconfig"
self._write_gitconfig(root)
self.env = {
**{
key: value
for key, value in os.environ.items()
if key not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
},
"GIT_CONFIG_GLOBAL": str(self.gitconfig),
"GIT_CONFIG_NOSYSTEM": "1",
}
for patcher in (
patch.dict(os.environ, self.env, clear=True),
patch("pkgmgr.core.git.run._passwd_home", return_value=self.root),
):
patcher.start()
self.addCleanup(patcher.stop)
self._init_remotes(root)
def _write_gitconfig(self, root: Path) -> None:
fakessh = root / "fakessh"
fakessh.write_text(
"#!/bin/sh\n"
"shift $(($# - 1))\n"
f'exec env -i PATH="$PATH" HOME={root} sh -c "$1"\n'
)
fakessh.chmod(0o755)
self.gitconfig.write_text(
"[user]\n\tname = t\n\temail = t@example.org\n"
f"\tsigningkey = {key}\n"
f"\tsigningkey = {self.key}\n"
"[gpg]\n\tformat = ssh\n"
f'[gpg "ssh"]\n\tallowedSignersFile = {root / "allowed"}\n'
"[commit]\n\tgpgsign = false\n"
"[init]\n\tdefaultBranch = main\n"
f"[core]\n\tsshCommand = {fakessh}\n"
"[ssh]\n\tvariant = simple\n"
)
env = patch.dict(
os.environ,
{"GIT_CONFIG_GLOBAL": str(root / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1"},
)
env.start()
self.addCleanup(env.stop)
def _init_remotes(self, root: Path) -> None:
self.canonical = str(root / "canonical.git")
self.mirror = str(root / "mirror.git")
self.repo = str(root / "repo")
git(self.root, "init", "-q", "--bare", self.canonical)
git(self.root, "init", "-q", "--bare", self.mirror)
git(self.root, "init", "-q", self.repo)
git(self.repo, "remote", "add", "origin", self.canonical)
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.canonical)
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.mirror)
git(self.repo, "remote", "add", "origin", ssh_url(self.canonical))
for bare in (self.canonical, self.mirror):
git(
self.repo,
"remote",
"set-url",
"--add",
"--push",
"origin",
ssh_url(bare),
)
self.init = self._commit("init")
git(self.repo, "push", "-q", self.canonical, "main")
git(self.repo, "push", "-q", self.mirror, "main")
@@ -78,6 +123,17 @@ class TestPushMirrorLeases(unittest.TestCase):
git(cwd, "commit", "-q", *flags, "-m", name)
return git(cwd, "rev-parse", "HEAD")
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
return _REAL_RUN(
[GIT, "rev-parse", "--verify", "--quiet", ref],
cwd=bare,
check=False,
capture_output=True,
text=True,
).stdout.strip()
class TestPushMirrorLeases(SignedRemotesCase):
def _push(self, rewrite: bool = False) -> str:
with redirect_stdout(io.StringIO()) as out:
sign_unpushed(self.repo)
@@ -102,15 +158,6 @@ class TestPushMirrorLeases(unittest.TestCase):
self.assertEqual(cm.exception.code, 0)
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
return subprocess.run(
["git", "rev-parse", "--verify", "--quiet", ref],
cwd=bare,
check=False,
capture_output=True,
text=True,
).stdout.strip()
def _assert_shipped_signed(self) -> None:
head = git(self.repo, "rev-parse", "HEAD")
self.assertEqual(self._tip(self.canonical), head)
@@ -226,7 +273,7 @@ class TestPushMirrorLeases(unittest.TestCase):
git(self.repo, "fetch", "-q", "origin")
self._commit("new")
upstream = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "@{u}"],
[GIT, "rev-parse", "--abbrev-ref", "@{u}"],
cwd=self.repo,
check=False,
capture_output=True,
@@ -302,12 +349,24 @@ class TestPushMirrorLeases(unittest.TestCase):
head = git(self.repo, "rev-parse", "HEAD")
git(self.repo, "config", "diff.ignoreSubmodules", "all")
git(self.repo, "update-index", "--add", "--cacheinfo", f"160000,{head},sub")
tree = git(self.repo, "rev-parse", "HEAD^{tree}")
with self.assertRaises(PushRefusedError) as cm:
self._push()
self._push()
self.assertIn("staged changes", str(cm.exception))
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
self._assert_shipped_signed()
self.assertNotEqual(git(self.repo, "rev-parse", "HEAD"), head)
self.assertEqual(git(self.repo, "rev-parse", "HEAD^{tree}"), tree)
self.assertEqual(
git(
self.repo,
"diff",
"--cached",
"--name-only",
"--ignore-submodules=none",
"HEAD",
),
"sub",
)
def test_unstaged_edit_stays_out_of_the_signed_head(self) -> None:
self._commit("feature")
@@ -339,10 +398,8 @@ class TestPushMirrorLeases(unittest.TestCase):
hooks_fire = marker.exists()
marker.unlink(missing_ok=True)
try:
with suppress(PushRefusedError):
self._push()
except PushRefusedError:
pass
self.assertFalse(marker.exists(), f"config hooks fire on commit: {hooks_fire}")
@@ -364,7 +421,7 @@ class TestPushMirrorLeases(unittest.TestCase):
self.assertFalse(marker.exists())
def test_remote_named_like_an_option_is_pushed(self) -> None:
git(self.repo, "config", "remote.-r.url", self.canonical)
git(self.repo, "config", "remote.-r.url", ssh_url(self.canonical))
git(self.repo, "config", "remote.-r.fetch", "+refs/heads/*:refs/remotes/-r/*")
git(self.repo, "config", "branch.main.pushRemote", "-r")
git(self.repo, "fetch", "-q", "--", "-r")
@@ -383,7 +440,11 @@ class TestPushMirrorLeases(unittest.TestCase):
with redirect_stdout(io.StringIO()), self.assertRaises(PushRefusedError):
_release_impl(
pyproject_path=os.path.join(self.repo, "pyproject.toml"), force=True
ReleaseOptions(
pyproject_path=os.path.join(self.repo, "pyproject.toml"),
force=True,
expect_tree=None,
)
)
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
@@ -14,7 +14,6 @@ from collections.abc import Sequence
from unittest.mock import patch
import pkgmgr.actions.install as install_mod
from pkgmgr.actions.install import install_repos
from pkgmgr.actions.install.installers.makefile import MakefileInstaller
from pkgmgr.actions.install.installers.nix import NixFlakeInstaller
from pkgmgr.actions.install.installers.os_packages.arch_pkgbuild import (
@@ -89,7 +88,7 @@ class TestRecursiveCapabilitiesIntegration(unittest.TestCase):
),
patch.object(install_mod, "clone_repos"),
):
install_repos(
install_mod.install_repos(
selected_repos=selected_repos,
repositories_base_dir=self.tmp_root,
bin_dir=self.bin_dir,
@@ -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 *_args, **_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()
@@ -14,7 +14,7 @@ class TestIntegrationReposCreatePreview(unittest.TestCase):
try:
repos_mod = importlib.import_module("pkgmgr.cli.commands.repos")
except ImportError as exc:
self.skipTest(f"CLI module not available: {exc}")
raise unittest.SkipTest(f"CLI module not available: {exc}") from exc
handle = getattr(repos_mod, "handle_repos_command", None)
if handle is None:
+22
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import io
import os
import re
import subprocess
import tempfile
import unittest
@@ -160,6 +161,27 @@ class TestReview(unittest.TestCase):
self.assertNotIn("big 11</td>", html)
self.assertIn("20 more lines not shown", html)
def test_toolbar_buttons_are_labelled_icons(self) -> None:
html = self._render("page.html", None, [])
for key, label in (("expand", "Expand all"), ("collapse", "Collapse all")):
with self.subTest(button=key):
button = re.search(
rf'<button type="button" id="{key}-all"([^>]*)>(.*?)</button>',
html,
re.DOTALL,
)
self.assertIsNotNone(button)
attrs, inner = button.groups()
self.assertIn(f'title="{label}"', attrs)
self.assertIn(f'aria-label="{label}"', attrs)
self.assertRegex(
inner, rf'^<svg class="bi bi-arrows-{key}"[^>]* aria-hidden="true"'
)
self.assertEqual(re.sub(r"<[^>]+>", "", inner).strip(), "")
self.assertNotIn("<link", html)
self.assertNotIn("<img", html)
def test_errors_exit_two(self) -> None:
plain = os.path.join(self.root, "plain")
os.makedirs(plain)
+1 -1
View File
@@ -58,7 +58,7 @@ class ReviewRepoCase(unittest.TestCase):
def _trap(self, path: str, tail: str) -> str:
write(path, f"#!/bin/sh\ntouch '{self.marker}'\n{tail}\n".encode())
os.chmod(path, 0o755)
os.chmod(path, 0o700)
return path
def _assert_fires(self, *args: str) -> None:
+2 -2
View File
@@ -331,7 +331,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
script = os.path.join(self.repo, name)
with open(script, "w") as fh:
fh.write(f"#!/bin/sh\ntouch {marker}\n")
os.chmod(script, 0o755)
os.chmod(script, 0o700)
git(self.repo, "add", name)
git(self.repo, "commit", "-m", name)
git(self.repo, "push", "origin", "main")
@@ -370,7 +370,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
fake = os.path.join(planted, "true")
with open(fake, "w") as fh:
fh.write(f"#!/bin/sh\ntouch {marker}\n")
os.chmod(fake, 0o755)
os.chmod(fake, 0o700)
if os.getuid() == 0:
os.chown(planted, 65534, 65534)
os.chown(fake, 65534, 65534)
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()
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more