diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml index a37a99c..38c99dc 100644 --- a/.template_sync/manifest.yaml +++ b/.template_sync/manifest.yaml @@ -1,4 +1,4 @@ -template_version: 0.1.43 +template_version: 0.1.44 migrations: - from: 0.0.0 to: 0.0.1 @@ -135,3 +135,6 @@ migrations: - from: 0.1.42 to: 0.1.43 script: migrations/v0_1_42_to_v0_1_43.py + - from: 0.1.43 + to: 0.1.44 + script: migrations/v0_1_43_to_v0_1_44.py diff --git a/.template_sync/migrations/v0_1_43_to_v0_1_44.py b/.template_sync/migrations/v0_1_43_to_v0_1_44.py new file mode 100644 index 0000000..3e365eb --- /dev/null +++ b/.template_sync/migrations/v0_1_43_to_v0_1_44.py @@ -0,0 +1,91 @@ +"""Template 0.1.43 -> 0.1.44: a lock file keeps the git references the requirements write (tags), so pip can install apps that depend on +MorphoBricks bricks. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_44.md + +lock_requirements.py wrote uv's resolution, in which `name @ git+URL@v1.2.0` becomes `name @ git+URL@`. pip compares git URLs as +text: when another git package requires the same package with the tag (morphobricks-preprocessing requires morphobricks-normalization +`@v0.10.0`), pip refused the lock file (ResolutionImpossible), the conda check of the workflow "Updates on notebook change" failed and the +app's commit was reverted. Now a git package the requirements name directly keeps the reference as written, with the resolved commit as a +comment. LOCK_FORMAT 3 writes every lock file again at the next run of the requirements workflow. + +What this changes in an app repository: lock_requirements.py is replaced by the 0.1.44 file when it is still the template file last shipped +(the 0.1.43 copy; compared with LF line endings; the file keeps its own line endings). A file the app changed itself stays as it is +(SKIPPED, with a note of what to change by hand). A missing file is not created, and nothing is deleted. The lock files change the next +time the requirements workflow runs (a notebook change, or Actions > Updates on notebook change > Run workflow). +""" +from __future__ import annotations + +from pathlib import Path +from typing import Any + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_44.md" +TAG = "[migration 0.1.44]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_43_to_v0_1_44" +PREVIOUS_ROOT = RESOURCE_ROOT / "previous" + +LOCK = Path(".tools/python/lock_requirements.py") +FILES = (LOCK,) + +BY_HAND = { + LOCK: ( + "after uv's resolution, write each git package that the requirements file names directly with the URL it writes (the tag), as " + "keep_requested_git_references of the template's script does, and set LOCK_FORMAT to \"3\"" + ), +} + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def lf_text(path: Path) -> str: + return path.read_bytes().decode("utf-8").replace("\r\n", "\n") + + +def replaced_file(relative: Path, text_lf: str) -> tuple[str, str]: + """The 0.1.44 text of `relative` for the app's `text_lf`, and what was done. Unchanged when it is not the 0.1.43 template file.""" + new = lf_text(RESOURCE_ROOT / relative) + if text_lf == new: + return text_lf, "already up to date" + if text_lf == lf_text(PREVIOUS_ROOT / relative): + return new, "replaced by the 0.1.44 file" + return text_lf, ( + "SKIPPED: customised (not the 0.1.43 template file), so it was left unchanged; compare it with the template's file. " + f"By hand: {BY_HAND[relative]}. See {DOCS_URL}" + ) + + +def update(path: Path, relative: Path) -> str: + data = path.read_bytes().decode("utf-8") + newline = "\r\n" if "\r\n" in data else "\n" + original = data.replace("\r\n", "\n") + text, note = replaced_file(relative, original) + if text == original: + return note if note.startswith("SKIPPED") else f"unchanged: {note}" + path.write_bytes(text.replace("\n", newline).encode("utf-8")) + return f"updated: {note}" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Apply the 0.1.44 change (idempotent, never raises for a customised file, creates and deletes nothing).""" + _ = context + changed = 0 + for relative in FILES: + path = repo_root / relative + if not path.is_file(): + log(f"{relative}: not present in this repository (nothing was created)") + continue + try: + status = update(path, relative) + except (OSError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + changed += status.startswith("updated") + log(f"{relative}: {status}") + if changed: + log( + f"done: {changed} file(s) changed. The lock files change at the next run of the workflow " + "Updates on notebook change (a notebook change, or run it by hand); the changes reach users with the app's next release." + ) + else: + log("done: no repository changes were required.") diff --git a/.template_sync/resources/v0_1_43_to_v0_1_44/.tools/python/lock_requirements.py b/.template_sync/resources/v0_1_43_to_v0_1_44/.tools/python/lock_requirements.py new file mode 100644 index 0000000..99c2881 --- /dev/null +++ b/.template_sync/resources/v0_1_43_to_v0_1_44/.tools/python/lock_requirements.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""Lock the merged requirements files: requirements*.txt -> requirements*.lock.txt. + +merge_requirements.py writes the requirements of the notebooks (requirements.txt, requirements_gpu.txt and the per-OS +requirements-.txt). Those files name the packages the notebooks need, but not the packages these depend on, so two +installations of the same release could get different versions. This script writes, next to each file, a lock file that lists +every package pip installs, each with its exact version, and post_install installs the lock file when the installer bundles one. + +How a lock file is made: +* `uv pip compile --universal`: one lock file that is valid on Windows, macOS and Linux (a package that only one platform needs carries + an environment marker, e.g. `colorama==0.4.6 ; sys_platform == 'win32'`). +* `--python-version` is the Python of environment.yaml. uv reads it as the lowest Python of the resolution, so a few packages can appear + twice with a `python_full_version` marker: pip installs the line that matches the Python of the installer. +* The conda packages of environment.yaml (jupyterlab, pip, setuptools, certifi, ...) are installed by the installer itself, so they are + not written to the lock file (their own dependencies are), and a conda pin such as `jupyterlab=4.4.0` constrains the resolution. +* The per-OS files are resolved with requirements.lock.txt as constraints, so a package that both files need gets the same version. +* Pip options of the requirements file (`--extra-index-url` of the GPU file, ...) are copied to the top of the lock file. +* A package required from a git URL (`name @ git+https://...@v1.2.0`) keeps the reference exactly as the requirements file writes it, with + the commit uv resolved as a comment. uv writes the commit instead, and pip treats `...@v1.2.0` and `...@` as two different + requirements: when another git package requires the same package with the tag (MorphoBricks bricks depend on each other this way), pip + refuses the lock file (ResolutionImpossible) and the installer cannot install it. + +A lock file is written again only when its requirements file, the Python or JupyterLab version (or this script's lock format) changed: +its header holds a fingerprint of those inputs. Re-running the script without such a change rewrites nothing, so a new release +installs the same versions as the previous one. To move every package to its newest version, delete the lock files and run the +workflow "Updates on notebook change" by hand (Actions > Run workflow). + +If a file cannot be locked (uv is missing, or the requirements cannot be resolved), the script prints a warning, removes the +out-of-date lock file of that file (an installer must never install versions that no longer match the requirements) and goes on: +the installer then installs the plain requirements file. The script itself always exits 0 for such a failure. +""" +from __future__ import annotations + +import argparse +import hashlib +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +import yaml + +# Bump when the uv arguments or the output change, so that every lock file is written again. +LOCK_FORMAT = "3" +BASE_INPUT = "requirements.txt" +GPU_INPUT = "requirements_gpu.txt" +OS_INPUTS = ("requirements-linux.txt", "requirements-windows.txt", "requirements-macos.txt") +INPUTS = (BASE_INPUT, GPU_INPUT, *OS_INPUTS) +FINGERPRINT_PREFIX = "# lock-input: sha256:" +# Pip options that choose where packages come from: copied to the top of the lock file, so pip finds the locked versions where uv found them. +INDEX_OPTION = re.compile(r"^\s*(--index-url|--extra-index-url|-i|--find-links|-f|--trusted-host)(\s|=)") +CONDA_SPEC = re.compile(r"^\s*([A-Za-z0-9_.-]+)\s*(?:(==?)\s*([0-9][A-Za-z0-9_.+!*-]*))?(?:=\S+)?\s*$") +PLACEHOLDER = re.compile(r"^[A-Z_]+$") +# `name[extras] @ git+URL`, the URL up to the first space or `;` (environment marker). +GIT_REQUIREMENT = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?\s*@\s*(git\+[^\s;#]+)") + + +def lock_path(requirements: Path) -> Path: + """requirements.txt -> requirements.lock.txt (same folder).""" + return requirements.with_name(requirements.stem + ".lock.txt") + + +def read_environment(path: Path) -> tuple[str | None, list[str], list[str]]: + """(Python version, conda package names, pip constraints from exact conda pins) of environment.yaml.""" + if not path.is_file(): + return None, [], [] + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + python_version = None + names: list[str] = [] + constraints: list[str] = [] + for dependency in data.get("dependencies", []) or []: + if not isinstance(dependency, str): + continue # the `pip:` subsection of an environment file + match = CONDA_SPEC.match(dependency) + if match: + name, operator, version = match.group(1), match.group(2), match.group(3) + else: + # a spec with a range or alternatives (`pip>=24.2`): only its name is used + name, operator, version = re.split(r"[\s<>=!|,\[]", dependency.strip(), maxsplit=1)[0], None, None + if not name: + continue + if version and PLACEHOLDER.match(version): + version = None # the template itself (python=PYTHON_VERSION) + if name.lower() == "python": + python_version = version + continue + names.append(name) + if version: + # conda `name=1.2` means any 1.2.* release, `name==1.2` exactly 1.2 + constraints.append(f"{name}=={version}" if operator == "==" else f"{name}=={version.removesuffix('.*')}.*") + return python_version, sorted(set(names), key=str.lower), constraints + + +def normalized_requirements(text: str) -> str: + """The requirement and option lines of a requirements file (comments, such as the timestamp of merge_requirements.py, are ignored).""" + lines = [] + for line in text.replace("\r\n", "\n").split("\n"): + stripped = line.strip() + if stripped and not stripped.startswith("#"): + lines.append(stripped) + return "\n".join(lines) + + +def fingerprint(requirements_text: str, python_version: str, constraints: list[str], no_emit: list[str], extra_constraints: str) -> str: + payload = "\n---\n".join( + [LOCK_FORMAT, normalized_requirements(requirements_text), python_version, "\n".join(constraints), "\n".join(no_emit), extra_constraints] + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def current_fingerprint(lock: Path) -> str | None: + if not lock.is_file(): + return None + for line in lock.read_text(encoding="utf-8").splitlines(): + if line.startswith(FINGERPRINT_PREFIX): + return line[len(FINGERPRINT_PREFIX):].strip() + return None + + +def run_uv(requirements: Path, python_version: str, constraint_files: list[Path], no_emit: list[str]) -> str: + """The resolution of `requirements` (stdout of uv pip compile); raises RuntimeError with uv's message when it fails.""" + command = [ + sys.executable, "-m", "uv", "pip", "compile", str(requirements), + "--universal", "--python-version", python_version, + "--no-header", "--no-annotate", "--no-config", "--quiet", + # With an extra index (the PyTorch CPU or CUDA index), take each package at the best version of all indexes. uv's default + # takes a package from the first index that has it, so packages that the PyTorch index also hosts (torchmetrics, numpy, idna, + # ...) were locked at its older copies, and a pin of a newer version made the lock fail. + "--index-strategy", "unsafe-best-match", + ] + for constraint in constraint_files: + command += ["--constraint", str(constraint)] + for name in no_emit: + command += ["--no-emit-package", name] + try: + result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", check=False) + except OSError as exc: + raise RuntimeError(f"uv could not be started: {exc}") from exc + if result.returncode != 0: + message = (result.stderr or result.stdout).strip() or f"exit code {result.returncode}" + raise RuntimeError(message) + return result.stdout + + +def uv_version() -> str: + try: + result = subprocess.run([sys.executable, "-m", "uv", "--version"], capture_output=True, text=True, check=False) + except OSError: + return "uv" + # "uv 0.13.3 (502f93ca6 2026-10-19 x86_64-pc-windows-msvc)" -> "uv 0.13.3": the build details differ between computers + return " ".join(result.stdout.split()[:2]) or "uv" + + +def canonical_name(name: str) -> str: + """The package name as pip compares it (PEP 503): lower case, runs of `-`, `_` and `.` as one `-`.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def keep_requested_git_references(requirements_text: str, packages: list[str]) -> list[str]: + """`packages` (uv's lines) with each git package the requirements name directly written with the requested reference. + + uv resolves `name @ git+URL@v1.2.0` to `name @ git+URL@`. pip compares the two URLs as text, so a lock line with the commit + conflicts with another git package that requires `name` with the tag. The lock line keeps the requested URL; the resolved commit + follows as a comment. A git package the requirements do not name directly (a dependency of a dependency) keeps uv's line. + """ + requested: dict[str, str] = {} + for line in requirements_text.replace("\r\n", "\n").split("\n"): + match = GIT_REQUIREMENT.match(line) + if match: + requested[canonical_name(match.group(1))] = match.group(3) + kept = [] + for line in packages: + match = GIT_REQUIREMENT.match(line) + url = requested.get(canonical_name(match.group(1))) if match else None + if match and url and url != match.group(3): + start, end = match.span(3) + line = f"{line[:start]}{url}{line[end:]} # resolved: {match.group(3)}" + kept.append(line) + return kept + + +def render_lock(requirements: Path, resolved: str, digest: str, python_version: str, uv: str) -> str: + text = requirements.read_text(encoding="utf-8") + options = [line.strip() for line in text.splitlines() if INDEX_OPTION.match(line)] + packages = [line.rstrip() for line in resolved.replace("\r\n", "\n").split("\n") if line.strip() and not line.lstrip().startswith("#")] + packages = keep_requested_git_references(text, packages) + header = [ + f"# Lock file of {requirements.name}: every package the installer installs with pip, with its exact version.", + f"# Written by .tools/python/lock_requirements.py ({uv}, universal resolution for Python {python_version}); do not edit it by hand.", + f"# It is written again only when {requirements.name}, the Python or JupyterLab version changes (see the fingerprint below).", + f"{FINGERPRINT_PREFIX}{digest}", + ] + body = options + ([""] if options else []) + packages + return "\n".join(header + [""] + body) + "\n" + + +def warn(message: str) -> None: + # `::warning::` shows the message on the summary page of the GitHub Actions run. + print(f"::warning::{message}", flush=True) + + +def lock_file( + requirements: Path, + python_version: str, + constraints: list[str], + no_emit: list[str], + base_lock: Path | None, + work_dir: Path, + uv: str, +) -> str: + """Lock one requirements file; returns what happened ("unchanged", "written", "failed").""" + lock = lock_path(requirements) + extra = base_lock.read_text(encoding="utf-8") if base_lock is not None and base_lock.is_file() else "" + digest = fingerprint(requirements.read_text(encoding="utf-8"), python_version, constraints, no_emit, normalized_requirements(extra)) + if current_fingerprint(lock) == digest: + print(f"{lock}: up to date (unchanged)") + return "unchanged" + constraint_files = [] + if constraints: + conda_constraints = work_dir / "conda_constraints.txt" + conda_constraints.write_text("\n".join(constraints) + "\n", encoding="utf-8") + constraint_files.append(conda_constraints) + if extra: + # Only the package lines: the pip options of the base lock are not constraints. + base_constraints = work_dir / "base_constraints.txt" + base_constraints.write_text( + "\n".join(line for line in extra.splitlines() if line.strip() and not line.startswith(("#", "-"))) + "\n", encoding="utf-8" + ) + constraint_files.append(base_constraints) + try: + resolved = run_uv(requirements, python_version, constraint_files, no_emit) + except RuntimeError as exc: + warn(f"{requirements} could not be locked, so the installer installs it without a lock file: {exc}") + if lock.exists(): + lock.unlink() + print(f"{lock}: removed (it no longer matches {requirements})") + return "failed" + with lock.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(render_lock(requirements, resolved, digest, python_version, uv)) + print(f"{lock}: written") + return "written" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Lock requirements*.txt into requirements*.lock.txt (every package with its exact version).") + parser.add_argument("--root", type=Path, default=Path("."), help="Folder with the requirements files and environment.yaml") + parser.add_argument("--environment", type=Path, default=None, help="Conda environment file (default: /environment.yaml)") + args = parser.parse_args(argv) + root: Path = args.root + environment = args.environment or root / "environment.yaml" + + python_version, conda_names, constraints = read_environment(environment) + if not python_version: + print(f"{environment}: no exact Python version (python=X.Y.Z), so nothing is locked.") + return 0 + no_emit = [name for name in conda_names if name.lower() not in {"git"}] + + # A lock file whose requirements file is gone is removed (the installer must not install it). + for name in INPUTS: + requirements = root / name + if not requirements.is_file() and lock_path(requirements).is_file(): + lock_path(requirements).unlink() + print(f"{lock_path(requirements)}: removed ({requirements} does not exist)") + + present = [root / name for name in INPUTS if (root / name).is_file()] + if not present: + print("No requirements files found: nothing to lock.") + return 0 + uv = uv_version() + results = {} + with tempfile.TemporaryDirectory() as temporary: + work_dir = Path(temporary) + for requirements in present: + base_lock = lock_path(root / BASE_INPUT) if requirements.name in OS_INPUTS else None + results[requirements.name] = lock_file(requirements, python_version, constraints, no_emit, base_lock, work_dir, uv) + failed = [name for name, status in results.items() if status == "failed"] + print(f"Lock files: {len(results) - len(failed)} of {len(results)} requirements files locked" + (f"; not locked: {', '.join(failed)}" if failed else "")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_43_to_v0_1_44/previous/.tools/python/lock_requirements.py b/.template_sync/resources/v0_1_43_to_v0_1_44/previous/.tools/python/lock_requirements.py new file mode 100644 index 0000000..315b054 --- /dev/null +++ b/.template_sync/resources/v0_1_43_to_v0_1_44/previous/.tools/python/lock_requirements.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Lock the merged requirements files: requirements*.txt -> requirements*.lock.txt. + +merge_requirements.py writes the requirements of the notebooks (requirements.txt, requirements_gpu.txt and the per-OS +requirements-.txt). Those files name the packages the notebooks need, but not the packages these depend on, so two +installations of the same release could get different versions. This script writes, next to each file, a lock file that lists +every package pip installs, each with its exact version, and post_install installs the lock file when the installer bundles one. + +How a lock file is made: +* `uv pip compile --universal`: one lock file that is valid on Windows, macOS and Linux (a package that only one platform needs carries + an environment marker, e.g. `colorama==0.4.6 ; sys_platform == 'win32'`). +* `--python-version` is the Python of environment.yaml. uv reads it as the lowest Python of the resolution, so a few packages can appear + twice with a `python_full_version` marker: pip installs the line that matches the Python of the installer. +* The conda packages of environment.yaml (jupyterlab, pip, setuptools, certifi, ...) are installed by the installer itself, so they are + not written to the lock file (their own dependencies are), and a conda pin such as `jupyterlab=4.4.0` constrains the resolution. +* The per-OS files are resolved with requirements.lock.txt as constraints, so a package that both files need gets the same version. +* Pip options of the requirements file (`--extra-index-url` of the GPU file, ...) are copied to the top of the lock file. + +A lock file is written again only when its requirements file, the Python or JupyterLab version (or this script's lock format) changed: +its header holds a fingerprint of those inputs. Re-running the script without such a change rewrites nothing, so a new release +installs the same versions as the previous one. To move every package to its newest version, delete the lock files and run the +workflow "Updates on notebook change" by hand (Actions > Run workflow). + +If a file cannot be locked (uv is missing, or the requirements cannot be resolved), the script prints a warning, removes the +out-of-date lock file of that file (an installer must never install versions that no longer match the requirements) and goes on: +the installer then installs the plain requirements file. The script itself always exits 0 for such a failure. +""" +from __future__ import annotations + +import argparse +import hashlib +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +import yaml + +# Bump when the uv arguments or the output change, so that every lock file is written again. +LOCK_FORMAT = "2" +BASE_INPUT = "requirements.txt" +GPU_INPUT = "requirements_gpu.txt" +OS_INPUTS = ("requirements-linux.txt", "requirements-windows.txt", "requirements-macos.txt") +INPUTS = (BASE_INPUT, GPU_INPUT, *OS_INPUTS) +FINGERPRINT_PREFIX = "# lock-input: sha256:" +# Pip options that choose where packages come from: copied to the top of the lock file, so pip finds the locked versions where uv found them. +INDEX_OPTION = re.compile(r"^\s*(--index-url|--extra-index-url|-i|--find-links|-f|--trusted-host)(\s|=)") +CONDA_SPEC = re.compile(r"^\s*([A-Za-z0-9_.-]+)\s*(?:(==?)\s*([0-9][A-Za-z0-9_.+!*-]*))?(?:=\S+)?\s*$") +PLACEHOLDER = re.compile(r"^[A-Z_]+$") + + +def lock_path(requirements: Path) -> Path: + """requirements.txt -> requirements.lock.txt (same folder).""" + return requirements.with_name(requirements.stem + ".lock.txt") + + +def read_environment(path: Path) -> tuple[str | None, list[str], list[str]]: + """(Python version, conda package names, pip constraints from exact conda pins) of environment.yaml.""" + if not path.is_file(): + return None, [], [] + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + python_version = None + names: list[str] = [] + constraints: list[str] = [] + for dependency in data.get("dependencies", []) or []: + if not isinstance(dependency, str): + continue # the `pip:` subsection of an environment file + match = CONDA_SPEC.match(dependency) + if match: + name, operator, version = match.group(1), match.group(2), match.group(3) + else: + # a spec with a range or alternatives (`pip>=24.2`): only its name is used + name, operator, version = re.split(r"[\s<>=!|,\[]", dependency.strip(), maxsplit=1)[0], None, None + if not name: + continue + if version and PLACEHOLDER.match(version): + version = None # the template itself (python=PYTHON_VERSION) + if name.lower() == "python": + python_version = version + continue + names.append(name) + if version: + # conda `name=1.2` means any 1.2.* release, `name==1.2` exactly 1.2 + constraints.append(f"{name}=={version}" if operator == "==" else f"{name}=={version.removesuffix('.*')}.*") + return python_version, sorted(set(names), key=str.lower), constraints + + +def normalized_requirements(text: str) -> str: + """The requirement and option lines of a requirements file (comments, such as the timestamp of merge_requirements.py, are ignored).""" + lines = [] + for line in text.replace("\r\n", "\n").split("\n"): + stripped = line.strip() + if stripped and not stripped.startswith("#"): + lines.append(stripped) + return "\n".join(lines) + + +def fingerprint(requirements_text: str, python_version: str, constraints: list[str], no_emit: list[str], extra_constraints: str) -> str: + payload = "\n---\n".join( + [LOCK_FORMAT, normalized_requirements(requirements_text), python_version, "\n".join(constraints), "\n".join(no_emit), extra_constraints] + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def current_fingerprint(lock: Path) -> str | None: + if not lock.is_file(): + return None + for line in lock.read_text(encoding="utf-8").splitlines(): + if line.startswith(FINGERPRINT_PREFIX): + return line[len(FINGERPRINT_PREFIX):].strip() + return None + + +def run_uv(requirements: Path, python_version: str, constraint_files: list[Path], no_emit: list[str]) -> str: + """The resolution of `requirements` (stdout of uv pip compile); raises RuntimeError with uv's message when it fails.""" + command = [ + sys.executable, "-m", "uv", "pip", "compile", str(requirements), + "--universal", "--python-version", python_version, + "--no-header", "--no-annotate", "--no-config", "--quiet", + # With an extra index (the PyTorch CPU or CUDA index), take each package at the best version of all indexes. uv's default + # takes a package from the first index that has it, so packages that the PyTorch index also hosts (torchmetrics, numpy, idna, + # ...) were locked at its older copies, and a pin of a newer version made the lock fail. + "--index-strategy", "unsafe-best-match", + ] + for constraint in constraint_files: + command += ["--constraint", str(constraint)] + for name in no_emit: + command += ["--no-emit-package", name] + try: + result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", check=False) + except OSError as exc: + raise RuntimeError(f"uv could not be started: {exc}") from exc + if result.returncode != 0: + message = (result.stderr or result.stdout).strip() or f"exit code {result.returncode}" + raise RuntimeError(message) + return result.stdout + + +def uv_version() -> str: + try: + result = subprocess.run([sys.executable, "-m", "uv", "--version"], capture_output=True, text=True, check=False) + except OSError: + return "uv" + # "uv 0.13.3 (502f93ca6 2026-10-19 x86_64-pc-windows-msvc)" -> "uv 0.13.3": the build details differ between computers + return " ".join(result.stdout.split()[:2]) or "uv" + + +def render_lock(requirements: Path, resolved: str, digest: str, python_version: str, uv: str) -> str: + options = [line.strip() for line in requirements.read_text(encoding="utf-8").splitlines() if INDEX_OPTION.match(line)] + packages = [line.rstrip() for line in resolved.replace("\r\n", "\n").split("\n") if line.strip() and not line.lstrip().startswith("#")] + header = [ + f"# Lock file of {requirements.name}: every package the installer installs with pip, with its exact version.", + f"# Written by .tools/python/lock_requirements.py ({uv}, universal resolution for Python {python_version}); do not edit it by hand.", + f"# It is written again only when {requirements.name}, the Python or JupyterLab version changes (see the fingerprint below).", + f"{FINGERPRINT_PREFIX}{digest}", + ] + body = options + ([""] if options else []) + packages + return "\n".join(header + [""] + body) + "\n" + + +def warn(message: str) -> None: + # `::warning::` shows the message on the summary page of the GitHub Actions run. + print(f"::warning::{message}", flush=True) + + +def lock_file( + requirements: Path, + python_version: str, + constraints: list[str], + no_emit: list[str], + base_lock: Path | None, + work_dir: Path, + uv: str, +) -> str: + """Lock one requirements file; returns what happened ("unchanged", "written", "failed").""" + lock = lock_path(requirements) + extra = base_lock.read_text(encoding="utf-8") if base_lock is not None and base_lock.is_file() else "" + digest = fingerprint(requirements.read_text(encoding="utf-8"), python_version, constraints, no_emit, normalized_requirements(extra)) + if current_fingerprint(lock) == digest: + print(f"{lock}: up to date (unchanged)") + return "unchanged" + constraint_files = [] + if constraints: + conda_constraints = work_dir / "conda_constraints.txt" + conda_constraints.write_text("\n".join(constraints) + "\n", encoding="utf-8") + constraint_files.append(conda_constraints) + if extra: + # Only the package lines: the pip options of the base lock are not constraints. + base_constraints = work_dir / "base_constraints.txt" + base_constraints.write_text( + "\n".join(line for line in extra.splitlines() if line.strip() and not line.startswith(("#", "-"))) + "\n", encoding="utf-8" + ) + constraint_files.append(base_constraints) + try: + resolved = run_uv(requirements, python_version, constraint_files, no_emit) + except RuntimeError as exc: + warn(f"{requirements} could not be locked, so the installer installs it without a lock file: {exc}") + if lock.exists(): + lock.unlink() + print(f"{lock}: removed (it no longer matches {requirements})") + return "failed" + with lock.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(render_lock(requirements, resolved, digest, python_version, uv)) + print(f"{lock}: written") + return "written" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Lock requirements*.txt into requirements*.lock.txt (every package with its exact version).") + parser.add_argument("--root", type=Path, default=Path("."), help="Folder with the requirements files and environment.yaml") + parser.add_argument("--environment", type=Path, default=None, help="Conda environment file (default: /environment.yaml)") + args = parser.parse_args(argv) + root: Path = args.root + environment = args.environment or root / "environment.yaml" + + python_version, conda_names, constraints = read_environment(environment) + if not python_version: + print(f"{environment}: no exact Python version (python=X.Y.Z), so nothing is locked.") + return 0 + no_emit = [name for name in conda_names if name.lower() not in {"git"}] + + # A lock file whose requirements file is gone is removed (the installer must not install it). + for name in INPUTS: + requirements = root / name + if not requirements.is_file() and lock_path(requirements).is_file(): + lock_path(requirements).unlink() + print(f"{lock_path(requirements)}: removed ({requirements} does not exist)") + + present = [root / name for name in INPUTS if (root / name).is_file()] + if not present: + print("No requirements files found: nothing to lock.") + return 0 + uv = uv_version() + results = {} + with tempfile.TemporaryDirectory() as temporary: + work_dir = Path(temporary) + for requirements in present: + base_lock = lock_path(root / BASE_INPUT) if requirements.name in OS_INPUTS else None + results[requirements.name] = lock_file(requirements, python_version, constraints, no_emit, base_lock, work_dir, uv) + failed = [name for name, status in results.items() if status == "failed"] + print(f"Lock files: {len(results) - len(failed)} of {len(results)} requirements files locked" + (f"; not locked: {', '.join(failed)}" if failed else "")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.tools/docs/migration_0_1_44.md b/.tools/docs/migration_0_1_44.md new file mode 100644 index 0000000..2799fd8 --- /dev/null +++ b/.tools/docs/migration_0_1_44.md @@ -0,0 +1,52 @@ +# Template 0.1.44: lock files keep the git references the requirements write + +Design note for the 0.1.44 migration (`.template_sync/migrations/v0_1_43_to_v0_1_44.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. The problem + +This was found in LabConstrictor-OpticalFlow3D. The app depends on two MorphoBricks bricks: +- `morphobricks-preprocessing`, from a git tag; +- `morphobricks-normalization`, also from a git tag. + +Preprocessing itself requires normalization with the same tag string: + +``` +morphobricks-normalization @ git+https://github.com/CellMigrationLab/morphobricks-normalization.git@v0.10.0 +morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0 +``` + +`lock_requirements.py` writes uv's resolution, and uv replaces each tag with its commit (`…normalization.git@1bdeb81…`). pip compares git URLs as text. So when it installed the lock file, it saw two requirements for normalization: the lock line with the commit, and preprocessing's with the tag. It refused with `ResolutionImpossible`. The conda check of **Updates on notebook change** then failed, and the workflow reverted the app's commit. + +Any app that depends on two git packages, one of which requires the other by tag, hits this. The MorphoBricks bricks all depend on one another this way. + +## 2. What changes + +- `lock_requirements.py`, after uv's resolution: a git package that the requirements file names directly keeps the URL the file writes (the tag). The commit uv resolved follows as a comment, for example: + + ``` + morphobricks-normalization @ git+https://…/morphobricks-normalization.git@v0.10.0 # resolved: git+https://…@1bdeb81… + ``` + + pip then finds one requirement per package and installs the same commit uv resolved. +- A git package that is only a dependency of a dependency keeps uv's line. List it in the notebook's `requirements.yaml` with the same string as the package that requires it. +- `LOCK_FORMAT` is now 3, so every lock file is written again at the next run of the requirements workflow. For apps without git requirements the content is the same. + +A tag can move, so the lock now pins a git package by its tag rather than its commit. The comment records which commit the tag pointed to when the lock was written. + +Checked on the OpticalFlow3D requirements with uv 0.9 and pip 25: +- before the change, `pip install --dry-run -r requirements.lock.txt` fails with `ResolutionImpossible`; +- after it, the same command succeeds and installs normalization at `1bdeb81` and preprocessing at `0a26b48`, the commits uv resolved. + +## 3. What the migration does + +- `lock_requirements.py` is replaced by the 0.1.44 file when it is still the template file last shipped. The comparison uses LF line endings; the frozen 0.1.43 copy is in `.template_sync/resources/v0_1_43_to_v0_1_44/previous/`. The file keeps its own line endings. +- A file the app changed is left as it is (`SKIPPED`, with what to change by hand). A missing file is not created, and nothing is deleted. A second run changes nothing. +- The lock files change at the next run of **Updates on notebook change**: a notebook change, or run it by hand. + +## 4. Adopting it + +1. Take this template version (the synchronization pull request). +2. Run **Actions > Updates on notebook change > Run workflow** so the lock files are written again. +3. Make a release. + +An app whose commit the workflow reverted can then apply that commit again. diff --git a/.tools/python/lock_requirements.py b/.tools/python/lock_requirements.py index 315b054..99c2881 100644 --- a/.tools/python/lock_requirements.py +++ b/.tools/python/lock_requirements.py @@ -15,6 +15,10 @@ not written to the lock file (their own dependencies are), and a conda pin such as `jupyterlab=4.4.0` constrains the resolution. * The per-OS files are resolved with requirements.lock.txt as constraints, so a package that both files need gets the same version. * Pip options of the requirements file (`--extra-index-url` of the GPU file, ...) are copied to the top of the lock file. +* A package required from a git URL (`name @ git+https://...@v1.2.0`) keeps the reference exactly as the requirements file writes it, with + the commit uv resolved as a comment. uv writes the commit instead, and pip treats `...@v1.2.0` and `...@` as two different + requirements: when another git package requires the same package with the tag (MorphoBricks bricks depend on each other this way), pip + refuses the lock file (ResolutionImpossible) and the installer cannot install it. A lock file is written again only when its requirements file, the Python or JupyterLab version (or this script's lock format) changed: its header holds a fingerprint of those inputs. Re-running the script without such a change rewrites nothing, so a new release @@ -38,7 +42,7 @@ import yaml # Bump when the uv arguments or the output change, so that every lock file is written again. -LOCK_FORMAT = "2" +LOCK_FORMAT = "3" BASE_INPUT = "requirements.txt" GPU_INPUT = "requirements_gpu.txt" OS_INPUTS = ("requirements-linux.txt", "requirements-windows.txt", "requirements-macos.txt") @@ -48,6 +52,8 @@ INDEX_OPTION = re.compile(r"^\s*(--index-url|--extra-index-url|-i|--find-links|-f|--trusted-host)(\s|=)") CONDA_SPEC = re.compile(r"^\s*([A-Za-z0-9_.-]+)\s*(?:(==?)\s*([0-9][A-Za-z0-9_.+!*-]*))?(?:=\S+)?\s*$") PLACEHOLDER = re.compile(r"^[A-Z_]+$") +# `name[extras] @ git+URL`, the URL up to the first space or `;` (environment marker). +GIT_REQUIREMENT = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?\s*@\s*(git\+[^\s;#]+)") def lock_path(requirements: Path) -> Path: @@ -146,9 +152,39 @@ def uv_version() -> str: return " ".join(result.stdout.split()[:2]) or "uv" +def canonical_name(name: str) -> str: + """The package name as pip compares it (PEP 503): lower case, runs of `-`, `_` and `.` as one `-`.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def keep_requested_git_references(requirements_text: str, packages: list[str]) -> list[str]: + """`packages` (uv's lines) with each git package the requirements name directly written with the requested reference. + + uv resolves `name @ git+URL@v1.2.0` to `name @ git+URL@`. pip compares the two URLs as text, so a lock line with the commit + conflicts with another git package that requires `name` with the tag. The lock line keeps the requested URL; the resolved commit + follows as a comment. A git package the requirements do not name directly (a dependency of a dependency) keeps uv's line. + """ + requested: dict[str, str] = {} + for line in requirements_text.replace("\r\n", "\n").split("\n"): + match = GIT_REQUIREMENT.match(line) + if match: + requested[canonical_name(match.group(1))] = match.group(3) + kept = [] + for line in packages: + match = GIT_REQUIREMENT.match(line) + url = requested.get(canonical_name(match.group(1))) if match else None + if match and url and url != match.group(3): + start, end = match.span(3) + line = f"{line[:start]}{url}{line[end:]} # resolved: {match.group(3)}" + kept.append(line) + return kept + + def render_lock(requirements: Path, resolved: str, digest: str, python_version: str, uv: str) -> str: - options = [line.strip() for line in requirements.read_text(encoding="utf-8").splitlines() if INDEX_OPTION.match(line)] + text = requirements.read_text(encoding="utf-8") + options = [line.strip() for line in text.splitlines() if INDEX_OPTION.match(line)] packages = [line.rstrip() for line in resolved.replace("\r\n", "\n").split("\n") if line.strip() and not line.lstrip().startswith("#")] + packages = keep_requested_git_references(text, packages) header = [ f"# Lock file of {requirements.name}: every package the installer installs with pip, with its exact version.", f"# Written by .tools/python/lock_requirements.py ({uv}, universal resolution for Python {python_version}); do not edit it by hand.", diff --git a/tests/_v0_1_43.py b/tests/_v0_1_43.py index dbaeccc..f21b8a6 100644 --- a/tests/_v0_1_43.py +++ b/tests/_v0_1_43.py @@ -8,6 +8,8 @@ from pathlib import Path +from _v0_1_44 import before_0_1_44 + PIN_0_1_42 = "v0.3.0-alpha.4" PIN_0_1_43 = "v0.3.0-alpha.5" PINNED_FILES = (Path("app/bash_bat_scripts/post_install.sh"), Path("app/bash_bat_scripts/post_install.bat")) @@ -15,6 +17,7 @@ def before_0_1_43(relative: Path | str, data: bytes) -> bytes: """`data` (a live template file at `relative`) with the 0.1.43 pin moved back; any other file is returned as it is.""" + data = before_0_1_44(relative, data) if Path(relative) not in PINNED_FILES: return data return data.replace(PIN_0_1_43.encode(), PIN_0_1_42.encode()) diff --git a/tests/_v0_1_44.py b/tests/_v0_1_44.py new file mode 100644 index 0000000..192cbaf --- /dev/null +++ b/tests/_v0_1_44.py @@ -0,0 +1,37 @@ +"""Helper of the tests: a live template file as it was before template 0.1.44. + +Template 0.1.44 replaces lock_requirements.py whole (FILES of the migration). The tests of the older migrations compare with the live files; +`before_0_1_44` gives the bytes of a live file without the 0.1.44 change (the frozen 0.1.43 copy when the file is the 0.1.44 file), so they +keep checking what they checked. The 0.1.44 change is tested in test_template_sync_0_1_44.py. +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parents[1] +MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_43_to_v0_1_44.py" + + +def _migration() -> ModuleType: + spec = importlib.util.spec_from_file_location("migration_0_1_44_for_older_tests", MIGRATION_PATH) + if spec is None or spec.loader is None: + raise RuntimeError(f"Unable to load {MIGRATION_PATH}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def before_0_1_44(relative: Path | str, data: bytes) -> bytes: + """`data` (a live template file at `relative`) without the 0.1.44 change; any other file is returned as it is.""" + migration = _migration() + relative = Path(relative) + if relative not in migration.FILES: + return data + text = data.decode("utf-8") + newline = "\r\n" if "\r\n" in text else "\n" + if text.replace("\r\n", "\n") != (migration.RESOURCE_ROOT / relative).read_bytes().decode("utf-8").replace("\r\n", "\n"): + return data + previous = (migration.PREVIOUS_ROOT / relative).read_bytes().decode("utf-8").replace("\r\n", "\n") + return previous.replace("\n", newline).encode("utf-8") diff --git a/tests/test_template_sync_0_1_41.py b/tests/test_template_sync_0_1_41.py index e7cc6bc..09514b1 100644 --- a/tests/test_template_sync_0_1_41.py +++ b/tests/test_template_sync_0_1_41.py @@ -38,7 +38,10 @@ def lf(path: Path) -> str: def live(relative: Path) -> bytes: - return (ROOT / relative).read_bytes() + """The live template file without the later changes (0.1.44 replaces lock_requirements.py): tests/_v0_1_44.py.""" + from _v0_1_44 import before_0_1_44 + + return before_0_1_44(relative, (ROOT / relative).read_bytes()) def previous(relative: Path) -> bytes: @@ -85,9 +88,9 @@ def test_the_older_tests_see_the_0_1_40_files(self) -> None: self.assertEqual(before_0_1_41(relative, live(relative)), previous(relative)) def test_the_lock_command_takes_the_best_version_of_every_index(self) -> None: - source = lf(ROOT / ".tools/python/lock_requirements.py") + source = live(Path(".tools/python/lock_requirements.py")).decode("utf-8") self.assertIn('"--index-strategy", "unsafe-best-match"', source) - self.assertEqual(LOCK.LOCK_FORMAT, "2", "a new format writes every lock file again") + self.assertIn('LOCK_FORMAT = "2"', source, "a new format writes every lock file again") class MergeTests(unittest.TestCase): diff --git a/tests/test_template_sync_0_1_44.py b/tests/test_template_sync_0_1_44.py new file mode 100644 index 0000000..c38c863 --- /dev/null +++ b/tests/test_template_sync_0_1_44.py @@ -0,0 +1,211 @@ +"""Tests of the 0.1.44 migration: lock files keep the git references the requirements write (pip can then install them).""" +from __future__ import annotations + +import importlib.util +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parents[1] +MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_43_to_v0_1_44.py" +SYNC_PATH = ROOT / ".template_sync/sync.py" +DOCS = ROOT / ".tools/docs" +NORM = "git+https://github.com/CellMigrationLab/morphobricks-normalization.git" +PREP = "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" + + +def load(path: Path, name: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +MIGRATION = load(MIGRATION_PATH, "migration_0_1_44") +LOCK = load(ROOT / ".tools/python/lock_requirements.py", "lock_requirements_0_1_44") + + +def lf(path: Path) -> str: + return path.read_bytes().decode("utf-8").replace("\r\n", "\n") + + +def live(relative: Path) -> bytes: + return (ROOT / relative).read_bytes() + + +def previous(relative: Path) -> bytes: + """The 0.1.43 template file (the frozen copy).""" + return (MIGRATION.PREVIOUS_ROOT / relative).read_bytes() + + +def with_version(text: str, version: str) -> str: + return re.sub(r"template_version: [0-9.]+", f"template_version: {version}", text) + + +class TemplateTests(unittest.TestCase): + def test_the_manifest_lists_the_migration_and_the_new_version(self) -> None: + text = lf(ROOT / ".template_sync/manifest.yaml") + self.assertRegex(text, r"template_version: 0\.1\.(4[4-9]|[5-9][0-9])\b") + self.assertIn(" - from: 0.1.43\n to: 0.1.44\n script: migrations/v0_1_43_to_v0_1_44.py\n", text) + + def test_chains_from_older_versions_reach_0_1_44(self) -> None: + sync = load(SYNC_PATH, "sync_for_0_1_44") + manifest = sync.parse_manifest(ROOT / ".template_sync/manifest.yaml") + for start in ("0.0.0", "0.1.16", "0.1.40", "0.1.43"): + chain = sync.resolve_migration_chain(manifest["migrations"], start, "0.1.44") + self.assertEqual(chain[-1]["to"], "0.1.44", start) + + def test_the_design_note_exists_and_is_not_in_the_docs_index(self) -> None: + self.assertIn(".tools/docs/migration_0_1_44.md", MIGRATION_PATH.read_text(encoding="utf-8")) + self.assertTrue((DOCS / "migration_0_1_44.md").is_file()) + self.assertNotIn("migration_0_1_44.md", lf(DOCS / "README.md")) + + def test_the_resources_are_the_live_file_and_the_0_1_43_one(self) -> None: + for relative in MIGRATION.FILES: + with self.subTest(file=str(relative)): + self.assertEqual((MIGRATION.RESOURCE_ROOT / relative).read_bytes(), live(relative)) + self.assertNotEqual(previous(relative), live(relative)) + resources = sorted(p.relative_to(MIGRATION.RESOURCE_ROOT) for p in MIGRATION.RESOURCE_ROOT.rglob("*") if p.is_file()) + self.assertEqual(resources, sorted([*MIGRATION.FILES, *(Path("previous") / r for r in MIGRATION.FILES)])) + + def test_the_older_tests_see_the_0_1_43_file(self) -> None: + from _v0_1_44 import before_0_1_44 + + for relative in MIGRATION.FILES: + with self.subTest(file=str(relative)): + self.assertEqual(before_0_1_44(relative, live(relative)), previous(relative)) + + def test_a_new_lock_format_writes_every_lock_file_again(self) -> None: + self.assertEqual(LOCK.LOCK_FORMAT, "3") + self.assertIn('LOCK_FORMAT = "2"', previous(MIGRATION.LOCK).decode("utf-8")) + + +class LockTests(unittest.TestCase): + """keep_requested_git_references on uv's output (no network: the resolution is given).""" + + REQUIREMENTS = f"numpy==2.2.6\nmorphobricks-normalization @ {NORM}@v0.10.0\nmorphobricks_Preprocessing @ {PREP}@v0.10.0\n" + RESOLVED = [ + "numpy==2.2.6", + f"morphobricks-normalization @ {NORM}@1bdeb817aeb5cd3078596eecb215342ae38b1d4c", + f"morphobricks-preprocessing @ {PREP}@0a26b48af8adca5345e06f44aceb4f96fc62bd28", + "pyarrow==26.0.1", + ] + + def test_a_git_package_named_directly_keeps_its_tag_with_the_commit_as_a_comment(self) -> None: + kept = LOCK.keep_requested_git_references(self.REQUIREMENTS, self.RESOLVED) + self.assertEqual(kept[0], "numpy==2.2.6") + self.assertEqual( + kept[1], + f"morphobricks-normalization @ {NORM}@v0.10.0 # resolved: {NORM}@1bdeb817aeb5cd3078596eecb215342ae38b1d4c", + ) + self.assertTrue(kept[2].startswith(f"morphobricks-preprocessing @ {PREP}@v0.10.0 # resolved: ")) # name compared as pip does + self.assertEqual(kept[3], "pyarrow==26.0.1") + + def test_a_git_package_not_named_directly_and_a_commit_pin_keep_uvs_line(self) -> None: + commit = f"morphobricks-normalization @ {NORM}@1bdeb817aeb5cd3078596eecb215342ae38b1d4c" + self.assertEqual(LOCK.keep_requested_git_references("numpy==2.2.6\n", self.RESOLVED), self.RESOLVED) + self.assertEqual(LOCK.keep_requested_git_references(commit + "\n", [commit]), [commit]) + + def test_extras_and_markers_are_kept(self) -> None: + line = f"morphobricks-normalization[histology] @ {NORM}@1bdeb81 ; sys_platform == 'linux'" + kept = LOCK.keep_requested_git_references(f"morphobricks-normalization[histology] @ {NORM}@v0.10.0\n", [line]) + self.assertEqual(kept, [f"morphobricks-normalization[histology] @ {NORM}@v0.10.0 ; sys_platform == 'linux' # resolved: {NORM}@1bdeb81"]) + + def test_render_lock_writes_the_requested_references(self) -> None: + work = Path(tempfile.mkdtemp(prefix="lc_0_1_44_lock_")) + self.addCleanup(shutil.rmtree, work, True) + requirements = work / "requirements.txt" + requirements.write_text(self.REQUIREMENTS, encoding="utf-8") + text = LOCK.render_lock(requirements, "\n".join(self.RESOLVED) + "\n", "0" * 64, "3.11", "uv test") + self.assertIn(f"morphobricks-normalization @ {NORM}@v0.10.0 # resolved: ", text) + self.assertNotIn(f"\nmorphobricks-normalization @ {NORM}@1bdeb81", text) + + +class MigrationTests(unittest.TestCase): + def setUp(self) -> None: + self.repo = Path(tempfile.mkdtemp(prefix="lc_0_1_44_")) + for relative in MIGRATION.FILES: + self.put(relative, previous(relative)) + + def tearDown(self) -> None: + shutil.rmtree(self.repo, ignore_errors=True) + + def put(self, relative: Path, data: bytes) -> Path: + target = self.repo / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + return target + + def run_migration(self) -> str: + out = StringIO() + with redirect_stdout(out): + MIGRATION.migrate(self.repo, {}) + return out.getvalue() + + def assert_template_state(self) -> None: + for relative in MIGRATION.FILES: + with self.subTest(file=str(relative)): + self.assertEqual((self.repo / relative).read_bytes().replace(b"\r\n", b"\n"), live(relative)) + + def test_an_app_of_0_1_43_gets_the_file_and_a_second_run_changes_nothing(self) -> None: + log = self.run_migration() + self.assert_template_state() + self.assertIn("done: 1 file(s) changed", log) + self.assertIn("Updates on notebook change", log) + self.assertIn("no repository changes were required", self.run_migration()) + self.assert_template_state() + + def test_crlf_is_kept(self) -> None: + for relative in MIGRATION.FILES: + self.put(relative, previous(relative).replace(b"\n", b"\r\n")) + self.assertNotIn("SKIPPED", self.run_migration()) + self.assert_template_state() + for relative in MIGRATION.FILES: + self.assertNotIn(b"\n", (self.repo / relative).read_bytes().replace(b"\r\n", b"")) + + def test_a_customised_script_is_skipped_with_what_to_do_by_hand(self) -> None: + own = previous(MIGRATION.LOCK) + b"\n# our own change\n" + path = self.put(MIGRATION.LOCK, own) + log = self.run_migration() + self.assertIn(f"{MIGRATION.LOCK}: SKIPPED: customised (not the 0.1.43 template file)", log) + self.assertIn("keep_requested_git_references", log) + self.assertEqual(path.read_bytes(), own) + + def test_a_missing_file_is_not_created(self) -> None: + (self.repo / MIGRATION.LOCK).unlink() + log = self.run_migration() + self.assertIn(f"{MIGRATION.LOCK}: not present in this repository (nothing was created)", log) + self.assertEqual([p for p in self.repo.rglob("*") if p.is_file()], []) + + def sync(self, start: str) -> subprocess.CompletedProcess[str]: + manifest = self.repo / ".template_sync/manifest.yaml" + if not manifest.exists(): + shutil.copytree(ROOT / ".template_sync", self.repo / ".template_sync") + manifest.write_text(with_version(manifest.read_text(encoding="utf-8"), "0.1.44"), encoding="utf-8") + command = [ + sys.executable, str(self.repo / ".template_sync/sync.py"), "--from-version", start, "--to-version", "0.1.44", + "--repository-root", str(self.repo), + ] + env = {key: value for key, value in os.environ.items() if key != "PYTHONPATH"} + return subprocess.run(command, capture_output=True, text=True, env=env, check=False) + + def test_the_sync_script_runs_the_migration_from_0_1_43(self) -> None: + result = self.sync("0.1.43") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("[migration 0.1.44]", result.stdout) + self.assert_template_state() + again = self.sync("0.1.43") + self.assertIn("[migration 0.1.44] done: no repository changes were required", again.stdout) + + +if __name__ == "__main__": + unittest.main()