diff --git a/src/pkgmgr/actions/publish/workflow.py b/src/pkgmgr/actions/publish/workflow.py index 3fe4dd9..5da28b0 100644 --- a/src/pkgmgr/actions/publish/workflow.py +++ b/src/pkgmgr/actions/publish/workflow.py @@ -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.") diff --git a/tests/unit/pkgmgr/actions/publish/test_workflow_children.py b/tests/unit/pkgmgr/actions/publish/test_workflow_children.py new file mode 100644 index 0000000..ab5b4ad --- /dev/null +++ b/tests/unit/pkgmgr/actions/publish/test_workflow_children.py @@ -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()