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
This commit is contained in:
Defame1297 committed 2026-12-06 07:21:44 +00:00
1 parent 535926b36e
commit 47641ae01d
7 files changed
+754 -10

No files matched your search

+52 -6
View File
@@ -12,6 +12,10 @@ When <head-ref> starts with `renovate/`, the diff of <base-ref>...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: <tag>` 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):
+198
View File
@@ -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"
+1
View File
@@ -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",