Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b06b33ff57 | ||
|
|
895ec2f0d4 | ||
|
|
d34c3f3772 | ||
|
|
2b18deede8 | ||
|
|
1707cc0192 | ||
|
|
d9a8746635 | ||
|
|
5151b36250 |
No files matched your search
@@ -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
|
||||
@@ -8,19 +8,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
lint-python:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install ruff
|
||||
run: pip install ruff
|
||||
|
||||
- name: Run ruff
|
||||
run: |
|
||||
ruff check src tests
|
||||
uses: infinito-nexus/quality/.github/workflows/tool.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
|
||||
with:
|
||||
tool: ruff
|
||||
args: check src tests
|
||||
@@ -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.")
|
||||
@@ -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
|
||||
|
||||
@@ -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.")
|
||||
|
||||
@@ -23,6 +23,7 @@ from pkgmgr.cli.commands import (
|
||||
)
|
||||
from pkgmgr.cli.context import CLIContext
|
||||
from pkgmgr.cli.proxy import maybe_handle_proxy
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
from pkgmgr.core.repository.dir import get_repo_dir
|
||||
from pkgmgr.core.repository.selected import get_selected_repos
|
||||
|
||||
@@ -60,6 +61,14 @@ def _select_repo_for_current_directory(ctx: CLIContext) -> list[dict[str, Any]]:
|
||||
return [matches[0][1]]
|
||||
|
||||
|
||||
def _at_cwd_checkout(selected: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
try:
|
||||
toplevel = run(["rev-parse", "--show-toplevel"])
|
||||
except GitRunError:
|
||||
return selected
|
||||
return [{**repo, "directory": toplevel} for repo in selected]
|
||||
|
||||
|
||||
def dispatch_command(args, ctx: CLIContext) -> None:
|
||||
if maybe_handle_proxy(args, ctx):
|
||||
return
|
||||
@@ -143,6 +152,8 @@ def dispatch_command(args, ctx: CLIContext) -> None:
|
||||
return
|
||||
|
||||
if args.command == "release":
|
||||
if not _has_explicit_selection(args):
|
||||
selected = _at_cwd_checkout(selected)
|
||||
handle_release(args, ctx, selected)
|
||||
return
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
|
||||
from pkgmgr.cli.context import CLIContext
|
||||
from pkgmgr.cli.dispatch import dispatch_command
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
class TestReleaseCwdCheckout(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
root = Path(os.path.realpath(self._tmp.name))
|
||||
(root / "gitconfig").write_text(
|
||||
"[user]\n\tname = t\n\temail = t@example.org\n"
|
||||
"[commit]\n\tgpgsign = false\n"
|
||||
"[init]\n\tdefaultBranch = main\n"
|
||||
)
|
||||
env = patch.dict(
|
||||
os.environ,
|
||||
{"GIT_CONFIG_GLOBAL": str(root / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1"},
|
||||
)
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
cwd = os.getcwd()
|
||||
self.addCleanup(os.chdir, cwd)
|
||||
|
||||
self.main = str(root / "app")
|
||||
git(str(root), "init", "-q", self.main)
|
||||
Path(self.main, "app.py").write_text("v1\n")
|
||||
git(self.main, "add", "app.py")
|
||||
git(self.main, "commit", "-q", "-m", "init")
|
||||
self.clone = os.path.join(self.main, ".worktrees", "release")
|
||||
git(str(root), "clone", "-q", self.main, self.clone)
|
||||
Path(self.main, "app.py").write_text("unfinished work\n")
|
||||
|
||||
self.ctx = CLIContext(
|
||||
config_merged={},
|
||||
repositories_base_dir=str(root / "repos"),
|
||||
all_repositories=[
|
||||
{
|
||||
"provider": "github.com",
|
||||
"account": "t",
|
||||
"repository": "app",
|
||||
"directory": self.main,
|
||||
}
|
||||
],
|
||||
binaries_dir=str(root / "bin"),
|
||||
user_config_path=str(root / "config.yaml"),
|
||||
)
|
||||
|
||||
def _release_cwd(self, cwd: str, *argv: str) -> str:
|
||||
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._release_cwd(self.clone, "patch"), self.clone)
|
||||
|
||||
def test_explicit_identifier_keeps_the_configured_checkout(self) -> None:
|
||||
self.assertEqual(self._release_cwd(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()
|
||||
@@ -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")
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user