Compare commits

..
Author SHA1 Message Date
Kevin Veen-BirkenbachandClaude Opus 5.5 28ff2f7a8e refactor(release): tighten the release-at-cwd code to Codacy
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 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 / 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 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 b06b33ff57 fix(release): release the cwd checkout and refuse tracked changes
CI / test-virgin-root (push) Blocked by required conditions
CI / quality (push) Skipped
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
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
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
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
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
11 changed files with 358 additions and 295 deletions

No files matched your search

+156 -22
View File
@@ -8,7 +8,6 @@ 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
@@ -29,7 +28,6 @@ from pkgmgr.core.git.run import (
)
from .gc_forge import ForgeFacts, fetch_forge_facts
from .held import _common_dir, _git_dirs, _held_branches, _symbolic
from .nofollow import canonical, remove_tree
Registrations = tuple[str, dict[str, list[str]]]
@@ -39,7 +37,6 @@ 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.
@@ -72,6 +69,12 @@ NO_REMOTE_DEFAULT = (
)
NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8"
DEFAULT_NAMES = ("HEAD", "main", "master")
HELD_FILES = (
("rebase-merge/head-name", "rebase in progress"),
("rebase-merge/update-refs", "rebase in progress"),
("rebase-apply/head-name", "rebase in progress"),
("BISECT_START", "bisect in progress"),
)
DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$"
SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs")
WALKED_STORES = ("refs", "reftable", "logs/refs")
@@ -260,6 +263,10 @@ def _config_read(args: list[str], cwd: str, view: str) -> str:
return run(args, cwd=cwd, scan=True, config_view=view)
def _common_dir(cwd: str) -> str:
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
def _docker(args: list[str]) -> str:
return subprocess.run(
["docker", *args], check=True, capture_output=True, text=True
@@ -658,7 +665,7 @@ def _build(
tree: Worktree | None,
snapshot: Snapshot,
) -> Item:
local, remote, cwds, tracking = snapshot[:4]
local, remote, cwds, tracking, registrations = snapshot
upstream, ahead, behind, gone = tracking.get(
branch or "", (None, None, None, False)
)
@@ -752,7 +759,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, snapshot)
item.actions = _actions(repo, item, tree, checkout, dirty, registrations)
if repo.unsafe:
item.actions = [a for a in item.actions if not a.startswith("remote-branch:")]
return item
@@ -764,11 +771,10 @@ def _actions(
tree: Worktree | None,
checkout: bool,
dirty: int,
snapshot: Snapshot,
registrations: Registrations,
) -> list[str]:
if repo.scope == "local":
return _local_actions(repo, item, tree, snapshot[5])
registrations = snapshot[4]
return _local_actions(repo, item, tree)
tree_part: list[str] = []
if tree:
if (
@@ -807,22 +813,29 @@ def _actions(
return actions
def _local_actions(
repo: Repo,
item: Item,
tree: Worktree | None,
held: Callable[[], dict[str, str]],
) -> list[str]:
def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]:
"""
Settle the actions of an item planned with scope `local`.
Args:
repo: the planned repository; its default and merged-into lines are
the refs the branch tip must be an ancestor of.
item: the classified item; a merged-clean one whose tip is an
ancestor of none of them gets that as its skip.
tree: the worktree holding its branch, or None.
Returns:
`local-branch` for a merged-clean local branch that no worktree,
worktree registration, rebase, bisect or symbolic ref holds and whose
tip is an ancestor of the default or a merged-into line, else
nothing; never a worktree, stack or remote action.
"""
if item.state != "merged-clean" or not item.local_sha or tree is not None:
return []
hold = held().get(item.branch)
if hold:
item.skip = item.skip or hold
held = _held_branches(repo.repo).get(item.branch)
if held:
item.skip = item.skip or held
return []
return _ancestor_action(repo, item)
def _ancestor_action(repo: Repo, item: Item) -> list[str]:
targets = [repo.default, *repo.lines]
if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets):
return ["local-branch"]
@@ -841,7 +854,6 @@ def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
cwds,
tracking,
_registrations(repo.repo),
cache(lambda: _held_branches(repo.repo)),
)
@@ -899,6 +911,25 @@ def _default_remote(remotes: list[str]) -> str | None:
return remotes[0] if len(remotes) == 1 else None
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
"""
List the resolvable refs under a prefix with their symref targets.
Args:
repo_root: main worktree root of the repository.
prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`.
git_dir: the git common dir (shared refs plus the main worktree's own)
or a `worktrees/<id>` dir whose refs to list, or "" for the refs
as repo_root's worktree sees them.
Returns:
Full ref name -> the ref it points to, or "" for a plain ref.
"""
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
return dict(line.split("\x00", 1) for line in out.splitlines())
def _resolve_within(refs: dict[str, str], ref: str) -> str | None:
"""
Follow a ref's symref chain without leaving a set of refs.
@@ -944,6 +975,109 @@ def _remote_default(repo_root: str, remotes: list[str]) -> str | None:
return None
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
"""
Read the branch every worktree's HEAD names, on any ref backend.
Args:
repo_root: main worktree root of the repository.
git_dirs: the git common dir first, then each `worktrees/<id>`.
Returns:
Branch name -> skip reason, from `git --git-dir=<dir> symbolic-ref
HEAD` for each of them, whatever its id.
Raises:
GitBaseError: when a HEAD is neither readable nor detached.
"""
heads: dict[str, str] = {}
for git_dir in git_dirs:
try:
target = _git(
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
)
except GitRunError as exc:
if exc.returncode == 1:
continue
raise
if target.startswith("refs/heads/"):
heads.setdefault(
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
)
return heads
def _git_dirs(repo_root: str) -> list[str]:
"""
List the git dirs of every worktree of the repository.
Args:
repo_root: main worktree root of the repository.
Returns:
The git common dir, then each entry of `<common>/worktrees/`, whatever
its id and whether `git worktree list` shows it.
"""
common = _common_dir(repo_root)
base = os.path.join(common, "worktrees")
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
return [common, *(os.path.join(base, entry) for entry in entries)]
def _held_branches(repo_root: str) -> dict[str, str]:
"""
Find the local branches that something besides a listed worktree holds.
Args:
repo_root: main worktree root of the repository.
Returns:
Branch name -> skip reason: a symbolic branch, the branch any symbolic
ref under `refs/` (also a tag or remote-tracking one) or under the
main worktree's or any registration's `refs/worktree/` names, the HEAD
of the main repository and of every `worktrees/<id>` registration,
also one `git worktree list` omits, each rebase-merge and rebase-apply
head-name, an interactive rebase's update-refs and BISECT_START; all
read through the git common dir, whichever worktree repo_root is.
Raises:
GitBaseError: when git cannot read a registration, symref or HEAD.
OSError: when a state file exists but cannot be read.
ValueError: when a state file is not UTF-8.
"""
git_dirs = _git_dirs(repo_root)
held: dict[str, str] = {}
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
for git_dir in git_dirs[1:]:
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
for ref, target in symrefs.items():
if target and ref.startswith("refs/heads/"):
held.setdefault(
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
)
if target.startswith("refs/heads/"):
held.setdefault(
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
)
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
held.setdefault(branch, reason)
for git_dir in git_dirs:
for name, operation in HELD_FILES:
try:
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
continue
for line in lines:
ref = line.strip().removeprefix("ref: ")
if ref.startswith("refs/heads/") or name == "BISECT_START":
held.setdefault(
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
)
return held
def _lines(
repo_root: str, refs: list[str], remotes: list[str], warnings: list[str]
) -> tuple[dict[str, tuple[str, set[str]]], set[str]]:
-93
View File
@@ -1,93 +0,0 @@
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}"
)
+12
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from pkgmgr.core.git import run
from pkgmgr.core.git.commands import (
fetch,
pull_ff_only,
@@ -14,7 +15,18 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
Always run a pull BEFORE modifying anything.
Uses --ff-only to avoid creating merge commits automatically.
If no upstream is configured, we skip.
Raises:
RuntimeError: a tracked file is modified; the release commit uses
``commit -a`` and would ship it.
"""
dirty = run(["status", "--porcelain", "--untracked-files=no"])
if dirty:
raise RuntimeError(
"Tracked changes in the release checkout; commit or park them "
f"first, the release commit would include them:\n{dirty}"
)
upstream = get_upstream_ref()
if not upstream:
print("[INFO] No upstream configured for current branch. Skipping pull.")
+2 -1
View File
@@ -6,7 +6,7 @@ from .config import handle_config
from .make import handle_make
from .mirror import handle_mirror_command
from .publish import handle_publish
from .release import handle_release
from .release import handle_release, release_at_cwd
from .repos import handle_repos_command
from .review import handle_review
from .tools import handle_tools_command
@@ -29,4 +29,5 @@ __all__ = [
"handle_tools_command",
"handle_version",
"handle_worktree",
"release_at_cwd",
]
+35
View File
@@ -7,12 +7,47 @@ from typing import Any
from pkgmgr.actions.publish import publish as run_publish
from pkgmgr.actions.release import release as run_release
from pkgmgr.cli.context import CLIContext
from pkgmgr.core.git import GitRunError, run
from pkgmgr.core.repository.dir import get_repo_dir
from pkgmgr.core.repository.identifier import get_repo_identifier
from pkgmgr.core.repository.selected import has_explicit_selection
Repository = dict[str, Any]
def _at_cwd_checkout(args, selected: list[Repository]) -> list[Repository]:
"""
Args:
args: parsed CLI arguments.
selected: the repositories dispatch picked.
Returns:
selected unchanged after an explicit selection or outside git; else each
repository pointed at the current directory's git toplevel, so a release
from a nested clone never commits in the configured main checkout.
"""
if has_explicit_selection(args):
return selected
try:
toplevel = run(["rev-parse", "--show-toplevel"])
except GitRunError:
return selected
return [{**repo, "directory": toplevel} for repo in selected]
def release_at_cwd(args, ctx: CLIContext, selected: list[Repository]) -> None:
"""
Args:
args: parsed CLI arguments.
ctx: the CLI context.
selected: the repositories dispatch picked; without an explicit
selection each is released in the current directory's checkout.
"""
handle_release(args, ctx, _at_cwd_checkout(args, selected))
def handle_release(
args,
ctx: CLIContext,
+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":
+19
View File
@@ -136,6 +136,25 @@ def _maybe_filter_ignored(args, repos: list[Repository]) -> list[Repository]:
return filter_ignored(repos)
def has_explicit_selection(args) -> bool:
"""
Args:
args: parsed CLI arguments.
Returns:
True when --all, an identifier, --category, --tag or --string picks
the repositories instead of the current directory.
"""
return bool(
getattr(args, "all", False)
or getattr(args, "identifiers", [])
or getattr(args, "category", [])
or getattr(args, "tag", [])
or getattr(args, "string", "")
)
def get_selected_repos(args, all_repositories: list[Repository]) -> list[Repository]:
"""
Compute the list of repositories selected by CLI arguments.
@@ -13,7 +13,7 @@ from contextlib import contextmanager, redirect_stderr, redirect_stdout
from types import SimpleNamespace
from unittest.mock import patch
from pkgmgr.actions.branch import gc, gc_forge, held, tree
from pkgmgr.actions.branch import gc, gc_forge, tree
from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots
from pkgmgr.cli.parser import create_parser
from pkgmgr.core.credentials.types import NoCredentialsError
@@ -1647,7 +1647,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
def test_failed_head_read_refuses_the_repository(self) -> None:
heads = self._refs(self.repo, "refs/heads")
real = held._git
real = gc._git
def timed_out(args: list[str], cwd: str) -> str:
if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]:
@@ -1656,7 +1656,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
raise err
return real(args, cwd)
with patch.object(held, "_git", side_effect=timed_out):
with patch.object(gc, "_git", side_effect=timed_out):
run = self._cleanup("local", apply=True)
self.assertEqual(run.code, 2)
@@ -1,10 +1,21 @@
from __future__ import annotations
import io
import os
import shutil
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
from pkgmgr.cli.context import CLIContext
GIT = shutil.which("git")
class TestIntegrationReleasePublishHook(unittest.TestCase):
def _ctx(self) -> SimpleNamespace:
@@ -65,5 +76,90 @@ class TestIntegrationReleasePublishHook(unittest.TestCase):
m_publish.assert_not_called()
@unittest.skipUnless(GIT, "git builds the clones under test")
class TestReleaseCwdCheckout(unittest.TestCase):
def _sh(self, cwd: str, *argv: str) -> None:
subprocess.run([GIT, *argv], cwd=cwd, check=True, capture_output=True)
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
base = os.path.realpath(self._tmp.name)
identity = {
f"GIT_{role}_{field}": value
for role in ("AUTHOR", "COMMITTER")
for field, value in (("NAME", "t"), ("EMAIL", "t@example.org"))
}
scrubbed = patch.dict(
os.environ,
{**identity, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"},
)
scrubbed.start()
self.addCleanup(scrubbed.stop)
self.addCleanup(os.chdir, os.getcwd())
self.main = os.path.join(base, "app")
self._sh(base, "init", "-q", "-b", "main", self.main)
Path(self.main, "app.py").write_text("v1\n")
self._sh(self.main, "add", "app.py")
self._sh(self.main, "commit", "-q", "--no-gpg-sign", "-m", "init")
self.clone = os.path.join(self.main, ".worktrees", "release")
self._sh(base, "clone", "-q", self.main, self.clone)
Path(self.main, "app.py").write_text("unfinished work\n")
self.ctx = CLIContext(
config_merged={},
repositories_base_dir=os.path.join(base, "repos"),
all_repositories=[
{
"provider": "github.com",
"account": "t",
"repository": "app",
"directory": self.main,
}
],
binaries_dir=os.path.join(base, "bin"),
user_config_path=os.path.join(base, "config.yaml"),
)
def _released_in(self, cwd: str, *argv: str) -> str:
from pkgmgr.cli.dispatch import dispatch_command
from pkgmgr.cli.parser import create_parser
seen: list[str] = []
os.chdir(cwd)
args = create_parser("test").parse_args(["release", *argv, "--no-publish"])
with (
patch(
"pkgmgr.cli.commands.release.run_release",
side_effect=lambda **_kwargs: seen.append(os.getcwd()),
),
redirect_stdout(io.StringIO()),
):
dispatch_command(args, self.ctx)
self.assertEqual(len(seen), 1)
return seen[0]
def test_release_from_a_nested_clone_runs_in_the_clone(self) -> None:
self.assertEqual(self._released_in(self.clone, "patch"), self.clone)
def test_explicit_identifier_keeps_the_configured_checkout(self) -> None:
self.assertEqual(self._released_in(self.clone, "patch", "app"), self.main)
def test_tracked_changes_refuse_the_release(self) -> None:
os.chdir(self.main)
with self.assertRaises(RuntimeError) as cm:
ensure_clean_and_synced(preview=False)
self.assertIn("app.py", str(cm.exception))
self.assertEqual(Path(self.main, "app.py").read_text(), "unfinished work\n")
def test_clean_clone_passes_the_check(self) -> None:
os.chdir(self.clone)
with redirect_stdout(io.StringIO()):
ensure_clean_and_synced(preview=False)
if __name__ == "__main__":
unittest.main()
@@ -1,162 +0,0 @@
from __future__ import annotations
import io
import json
import os
import shutil
import tempfile
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
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
@unittest.skipUnless(shutil.which("git"), "git builds the repository under test")
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, **AUTHOR, "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 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()
@@ -6,6 +6,7 @@ from unittest.mock import patch
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
@patch("pkgmgr.actions.release.git_ops.run", return_value="")
class TestEnsureCleanAndSynced(unittest.TestCase):
@patch("pkgmgr.actions.release.git_ops.pull_ff_only")
@patch("pkgmgr.actions.release.git_ops.fetch")
@@ -15,6 +16,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
_mock_run,
) -> None:
mock_get_upstream_ref.return_value = None
@@ -31,6 +33,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
_mock_run,
) -> None:
mock_get_upstream_ref.return_value = "origin/main"
@@ -53,6 +56,7 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
_mock_run,
) -> None:
mock_get_upstream_ref.return_value = "origin/main"
@@ -66,3 +70,30 @@ class TestEnsureCleanAndSynced(unittest.TestCase):
preview=False,
)
mock_pull_ff_only.assert_called_once_with(preview=False)
@patch("pkgmgr.actions.release.git_ops.pull_ff_only")
@patch("pkgmgr.actions.release.git_ops.fetch")
@patch("pkgmgr.actions.release.git_ops.get_upstream_ref")
def test_tracked_changes_refuse_before_any_sync(
self,
mock_get_upstream_ref,
mock_fetch,
mock_pull_ff_only,
mock_run,
) -> None:
mock_run.return_value = " M src/app.py"
with self.assertRaises(RuntimeError) as cm:
ensure_clean_and_synced(preview=True)
self.assertIn("src/app.py", str(cm.exception))
mock_run.assert_called_once_with(
["status", "--porcelain", "--untracked-files=no"]
)
mock_get_upstream_ref.assert_not_called()
mock_fetch.assert_not_called()
mock_pull_ff_only.assert_not_called()
if __name__ == "__main__":
unittest.main()