Compare commits

..
Author SHA1 Message Date
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 / security-codeql (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
CI / quality (push) Blocked by required conditions
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
CI / quality (push) Skipped
CI / security-codeql (push) Blocked by required conditions
CodeQL Advanced / Check security (none, actions) (push) Blocked by required conditions
CodeQL Advanced / Check security (none, python) (push) Blocked by required conditions
CI / test-unit (push) Blocked by required conditions
Test Units / test-unit (push) Blocked by required conditions
CI / test-integration (push) Blocked by required conditions
Test Code Integration / test-integration (push) Blocked by required conditions
CI / test-env-virtual (push) Blocked by required conditions
Test OS Containers / test-env-virtual (arch) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (centos) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (debian) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (fedora) (push) Blocked by required conditions
Test OS Containers / test-env-virtual (ubuntu) (push) Blocked by required conditions
CI / test-env-nix (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (arch) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (centos) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (debian) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (fedora) (push) Blocked by required conditions
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Blocked by required conditions
CI / test-e2e (push) Blocked by required conditions
Test End-To-End / test-e2e (arch) (push) Blocked by required conditions
Test End-To-End / test-e2e (centos) (push) Blocked by required conditions
Test End-To-End / test-e2e (debian) (push) Blocked by required conditions
Test End-To-End / test-e2e (fedora) (push) Blocked by required conditions
Test End-To-End / test-e2e (ubuntu) (push) Blocked by required conditions
CI / test-virgin-user (push) Blocked by required conditions
Test Virgin User / test-virgin-user (arch) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (centos) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (debian) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (fedora) (push) Blocked by required conditions
Test Virgin User / test-virgin-user (ubuntu) (push) Blocked by required conditions
CI / test-virgin-root (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (arch) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (centos) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (debian) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (fedora) (push) Blocked by required conditions
Test Virgin Root / test-virgin-root (ubuntu) (push) Blocked by required conditions
CI / lint-shell (push) Blocked by required conditions
ShellCheck / lint-shell (push) Blocked by required conditions
CI / lint-python (push) Blocked by required conditions
Ruff (Python code sniffer) / lint-python (push) Blocked by required conditions
CI / lint-docker (push) Blocked by required conditions
Docker Linter / Lint Dockerfile (push) Blocked by required conditions
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-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 / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s
Both reusable quality workflows move from quality main ed91a38 to the v0.2.0 release commit 003eed6, pinned by sha with the version comment that Dependabot's github-actions updates. job.workflow_sha resolves to the same commit, so the tool versions follow this one pin.

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

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

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

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 19:53:16 +00:00
Kevin Veen-BirkenbachandClaude Opus 5.5 1707cc0192 ci: run quality's gate and take ruff from the quality flake
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (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 Virgin Nix (flake only) / test-env-nix (arch) (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 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 (debian) (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 / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Docker Linter / Lint Dockerfile (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / lint-python (push) Failing after 0s
Ruff (Python code sniffer) / lint-python (push) Failing after 0s
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 / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
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
CodeQL Advanced / Check security (none, python) (push) Canceled after 0s
CodeQL Advanced / Check security (none, actions) (push) Canceled after 0s
CI / security-codeql (push) Canceled after 0s
Test Units / test-unit (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
Test Code Integration / test-integration (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
Test OS Containers / test-env-virtual (ubuntu) (push) Canceled after 0s
Test OS Containers / test-env-virtual (fedora) (push) Canceled after 0s
Test OS Containers / test-env-virtual (debian) (push) Canceled after 0s
Test OS Containers / test-env-virtual (centos) (push) Canceled after 0s
Test OS Containers / test-env-virtual (arch) (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (ubuntu) (push) Canceled after 0s
Test Virgin Nix (flake only) / test-env-nix (fedora) (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 Virgin Nix (flake only) / test-env-nix (arch) (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 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 (debian) (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 / test-virgin-user (push) Canceled after 0s
Test Virgin Root / test-virgin-root (ubuntu) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (fedora) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (debian) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (centos) (push) Canceled after 0s
Test Virgin Root / test-virgin-root (arch) (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
ShellCheck / lint-shell (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
Ruff (Python code sniffer) / lint-python (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
Docker Linter / Lint Dockerfile (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
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
11 changed files with 715 additions and 185 deletions

No files matched your search

+6
View File
@@ -71,3 +71,9 @@ jobs:
contents: read contents: read
security-events: write security-events: write
uses: ./.github/workflows/lint-docker.yml uses: ./.github/workflows/lint-docker.yml
quality:
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
permissions:
contents: read
uses: infinito-nexus/quality/.github/workflows/quality.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
+3 -15
View File
@@ -8,19 +8,7 @@ permissions:
jobs: jobs:
lint-python: lint-python:
runs-on: ubuntu-latest uses: infinito-nexus/quality/.github/workflows/tool.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with: with:
python-version: "3.12" tool: ruff
args: check src tests
- name: Install ruff
run: pip install ruff
- name: Run ruff
run: |
ruff check src tests
+21 -140
View File
@@ -8,6 +8,7 @@ import sys
import time import time
from collections.abc import Callable from collections.abc import Callable
from dataclasses import asdict, dataclass, field from dataclasses import asdict, dataclass, field
from functools import cache
from graphlib import CycleError, TopologicalSorter from graphlib import CycleError, TopologicalSorter
from pkgmgr.actions.worktree.hooks import FINI_HOOK, hook_command, run_hook from pkgmgr.actions.worktree.hooks import FINI_HOOK, hook_command, run_hook
@@ -28,6 +29,7 @@ from pkgmgr.core.git.run import (
) )
from .gc_forge import ForgeFacts, fetch_forge_facts from .gc_forge import ForgeFacts, fetch_forge_facts
from .gc_refs import _common_dir, _git_dirs, _held_branches, _symbolic
from .nofollow import canonical, remove_tree from .nofollow import canonical, remove_tree
Registrations = tuple[str, dict[str, list[str]]] Registrations = tuple[str, dict[str, list[str]]]
@@ -37,6 +39,7 @@ Snapshot = tuple[
dict[int, str], dict[int, str],
dict[str, tuple[str | None, int | None, int | None, bool]], dict[str, tuple[str | None, int | None, int | None, bool]],
Registrations, Registrations,
Callable[[], dict[str, str]],
] ]
# PROC_PID_INIT_INO: only the initial PID namespace sees every process of the host. # PROC_PID_INIT_INO: only the initial PID namespace sees every process of the host.
@@ -69,12 +72,6 @@ NO_REMOTE_DEFAULT = (
) )
NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8" NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8"
DEFAULT_NAMES = ("HEAD", "main", "master") DEFAULT_NAMES = ("HEAD", "main", "master")
HELD_FILES = (
("rebase-merge/head-name", "rebase in progress"),
("rebase-merge/update-refs", "rebase in progress"),
("rebase-apply/head-name", "rebase in progress"),
("BISECT_START", "bisect in progress"),
)
DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$" DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$"
SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs") SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs")
WALKED_STORES = ("refs", "reftable", "logs/refs") WALKED_STORES = ("refs", "reftable", "logs/refs")
@@ -263,10 +260,6 @@ def _config_read(args: list[str], cwd: str, view: str) -> str:
return run(args, cwd=cwd, scan=True, config_view=view) return run(args, cwd=cwd, scan=True, config_view=view)
def _common_dir(cwd: str) -> str:
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
def _docker(args: list[str]) -> str: def _docker(args: list[str]) -> str:
return subprocess.run( return subprocess.run(
["docker", *args], check=True, capture_output=True, text=True ["docker", *args], check=True, capture_output=True, text=True
@@ -665,7 +658,7 @@ def _build(
tree: Worktree | None, tree: Worktree | None,
snapshot: Snapshot, snapshot: Snapshot,
) -> Item: ) -> Item:
local, remote, cwds, tracking, registrations = snapshot local, remote, cwds, tracking, registrations, held = snapshot
upstream, ahead, behind, gone = tracking.get( upstream, ahead, behind, gone = tracking.get(
branch or "", (None, None, None, False) branch or "", (None, None, None, False)
) )
@@ -759,7 +752,11 @@ def _build(
and (time.time() - item.last_activity) / 3600 < repo.min_age and (time.time() - item.last_activity) / 3600 < repo.min_age
): ):
item.skip = f"younger than {repo.min_age:g} h" item.skip = f"younger than {repo.min_age:g} h"
item.actions = _actions(repo, item, tree, checkout, dirty, registrations) item.actions = (
_local_actions(repo, item, tree, held)
if repo.scope == "local"
else _actions(repo, item, tree, checkout, dirty, registrations)
)
if repo.unsafe: if repo.unsafe:
item.actions = [a for a in item.actions if not a.startswith("remote-branch:")] item.actions = [a for a in item.actions if not a.startswith("remote-branch:")]
return item return item
@@ -773,8 +770,6 @@ def _actions(
dirty: int, dirty: int,
registrations: Registrations, registrations: Registrations,
) -> list[str]: ) -> list[str]:
if repo.scope == "local":
return _local_actions(repo, item, tree)
tree_part: list[str] = [] tree_part: list[str] = []
if tree: if tree:
if ( if (
@@ -813,7 +808,12 @@ def _actions(
return actions return actions
def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]: def _local_actions(
repo: Repo,
item: Item,
tree: Worktree | None,
held: Callable[[], dict[str, str]],
) -> list[str]:
""" """
Settle the actions of an item planned with scope `local`. Settle the actions of an item planned with scope `local`.
@@ -823,6 +823,8 @@ def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]:
item: the classified item; a merged-clean one whose tip is an item: the classified item; a merged-clean one whose tip is an
ancestor of none of them gets that as its skip. ancestor of none of them gets that as its skip.
tree: the worktree holding its branch, or None. tree: the worktree holding its branch, or None.
held: the snapshot's _held_branches of the repository, read on the
first call and reused for every later item of that snapshot.
Returns: Returns:
`local-branch` for a merged-clean local branch that no worktree, `local-branch` for a merged-clean local branch that no worktree,
@@ -832,9 +834,9 @@ def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]:
""" """
if item.state != "merged-clean" or not item.local_sha or tree is not None: if item.state != "merged-clean" or not item.local_sha or tree is not None:
return [] return []
held = _held_branches(repo.repo).get(item.branch) hold = held().get(item.branch)
if held: if hold:
item.skip = item.skip or held item.skip = item.skip or hold
return [] return []
targets = [repo.default, *repo.lines] targets = [repo.default, *repo.lines]
if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets): if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets):
@@ -854,6 +856,7 @@ def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
cwds, cwds,
tracking, tracking,
_registrations(repo.repo), _registrations(repo.repo),
cache(lambda: _held_branches(repo.repo)),
) )
@@ -911,25 +914,6 @@ def _default_remote(remotes: list[str]) -> str | None:
return remotes[0] if len(remotes) == 1 else None return remotes[0] if len(remotes) == 1 else None
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
"""
List the resolvable refs under a prefix with their symref targets.
Args:
repo_root: main worktree root of the repository.
prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`.
git_dir: the git common dir (shared refs plus the main worktree's own)
or a `worktrees/<id>` dir whose refs to list, or "" for the refs
as repo_root's worktree sees them.
Returns:
Full ref name -> the ref it points to, or "" for a plain ref.
"""
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
return dict(line.split("\x00", 1) for line in out.splitlines())
def _resolve_within(refs: dict[str, str], ref: str) -> str | None: def _resolve_within(refs: dict[str, str], ref: str) -> str | None:
""" """
Follow a ref's symref chain without leaving a set of refs. Follow a ref's symref chain without leaving a set of refs.
@@ -975,109 +959,6 @@ def _remote_default(repo_root: str, remotes: list[str]) -> str | None:
return None return None
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
"""
Read the branch every worktree's HEAD names, on any ref backend.
Args:
repo_root: main worktree root of the repository.
git_dirs: the git common dir first, then each `worktrees/<id>`.
Returns:
Branch name -> skip reason, from `git --git-dir=<dir> symbolic-ref
HEAD` for each of them, whatever its id.
Raises:
GitBaseError: when a HEAD is neither readable nor detached.
"""
heads: dict[str, str] = {}
for git_dir in git_dirs:
try:
target = _git(
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
)
except GitRunError as exc:
if exc.returncode == 1:
continue
raise
if target.startswith("refs/heads/"):
heads.setdefault(
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
)
return heads
def _git_dirs(repo_root: str) -> list[str]:
"""
List the git dirs of every worktree of the repository.
Args:
repo_root: main worktree root of the repository.
Returns:
The git common dir, then each entry of `<common>/worktrees/`, whatever
its id and whether `git worktree list` shows it.
"""
common = _common_dir(repo_root)
base = os.path.join(common, "worktrees")
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
return [common, *(os.path.join(base, entry) for entry in entries)]
def _held_branches(repo_root: str) -> dict[str, str]:
"""
Find the local branches that something besides a listed worktree holds.
Args:
repo_root: main worktree root of the repository.
Returns:
Branch name -> skip reason: a symbolic branch, the branch any symbolic
ref under `refs/` (also a tag or remote-tracking one) or under the
main worktree's or any registration's `refs/worktree/` names, the HEAD
of the main repository and of every `worktrees/<id>` registration,
also one `git worktree list` omits, each rebase-merge and rebase-apply
head-name, an interactive rebase's update-refs and BISECT_START; all
read through the git common dir, whichever worktree repo_root is.
Raises:
GitBaseError: when git cannot read a registration, symref or HEAD.
OSError: when a state file exists but cannot be read.
ValueError: when a state file is not UTF-8.
"""
git_dirs = _git_dirs(repo_root)
held: dict[str, str] = {}
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
for git_dir in git_dirs[1:]:
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
for ref, target in symrefs.items():
if target and ref.startswith("refs/heads/"):
held.setdefault(
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
)
if target.startswith("refs/heads/"):
held.setdefault(
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
)
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
held.setdefault(branch, reason)
for git_dir in git_dirs:
for name, operation in HELD_FILES:
try:
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
continue
for line in lines:
ref = line.strip().removeprefix("ref: ")
if ref.startswith("refs/heads/") or name == "BISECT_START":
held.setdefault(
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
)
return held
def _lines( def _lines(
repo_root: str, refs: list[str], remotes: list[str], warnings: list[str] repo_root: str, refs: list[str], remotes: list[str], warnings: list[str]
) -> tuple[dict[str, tuple[str, set[str]]], set[str]]: ) -> tuple[dict[str, tuple[str, set[str]]], set[str]]:
+142
View File
@@ -0,0 +1,142 @@
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]:
"""
List the resolvable refs under a prefix with their symref targets.
Args:
repo_root: main worktree root of the repository.
prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`.
git_dir: the git common dir (shared refs plus the main worktree's own)
or a `worktrees/<id>` dir whose refs to list, or "" for the refs
as repo_root's worktree sees them.
Returns:
Full ref name -> the ref it points to, or "" for a plain ref.
"""
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
return dict(line.split("\x00", 1) for line in out.splitlines())
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
"""
Read the branch every worktree's HEAD names, on any ref backend.
Args:
repo_root: main worktree root of the repository.
git_dirs: the git common dir first, then each `worktrees/<id>`.
Returns:
Branch name -> skip reason, from `git --git-dir=<dir> symbolic-ref
HEAD` for each of them, whatever its id.
Raises:
GitBaseError: when a HEAD is neither readable nor detached.
"""
heads: dict[str, str] = {}
for git_dir in git_dirs:
try:
target = _git(
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
)
except GitRunError as exc:
if exc.returncode == 1:
continue
raise
if target.startswith("refs/heads/"):
heads.setdefault(
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
)
return heads
def _git_dirs(repo_root: str) -> list[str]:
"""
List the git dirs of every worktree of the repository.
Args:
repo_root: main worktree root of the repository.
Returns:
The git common dir, then each entry of `<common>/worktrees/`, whatever
its id and whether `git worktree list` shows it.
"""
common = _common_dir(repo_root)
base = os.path.join(common, "worktrees")
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
return [common, *(os.path.join(base, entry) for entry in entries)]
def _held_branches(repo_root: str) -> dict[str, str]:
"""
Find the local branches that something besides a listed worktree holds.
Args:
repo_root: main worktree root of the repository.
Returns:
Branch name -> skip reason: a symbolic branch, the branch any symbolic
ref under `refs/` (also a tag or remote-tracking one) or under the
main worktree's or any registration's `refs/worktree/` names, the HEAD
of the main repository and of every `worktrees/<id>` registration,
also one `git worktree list` omits, each rebase-merge and rebase-apply
head-name, an interactive rebase's update-refs and BISECT_START; all
read through the git common dir, whichever worktree repo_root is.
Raises:
GitBaseError: when git cannot read a registration, symref or HEAD.
OSError: when a state file exists but cannot be read.
ValueError: when a state file is not UTF-8.
"""
git_dirs = _git_dirs(repo_root)
held: dict[str, str] = {}
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
for git_dir in git_dirs[1:]:
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
for ref, target in symrefs.items():
if target and ref.startswith("refs/heads/"):
held.setdefault(
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
)
if target.startswith("refs/heads/"):
held.setdefault(
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
)
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
held.setdefault(branch, reason)
for git_dir in git_dirs:
for name, operation in HELD_FILES:
try:
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
continue
for line in lines:
ref = line.strip().removeprefix("ref: ")
if ref.startswith("refs/heads/") or name == "BISECT_START":
held.setdefault(
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
)
return held
+85 -24
View File
@@ -1,9 +1,9 @@
from __future__ import annotations from __future__ import annotations
import glob
import os import os
import shutil
import subprocess import subprocess
import sys
import tempfile
from pkgmgr.actions.mirror.io import read_mirrors_file from pkgmgr.actions.mirror.io import read_mirrors_file
from pkgmgr.actions.mirror.types import Repository 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 .git_tags import head_semver_tags
from .pypi_url import parse_pypi_project_url 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: try:
subprocess.run( subprocess.run(
["python", "-m", module, "--help"], [sys.executable, "-m", module, "--help"],
cwd=cwd,
env=env,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
check=True, check=True,
) )
except Exception as exc: except Exception as exc:
raise RuntimeError( raise RuntimeError(
f"Required Python module '{module}' is not available. " f"Required Python module '{module}' is not available to "
f"Install it via: pip install {module}" f"{sys.executable}. Install it via: "
f"{sys.executable} -m pip install {module}"
) from exc ) from exc
@@ -66,22 +108,38 @@ def publish(
print("[PREVIEW] Would build and upload to PyPI.") print("[PREVIEW] Would build and upload to PyPI.")
return return
_require_tool("build") with tempfile.TemporaryDirectory() as out:
_require_tool("twine") _upload(target, os.path.abspath(repo_dir), out, interactive, allow_prompt)
dist_dir = os.path.join(repo_dir, "dist") print("[INFO] Publish completed.")
if os.path.isdir(dist_dir):
shutil.rmtree(dist_dir, ignore_errors=True)
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( subprocess.run(
["python", "-m", "build"], [sys.executable, "-m", "build", "--outdir", out, repo_dir],
cwd=repo_dir, cwd=out,
env=env,
check=True, 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: if not artifacts:
raise RuntimeError("No build artifacts found in dist/.") raise RuntimeError("No build artifacts found.")
resolver = TokenResolver() resolver = TokenResolver()
@@ -98,15 +156,18 @@ def publish(
), ),
).token ).token
env = dict(os.environ)
env["TWINE_USERNAME"] = "__token__"
env["TWINE_PASSWORD"] = token
subprocess.run( subprocess.run(
["python", "-m", "twine", "upload", *artifacts], [
cwd=repo_dir, sys.executable,
env=env, "-m",
"twine",
"upload",
"--non-interactive",
"--repository-url",
UPLOAD_URLS[target.host],
*artifacts,
],
cwd=out,
env={**env, "TWINE_USERNAME": "__token__", "TWINE_PASSWORD": token},
check=True, check=True,
) )
print("[INFO] Publish completed.")
+36 -1
View File
@@ -8,6 +8,36 @@ try:
except ImportError: except ImportError:
import tomli as tomllib # type: ignore 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( def update_pyproject_version(
pyproject_path: str, new_version: str, preview: bool = False 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}") print(f"[WARN] Could not read pyproject.toml: {exc}")
return 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", []): if project is None or "version" in project.get("dynamic", []):
print("[INFO] pyproject.toml declares no static version, skipping.") print("[INFO] pyproject.toml declares no static version, skipping.")
return return
+57 -2
View File
@@ -9,11 +9,59 @@ import yaml
from pkgmgr.core.repository.paths import resolve_repo_paths 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: def read_pyproject_version(repo_dir: str) -> str | None:
""" """
Read the version from pyproject.toml in repo_dir, if present. 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) paths = resolve_repo_paths(repo_dir)
path = paths.pyproject_toml path = paths.pyproject_toml
@@ -30,7 +78,14 @@ def read_pyproject_version(repo_dir: str) -> str | None:
data = tomllib.load(f) data = tomllib.load(f)
project = data.get("project") or {} project = data.get("project") or {}
version = project.get("version") 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): except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
return None return None
@@ -13,7 +13,7 @@ from contextlib import contextmanager, redirect_stderr, redirect_stdout
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import patch from unittest.mock import patch
from pkgmgr.actions.branch import gc, gc_forge, tree from pkgmgr.actions.branch import gc, gc_forge, gc_refs, tree
from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots
from pkgmgr.cli.parser import create_parser from pkgmgr.cli.parser import create_parser
from pkgmgr.core.credentials.types import NoCredentialsError from pkgmgr.core.credentials.types import NoCredentialsError
@@ -1647,7 +1647,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
def test_failed_head_read_refuses_the_repository(self) -> None: def test_failed_head_read_refuses_the_repository(self) -> None:
heads = self._refs(self.repo, "refs/heads") heads = self._refs(self.repo, "refs/heads")
real = gc._git real = gc_refs._git
def timed_out(args: list[str], cwd: str) -> str: def timed_out(args: list[str], cwd: str) -> str:
if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]: if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]:
@@ -1656,7 +1656,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
raise err raise err
return real(args, cwd) return real(args, cwd)
with patch.object(gc, "_git", side_effect=timed_out): with patch.object(gc_refs, "_git", side_effect=timed_out):
run = self._cleanup("local", apply=True) run = self._cleanup("local", apply=True)
self.assertEqual(run.code, 2) self.assertEqual(run.code, 2)
@@ -0,0 +1,169 @@
from __future__ import annotations
import io
import json
import os
import subprocess
import tempfile
import unittest
from contextlib import ExitStack, redirect_stderr, redirect_stdout
from unittest.mock import patch
from pkgmgr.actions.branch import gc
AUTHOR = {
"GIT_AUTHOR_NAME": "t",
"GIT_AUTHOR_EMAIL": "t@example.org",
"GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@example.org",
}
MERGED = 12
REGISTRATIONS = 40
class TestHeldBranchesReadOnce(unittest.TestCase):
def setUp(self) -> None:
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = os.path.realpath(tmp.name)
self.addCleanup(os.chdir, os.getcwd())
os.chdir(self.root)
home = os.path.join(self.root, "home")
os.makedirs(home)
clean = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
patcher = patch.dict(os.environ, {**clean, "HOME": home}, clear=True)
patcher.start()
self.addCleanup(patcher.stop)
self.repo = os.path.join(self.root, "repo")
self._shape()
def git(self, *args: str) -> str:
return subprocess.run(
["git", "-c", "commit.gpgsign=false", *args],
cwd=self.repo,
env={**os.environ, **AUTHOR},
check=True,
capture_output=True,
text=True,
).stdout.strip()
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")
subprocess.run(
["git", "init", "-q", "--bare", "-b", "main", origin], check=True
)
subprocess.run(["git", "init", "-q", "-b", "main", self.repo], check=True)
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 = True, apply: bool = False) -> 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)
once, new_reads = self._run()
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:
real = gc._rebuild
changes = [
lambda: self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005")
]
def late(repo: gc.Repo, item: gc.Item) -> gc.Item:
if changes:
changes.pop()()
return real(repo, item)
with patch.object(gc, "_rebuild", side_effect=late):
plan, reads = self._run(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,124 @@
import os
import shutil
import sys
import tempfile
import unittest
from contextlib import ExitStack
from unittest.mock import MagicMock, patch
from pkgmgr.actions.publish.workflow import publish
class TestPublishWorkflowChildren(unittest.TestCase):
def publish_with(self, mirror: str, environ: dict) -> tuple[list, str]:
"""
Args:
mirror: the PyPI project URL of the mirrors file.
environ: extra environment variables of the pkgmgr process;
"{repo}" in a value becomes the repository directory.
Returns:
The recorded subprocess.run calls and the repository directory,
whose dist is a symlink to a foreign directory with an old
artifact.
"""
repo_dir = tempfile.mkdtemp()
foreign = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, repo_dir)
self.addCleanup(shutil.rmtree, foreign)
with open(os.path.join(foreign, "example-0.9.0.tar.gz"), "w"):
pass
os.symlink(foreign, os.path.join(repo_dir, "dist"))
def run(argv, *_args, **kwargs):
if argv[2] == "build" and "--help" not in argv:
if "--outdir" in argv:
out = argv[argv.index("--outdir") + 1]
else:
out = os.path.join(kwargs["cwd"], "dist")
with open(os.path.join(out, "example-1.0.0.tar.gz"), "w"):
pass
return kwargs
module = "pkgmgr.actions.publish.workflow"
with ExitStack() as stack:
stack.enter_context(
patch(f"{module}.read_mirrors_file", return_value={"pypi": mirror})
)
stack.enter_context(
patch(f"{module}.head_semver_tags", return_value=["v1.0.0"])
)
resolver = stack.enter_context(patch(f"{module}.TokenResolver"))
mock_run = stack.enter_context(
patch(f"{module}.subprocess.run", side_effect=run)
)
stack.enter_context(
patch.dict(
os.environ,
{
name: value.format(repo=repo_dir)
for name, value in environ.items()
},
)
)
resolver.return_value.get_token.return_value = MagicMock(token="t")
publish(repo={}, repo_dir=repo_dir, interactive=False, allow_prompt=False)
return mock_run.call_args_list, repo_dir
def test_every_child_runs_under_the_current_interpreter(self):
calls, _ = self.publish_with("https://pypi.org/project/example/", {})
argvs = [call.args[0] for call in calls]
self.assertEqual(
[argv[2] for argv in argvs], ["build", "twine", "build", "twine"]
)
self.assertEqual({argv[0] for argv in argvs}, {sys.executable})
def test_children_never_run_in_the_repository(self):
calls, repo_dir = self.publish_with("https://pypi.org/project/example/", {})
cwds = {call.kwargs["cwd"] for call in calls}
self.assertEqual(len(cwds), 1)
self.assertNotEqual(os.path.realpath(cwds.pop()), os.path.realpath(repo_dir))
def test_only_the_fresh_build_is_uploaded(self):
calls, repo_dir = self.publish_with("https://pypi.org/project/example/", {})
upload = calls[-1].args[0]
self.assertEqual(
[os.path.basename(path) for path in upload if path.endswith(".tar.gz")],
["example-1.0.0.tar.gz"],
)
self.assertEqual(calls[2].args[0][-1], repo_dir)
def test_no_pkgmgr_variable_reaches_a_child(self):
calls, _ = self.publish_with(
"https://pypi.org/project/example/",
{"PKGMGR_PYPI_TOKEN": "secret", "PKGMGR_GITHUB_TOKEN": "secret"},
)
for call in calls:
self.assertFalse(
[name for name in call.kwargs["env"] if name.startswith("PKGMGR_")]
)
self.assertEqual(calls[-1].kwargs["env"]["TWINE_PASSWORD"], "t")
def test_no_repository_path_stays_on_the_children_pythonpath(self):
calls, _ = self.publish_with(
"https://pypi.org/project/example/",
{"PYTHONPATH": os.pathsep.join(["{repo}", "{repo}/src", "/opt/keep"])},
)
self.assertEqual(
{call.kwargs["env"]["PYTHONPATH"] for call in calls}, {"/opt/keep"}
)
def test_the_upload_goes_to_the_host_of_the_mirror(self):
for mirror, url in (
("https://pypi.org/project/example/", "https://upload.pypi.org/legacy/"),
("https://test.pypi.org/project/example/", "https://test.pypi.org/legacy/"),
):
with self.subTest(mirror=mirror):
calls, _ = self.publish_with(mirror, {})
upload = calls[-1].args[0]
self.assertIn("--non-interactive", upload)
self.assertEqual(upload[upload.index("--repository-url") + 1], url)
if __name__ == "__main__":
unittest.main()
@@ -140,6 +140,75 @@ class TestUpdatePyprojectVersion(unittest.TestCase):
self.assertEqual(content, original) self.assertEqual(content, original)
def write_dynamic_attr_project(self, tmpdir: str, module: str) -> str:
with open(os.path.join(tmpdir, "pyproject.toml"), "w", encoding="utf-8") as f:
f.write(
textwrap.dedent(
"""
[project]
name = "quality"
dynamic = ["version"]
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.dynamic]
version = {attr = "quality.__version__"}
"""
).lstrip()
)
os.makedirs(os.path.join(tmpdir, "src", "quality"))
path = os.path.join(tmpdir, "src", "quality", "__init__.py")
with open(path, "w", encoding="utf-8") as f:
f.write(module)
return path
def test_a_dynamic_attr_version_is_bumped_in_its_module_and_read_back(self) -> None:
from pkgmgr.core.version.source import read_pyproject_version
with tempfile.TemporaryDirectory() as tmpdir:
module = self.write_dynamic_attr_project(
tmpdir, '"""Quality."""\n\n__version__ = "0.1.0"\n'
)
with open(os.path.join(tmpdir, "pyproject.toml"), encoding="utf-8") as f:
before = f.read()
self.assertEqual(read_pyproject_version(tmpdir), "0.1.0")
update_pyproject_version(
os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=False
)
with open(module, encoding="utf-8") as f:
self.assertEqual(f.read(), '"""Quality."""\n\n__version__ = "0.2.0"\n')
with open(os.path.join(tmpdir, "pyproject.toml"), encoding="utf-8") as f:
self.assertEqual(f.read(), before)
self.assertEqual(read_pyproject_version(tmpdir), "0.2.0")
def test_a_dynamic_attr_version_preview_writes_nothing(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
module = self.write_dynamic_attr_project(tmpdir, "__version__ = '0.1.0'\n")
update_pyproject_version(
os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=True
)
with open(module, encoding="utf-8") as f:
self.assertEqual(f.read(), "__version__ = '0.1.0'\n")
def test_a_dynamic_attr_module_without_the_literal_raises(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
self.write_dynamic_attr_project(
tmpdir,
"from importlib.metadata import version\n__version__ = version('quality')\n",
)
with self.assertRaises(RuntimeError) as cm:
update_pyproject_version(
os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=False
)
self.assertIn("Missing __version__ literal", str(cm.exception))
def test_update_pyproject_version_missing_file_is_skipped(self) -> None: def test_update_pyproject_version_missing_file_is_skipped(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir: with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "pyproject.toml") path = os.path.join(tmpdir, "pyproject.toml")