Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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@ed91a38fa19c2734d2cf07a0ade77bbb63f3096f
|
||||
@@ -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@ed91a38fa19c2734d2cf07a0ade77bbb63f3096f
|
||||
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
|
||||
|
||||
@@ -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,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")
|
||||
|
||||
Reference in new issue
Block a user