Merge pull request #12 from kevinveenbirkenbach/fix/release-cwd

fix(release): release the cwd checkout and refuse tracked changes
This commit is contained in:
Kevin Veen-Birkenbach authored and GitHub committed 2026-11-29 16:00:09 +01:00
commit 83297dab67
7 files changed
+199 -15

No files matched your search

+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.
@@ -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()
@@ -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()