diff --git a/plugins/lookup/requires_python.py b/plugins/lookup/requires_python.py new file mode 100644 index 0000000000..2700034c47 --- /dev/null +++ b/plugins/lookup/requires_python.py @@ -0,0 +1,24 @@ +""" +Ansible lookup plugin: requires_python + +Args: + terms: none. + +Returns: + The ``requires-python`` spec of pyproject.toml at the repository root. +""" + +from __future__ import annotations + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from plugins.lookup import PROJECT_ROOT +from utils.requires_python import requires_python + + +class LookupModule(LookupBase): + def run(self, terms, variables=None, **kwargs): + if terms: + raise AnsibleError("requires_python lookup takes no terms") + return [requires_python(PROJECT_ROOT)] diff --git a/roles/dev-python/tasks/00_core.yml b/roles/dev-python/tasks/00_core.yml index 248682831b..3d18f01d77 100644 --- a/roles/dev-python/tasks/00_core.yml +++ b/roles/dev-python/tasks/00_core.yml @@ -8,10 +8,7 @@ ansible.builtin.script: "{{ role_path }}/files/shell/install.sh" environment: SKIP_DOCKER_APT_SANITIZER: "1" - DEV_PYTHON_REQUIRES: >- - {{ lookup('file', lookup('path_absolute', 'pyproject.toml')) - | regex_search('(?m)^requires-python\\s*=\\s*"([^"]+)"', '\\1') - | first }} + DEV_PYTHON_REQUIRES: "{{ lookup('requires_python') }}" become: true - include_tasks: utils/once/flag.yml diff --git a/roles/web-app-docs/meta/services.yml b/roles/web-app-docs/meta/services.yml index 66ca95bc4a..3d468dae1c 100644 --- a/roles/web-app-docs/meta/services.yml +++ b/roles/web-app-docs/meta/services.yml @@ -28,7 +28,8 @@ docs: swarm: enabled: true image: python - version: 3.15-slim + version: 3.14-slim + follow: requires-python custom: true source_repository: "{{ SOFTWARE_REPOSITORY }}" mermaid_version: 12.3.0 diff --git a/tests/external/update/pip/test_ansible_python_cap.py b/tests/external/update/pip/test_ansible_python_cap.py index 4f8ba83861..25c7a17435 100644 --- a/tests/external/update/pip/test_ansible_python_cap.py +++ b/tests/external/update/pip/test_ansible_python_cap.py @@ -24,7 +24,6 @@ from __future__ import annotations import http.client import json import re -import tomllib import unittest import urllib.error import urllib.request @@ -33,7 +32,7 @@ from packaging.requirements import Requirement from packaging.version import InvalidVersion, Version from utils.annotations.message import warning -from utils.cache.files import read_text +from utils.requires_python import requires_python, supported_minors from . import PROJECT_ROOT @@ -41,8 +40,6 @@ PYPI_API = "https://pypi.org/pypi/{}" TIMEOUT_SECONDS = 15 USER_AGENT = "infinito-nexus python cap check" CLASSIFIER = re.compile(r"^Programming Language :: Python :: 3\.(\d+)$") -REQUIRES_PYTHON = re.compile(r"^>=3\.(\d+),<3\.(\d+)$") -PYPROJECT = PROJECT_ROOT / "pyproject.toml" class PyPIUnavailableError(Exception): @@ -75,13 +72,7 @@ def pypi_json(path: str) -> dict: def declared_cap() -> int: """Return the highest Python 3 minor ``requires-python`` admits.""" - spec = tomllib.loads(read_text(str(PYPROJECT)))["project"]["requires-python"] - match = REQUIRES_PYTHON.fullmatch(spec) - if match is None: - raise AssertionError( - f"pyproject.toml requires-python {spec!r} must read >=3.X,<3.Y" - ) - return int(match[2]) - 1 + return max(supported_minors(requires_python(PROJECT_ROOT))) def core_requirement(ansible: dict) -> Requirement: diff --git a/tests/lint/repository/dependencies/test_requires_python_followers.py b/tests/lint/repository/dependencies/test_requires_python_followers.py new file mode 100644 index 0000000000..b6c1f60ecd --- /dev/null +++ b/tests/lint/repository/dependencies/test_requires_python_followers.py @@ -0,0 +1,89 @@ +"""Lint guard: a role image that pip-installs core runs a Python core supports. + +pip refuses ``infinito-nexus`` on a base outside ``requires-python`` of +pyproject.toml. The image updater bumped ``web-app-docs`` to +``python:3.15-slim`` that way (PR 1448) and broke every deploy with docs. +``follow: requires-python`` holds the updater inside the range; this guard +makes every such role declare it and pin a base inside the range. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.requires_python import FOLLOW, requires_python, supported_minors +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.base import version_key + +from . import PROJECT_ROOT + +_INSTALLS_CORE = re.compile(r"infinito-nexus(\[[^\]]*\])? @ git\+") + + +def _entities(role): + data = load_yaml_any(str(role / ROLE_FILE_META_SERVICES), default_if_missing={}) + return { + name: entity + for name, entity in (data or {}).items() + if isinstance(entity, dict) + } + + +def _roles_installing_core(): + return sorted( + { + path.relative_to(PROJECT_ROOT / "roles").parts[0] + for path in (PROJECT_ROOT / "roles").glob("*/*/Dockerfile*") + if path.is_file() and _INSTALLS_CORE.search(read_text(str(path))) + } + ) + + +class TestRequiresPythonFollowers(unittest.TestCase): + def test_every_role_installing_core_follows_requires_python(self) -> None: + roles = _roles_installing_core() + self.assertIn("web-app-docs", roles) + missing = [ + role + for role in roles + if not any( + entity.get("follow") == FOLLOW + for entity in _entities(PROJECT_ROOT / "roles" / role).values() + ) + ] + self.assertEqual( + missing, + [], + f"these roles pip-install infinito-nexus into their image but no " + f"entity of meta/services.yml sets 'follow: {FOLLOW}', so the image " + f"updater may move the base past requires-python", + ) + + def test_every_follower_pins_a_supported_python(self) -> None: + minors = supported_minors(requires_python(PROJECT_ROOT)) + followers = { + f"{role.name}/{name}": str(entity.get("version")) + for role in sorted((PROJECT_ROOT / "roles").iterdir()) + for name, entity in _entities(role).items() + if entity.get("follow") == FOLLOW + } + self.assertIn("web-app-docs/docs", followers) + outside = { + key: version + for key, version in followers.items() + if version_key(version)[0] != 3 or version_key(version)[1] not in minors + } + self.assertEqual( + outside, + {}, + f"these pins lie outside requires-python of pyproject.toml " + f"(Python 3.{minors.start} to 3.{minors.stop - 1}); pip refuses to " + f"install infinito-nexus there", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_requires_python.py b/tests/unit/python/plugins/lookup/test_requires_python.py new file mode 100644 index 0000000000..478e8be4b7 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_requires_python.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from ansible.errors import AnsibleError + +from plugins.lookup import requires_python as plugin + + +class TestRequiresPythonLookup(unittest.TestCase): + def test_the_lookup_returns_the_pyproject_spec(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "pyproject.toml").write_text( + '[project]\nname = "demo"\nrequires-python = ">=3.12,<3.14"\n', + encoding="utf-8", + ) + with mock.patch.object(plugin, "PROJECT_ROOT", Path(tmp)): + self.assertEqual(plugin.LookupModule().run([]), [">=3.12,<3.14"]) + + def test_the_lookup_takes_no_terms(self) -> None: + with self.assertRaises(AnsibleError): + plugin.LookupModule().run(["range"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/dev-python/files/test_install.py b/tests/unit/python/roles/dev-python/files/test_install.py index 41c19b413e..d8c18e646b 100644 --- a/tests/unit/python/roles/dev-python/files/test_install.py +++ b/tests/unit/python/roles/dev-python/files/test_install.py @@ -7,8 +7,8 @@ import unittest from pathlib import Path import jinja2 -from ansible.plugins.filter.core import regex_search +from plugins.lookup.requires_python import LookupModule as RequiresPythonLookup from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml_str @@ -210,16 +210,12 @@ class TestBoundsFromRequiresPython(unittest.TestCase): ) expression = task["environment"]["DEV_PYTHON_REQUIRES"] - def lookup(name: str, term: str) -> str: - return { - "path_absolute": lambda: str(PROJECT_ROOT / term), - "file": lambda: read_text(term), - }[name]() + def lookup(name: str, *terms: str) -> str: + return {"requires_python": RequiresPythonLookup}[name]().run(list(terms))[0] environment = jinja2.Environment( autoescape=jinja2.select_autoescape(default_for_string=False) ) - environment.filters["regex_search"] = regex_search environment.globals["lookup"] = lookup spec = tomllib.loads(read_text(str(PROJECT_ROOT / "pyproject.toml")))[ "project" diff --git a/tests/unit/python/utils/test_requires_python.py b/tests/unit/python/utils/test_requires_python.py new file mode 100644 index 0000000000..a0c685475a --- /dev/null +++ b/tests/unit/python/utils/test_requires_python.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from utils.requires_python import requires_python, supported_minors + + +class TestRequiresPython(unittest.TestCase): + def test_the_spec_is_read_from_pyproject(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "pyproject.toml").write_text( + '[project]\nname = "demo"\nrequires-python = ">=3.11,<3.15"\n', + encoding="utf-8", + ) + self.assertEqual(requires_python(Path(tmp)), ">=3.11,<3.15") + + def test_the_range_admits_every_minor_below_the_cap(self) -> None: + self.assertEqual(list(supported_minors(">=3.11,<3.15")), [11, 12, 13, 14]) + + def test_another_shape_is_refused(self) -> None: + for spec in (">=3.11", ">=3.11,<=3.14", "~=3.11", ">=3.11, <3.15"): + with self.subTest(spec=spec), self.assertRaises(ValueError): + supported_minors(spec) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_follow.py b/tests/unit/python/utils/update/test_follow.py index d119f19b3c..6045d6c3e5 100644 --- a/tests/unit/python/utils/update/test_follow.py +++ b/tests/unit/python/utils/update/test_follow.py @@ -69,6 +69,47 @@ class TestFollowedTags(unittest.TestCase): self.assertIn("WARN fedora:44", stderr.getvalue()) self.assertIn("IncompleteRead", stderr.getvalue()) + def test_requires_python_keeps_only_supported_minors(self) -> None: + tags = [ + "3.13-slim", + "3.14-slim", + "3.15-slim", + "3.16-slim", + "3.15", + "3.14.2-slim", + ] + with ( + mock.patch( + "utils.update.follow.requires_python", return_value=">=3.11,<3.16" + ), + mock.patch("utils.update.follow.tag_digest") as digest, + contextlib.redirect_stderr(io.StringIO()), + ): + found = followed_tags( + "python", tags, {"follow": "requires-python"}, "3.14-slim" + ) + self.assertEqual(found, ["3.15-slim"]) + digest.assert_not_called() + + def test_requires_python_at_the_cap_proposes_nothing(self) -> None: + with ( + mock.patch( + "utils.update.follow.requires_python", return_value=">=3.11,<3.15" + ), + mock.patch( + "utils.update.follow.tag_digest", return_value="sha256:one" + ) as digest, + contextlib.redirect_stderr(io.StringIO()), + ): + found = followed_tags( + "python", + ["3.14-slim", "3.15-slim"], + {"follow": "requires-python"}, + "3.14-slim", + ) + self.assertEqual(found, []) + digest.assert_not_called() + def test_a_rate_limited_digest_is_retried(self) -> None: limited = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None) body = json.dumps({"digest": "sha256:45"}).encode() diff --git a/utils/requires_python.py b/utils/requires_python.py new file mode 100644 index 0000000000..dcfed60a97 --- /dev/null +++ b/utils/requires_python.py @@ -0,0 +1,37 @@ +"""The Python 3 minors core runs on, read from ``requires-python`` of pyproject.toml.""" + +from __future__ import annotations + +import re +import tomllib +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT, read_text + +FOLLOW = "requires-python" +_RANGE = re.compile(r"^>=3\.(\d+),<3\.(\d+)$") + + +def requires_python(root: Path = PROJECT_ROOT) -> str: + """Return the ``requires-python`` spec of ``/pyproject.toml``. + + Args: + root: the repository root holding pyproject.toml. + """ + pyproject = tomllib.loads(read_text(str(Path(root) / "pyproject.toml"))) + return str(pyproject["project"]["requires-python"]) + + +def supported_minors(spec: str) -> range: + """Return the Python 3 minors a ``>=3.X,<3.Y`` spec admits. + + Args: + spec: the ``requires-python`` value. + + Raises: + ValueError: the spec has another shape. + """ + match = _RANGE.fullmatch(spec) + if match is None: + raise ValueError(f"requires-python {spec!r} must read >=3.X,<3.Y") + return range(int(match[1]), int(match[2])) diff --git a/utils/update/follow.py b/utils/update/follow.py index 8c22f84128..76a0225bb7 100644 --- a/utils/update/follow.py +++ b/utils/update/follow.py @@ -5,6 +5,10 @@ newer tag of the same shape whose digest equals the one ```` points at. Ubuntu's ``latest`` names the newest LTS release and Fedora's the newest stable one, while the higher numbers (Ubuntu's interim releases, Fedora's rawhide) point elsewhere. + +``follow: requires-python`` holds a ``python`` base that pip-installs core to +the minors ``requires-python`` of pyproject.toml admits, since pip refuses +core on any other. """ from __future__ import annotations @@ -16,6 +20,7 @@ import time import urllib.error from utils.docker.image.ref import dockerhub_repo +from utils.requires_python import FOLLOW, requires_python, supported_minors from utils.update.base import version_depth, version_flavor, version_key from utils.update.fetch import get @@ -53,9 +58,11 @@ def followed_tags( current: the pinned version. Returns: - The tags unchanged without ``follow``; otherwise the newer tags of the - pin's depth and flavor that share the followed tag's digest, and none - when Docker Hub cannot be read, which is reported on stderr. + The tags unchanged without ``follow``; with ``follow: requires-python`` + the newer tags of the pin's depth and flavor on a Python 3 minor that + ``requires-python`` admits; otherwise the newer ones that share the + followed tag's digest, and none when Docker Hub cannot be read, which + is reported on stderr. """ follow = config.get("follow") if isinstance(config, dict) else None if follow is None: @@ -67,6 +74,19 @@ def followed_tags( and version_flavor(tag) == version_flavor(current) and version_key(tag) > version_key(current) ] + if follow == FOLLOW: + minors = supported_minors(requires_python()) + kept = [ + tag + for tag in newer + if version_key(tag)[0] == 3 and version_key(tag)[1] in minors + ] + print( + f"[follow] {image}:{current}: requires-python admits " + f"{kept or 'none'} among newer {newer or 'none'}", + file=sys.stderr, + ) + return kept try: target = tag_digest(image, str(follow)) kept = [tag for tag in newer if tag_digest(image, tag) == target]