# 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"