Compare commits

..
Author SHA1 Message Date
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
9 changed files with 444 additions and 49 deletions

No files matched your search

+6
View File
@@ -71,3 +71,9 @@ jobs:
contents: read
security-events: write
uses: ./.github/workflows/lint-docker.yml
quality:
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
permissions:
contents: read
uses: infinito-nexus/quality/.github/workflows/quality.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
+3 -15
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
uses: infinito-nexus/quality/.github/workflows/tool.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
with:
python-version: "3.12"
- name: Install ruff
run: pip install ruff
- name: Run ruff
run: |
ruff check src tests
tool: ruff
args: check src tests
+18 -7
View File
@@ -8,6 +8,7 @@ import sys
import time
from collections.abc import Callable
from dataclasses import asdict, dataclass, field
from functools import cache
from graphlib import CycleError, TopologicalSorter
from pkgmgr.actions.worktree.hooks import FINI_HOOK, hook_command, run_hook
@@ -37,6 +38,7 @@ Snapshot = tuple[
dict[int, str],
dict[str, tuple[str | None, int | None, int | None, bool]],
Registrations,
Callable[[], dict[str, str]],
]
# PROC_PID_INIT_INO: only the initial PID namespace sees every process of the host.
@@ -665,7 +667,7 @@ def _build(
tree: Worktree | None,
snapshot: Snapshot,
) -> Item:
local, remote, cwds, tracking, registrations = snapshot
local, remote, cwds, tracking, registrations, held = snapshot
upstream, ahead, behind, gone = tracking.get(
branch or "", (None, None, None, False)
)
@@ -759,7 +761,7 @@ def _build(
and (time.time() - item.last_activity) / 3600 < repo.min_age
):
item.skip = f"younger than {repo.min_age:g} h"
item.actions = _actions(repo, item, tree, checkout, dirty, registrations)
item.actions = _actions(repo, item, tree, checkout, dirty, registrations, held)
if repo.unsafe:
item.actions = [a for a in item.actions if not a.startswith("remote-branch:")]
return item
@@ -772,9 +774,10 @@ def _actions(
checkout: bool,
dirty: int,
registrations: Registrations,
held: Callable[[], dict[str, str]],
) -> list[str]:
if repo.scope == "local":
return _local_actions(repo, item, tree)
return _local_actions(repo, item, tree, held)
tree_part: list[str] = []
if tree:
if (
@@ -813,7 +816,12 @@ def _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`.
@@ -823,6 +831,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
ancestor of none of them gets that as its skip.
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:
`local-branch` for a merged-clean local branch that no worktree,
@@ -832,9 +842,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:
return []
held = _held_branches(repo.repo).get(item.branch)
if held:
item.skip = item.skip or held
hold = held().get(item.branch)
if hold:
item.skip = item.skip or hold
return []
targets = [repo.default, *repo.lines]
if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets):
@@ -854,6 +864,7 @@ def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
cwds,
tracking,
_registrations(repo.repo),
cache(lambda: _held_branches(repo.repo)),
)
+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.")
+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
+57 -2
View File
@@ -9,11 +9,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 +78,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
@@ -489,6 +489,52 @@ class TestBranchCleanupLocal(unittest.TestCase):
heads["refs/heads/local-done"],
)
def test_plan_reads_the_held_branches_once_per_repository(self) -> None:
self._set_head()
extra = ("more-a", "more-b", "more-c")
for name in extra:
git(self.repo, "branch", name, "done")
with patch.object(gc, "_held_branches", wraps=gc._held_branches) as held:
run = self._cleanup("local", apply=False)
self.assertEqual(held.call_count, 1)
self.assertEqual(
{name for name, i in run.items.items() if i["actions"]},
{"done", "local-done", *extra},
)
def test_branch_held_after_the_plan_is_not_deleted(self) -> None:
self._set_head()
real = gc._rebuild
changes = [
lambda: git(
self.repo, "symbolic-ref", "refs/tags/pin", "refs/heads/local-done"
)
]
def late(repo: gc.Repo, item: gc.Item) -> gc.Item:
if changes:
changes.pop()()
return real(repo, item)
with (
patch.object(gc, "_held_branches", wraps=gc._held_branches) as held,
patch.object(gc, "_rebuild", side_effect=late),
):
run = self._cleanup("local", apply=True)
self.assertEqual(held.call_count, 3)
self.assertEqual(
self._results(run),
{
"done": "done",
"local-done": "skipped: changed since plan "
"(target of symbolic ref refs/tags/pin)",
},
)
self.assertIn("refs/heads/local-done", self._refs(self.repo, "refs/heads"))
def test_delete_never_follows_a_symref_made_after_the_check(self) -> None:
planned = git(self.repo, "rev-parse", "held-done")
@@ -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)
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:
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "pyproject.toml")