From 47641ae01d8ec8b5d79fdc0dd2bcd2c0ef6b75ab Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 6 Dec 2026 07:21:44 +0000 Subject: [PATCH 1/3] ci(lint): accept an apm-cli bump in the bot-diff check A Renovate pull request may now change pyproject.toml and uv.lock, but only together, so the pep621 manager can move the apm pin. In pyproject.toml only the version of a quoted name==version pin may change. uv.lock is parsed with tomllib in a module of its own, check_uv_lock.py, because uv installs whatever the lock names and a line-shape rule cannot tie a file to its package: a file of another package under apm-cli, an added package, a marker that drops a dependency and a downgrade all passed one. The parsed rule allows only apm-cli moving up to the pin in pyproject.toml, as plain releases compared as numbers, with the same kinds of file as before (an sdist if it had one, the same wheel tags), each on files.pythonhosted.org under /packages/ without dot segments or escapes, named for apm-cli at the pin, by sha256. Every other package, the root project beyond its apm-cli specifier and the top level beyond `revision` must stay as they are. Without the same file kinds, a lock could drop the wheels and make uv build apm-cli from its sdist with a build backend fetched at sync time. A bump that moves anything else is made by hand. Refs: #518 Assisted-by: Claude Code --- .gitea/workflows/AGENTS.md | 11 +- scripts/check_bot_pr_diff.py | 58 +++- scripts/check_uv_lock.py | 198 +++++++++++ scripts/select_molecule_scenarios.py | 1 + tests/scripts/test_check_bot_pr_diff.py | 169 +++++++++ tests/scripts/test_check_uv_lock.py | 321 ++++++++++++++++++ .../scripts/test_select_molecule_scenarios.py | 6 + 7 files changed, 754 insertions(+), 10 deletions(-) create mode 100644 scripts/check_uv_lock.py create mode 100644 tests/scripts/test_check_uv_lock.py diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index 6028c7a..4a1cc10 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -39,11 +39,14 @@ issue. while a content check must see the content it is given. *Held:* review (`CODEOWNERS`). - **A pull request from a `renovate/` branch changes only version, tag, digest and pin lines** (tool pins with their lock entries and hashes, hook `rev:` lines, Dockerfile `FROM` tags and - digests, `job_image:` pins, consumer image pins). + digests, `job_image:` pins, consumer image pins). In `pyproject.toml` only a pin's version + moves; in `uv.lock` only apm-cli moves, to that pin, with its files from PyPI by sha256, and + every other package stays as it is. *Why:* the bot's minor and patch pull requests automerge, so they must not be able to change - anything else. *Held:* control: the Lint check's "Check a bot pull request only moves pins" - step, `scripts/check_bot_pr_diff.py` run from `main`'s copy. The branch name is chosen by the - pusher, so this constrains only the bot's own pull requests. + anything else; uv installs whatever `uv.lock` names, so it is parsed, not read line by line. + *Held:* control: the Lint check's "Check a bot pull request only moves pins" step, + `scripts/check_bot_pr_diff.py` with `scripts/check_uv_lock.py`, run from `main`'s copy. The + branch name is chosen by the pusher, so this constrains only the bot's own pull requests. - **Workflows never mention the image namespace this repository's CI must not use** (the string is in `scripts/check_image_versions.py`). *Why:* this repository's images are built and pulled only under its own organisation's namespace. *Held:* control: the Lint check's "Check image diff --git a/scripts/check_bot_pr_diff.py b/scripts/check_bot_pr_diff.py index 0f8c689..f456029 100644 --- a/scripts/check_bot_pr_diff.py +++ b/scripts/check_bot_pr_diff.py @@ -12,6 +12,10 @@ When starts with `renovate/`, the diff of ...HEAD may only `name==version` entries, `--hash=sha256:<64 hex>` lines and plain `# via` or prose comments, nothing else; packages may be added or removed (a transitive dependency), but the `# pip-compile ...` command in the header, which Renovate runs again, must stay as it is; + * pyproject.toml: the version of a quoted `"name==version"` pin (the names, spelled as they + are, and every other line, stay), only together with uv.lock; + * uv.lock: the apm-cli bump to the pin of the new pyproject.toml, and nothing else + (check_uv_lock.py), only together with pyproject.toml; * requirements.yml and extensions/molecule/requirements.yml: `version:` lines (the collection names, and every other line, stay); * .pre-commit-config.yaml: `rev:` lines (a tag, or a commit SHA with its `# frozen: ` comment); @@ -50,6 +54,7 @@ import re import sys import check_image_versions as civ +import check_uv_lock PREFIX = "renovate/" TAG = r"[A-Za-z0-9._-]+" @@ -73,6 +78,7 @@ COLLECTION_PINS = {"requirements.yml", "extensions/molecule/requirements.yml"} # Lint's and the molecule-controller image's requirements, each with its pip-compile lock. REQUIREMENTS = {"requirements-dev.txt", "requirements-molecule.txt"} LOCKS = {"requirements-dev.lock", "requirements-molecule.lock"} +UV_LOCK = "uv.lock" CONSUMERS = { ".gitea/workflows/lint.yml", ".gitea/workflows/build.yml", @@ -144,6 +150,16 @@ def lock_problem(removed, added): return None +# A quoted `name==version` pin in a pyproject.toml dependency array. +PYPROJECT_PIN = re.compile(r'"([A-Za-z0-9][A-Za-z0-9._-]*)==[0-9][0-9A-Za-z.+!_-]*"') + + +def reduce_pyproject(line): + if not PYPROJECT_PIN.search(line): + return None + return PYPROJECT_PIN.sub(lambda m: f'"{m[1]}==X"', line) + + def reduce_rev(line): return "rev" if REV_LINE.match(line) else None @@ -178,6 +194,10 @@ def file_problem(path, removed, added): ) if path in LOCKS: return lock_problem(removed, added) + if path == "pyproject.toml": + return same_shape( + removed, added, reduce_pyproject, "a quoted `name==version` pin" + ) if path in COLLECTION_PINS: return same_shape(removed, added, reduce_version, "a `version:` line") if path == ".pre-commit-config.yaml": @@ -254,15 +274,22 @@ def moved_problem(removed, added): return None -def check(entries, patch_of): - """One message per offending file; patch_of(path) returns that file's -U0 patch text.""" +def check(entries, patch_of, show=None): + """One message per offending file; patch_of(path) returns that file's -U0 patch text and + show(side, path) its text on the "base" or "head" side (needed for uv.lock).""" problems = [] + # The pin and its lock move together, so neither can change what the other one locks. + partners = {"pyproject.toml": UV_LOCK, UV_LOCK: "pyproject.toml"} + paths = {path for unused, unused, unused, path in entries} for old_mode, new_mode, status, path in entries: if status != "M" or old_mode != new_mode or new_mode != "100644": problems.append( f"{path}: a bot pull request may not add, delete, rename or change the mode of a file" ) continue + if path in partners and partners[path] not in paths: + problems.append(f"{path}: changes without {partners[path]}") + continue patch = patch_of(path) if BINARY.search(patch): problems.append( @@ -276,9 +303,22 @@ def check(entries, patch_of): f"{len(removed)} removed and {len(added)} added (binary or empty change?)" ) continue - reason = file_problem( - path, [line for unused, line in removed], [line for unused, line in added] - ) + if path == UV_LOCK: + reason = ( + check_uv_lock.lock_problem( + show("base", path), + show("head", path), + show("head", "pyproject.toml"), + ) + if show + else "is not a file a bot pull request may change" + ) + else: + reason = file_problem( + path, + [line for unused, line in removed], + [line for unused, line in added], + ) if not reason and path == civ.MATRIX_FILE: reason = moved_problem(removed, added) if reason: @@ -336,8 +376,14 @@ def run(argv): path, ) + def show(side, path): + rev = base if side == "base" else "HEAD" + return civ.git("cat-file", "blob", f"{rev}:{path}") + entries = parse_raw(raw) - return check(entries, patch_of), f"{len(entries)} file(s) within the bot allowance" + return check( + entries, patch_of, show + ), f"{len(entries)} file(s) within the bot allowance" def main(argv): diff --git a/scripts/check_uv_lock.py b/scripts/check_uv_lock.py new file mode 100644 index 0000000..0e7ef61 --- /dev/null +++ b/scripts/check_uv_lock.py @@ -0,0 +1,198 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""The uv.lock rule of check_bot_pr_diff.py: a bot may move apm-cli to its pin, nothing else. + +Both locks are parsed. The top level stays as it is, except `revision`. The same packages are +locked, and every one but apm-cli and the root project is unchanged. The root project changes +only its apm-cli specifier, to the pin in pyproject.toml. apm-cli changes only its version, up +to that pin, and its files: the same kinds (an sdist if it had one, the same wheel tags), each +on PyPI's download host, named for apm-cli at the pin, by sha256. Versions are plain releases +compared as numbers. A bump that moves anything else fails, and a person makes it by hand. +""" + +import copy +import re +import tomllib +import urllib.parse + +PACKAGE = "apm-cli" +REGISTRY = {"registry": "https://pypi.org/simple"} +ROOT_SOURCE = {"virtual": "."} +FILE_KEYS = {"url", "hash", "size", "upload-time"} +SHA256 = re.compile(r"sha256:[0-9a-f]{64}") +PIN = re.compile(rf"{re.escape(PACKAGE)}==([0-9][0-9A-Za-z.+!_-]*)") +# A plain release; pre-, post- and dev-releases, epochs and local versions are bumped by hand. +RELEASE = re.compile(r"[0-9]+(?:\.[0-9]+)*") +DIST = re.sub(r"[-_.]+", "_", PACKAGE).lower() + + +class Refused(Exception): + pass + + +def parse(text, what): + try: + return tomllib.loads(text) + except tomllib.TOMLDecodeError as exc: + raise Refused(f"{what} is not valid TOML ({exc})") from None + + +def pinned_version(pyproject): + pins = [ + m[1] + for entry in parse(pyproject, "pyproject.toml") + .get("dependency-groups", {}) + .get("dev", []) + if isinstance(entry, str) and (m := PIN.fullmatch(entry)) + ] + if len(pins) != 1: + raise Refused(f"pyproject.toml does not pin {PACKAGE} once with ==") + return pins[0] + + +def by_name(lock): + packages = {} + for package in lock.get("package", []): + packages.setdefault(package.get("name"), []).append(package) + return packages + + +def only(packages, what): + if len(packages) != 1: + raise Refused(f"the lock does not hold exactly one {what}") + return packages[0] + + +def without_apm_specifier(root): + """The root project with its apm-cli dev specifier blanked, and that specifier.""" + root = copy.deepcopy(root) + entries = [ + entry + for entry in root.get("metadata", {}).get("requires-dev", {}).get("dev", []) + if entry.get("name") == PACKAGE + ] + entry = only(entries, f"{PACKAGE} dev requirement in the root project") + specifier = entry.pop("specifier", None) + return root, specifier + + +def release(version): + """A plain release as a tuple of numbers without trailing zeros, or None.""" + if not isinstance(version, str) or not RELEASE.fullmatch(version): + return None + parts = [int(part) for part in version.split(".")] + while len(parts) > 1 and parts[-1] == 0: + parts.pop() + return tuple(parts) + + +def file_kinds(package): + """The kinds of file a package locks: "sdist" and the tag of each wheel.""" + version = package.get("version") + kinds = {"sdist"} if "sdist" in package else set() + for wheel in package.get("wheels", []): + name = urllib.parse.urlsplit(wheel.get("url", "")).path.rsplit("/", 1)[-1] + prefix = f"{DIST}-{version}-" + if not (name.startswith(prefix) and name.endswith(".whl")): + raise Refused(f"the {PACKAGE} wheel {name} is not {PACKAGE} {version}") + kinds.add(name[len(prefix) : -len(".whl")]) + return kinds + + +def file_problem(pin, file): + url = urllib.parse.urlsplit(file.get("url", "")) + segments = url.path.split("/") + name = segments[-1] + if not ( + set(file) <= FILE_KEYS + and url.scheme == "https" + and url.netloc == "files.pythonhosted.org" + and segments[:2] == ["", "packages"] + and not any(part in ("", ".", "..") for part in segments[1:]) + and "%" not in url.path + and not (url.query or url.fragment) + ): + return f"an {PACKAGE} file is not a plain download from files.pythonhosted.org" + if not ( + name == f"{DIST}-{pin}.tar.gz" + or (name.startswith(f"{DIST}-{pin}-") and name.endswith(".whl")) + ): + return f"the {PACKAGE} file {name} is not {PACKAGE} {pin}" + if not SHA256.fullmatch(str(file.get("hash", ""))): + return f"the {PACKAGE} file {name} has no sha256 hash" + return None + + +def apm_problem(old, new, pin): + if new.get("version") != pin: + return f"{PACKAGE} is locked at {new.get('version')}, not at the pin {pin}" + old_release, new_release = release(old.get("version")), release(pin) + if old_release is None or new_release is None: + return f"{PACKAGE} {old.get('version')} or {pin} is not a plain release" + if new_release <= old_release: + return f"{PACKAGE} does not move up from {old.get('version')} to {pin}" + rest = {"version", "sdist", "wheels"} + if {k: v for k, v in old.items() if k not in rest} != { + k: v for k, v in new.items() if k not in rest + }: + return f"changes the source or dependencies of {PACKAGE}" + files = ([new["sdist"]] if "sdist" in new else []) + new.get("wheels", []) + if not files: + return f"locks no file for {PACKAGE}" + for file in files: + reason = file_problem(pin, file) + if reason: + return reason + if file_kinds(old) != file_kinds(new): + return f"changes which kinds of file {PACKAGE} locks (sdist, wheel tags)" + return None + + +def compare(old, new, pin): + rest = {"revision", "package"} + if {k: v for k, v in old.items() if k not in rest} != { + k: v for k, v in new.items() if k not in rest + }: + return "changes a top-level setting other than revision" + if not isinstance(new.get("revision"), int): + return "the lock revision is not a number" + old_packages, new_packages = by_name(old), by_name(new) + if set(old_packages) != set(new_packages): + return "adds or removes a package" + roots = [ + name + for name, entries in new_packages.items() + if any(e.get("source") == ROOT_SOURCE for e in entries) + ] + root = only(roots, "root project") + for name in new_packages: + if name not in (PACKAGE, root) and old_packages[name] != new_packages[name]: + return f"changes the package {name}" + old_root, _unused = without_apm_specifier(only(old_packages[root], "root project")) + new_root, specifier = without_apm_specifier( + only(new_packages[root], "root project") + ) + if old_root != new_root: + return "changes the root project beyond its apm-cli specifier" + if specifier != f"=={pin}": + return f"the root project's {PACKAGE} specifier is not =={pin}" + return apm_problem( + only(old_packages.get(PACKAGE, []), PACKAGE), + only(new_packages.get(PACKAGE, []), PACKAGE), + pin, + ) + + +def lock_problem(old_lock, new_lock, pyproject): + """None when new_lock differs from old_lock only by the apm-cli bump to the pin of + pyproject (the new pyproject.toml's text); else a one-line reason.""" + try: + return compare( + parse(old_lock, "the old uv.lock"), + parse(new_lock, "the new uv.lock"), + pinned_version(pyproject), + ) + except Refused as exc: + return str(exc) + except (AttributeError, TypeError): + return "the lock does not have the shape uv writes" diff --git a/scripts/select_molecule_scenarios.py b/scripts/select_molecule_scenarios.py index 1a04841..73aa390 100644 --- a/scripts/select_molecule_scenarios.py +++ b/scripts/select_molecule_scenarios.py @@ -107,6 +107,7 @@ IGNORED = ( ".gitea/workflows/renovate.yml", ".gitea/workflows/gitea-release-key.yml", "scripts/check_bot_pr_diff.py", + "scripts/check_uv_lock.py", "scripts/check_image_versions.py", "scripts/next_image_version.py", "scripts/check_tarball.py", diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py index 54d8314..d70891f 100644 --- a/tests/scripts/test_check_bot_pr_diff.py +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -13,6 +13,7 @@ from unittest import mock SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" sys.path.insert(0, str(SCRIPTS)) import check_bot_pr_diff as cbd +from test_check_uv_lock import APM_NEW, APM_OLD, CLICK_OLD, UV_LOCK, uv_files D1, D2 = "sha256:" + "a" * 64, "sha256:" + "b" * 64 FILES = { @@ -30,6 +31,7 @@ FILES = { ".gitea/workflows/lint.yml": f"container:\n image: git.rkdr.net/mortis/ci:0.2.0@{D1}\nrun: echo a\n", ".gitea/workflows/molecule.yml": f"env:\n MOLECULE_IMAGE: >-\n git.rkdr.net/mortis/mol:0.1.0@{D1}\n", "renovate.json": "{}\n", + "pyproject.toml": '[project]\nrequires-python = ">=3.11"\n\n[dependency-groups]\ndev = ["apm-cli==0.39.3"]\n', } @@ -49,6 +51,7 @@ def run(cwd, *cmd): H1, H2 = "a" * 64, "b" * 64 +FILES["uv.lock"] = UV_LOCK class LockRuleTest(unittest.TestCase): @@ -113,6 +116,69 @@ class LockRuleTest(unittest.TestCase): ) +class PyprojectRuleTest(unittest.TestCase): + def test_an_apm_cli_bump_is_allowed(self): + self.assertIsNone( + cbd.file_problem( + "pyproject.toml", + ['dev = ["apm-cli==0.39.3"]'], + ['dev = ["apm-cli==0.39.4"]'], + ) + ) + + def test_a_new_dependency_is_refused(self): + old = 'dev = ["apm-cli==0.39.3"]' + for new in ( + 'dev = ["apm-cli==0.39.4", "evil==1.0"]', + 'dev = ["evil==0.39.4"]', + 'dev = ["apm-cli==0.39.4"]\nprod = ["evil==1.0"]', + ): + with self.subTest(new=new): + self.assertIsNotNone( + cbd.file_problem("pyproject.toml", [old], new.split("\n")) + ) + + def test_a_pinned_name_keeps_its_spelling(self): + self.assertIsNotNone( + cbd.file_problem( + "pyproject.toml", + ['dev = ["apm-cli==0.39.3"]'], + ['dev = ["APM-CLI==0.39.4"]'], + ) + ) + + def test_an_edit_to_another_setting_is_refused(self): + for old, new in ( + ('requires-python = ">=3.11"', 'requires-python = ">=3.12"'), + ("package = false", "package = true"), + ( + 'dev = ["apm-cli==0.39.3"]', + 'dev = ["apm-cli @ https://evil.example/apm.tgz"]', + ), + ( + 'dev = ["apm-cli==0.39.3"]', + 'dev = ["apm-cli==0.39.4"] # index-url = "https://evil/simple"', + ), + ): + with self.subTest(new=new): + self.assertIsNotNone(cbd.file_problem("pyproject.toml", [old], [new])) + + +class UvLockTest(unittest.TestCase): + def test_uv_lock_is_refused_without_both_sides_to_parse(self): + entries = [ + ("100644", "100644", "M", "pyproject.toml"), + ("100644", "100644", "M", "uv.lock"), + ] + patches = { + "pyproject.toml": '@@ -1 +1 @@\n-dev = ["apm-cli==0.39.3"]\n+dev = ["apm-cli==0.39.4"]\n', + "uv.lock": "@@ -1 +1 @@\n-revision = 3\n+revision = 5\n", + } + problems = cbd.check(entries, patches.get) + self.assertEqual(len(problems), 1, problems) + self.assertTrue(problems[0].startswith("uv.lock: "), problems) + + class RuleTest(unittest.TestCase): def problem(self, path, old, new): return cbd.file_problem(path, [old], [new]) @@ -499,6 +565,109 @@ class RepoTest(unittest.TestCase): self.assertEqual(code, 0, err) self.assertIn("5 file(s)", out) + def bump_apm_cli(self): + """The change Renovate makes for apm-cli 0.39.4, as uv 0.13.1 writes it.""" + self.edit("pyproject.toml", "apm-cli==0.39.3", "apm-cli==0.39.4") + self.edit("uv.lock", 'version = "0.39.3"', 'version = "0.39.4"') + self.edit("uv.lock", '"==0.39.3"', '"==0.39.4"') + self.edit("uv.lock", "apm_cli-0.39.3", "apm_cli-0.39.4") + self.edit("uv.lock", APM_OLD, APM_NEW) + + def assert_lock_refused(self): + self.commit("bot") + code, _unused, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn("uv.lock", err) + + def test_an_apm_cli_bump_with_its_lock_passes(self): + self.bump_apm_cli() + self.commit("bot") + code, out, err = self.gate() + self.assertEqual(code, 0, err) + self.assertIn("2 file(s)", out) + + def test_another_packages_file_under_the_apm_cli_entry_is_refused(self): + self.bump_apm_cli() + lock = (self.repo / "uv.lock").read_text() + start = lock.index('version = "0.39.4"') + end = lock.index("[[package]]", start) + six = ( + 'version = "1.17.0"\nsource = { registry = "https://pypi.org/simple" }\n' + 'dependencies = [\n { name = "click" },\n { name = "watchdog" },\n]\n' + 'wheels = [\n { url = "https://files.pythonhosted.org/packages/b7/ce/' + '149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", ' + 'hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", ' + 'size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },\n]\n\n' + ) + self.write("uv.lock", lock[:start] + six + lock[end:]) + self.assert_lock_refused() + + def test_a_new_package_is_refused(self): + self.bump_apm_cli() + self.edit( + "uv.lock", + 'dev = [\n { name = "apm-cli" },\n]', + 'dev = [\n { name = "apm-cli" },\n { name = "six" },\n]', + ) + self.write( + "uv.lock", + (self.repo / "uv.lock").read_text() + + '\n[[package]]\nname = "six"\nversion = "1.17.0"\n' + 'source = { registry = "https://pypi.org/simple" }\n' + + uv_files("six", "1.17.0", H2), + ) + self.assert_lock_refused() + + def test_a_marker_that_drops_a_dependency_is_refused(self): + self.bump_apm_cli() + self.edit( + "uv.lock", + ' { name = "watchdog" },', + ' { name = "watchdog", marker = "sys_platform == \'never\'" },', + ) + self.assert_lock_refused() + + def test_a_downgraded_transitive_package_is_refused(self): + self.bump_apm_cli() + self.edit("uv.lock", 'version = "8.5.1"', 'version = "8.5.0"') + self.edit("uv.lock", "click-8.5.1", "click-8.5.0") + self.edit("uv.lock", CLICK_OLD, H2) + self.assert_lock_refused() + + def test_a_pyproject_change_without_its_lock_is_refused(self): + self.edit("pyproject.toml", "apm-cli==0.39.3", "apm-cli==0.39.4") + self.commit("bot") + code, _unused, err = self.gate() + self.assertEqual(code, 1, err) + self.assertIn("pyproject.toml", err) + + def test_an_apm_cli_lock_change_without_pyproject_is_refused(self): + self.bump_apm_cli() + self.edit("pyproject.toml", "apm-cli==0.39.4", "apm-cli==0.39.3") + self.assert_lock_refused() + + def test_a_changed_apm_cli_source_is_refused(self): + self.bump_apm_cli() + lock = (self.repo / "uv.lock").read_text() + start = lock.index('name = "apm-cli"') + self.write( + "uv.lock", + lock[:start] + + lock[start:].replace( + "https://pypi.org/simple", "https://evil.example/simple", 1 + ), + ) + self.assert_lock_refused() + + def test_a_changed_apm_cli_download_host_is_refused(self): + self.bump_apm_cli() + self.edit( + "uv.lock", + "https://files.pythonhosted.org/packages/ab/cd/apm_cli-0.39.4-py3", + "https://files.evil.example/packages/ab/cd/apm_cli-0.39.4-py3", + ) + self.assert_lock_refused() + def test_each_violation_gets_one_line(self): self.edit(".gitea/workflows/lint.yml", "echo a", "echo b") self.write("roles/x/main.yml", "a\n") diff --git a/tests/scripts/test_check_uv_lock.py b/tests/scripts/test_check_uv_lock.py new file mode 100644 index 0000000..4351615 --- /dev/null +++ b/tests/scripts/test_check_uv_lock.py @@ -0,0 +1,321 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Run with: python3 -m unittest discover -s tests/scripts""" + +import pathlib +import sys +import unittest + +SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" +sys.path.insert(0, str(SCRIPTS)) +import check_uv_lock as cul + +APM_OLD, APM_NEW, CLICK_OLD, OTHER = "c" * 64, "d" * 64, "e" * 64, "f" * 64 +PYPI_FILES = "https://files.pythonhosted.org/packages/ab/cd/" + + +def uv_files(dist, version, digest): + return ( + f'sdist = {{ url = "{PYPI_FILES}{dist}-{version}.tar.gz", hash = "sha256:{digest}", ' + f'size = 3132901, upload-time = "2026-12-01T18:11:22.037Z" }}\n' + f'wheels = [\n {{ url = "{PYPI_FILES}{dist}-{version}-py3-none-any.whl", ' + f'hash = "sha256:{digest}", size = 3536708, upload-time = "2026-12-01T18:11:19.761Z" }},\n]\n' + ) + + +# A uv.lock as uv 0.13.1 writes it: apm-cli, two of its dependencies and the root project. +UV_LOCK = ( + 'version = 1\nrevision = 5\nrequires-python = ">=3.11"\n\n' + '[[package]]\nname = "apm-cli"\nversion = "0.39.3"\n' + 'source = { registry = "https://pypi.org/simple" }\n' + 'dependencies = [\n { name = "click" },\n { name = "watchdog" },\n]\n' + + uv_files("apm_cli", "0.39.3", APM_OLD) + + '\n[[package]]\nname = "click"\nversion = "8.5.1"\n' + 'source = { registry = "https://pypi.org/simple" }\n' + + uv_files("click", "8.5.1", CLICK_OLD) + + '\n[[package]]\nname = "kamino"\nversion = "0"\nsource = { virtual = "." }\n\n' + '[package.dev-dependencies]\ndev = [\n { name = "apm-cli" },\n]\n\n' + "[package.metadata]\n\n[package.metadata.requires-dev]\n" + 'dev = [{ name = "apm-cli", specifier = "==0.39.3" }]\n' + '\n[[package]]\nname = "watchdog"\nversion = "7.1.1"\n' + 'source = { registry = "https://pypi.org/simple" }\n' + + uv_files("watchdog", "7.1.1", OTHER) +) +PYPROJECT = ( + '[project]\nname = "kamino"\n\n[dependency-groups]\ndev = ["apm-cli==VERSION"]\n' +) + + +def bumped(lock=UV_LOCK): + """The lock after Renovate's apm-cli 0.39.4 bump.""" + return ( + lock.replace('version = "0.39.3"', 'version = "0.39.4"') + .replace('"==0.39.3"', '"==0.39.4"') + .replace("apm_cli-0.39.3", "apm_cli-0.39.4") + .replace(APM_OLD, APM_NEW) + ) + + +def problem(new, pin="0.39.4", old=UV_LOCK): + return cul.lock_problem(old, new, PYPROJECT.replace("VERSION", pin)) + + +class AllowedTest(unittest.TestCase): + def test_an_apm_cli_bump_is_allowed(self): + self.assertIsNone(problem(bumped())) + + def test_a_new_lock_revision_is_allowed(self): + old = UV_LOCK.replace("revision = 5", "revision = 3") + self.assertIsNone(problem(bumped(), old=old)) + + def test_a_package_without_an_sdist_is_allowed(self): + start = UV_LOCK.index("sdist = { url") + old = UV_LOCK[:start] + UV_LOCK[UV_LOCK.index("wheels = [", start) :] + self.assertIsNone(problem(bumped(old), old=old)) + + +class RefusedTest(unittest.TestCase): + def assert_refused(self, new, **kwargs): + self.assertIsNotNone(problem(new, **kwargs)) + + def test_a_lock_that_is_not_toml_is_refused(self): + self.assert_refused(bumped() + "[[package\n") + + def test_a_lock_of_another_shape_is_refused(self): + top = 'version = 1\nrevision = 5\nrequires-python = ">=3.11"\n' + for package in ('package = ["x"]\n', "package = 1\n"): + with self.subTest(package=package): + self.assertEqual( + problem(top + package), "the lock does not have the shape uv writes" + ) + + def test_the_lock_version_must_be_the_pin(self): + self.assert_refused(bumped(), pin="0.39.5") + self.assert_refused( + bumped().replace('version = "0.39.4"', 'version = "0.39.5"') + ) + + def test_the_dev_specifier_must_be_the_pin(self): + self.assert_refused(bumped().replace('"==0.39.4"', '"==0.39.3"')) + self.assert_refused(bumped().replace('"==0.39.4"', '">=0.39.4"')) + + def test_a_pyproject_without_one_apm_cli_pin_is_refused(self): + for pyproject in ( + '[dependency-groups]\ndev = ["apm-cli>=0.39.4"]\n', + '[dependency-groups]\ndev = ["apm-cli==0.39.4", "apm-cli==0.39.5"]\n', + "[dependency-groups]\ndev = [\n", + ): + with self.subTest(pyproject=pyproject): + self.assertIsNotNone(cul.lock_problem(UV_LOCK, bumped(), pyproject)) + + def test_another_top_level_setting_is_refused(self): + for old, new in ( + ('requires-python = ">=3.11"', 'requires-python = ">=3.12"'), + ("version = 1\n", "version = 2\n"), + ("revision = 5", 'revision = "5"'), + ( + "revision = 5", + 'revision = 5\n[options]\nexclude-newer = "2026-01-01T00:00:00Z"', + ), + ): + with self.subTest(new=new): + self.assert_refused(bumped().replace(old, new, 1)) + + def test_an_apm_cli_dependency_change_is_refused(self): + for new in ( + ' { name = "click" },\n { name = "watchdog" },\n { name = "six" },\n', + ' { name = "click" },\n', + ' { name = "click", marker = "sys_platform == \'never\'" },\n { name = "watchdog" },\n', + ' { name = "click", extra = ["evil"] },\n { name = "watchdog" },\n', + ): + with self.subTest(new=new): + self.assert_refused( + bumped().replace( + ' { name = "click" },\n { name = "watchdog" },\n', new, 1 + ) + ) + + def test_a_changed_apm_cli_source_is_refused(self): + lock = bumped() + start = lock.index('name = "apm-cli"') + for source in ( + 'source = { registry = "https://evil.example/simple" }', + 'source = { git = "https://evil.example/apm.git?rev=main#0123abc" }', + 'source = { url = "https://evil.example/apm_cli-0.39.4.tar.gz" }', + ): + with self.subTest(source=source): + self.assert_refused( + lock[:start] + + lock[start:].replace( + 'source = { registry = "https://pypi.org/simple" }', source, 1 + ) + ) + + def test_a_file_that_is_not_the_pinned_apm_cli_from_pypi_is_refused(self): + wheel = f"{PYPI_FILES}apm_cli-0.39.4-py3-none-any.whl" + for old, new in ( + (wheel, wheel.replace("files.pythonhosted.org", "files.evil.example")), + (wheel, wheel.replace("https://", "http://")), + ( + wheel, + wheel.replace( + "files.pythonhosted.org", "files.pythonhosted.org.evil.example" + ), + ), + (wheel, wheel.replace("/packages/", "/other/")), + (wheel, wheel + "?x=/packages/apm_cli-0.39.4-py3-none-any.whl"), + (wheel, wheel.replace("apm_cli-0.39.4", "six-1.17.0")), + (wheel, wheel.replace("apm_cli-0.39.4", "apm_cli-0.39.3")), + (wheel, wheel.replace("apm_cli-0.39.4", "apm_cli-0.39.40")), + (wheel, wheel.replace(".whl", ".exe")), + (f"sha256:{APM_NEW}", "md5:" + "d" * 32), + (f"sha256:{APM_NEW}", "sha256:" + "d" * 63), + (f"sha256:{APM_NEW}", "sha256:" + "D" * 64), + ): + with self.subTest(new=new): + self.assert_refused(bumped().replace(old, new)) + + def test_a_file_with_another_key_is_refused(self): + wheel = f'{{ url = "{PYPI_FILES}apm_cli-0.39.4-py3-none-any.whl", ' + self.assert_refused( + bumped().replace(wheel, wheel + 'path = "../evil.whl", ', 1) + ) + + def test_an_apm_cli_without_files_is_refused(self): + lock = bumped() + start = lock.index("sdist = { url", lock.index('name = "apm-cli"')) + end = lock.index("]\n", start) + 2 + self.assert_refused(lock[:start] + lock[end:]) + + def test_a_change_to_another_package_is_refused(self): + for old, new in ( + ('version = "8.5.1"', 'version = "8.5.0"'), + (CLICK_OLD, OTHER), + ( + 'name = "watchdog"\n', + 'name = "watchdog"\ndependencies = [{ name = "click" }]\n', + ), + ( + 'version = "0"\nsource = { virtual = "." }', + 'version = "1"\nsource = { virtual = "." }', + ), + ( + 'dev = [\n { name = "apm-cli" },\n]', + 'dev = [\n { name = "apm-cli" },\n { name = "click" },\n]', + ), + ): + with self.subTest(new=new): + self.assert_refused(bumped().replace(old, new, 1)) + + def test_an_added_or_removed_package_is_refused(self): + six = ( + '\n[[package]]\nname = "six"\nversion = "1.17.0"\n' + 'source = { registry = "https://pypi.org/simple" }\n' + + uv_files("six", "1.17.0", OTHER) + ) + self.assert_refused(bumped() + six) + watchdog = bumped().index('\n[[package]]\nname = "watchdog"') + self.assert_refused(bumped()[:watchdog]) + + def test_a_second_apm_cli_or_root_entry_is_refused(self): + apm = bumped() + start = apm.index('[[package]]\nname = "apm-cli"') + end = apm.index("[[package]]", start + 1) + self.assert_refused(apm + "\n" + apm[start:end]) + root = apm.index('[[package]]\nname = "kamino"') + self.assert_refused( + apm + + '\n[[package]]\nname = "other"\nversion = "0"\nsource = { virtual = "." }\n', + old=UV_LOCK + + '\n[[package]]\nname = "other"\nversion = "0"\nsource = { virtual = "." }\n', + ) + self.assertGreater(root, 0) + + +def moved(lock, old, new): + """lock with apm-cli moved from version old to new.""" + return ( + lock.replace(f'version = "{old}"', f'version = "{new}"') + .replace(f'"=={old}"', f'"=={new}"') + .replace(f"apm_cli-{old}", f"apm_cli-{new}") + ) + + +def without_apm_wheels(lock): + start = lock.index("wheels = [", lock.index('name = "apm-cli"')) + return lock[:start] + lock[lock.index("]\n", start) + 2 :] + + +class FileKindsAndOrderTest(unittest.TestCase): + def test_dropped_wheels_without_a_version_change_are_refused(self): + new = without_apm_wheels(UV_LOCK).replace("size = 3132901", "size = 3132902", 1) + self.assertIsNotNone(problem(new, pin="0.39.3")) + + def test_a_downgrade_is_refused(self): + self.assertIsNotNone(problem(UV_LOCK, pin="0.39.3", old=bumped())) + + def test_the_version_must_rise(self): + self.assertIsNotNone(problem(UV_LOCK.replace(APM_OLD, APM_NEW), pin="0.39.3")) + + def test_versions_are_compared_as_numbers(self): + old = moved(UV_LOCK, "0.39.3", "0.39.9") + self.assertIsNone( + problem(moved(old, "0.39.9", "0.39.10"), pin="0.39.10", old=old) + ) + old = moved(UV_LOCK, "0.39.3", "0.9.0") + self.assertIsNone(problem(moved(old, "0.9.0", "0.10.0"), pin="0.10.0", old=old)) + old = moved(UV_LOCK, "0.39.3", "0.40.0") + self.assertIsNotNone( + problem(moved(old, "0.40.0", "0.39.10"), pin="0.39.10", old=old) + ) + + def test_a_version_that_is_not_a_plain_release_is_refused(self): + for version in ( + "0.40.0rc1", + "0.40.0.post1", + "0.40.0.dev1", + "1!0.1.0", + "0.40.0+local", + ): + with self.subTest(version=version): + self.assertIsNotNone( + problem(moved(UV_LOCK, "0.39.3", version), pin=version) + ) + + def test_the_kinds_of_file_stay_the_same(self): + self.assertIsNotNone(problem(without_apm_wheels(bumped()))) + start = bumped().index("sdist = { url", bumped().index('name = "apm-cli"')) + no_sdist = bumped()[:start] + bumped()[bumped().index("wheels = [", start) :] + self.assertIsNotNone(problem(no_sdist)) + old_no_sdist = ( + UV_LOCK[: UV_LOCK.index("sdist = { url")] + + UV_LOCK[UV_LOCK.index("wheels = [") :] + ) + self.assertIsNotNone(problem(bumped(), old=old_no_sdist)) + self.assertIsNone(problem(no_sdist, old=old_no_sdist)) + for tag in ("cp311-cp311-manylinux_2_17_x86_64", "py2.py3-none-any"): + with self.subTest(tag=tag): + self.assertIsNotNone( + problem(bumped().replace("0.39.4-py3-none-any", f"0.39.4-{tag}")) + ) + + def test_a_path_that_leaves_packages_is_refused(self): + wheel = f"{PYPI_FILES}apm_cli-0.39.4-py3-none-any.whl" + for path in ( + "/packages/../../simple/x/", + "/packages/ab/./cd/", + "/packages//ab/", + "/packages/%2e%2e/%2e%2e/simple/x/", + "/packages/ab/cd%2F/", + ): + with self.subTest(path=path): + bad = ( + "https://files.pythonhosted.org" + + path + + "apm_cli-0.39.4-py3-none-any.whl" + ) + self.assertIsNotNone(problem(bumped().replace(wheel, bad))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/scripts/test_select_molecule_scenarios.py b/tests/scripts/test_select_molecule_scenarios.py index 2ac424c..e49ac30 100644 --- a/tests/scripts/test_select_molecule_scenarios.py +++ b/tests/scripts/test_select_molecule_scenarios.py @@ -221,6 +221,12 @@ class SelectTest(unittest.TestCase): chosen, _reason = self.select(["pyproject.toml", "uv.lock"]) self.assertEqual(chosen, []) + def test_the_bot_diff_check_selects_nothing(self): + chosen, _reason = self.select( + ["scripts/check_bot_pr_diff.py", "scripts/check_uv_lock.py"] + ) + self.assertEqual(chosen, []) + def test_molecule_requirements_select_everything(self): # An ansible-core or molecule bump there changes the tools every scenario runs with. for path in ("requirements-molecule.txt", "requirements-molecule.lock"): -- 2.43.0 From 1e95d8cbdd0fe9cb0d9e874c5de8fc0d47e89e0f Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 6 Dec 2026 07:21:56 +0000 Subject: [PATCH 2/3] chore(uv): rewrite uv.lock as the Renovate image's uv writes it uv 0.13.1, the version in the pinned Renovate image, writes lock revision 5 and drops two markers on httpcore2's dependencies that uv 0.11 kept. The bot-diff check refuses a change to any package but apm-cli, so the lock is rewritten once here, with `uv lock --upgrade-package apm-cli` at the unchanged pin. No package, version, source, file or hash changes, and uv 0.11.24 reads the lock and leaves it as it is. Refs: #518 Assisted-by: Claude Code --- uv.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/uv.lock b/uv.lock index 1d6b725..3701cba 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.12' and sys_platform == 'emscripten'", @@ -622,8 +622,8 @@ name = "httpcore2" version = "2.18.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, - { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, + { name = "h11" }, + { name = "truststore" }, ] sdist = { url = "https://files.pythonhosted.org/packages/05/38/48d4836fd8711f0ab56f33a4018dcd1a3bea4ba783780c8750f4c2ecbd62/httpcore2-2.18.0.tar.gz", hash = "sha256:b1214ec379c7f96d8c7c587fb4d7fe13489c399899705c2f2d99a1a1051d3e18", size = 72522, upload-time = "2026-12-04T11:08:49.627Z" } wheels = [ -- 2.43.0 From 2b0326801f3c2fd2c07a8525e24788134d5fec59 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 6 Dec 2026 07:22:02 +0000 Subject: [PATCH 3/3] chore(renovate): update the apm pin in pyproject.toml and uv.lock Enable the pep621 manager for the root pyproject.toml, which updates uv.lock with it. apm-cli gets its own pull request without automerge: CI never runs apm, so a green run says nothing about a new version. The manager also reads requires-python, a floor for ruff rather than a pin, so it is disabled, and lock file maintenance is off for uv.lock, whose check refuses a change to any package but apm-cli. Closes: #518 Assisted-by: Claude Code --- renovate.json | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/renovate.json b/renovate.json index 74ba441..e5a5df4 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,6 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit. Updates open on Mondays (UTC), so any Monday run can act; the own image pins and vulnerability fixes found on osv.dev open at any time. The weekly window and the groups bound the volume, so there is no hourly pull request limit. Vulnerability fixes skip the release-age wait, so they are never automerged: a person checks a fix that had no time to be pulled as a compromised release. Base-image bumps are manual: every Dockerfile is FROM ubuntu, grouped with the job containers.", + "description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines, and in uv.lock only the apm-cli bump to the pin in pyproject.toml (scripts/check_uv_lock.py). Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit. Updates open on Mondays (UTC), so any Monday run can act; the own image pins and vulnerability fixes found on osv.dev open at any time. The weekly window and the groups bound the volume, so there is no hourly pull request limit. Vulnerability fixes skip the release-age wait, so they are never automerged: a person checks a fix that had no time to be pulled as a compromised release. Base-image bumps are manual: every Dockerfile is FROM ubuntu, grouped with the job containers.", "extends": [ "config:recommended", ":enablePreCommit" @@ -11,6 +11,7 @@ "semanticCommitScope": "deps", "enabledManagers": [ "pip-compile", + "pep621", "ansible-galaxy", "pre-commit", "github-actions", @@ -35,6 +36,11 @@ "/^requirements-molecule\\.lock$/" ] }, + "pep621": { + "managerFilePatterns": [ + "/^pyproject\\.toml$/" + ] + }, "pre-commit": { "enabled": true, "managerFilePatterns": [ @@ -210,6 +216,36 @@ "pre-commit" ], "groupName": "pre-commit hooks" + }, + { + "description": "requires-python in pyproject.toml is the floor ruff formats for, not a pin: never updated by the bot.", + "matchManagers": [ + "pep621" + ], + "matchDepTypes": [ + "requires-python" + ], + "enabled": false + }, + { + "description": "No lock file maintenance for uv.lock: scripts/check_uv_lock.py refuses any change to a package other than apm-cli, so a person refreshes uv.lock by hand.", + "matchManagers": [ + "pep621" + ], + "matchUpdateTypes": [ + "lockFileMaintenance" + ], + "enabled": false + }, + { + "description": "apm-cli (pyproject.toml and uv.lock) gets its own pull request, never automerged: CI never runs apm, so a green run says nothing about a new version. Placed last so no rule above turns automerge back on.", + "matchManagers": [ + "pep621" + ], + "matchPackageNames": [ + "apm-cli" + ], + "automerge": false } ], "lockFileMaintenance": { -- 2.43.0