diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml index e29432f..94c9322 100644 --- a/.template_sync/manifest.yaml +++ b/.template_sync/manifest.yaml @@ -1,4 +1,4 @@ -template_version: 0.1.41 +template_version: 0.1.42 migrations: - from: 0.0.0 to: 0.0.1 @@ -129,3 +129,6 @@ migrations: - from: 0.1.40 to: 0.1.41 script: migrations/v0_1_40_to_v0_1_41.py + - from: 0.1.41 + to: 0.1.42 + script: migrations/v0_1_41_to_v0_1_42.py diff --git a/.template_sync/migrations/v0_1_41_to_v0_1_42.py b/.template_sync/migrations/v0_1_41_to_v0_1_42.py new file mode 100644 index 0000000..fccf687 --- /dev/null +++ b/.template_sync/migrations/v0_1_41_to_v0_1_42.py @@ -0,0 +1,126 @@ +"""Template 0.1.41 -> 0.1.42: no menuinst 2.5.2 in the installer, and the release names its own version on the installer's last page +when construct.yaml has conclusion_text wrapped over several lines. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_42.md + +1. environment.yaml asks for `menuinst>=2,!=2.5.2` (was `menuinst>=2`): menuinst 2.5.2 writes `Icon={_escape_desktop_string(self.render_key('icon')}` + unrendered into the Linux .desktop file, so the menu entry has no icon (conda/menuinst#535, fixed upstream but not released). +2. bump_version.py joins a `conclusion_text` written as a plain scalar over several lines (the repository initialiser wraps it for a long + project name) before it updates the version in it: the one-line update missed it, and the installer of LabConstrictor-CAREamics 0.0.3 + said 0.0.2 on its last page. + +What this changes in an app repository: in environment.yaml, only the line `- menuinst>=2` is changed (the app may have changed other +lines); a line with another menuinst requirement is left as it is (SKIPPED, with a note of what to change by hand), and no line is added +when there is none. bump_version.py is replaced by the 0.1.42 file when it is still the template file last shipped (the 0.1.41 copy; +compared with LF line endings; the file keeps its own line endings); a file the app changed stays as it is (SKIPPED, with a note). A +missing file is not created, and nothing is deleted. The changes reach users with the app's next release. +""" +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_42.md" +TAG = "[migration 0.1.42]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_41_to_v0_1_42" +PREVIOUS_ROOT = RESOURCE_ROOT / "previous" + +ENVIRONMENT = Path("environment.yaml") +BUMP = Path(".tools/python/bump_version.py") +FILES = (BUMP,) # replaced whole when they are the 0.1.41 template file + +MENUINST_OLD = "menuinst>=2" +MENUINST_NEW = "menuinst>=2,!=2.5.2" +# A dependency line naming menuinst (with or without a channel and a version): ` - menuinst>=2 # comment` +MENUINST_LINE_RE = re.compile( + r"^(?P
[ \t]*-[ \t]*)(?P["\']?)(?P\d+\.\d+\.\d+)(?P=quote)(?P \s*(?:#.*)?)$', + re.MULTILINE, +) +CONCLUSION_LINE_RE = re.compile( + r'^(conclusion_text:\s*)(?:(?P ["\'])(?P.*?)(?P=quote)|(?P .*?))(?P \s*(?:#.*)?)$', + re.MULTILINE, +) +# The conclusion_text key line, for joining a plain scalar that is wrapped over several lines. +CONCLUSION_KEY_RE = re.compile(r"^(?P [ \t]*)conclusion_text:(?P .*)$") +PKG_VERSION_RE = re.compile(r'^(\s*SET\s+"PKG_VERSION=)(\d+\.\d+\.\d+)("\s*)$', re.MULTILINE) +POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat" +# version="1.2.3" in setup.py: the version of the app's Python package (src/) +SETUP = ROOT / "setup.py" +SETUP_VERSION_RE = re.compile(r"^(?P[ \t]*version\s*=\s*)(?P [\"'])\d+\.\d+\.\d+(?P=quote)", re.MULTILINE) + +# The folder of a release in a download link: /releases/download// (the tag is 1.2.3 or v1.2.3). +DOWNLOAD_PATH_RE = re.compile(r"/releases/download/v?\d+\.\d+\.\d+/") +# A button of the download page: +DOWNLOAD_BUTTON_RE = re.compile(r'\s*
]*>\s*') +NOT_BUILT_NOTE = "> No installer is built for {label}: this app does not support it." + + +def replace_version_placeholder(text: str, new_version: str, tag: str | None = None) -> str: + """Render the release version in download documentation. + + Handles both pristine templates containing ``VERSION_NUMBER`` and + initialized repositories where that placeholder was already rendered to an + older explicit version such as ``0.0.0``. The links point to the release + tag as it was typed (``v1.2.3`` or ``1.2.3``); the installer names carry + the version without ``v`` (CellMigrationLab/LabConstrictor#41). + """ + explicit_versions = set( + re.findall(r"/releases/download/v?(\d+\.\d+\.\d+)/", text) + ) + + text = text.replace("VERSION_NUMBER", new_version) + for previous_version in explicit_versions: + text = text.replace(previous_version, new_version) + return DOWNLOAD_PATH_RE.sub(f"/releases/download/{tag or new_version}/", text) + + +def drop_unbuilt_buttons(text: str, not_built: list[tuple[tuple[str, ...], str]]) -> str: + """Replace the download button of each system the release does not build with a note (CellMigrationLab/LabConstrictor#42). + + ``not_built`` holds (installer name endings, label) pairs, from release_platforms.py. The "or" between + two buttons goes when one of them became a note. + """ + if not not_built: + return text + + def _button(match: re.Match) -> str: + link = match.group(0).split('"', 2)[1] + for endings, label in not_built: + if link.endswith(endings): + return NOT_BUILT_NOTE.format(label=label) + return match.group(0) + + lines = DOWNLOAD_BUTTON_RE.sub(_button, text).split("\n") + note_start = NOT_BUILT_NOTE.split("{", 1)[0] + kept = [] + for index, line in enumerate(lines): + if line.strip() == "or": + before = next((other for other in reversed(lines[:index]) if other.strip()), "") + after = next((other for other in lines[index + 1 :] if other.strip()), "") + if before.startswith(note_start) or after.startswith(note_start): + continue + kept.append(line) + return "\n".join(kept) + + +def not_built_systems() -> list[tuple[tuple[str, ...], str]]: + """(installer name endings, label) of each system left out of distribution.platforms in labconstrictor-app.yaml.""" + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + import release_platforms + + return [(build.files, build.label) for build in release_platforms.skipped_builds(ROOT)] + +def replace_version_in_file(file_path: pathlib.Path, old_version: str, new_version: str) -> bool: + """Replace all occurrences of old_version with new_version in a file. + + Works for markdown and Python files. Handles various version formats: + - Bare versions: 1.2.3 + - With 'v' prefix: v1.2.3 + - In quotes: "1.2.3" or '1.2.3' + - In version strings: version 1.2.3, __version__ = "1.2.3" + + Args: + file_path: Path to the file to update + old_version: Current version string (X.Y.Z format) + new_version: New version string (X.Y.Z format) + + Returns: + True if any replacements were made, False otherwise + """ + if not file_path.exists(): + return False + + text = file_path.read_text(encoding="utf-8") + original_text = text + + # Escape dots for regex + old_escaped = re.escape(old_version) + + # Pattern matches version with optional surrounding characters but preserves them + # Matches: v1.2.3, "1.2.3", '1.2.3', (1.2.3), [1.2.3], bare 1.2.3 + # Does NOT match partial versions like 1.2.34 or 11.2.3 + pattern = re.compile( + r'(?<=["\'\[(\s>v]|^)' + # Lookbehind: quote, bracket, paren, space, >, v, or start + old_escaped + + r'(?=["\'\])\s<,;]|$)' # Lookahead: quote, bracket, paren, space, <, comma, semicolon, or end + ) + + # Also match v-prefixed versions explicitly + v_pattern = re.compile(r'(v)' + old_escaped + r'(?=["\'\])\s<,;!]|$)') + + # Replace v-prefixed versions + text = v_pattern.sub(r'\g<1>' + new_version, text) + + # Replace other versions + text = pattern.sub(new_version, text) + + if text != original_text: + file_path.write_text(text, encoding="utf-8") + return True + return False + + +def read_current_version() -> tuple[str, str]: + """Read construct.yaml as text and extract current SemVer. + + Returns (file_text, version_string). Exits if not found. + """ + text = CONSTRUCT.read_text(encoding="utf-8") + m = VERSION_LINE_RE.search(text) + if not m: + raise ValueError("Could not find version in construct.yaml") + return text, m.group("version") + + +def join_wrapped_conclusion(text: str) -> str: + """Put a `conclusion_text` written as a plain scalar over several lines on one line. + + A YAML writer wraps a long value (the repository initialiser does so for a long project name): + + conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics + 0.0.2. + + The continuation lines are the non-blank lines more indented than the key; YAML reads them as one line joined by spaces, so + joining them keeps the value and lets the one-line update below find the version. A quoted or block scalar is left as it is. + """ + lines = text.split("\n") + for index, line in enumerate(lines): + match = CONCLUSION_KEY_RE.match(line) + if not match: + continue + value = match.group("value").strip() + if value[:1] in ("'", '"', "|", ">", "#"): + return text + indent = len(match.group("indent")) + end = index + 1 + while end < len(lines): + following = lines[end].rstrip("\r") + if not following.strip() or len(following) - len(following.lstrip(" \t")) <= indent: + break + end += 1 + if end == index + 1: + return text + carriage = "\r" if line.endswith("\r") else "" + parts = [value] if value else [] + parts += [lines[position].strip() for position in range(index + 1, end)] + joined = f"{match.group('indent')}conclusion_text: {' '.join(parts)}{carriage}" + return "\n".join([*lines[:index], joined, *lines[end:]]) + return text + + +def bump_construct_text(text: str, old_version: str, new_version: str) -> str: + """Return updated file text with bumped version, preserving YAML structure/comments. + + - Updates the `version: "X.Y.Z"` line. + - Updates the version inside `conclusion_text`, replacing either + `VERSION_NUMBER` or the previous explicit version if present. A plain + `conclusion_text` wrapped over several lines is first joined on one line. + """ + text = join_wrapped_conclusion(text) + # 1) Update the explicit version line + def _repl_version(m: re.Match) -> str: + # Preserve original quoting and trailing comment/whitespace + return f"{m.group(1)}{m.group('quote')}{new_version}{m.group('quote')}{m.group('trailing')}" + + text = VERSION_LINE_RE.sub(_repl_version, text, count=1) + + # 2) Update the version inside conclusion_text if present. + def _repl_conclusion(m: re.Match) -> str: + quote = m.group("quote") or "" + body = m.group("quoted_body") if quote else (m.group("bare_body") or "") + if "VERSION_NUMBER" in body: + updated_body = body.replace("VERSION_NUMBER", new_version) + else: + updated_body = re.sub( + r"\b\d+\.\d+\.\d+\b", + new_version, + body, + count=1, + ) + return f"{m.group(1)}{quote}{updated_body}{quote}{m.group('trailing')}" + + text = CONCLUSION_LINE_RE.sub(_repl_conclusion, text, count=1) + return text + + +def bump_post_install_bat(new_version: str) -> None: + if not POST_INSTALL.exists(): + return + text = POST_INSTALL.read_text(encoding="utf-8") + if not PKG_VERSION_RE.search(text): + return + updated = PKG_VERSION_RE.sub(lambda m: f"{m.group(1)}{new_version}{m.group(3)}", text, count=1) + POST_INSTALL.write_text(updated, encoding="utf-8") + print(f"Updated post_install.bat PKG_VERSION to {new_version}") + + +def bump_setup_py(new_version: str) -> None: + """The version of the app's Python package in setup.py, when it is written there as X.Y.Z. + + The package in the installer and the one publish_pypi.yml publishes on PyPI then carry the release version. The line + endings of the file are kept. + """ + if not SETUP.exists(): + return + with SETUP.open(encoding="utf-8", newline="") as handle: + text = handle.read() + updated = SETUP_VERSION_RE.sub(lambda m: f"{m.group('head')}{m.group('quote')}{new_version}{m.group('quote')}", text, count=1) + if updated != text: + with SETUP.open("w", encoding="utf-8", newline="") as handle: + handle.write(updated) + print(f"Updated setup.py version to {new_version}") + +def bump_version_in_download_executable_md( + new_version: str, tag: str | None = None, not_built: list[tuple[tuple[str, ...], str]] | None = None +) -> None: + possible_download_md_paths = [ + ROOT / "docs" / "download_executable.md", + ROOT / ".tools" / "docs" / "download_executable.md" + ] + template_md = ROOT / ".tools" / "templates" / "download_executable_template.md" + + for download_md in possible_download_md_paths: + # We only want to update the existing files + if download_md.exists(): + # Replace download_executable.md with the template (but only if it exists) + if template_md.exists(): + # Remove existing download_executable.md if present + if download_md.exists(): + download_md.unlink() + # Copy the template to the docs folder using shutil for cross-platform support + shutil.copy(template_md, download_md) + else: + print("Template for download_executable.md not found! Skipping creation of download_executable.md") + return + + # This file contains placeholders, update them with the new version + text = download_md.read_text(encoding="utf-8") + updated_text = drop_unbuilt_buttons(replace_version_placeholder(text, new_version, tag), not_built or []) + if updated_text != text: + download_md.write_text(updated_text, encoding="utf-8") + print(f"Updated download_executable.md to version {new_version}") + else: + print("No version string found in download_executable.md to update.") + +def main() -> None: + parser = argparse.ArgumentParser( + description="Update project version across release artifacts.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=textwrap.dedent( + """\ + Example: + python .tools/python/bump_version.py 0.0.4 + python .tools/python/bump_version.py 0.0.4 --files README.md src/__init__.py + """ + ), + ) + parser.add_argument("new_version", help="SemVer version, e.g. 0.0.4") + parser.add_argument( + "--files", + nargs="+", + help="Additional files to update (e.g., README.md, __init__.py)" + ) + parser.add_argument( + "--tag", + default=os.environ.get("RELEASE_TAG") or None, + help="The release tag the download links point to: 0.0.4 or v0.0.4 (default: $RELEASE_TAG, else the version)", + ) + args = parser.parse_args() + + if not re.fullmatch(r"\d+\.\d+\.\d+", args.new_version): + sys.exit("Version must look like X.Y.Z") + if args.tag and args.tag not in (args.new_version, f"v{args.new_version}"): + sys.exit(f"The release tag {args.tag} does not match the version {args.new_version} (expected {args.new_version} or v{args.new_version})") + + text, current = read_current_version() + updated_text = bump_construct_text(text, current, args.new_version) + + if updated_text != text: + CONSTRUCT.write_text(updated_text, encoding="utf-8") + print(f"Bumped {current} -> {args.new_version}") + else: + print( + f"Project version already at {args.new_version}; " + "checking dependent versioned files." + ) + + # Also bump PKG_VERSION in post_install.bat + bump_post_install_bat(args.new_version) + + # The version of the app's Python package (setup.py), also the version publish_pypi.yml publishes on PyPI + bump_setup_py(args.new_version) + + # Update download_executable.md: the links point to the release tag, and a system that is not built has no button + bump_version_in_download_executable_md(args.new_version, args.tag, not_built_systems()) + + # Update additional files if specified + if args.files: + for file_path in args.files: + full_path = ROOT / file_path + if replace_version_in_file(full_path, current, args.new_version): + print(f"Updated {file_path}") + else: + print(f"No changes in {file_path}") + + +if __name__ == "__main__": + main() diff --git a/.template_sync/resources/v0_1_41_to_v0_1_42/previous/.tools/python/bump_version.py b/.template_sync/resources/v0_1_41_to_v0_1_42/previous/.tools/python/bump_version.py new file mode 100644 index 0000000..e8e5f10 --- /dev/null +++ b/.template_sync/resources/v0_1_41_to_v0_1_42/previous/.tools/python/bump_version.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +import argparse +import os +import pathlib +import re +import shutil +import sys +import textwrap + +ROOT = pathlib.Path(__file__).resolve().parents[2] +CONSTRUCT = ROOT / "construct.yaml" + +# Match version line with optional quotes and optional trailing comment +VERSION_LINE_RE = re.compile( + r'^(version:\s*)(?P
["\']?)(?P\d+\.\d+\.\d+)(?P=quote)(?P \s*(?:#.*)?)$', + re.MULTILINE, +) +CONCLUSION_LINE_RE = re.compile( + r'^(conclusion_text:\s*)(?:(?P ["\'])(?P.*?)(?P=quote)|(?P .*?))(?P \s*(?:#.*)?)$', + re.MULTILINE, +) +PKG_VERSION_RE = re.compile(r'^(\s*SET\s+"PKG_VERSION=)(\d+\.\d+\.\d+)("\s*)$', re.MULTILINE) +POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat" +# version="1.2.3" in setup.py: the version of the app's Python package (src/) +SETUP = ROOT / "setup.py" +SETUP_VERSION_RE = re.compile(r"^(?P[ \t]*version\s*=\s*)(?P [\"'])\d+\.\d+\.\d+(?P=quote)", re.MULTILINE) + +# The folder of a release in a download link: /releases/download// (the tag is 1.2.3 or v1.2.3). +DOWNLOAD_PATH_RE = re.compile(r"/releases/download/v?\d+\.\d+\.\d+/") +# A button of the download page: +DOWNLOAD_BUTTON_RE = re.compile(r'\s*
]*>\s*') +NOT_BUILT_NOTE = "> No installer is built for {label}: this app does not support it." + + +def replace_version_placeholder(text: str, new_version: str, tag: str | None = None) -> str: + """Render the release version in download documentation. + + Handles both pristine templates containing ``VERSION_NUMBER`` and + initialized repositories where that placeholder was already rendered to an + older explicit version such as ``0.0.0``. The links point to the release + tag as it was typed (``v1.2.3`` or ``1.2.3``); the installer names carry + the version without ``v`` (CellMigrationLab/LabConstrictor#41). + """ + explicit_versions = set( + re.findall(r"/releases/download/v?(\d+\.\d+\.\d+)/", text) + ) + + text = text.replace("VERSION_NUMBER", new_version) + for previous_version in explicit_versions: + text = text.replace(previous_version, new_version) + return DOWNLOAD_PATH_RE.sub(f"/releases/download/{tag or new_version}/", text) + + +def drop_unbuilt_buttons(text: str, not_built: list[tuple[tuple[str, ...], str]]) -> str: + """Replace the download button of each system the release does not build with a note (CellMigrationLab/LabConstrictor#42). + + ``not_built`` holds (installer name endings, label) pairs, from release_platforms.py. The "or" between + two buttons goes when one of them became a note. + """ + if not not_built: + return text + + def _button(match: re.Match) -> str: + link = match.group(0).split('"', 2)[1] + for endings, label in not_built: + if link.endswith(endings): + return NOT_BUILT_NOTE.format(label=label) + return match.group(0) + + lines = DOWNLOAD_BUTTON_RE.sub(_button, text).split("\n") + note_start = NOT_BUILT_NOTE.split("{", 1)[0] + kept = [] + for index, line in enumerate(lines): + if line.strip() == "or": + before = next((other for other in reversed(lines[:index]) if other.strip()), "") + after = next((other for other in lines[index + 1 :] if other.strip()), "") + if before.startswith(note_start) or after.startswith(note_start): + continue + kept.append(line) + return "\n".join(kept) + + +def not_built_systems() -> list[tuple[tuple[str, ...], str]]: + """(installer name endings, label) of each system left out of distribution.platforms in labconstrictor-app.yaml.""" + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + import release_platforms + + return [(build.files, build.label) for build in release_platforms.skipped_builds(ROOT)] + +def replace_version_in_file(file_path: pathlib.Path, old_version: str, new_version: str) -> bool: + """Replace all occurrences of old_version with new_version in a file. + + Works for markdown and Python files. Handles various version formats: + - Bare versions: 1.2.3 + - With 'v' prefix: v1.2.3 + - In quotes: "1.2.3" or '1.2.3' + - In version strings: version 1.2.3, __version__ = "1.2.3" + + Args: + file_path: Path to the file to update + old_version: Current version string (X.Y.Z format) + new_version: New version string (X.Y.Z format) + + Returns: + True if any replacements were made, False otherwise + """ + if not file_path.exists(): + return False + + text = file_path.read_text(encoding="utf-8") + original_text = text + + # Escape dots for regex + old_escaped = re.escape(old_version) + + # Pattern matches version with optional surrounding characters but preserves them + # Matches: v1.2.3, "1.2.3", '1.2.3', (1.2.3), [1.2.3], bare 1.2.3 + # Does NOT match partial versions like 1.2.34 or 11.2.3 + pattern = re.compile( + r'(?<=["\'\[(\s>v]|^)' + # Lookbehind: quote, bracket, paren, space, >, v, or start + old_escaped + + r'(?=["\'\])\s<,;]|$)' # Lookahead: quote, bracket, paren, space, <, comma, semicolon, or end + ) + + # Also match v-prefixed versions explicitly + v_pattern = re.compile(r'(v)' + old_escaped + r'(?=["\'\])\s<,;!]|$)') + + # Replace v-prefixed versions + text = v_pattern.sub(r'\g<1>' + new_version, text) + + # Replace other versions + text = pattern.sub(new_version, text) + + if text != original_text: + file_path.write_text(text, encoding="utf-8") + return True + return False + + +def read_current_version() -> tuple[str, str]: + """Read construct.yaml as text and extract current SemVer. + + Returns (file_text, version_string). Exits if not found. + """ + text = CONSTRUCT.read_text(encoding="utf-8") + m = VERSION_LINE_RE.search(text) + if not m: + raise ValueError("Could not find version in construct.yaml") + return text, m.group("version") + + +def bump_construct_text(text: str, old_version: str, new_version: str) -> str: + """Return updated file text with bumped version, preserving YAML structure/comments. + + - Updates the `version: "X.Y.Z"` line. + - Updates the version inside `conclusion_text`, replacing either + `VERSION_NUMBER` or the previous explicit version if present. + """ + # 1) Update the explicit version line + def _repl_version(m: re.Match) -> str: + # Preserve original quoting and trailing comment/whitespace + return f"{m.group(1)}{m.group('quote')}{new_version}{m.group('quote')}{m.group('trailing')}" + + text = VERSION_LINE_RE.sub(_repl_version, text, count=1) + + # 2) Update the version inside conclusion_text if present. + def _repl_conclusion(m: re.Match) -> str: + quote = m.group("quote") or "" + body = m.group("quoted_body") if quote else (m.group("bare_body") or "") + if "VERSION_NUMBER" in body: + updated_body = body.replace("VERSION_NUMBER", new_version) + else: + updated_body = re.sub( + r"\b\d+\.\d+\.\d+\b", + new_version, + body, + count=1, + ) + return f"{m.group(1)}{quote}{updated_body}{quote}{m.group('trailing')}" + + text = CONCLUSION_LINE_RE.sub(_repl_conclusion, text, count=1) + return text + + +def bump_post_install_bat(new_version: str) -> None: + if not POST_INSTALL.exists(): + return + text = POST_INSTALL.read_text(encoding="utf-8") + if not PKG_VERSION_RE.search(text): + return + updated = PKG_VERSION_RE.sub(lambda m: f"{m.group(1)}{new_version}{m.group(3)}", text, count=1) + POST_INSTALL.write_text(updated, encoding="utf-8") + print(f"Updated post_install.bat PKG_VERSION to {new_version}") + + +def bump_setup_py(new_version: str) -> None: + """The version of the app's Python package in setup.py, when it is written there as X.Y.Z. + + The package in the installer and the one publish_pypi.yml publishes on PyPI then carry the release version. The line + endings of the file are kept. + """ + if not SETUP.exists(): + return + with SETUP.open(encoding="utf-8", newline="") as handle: + text = handle.read() + updated = SETUP_VERSION_RE.sub(lambda m: f"{m.group('head')}{m.group('quote')}{new_version}{m.group('quote')}", text, count=1) + if updated != text: + with SETUP.open("w", encoding="utf-8", newline="") as handle: + handle.write(updated) + print(f"Updated setup.py version to {new_version}") + +def bump_version_in_download_executable_md( + new_version: str, tag: str | None = None, not_built: list[tuple[tuple[str, ...], str]] | None = None +) -> None: + possible_download_md_paths = [ + ROOT / "docs" / "download_executable.md", + ROOT / ".tools" / "docs" / "download_executable.md" + ] + template_md = ROOT / ".tools" / "templates" / "download_executable_template.md" + + for download_md in possible_download_md_paths: + # We only want to update the existing files + if download_md.exists(): + # Replace download_executable.md with the template (but only if it exists) + if template_md.exists(): + # Remove existing download_executable.md if present + if download_md.exists(): + download_md.unlink() + # Copy the template to the docs folder using shutil for cross-platform support + shutil.copy(template_md, download_md) + else: + print("Template for download_executable.md not found! Skipping creation of download_executable.md") + return + + # This file contains placeholders, update them with the new version + text = download_md.read_text(encoding="utf-8") + updated_text = drop_unbuilt_buttons(replace_version_placeholder(text, new_version, tag), not_built or []) + if updated_text != text: + download_md.write_text(updated_text, encoding="utf-8") + print(f"Updated download_executable.md to version {new_version}") + else: + print("No version string found in download_executable.md to update.") + +def main() -> None: + parser = argparse.ArgumentParser( + description="Update project version across release artifacts.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=textwrap.dedent( + """\ + Example: + python .tools/python/bump_version.py 0.0.4 + python .tools/python/bump_version.py 0.0.4 --files README.md src/__init__.py + """ + ), + ) + parser.add_argument("new_version", help="SemVer version, e.g. 0.0.4") + parser.add_argument( + "--files", + nargs="+", + help="Additional files to update (e.g., README.md, __init__.py)" + ) + parser.add_argument( + "--tag", + default=os.environ.get("RELEASE_TAG") or None, + help="The release tag the download links point to: 0.0.4 or v0.0.4 (default: $RELEASE_TAG, else the version)", + ) + args = parser.parse_args() + + if not re.fullmatch(r"\d+\.\d+\.\d+", args.new_version): + sys.exit("Version must look like X.Y.Z") + if args.tag and args.tag not in (args.new_version, f"v{args.new_version}"): + sys.exit(f"The release tag {args.tag} does not match the version {args.new_version} (expected {args.new_version} or v{args.new_version})") + + text, current = read_current_version() + updated_text = bump_construct_text(text, current, args.new_version) + + if updated_text != text: + CONSTRUCT.write_text(updated_text, encoding="utf-8") + print(f"Bumped {current} -> {args.new_version}") + else: + print( + f"Project version already at {args.new_version}; " + "checking dependent versioned files." + ) + + # Also bump PKG_VERSION in post_install.bat + bump_post_install_bat(args.new_version) + + # The version of the app's Python package (setup.py), also the version publish_pypi.yml publishes on PyPI + bump_setup_py(args.new_version) + + # Update download_executable.md: the links point to the release tag, and a system that is not built has no button + bump_version_in_download_executable_md(args.new_version, args.tag, not_built_systems()) + + # Update additional files if specified + if args.files: + for file_path in args.files: + full_path = ROOT / file_path + if replace_version_in_file(full_path, current, args.new_version): + print(f"Updated {file_path}") + else: + print(f"No changes in {file_path}") + + +if __name__ == "__main__": + main() diff --git a/.tools/docs/migration_0_1_42.md b/.tools/docs/migration_0_1_42.md new file mode 100644 index 0000000..4571ca9 --- /dev/null +++ b/.tools/docs/migration_0_1_42.md @@ -0,0 +1,35 @@ +# Template 0.1.42: no menuinst 2.5.2, and the installer names the version it installs + +Design note for the 0.1.42 migration (`.template_sync/migrations/v0_1_41_to_v0_1_42.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 + +* **No menu icon on Linux with menuinst 2.5.2.** menuinst 2.5.2 writes the line `Icon={_escape_desktop_string(self.render_key('icon')}` into the `.desktop` file, unrendered, so the menu entry of the app has no icon. Checked with a real install: menuinst 2.5.1 writes the path of the icon, 2.5.2 the broken line. It is fixed upstream (conda/menuinst#535) but not released. `environment.yaml` asked for `menuinst>=2`, so a new installer took 2.5.2. +* **The installer's last page named the previous version.** `bump_version.py` updates the version inside `conclusion_text` of `construct.yaml` with a one-line pattern. For a long project name the repository initialiser writes that value as a plain YAML scalar wrapped over two lines: + + ```yaml + conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics + 0.0.2. + ``` + + The pattern saw only the first line, which has no version, so the release left `0.0.2` in place: the installer of LabConstrictor-CAREamics 0.0.3 said 0.0.2 on its last page. + +## 2. What changes + +* `environment.yaml`: `- menuinst>=2,!=2.5.2`. A later menuinst (with the fix) is taken when it is released. +* `bump_version.py`: `bump_construct_text` first joins a plain `conclusion_text` written over several lines (the non-blank lines more indented than the key) into one line, which is how YAML reads it, then updates the version as before. The release writes the value on one line with the new version. A quoted one-line value, a bare one-line value and the `VERSION_NUMBER` placeholder are handled as before; a quoted or block (`|`, `>`) value over several lines is left to the one-line update. + +## 3. What the migration does + +* `environment.yaml`: only the line `- menuinst>=2` is changed, to `- menuinst>=2,!=2.5.2` (an app may have changed other lines; its comment and line endings are kept). A line that is already `menuinst>=2,!=2.5.2` is up to date. Any other menuinst requirement is left as it is (`SKIPPED`, with what to change by hand). With no menuinst line, nothing is added (a note says so). +* `bump_version.py` is replaced by the 0.1.42 file when it is still the template file last shipped, compared with LF line endings (the frozen 0.1.41 copy is in `.template_sync/resources/v0_1_41_to_v0_1_42/previous/`). The file keeps its own line endings. A customised file is left as it is (`SKIPPED`, with what to change by hand). +* A missing file is not created, nothing is deleted, and a second run changes nothing. `construct.yaml` is not edited by the migration: the next release writes `conclusion_text` on one line. + +## 4. Adopting it + +Take this template version (the synchronization pull request) and make a release: the new installer excludes menuinst 2.5.2 and its last page names the release version. + +## 5. What is checked here + +* Tests (`tests/test_template_sync_0_1_42.py`): the resources are the live file and differ from the 0.1.41 one; the live `environment.yaml` excludes 2.5.2; a 0.1.41 app reaches the 0.1.42 files with LF and CRLF line endings, and a second run changes nothing; only the menuinst line of a customised `environment.yaml` changes; another menuinst requirement and a customised `bump_version.py` are skipped with their notes; no menuinst line is added; a missing file is not created; an unreadable file does not stop the migration; the sync from 0.1.41 and the chain from older versions; `bump_construct_text` on a wrapped plain value (one line with the new version, LF and CRLF), a one-line quoted value, a one-line bare value and the `VERSION_NUMBER` placeholder. +* The older tests compare with the 0.1.41 files (`tests/_v0_1_42.py`, `before_0_1_42`). diff --git a/.tools/python/bump_version.py b/.tools/python/bump_version.py index e8e5f10..9619333 100644 --- a/.tools/python/bump_version.py +++ b/.tools/python/bump_version.py @@ -19,6 +19,8 @@ r'^(conclusion_text:\s*)(?:(?P
["\'])(?P.*?)(?P=quote)|(?P .*?))(?P \s*(?:#.*)?)$', re.MULTILINE, ) +# The conclusion_text key line, for joining a plain scalar that is wrapped over several lines. +CONCLUSION_KEY_RE = re.compile(r"^(?P [ \t]*)conclusion_text:(?P .*)$") PKG_VERSION_RE = re.compile(r'^(\s*SET\s+"PKG_VERSION=)(\d+\.\d+\.\d+)("\s*)$', re.MULTILINE) POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat" # version="1.2.3" in setup.py: the version of the app's Python package (src/) @@ -149,13 +151,51 @@ def read_current_version() -> tuple[str, str]: return text, m.group("version") +def join_wrapped_conclusion(text: str) -> str: + """Put a `conclusion_text` written as a plain scalar over several lines on one line. + + A YAML writer wraps a long value (the repository initialiser does so for a long project name): + + conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics + 0.0.2. + + The continuation lines are the non-blank lines more indented than the key; YAML reads them as one line joined by spaces, so + joining them keeps the value and lets the one-line update below find the version. A quoted or block scalar is left as it is. + """ + lines = text.split("\n") + for index, line in enumerate(lines): + match = CONCLUSION_KEY_RE.match(line) + if not match: + continue + value = match.group("value").strip() + if value[:1] in ("'", '"', "|", ">", "#"): + return text + indent = len(match.group("indent")) + end = index + 1 + while end < len(lines): + following = lines[end].rstrip("\r") + if not following.strip() or len(following) - len(following.lstrip(" \t")) <= indent: + break + end += 1 + if end == index + 1: + return text + carriage = "\r" if line.endswith("\r") else "" + parts = [value] if value else [] + parts += [lines[position].strip() for position in range(index + 1, end)] + joined = f"{match.group('indent')}conclusion_text: {' '.join(parts)}{carriage}" + return "\n".join([*lines[:index], joined, *lines[end:]]) + return text + + def bump_construct_text(text: str, old_version: str, new_version: str) -> str: """Return updated file text with bumped version, preserving YAML structure/comments. - Updates the `version: "X.Y.Z"` line. - Updates the version inside `conclusion_text`, replacing either - `VERSION_NUMBER` or the previous explicit version if present. + `VERSION_NUMBER` or the previous explicit version if present. A plain + `conclusion_text` wrapped over several lines is first joined on one line. """ + text = join_wrapped_conclusion(text) # 1) Update the explicit version line def _repl_version(m: re.Match) -> str: # Preserve original quoting and trailing comment/whitespace diff --git a/environment.yaml b/environment.yaml index 93b9e12..c731c80 100644 --- a/environment.yaml +++ b/environment.yaml @@ -10,7 +10,7 @@ dependencies: - pip>=24.2 - setuptools - wheel - - menuinst>=2 + - menuinst>=2,!=2.5.2 - truststore>=0.10.4 - certifi - jupyterlab=JUPYTERLAB_VERSION diff --git a/tests/_v0_1_41.py b/tests/_v0_1_41.py index b2a9471..44d6482 100644 --- a/tests/_v0_1_41.py +++ b/tests/_v0_1_41.py @@ -10,6 +10,8 @@ from pathlib import Path from types import ModuleType +from _v0_1_42 import before_0_1_42 + ROOT = Path(__file__).resolve().parents[1] MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_40_to_v0_1_41.py" @@ -25,6 +27,7 @@ def _migration() -> ModuleType: def before_0_1_41(relative: Path | str, data: bytes) -> bytes: """`data` (a live template file at `relative`) without the 0.1.41 change; any other file is returned as it is.""" + data = before_0_1_42(relative, data) migration = _migration() relative = Path(relative) if relative not in migration.FILES: diff --git a/tests/_v0_1_42.py b/tests/_v0_1_42.py new file mode 100644 index 0000000..f268c91 --- /dev/null +++ b/tests/_v0_1_42.py @@ -0,0 +1,47 @@ +"""Helper of the tests: a live template file as it was before template 0.1.42. + +Template 0.1.42 replaces bump_version.py whole (FILES of the migration) and changes one line of environment.yaml (`- menuinst>=2` to +`- menuinst>=2,!=2.5.2`). The tests of the older migrations compare with the live files; `before_0_1_42` gives the bytes of a live file +without the 0.1.42 change (the frozen 0.1.41 copy when the file is the 0.1.42 file; the menuinst line put back), so they keep checking what +they checked. The 0.1.42 changes are tested in test_template_sync_0_1_42.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_41_to_v0_1_42.py" + + +def _migration() -> ModuleType: + spec = importlib.util.spec_from_file_location("migration_0_1_42_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_42(relative: Path | str, data: bytes) -> bytes: + """`data` (a live template file at `relative`) without the 0.1.42 change; any other file is returned as it is.""" + migration = _migration() + relative = Path(relative) + if relative != migration.ENVIRONMENT and relative not in migration.FILES: + return data + text = data.decode("utf-8") + newline = "\r\n" if "\r\n" in text else "\n" + text = text.replace("\r\n", "\n") + if relative == migration.ENVIRONMENT: + lines = text.split("\n") + for index, line in enumerate(lines): + match = migration.MENUINST_LINE_RE.match(line) + if match and match.group("spec").strip() == migration.MENUINST_NEW: + lines[index] = f"{match.group('head')}{migration.MENUINST_OLD}{match.group('tail')}" + return "\n".join(lines).replace("\n", newline).encode("utf-8") + # Only the 0.1.42 file is swapped back: older helpers may run this chain again on text that is already older. + if text != (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_25.py b/tests/test_template_sync_0_1_25.py index 79af978..5b9d2fe 100644 --- a/tests/test_template_sync_0_1_25.py +++ b/tests/test_template_sync_0_1_25.py @@ -28,6 +28,7 @@ import yaml from _v0_1_25 import before_0_1_25 +from _v0_1_30 import before_0_1_30 ROOT = Path(__file__).resolve().parents[1] @@ -80,6 +81,11 @@ def old_setup(values: dict[str, str] | None = None) -> str: return MIGRATION.render_setup(MIGRATION.OLD_SETUP, values) if values else MIGRATION.OLD_SETUP +def bump_0_1_25() -> str: + """The 0.1.25 file: the live bump_version.py without the changes of later templates (0.1.42 changed it again).""" + return before_0_1_30(BUMP, (ROOT / BUMP).read_bytes()).decode("utf-8").replace("\r\n", "\n") + + def bump_0_1_24() -> str: return before_0_1_25(BUMP, (ROOT / BUMP).read_bytes()).decode("utf-8").replace("\r\n", "\n") @@ -112,8 +118,8 @@ def test_the_resources_are_the_live_files(self) -> None: self.assertEqual((MIGRATION.RESOURCE_ROOT / relative).read_bytes(), (ROOT / relative).read_bytes()) def test_the_live_bump_version_is_the_0_1_24_file_migrated(self) -> None: - self.assertNotEqual(bump_0_1_24(), lf(ROOT / BUMP)) - self.assertEqual(MIGRATION.apply_blocks(bump_0_1_24(), MIGRATION.BUMP_BLOCKS), lf(ROOT / BUMP)) + self.assertNotEqual(bump_0_1_24(), bump_0_1_25()) + self.assertEqual(MIGRATION.apply_blocks(bump_0_1_24(), MIGRATION.BUMP_BLOCKS), bump_0_1_25()) def test_the_setup_py_keeps_the_placeholders_the_form_and_the_scripts_fill_in(self) -> None: text = template_setup() @@ -491,7 +497,7 @@ def test_a_0_1_24_app_reaches_the_0_1_25_files_and_a_second_run_changes_nothing( self.assertRegex(output, rf"{re.escape(str(relative))}: updated") self.assertNotIn("SKIPPED", output) self.assertEqual(lf(self.repo / SETUP), template_setup(VALUES)) - self.assertEqual(lf(self.repo / BUMP), lf(ROOT / BUMP)) + self.assertEqual(lf(self.repo / BUMP), bump_0_1_25()) for relative in (WORKFLOW, MIGRATION.PACKAGE_SCRIPT, MANIFEST_IN): self.assertEqual((self.repo / relative).read_bytes(), (ROOT / relative).read_bytes()) self.assertIn("Nothing is published until you turn it on", output) @@ -521,7 +527,7 @@ def test_crlf_files_keep_their_line_endings(self) -> None: data = (self.repo / relative).read_bytes() self.assertNotIn(b"\n", data.replace(b"\r\n", b"")) self.assertEqual(lf(self.repo / SETUP), template_setup(VALUES)) - self.assertEqual(lf(self.repo / BUMP), lf(ROOT / BUMP)) + self.assertEqual(lf(self.repo / BUMP), bump_0_1_25()) def test_a_setup_py_changed_by_hand_is_left_as_it_is_and_gets_no_manifest_in(self) -> None: """The Playground lists its dependencies in setup.py; CellPatcher has a URL dependency.""" diff --git a/tests/test_template_sync_0_1_42.py b/tests/test_template_sync_0_1_42.py new file mode 100644 index 0000000..5da44d2 --- /dev/null +++ b/tests/test_template_sync_0_1_42.py @@ -0,0 +1,290 @@ +"""Tests of the 0.1.42 migration: menuinst 2.5.2 excluded in environment.yaml, and a wrapped conclusion_text bumped by the release.""" +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_41_to_v0_1_42.py" +SYNC_PATH = ROOT / ".template_sync/sync.py" +DOCS = ROOT / ".tools/docs" + + +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_42") +BUMP = load(ROOT / ".tools/python/bump_version.py", "bump_version_0_1_42") +ENVIRONMENT = MIGRATION.ENVIRONMENT +# environment.yaml of an initialised 0.1.41 app (the template file with its placeholders filled in) +ENVIRONMENT_0_1_41 = """name: careamics +channels: + - conda-forge + - bioconda + - nodefaults +dependencies: + - python=3.12 + - conda + - git + - pip>=24.2 + - setuptools + - wheel + - menuinst>=2 + - truststore>=0.10.4 + - certifi + - jupyterlab=4.4.0 +""" +ENVIRONMENT_0_1_42 = ENVIRONMENT_0_1_41.replace(" - menuinst>=2\n", " - menuinst>=2,!=2.5.2\n") + + +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.41 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[2-9]|[5-9][0-9])\b") + self.assertIn(" - from: 0.1.41\n to: 0.1.42\n script: migrations/v0_1_41_to_v0_1_42.py\n", text) + + def test_chains_from_older_versions_reach_0_1_42(self) -> None: + sync = load(SYNC_PATH, "sync_for_0_1_42") + manifest = sync.parse_manifest(ROOT / ".template_sync/manifest.yaml") + for start in ("0.0.0", "0.1.9", "0.1.16", "0.1.40", "0.1.41"): + chain = sync.resolve_migration_chain(manifest["migrations"], start, "0.1.42") + self.assertEqual(chain[-1]["to"], "0.1.42", start) + + def test_the_design_note_exists_and_is_not_in_the_docs_index(self) -> None: + self.assertIn(".tools/docs/migration_0_1_42.md", MIGRATION_PATH.read_text(encoding="utf-8")) + self.assertTrue((DOCS / "migration_0_1_42.md").is_file()) + self.assertNotIn("migration_0_1_42.md", lf(DOCS / "README.md")) + + def test_the_resources_are_the_live_files_and_the_0_1_41_ones(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()) + expected = sorted([*MIGRATION.FILES, *(Path("previous") / relative for relative in MIGRATION.FILES)]) + self.assertEqual(resources, expected) + + def test_the_live_environment_excludes_menuinst_2_5_2(self) -> None: + lines = lf(ROOT / ENVIRONMENT).split("\n") + self.assertIn(f" - {MIGRATION.MENUINST_NEW}", lines) + self.assertNotIn(f" - {MIGRATION.MENUINST_OLD}", lines) + + def test_the_older_tests_see_the_0_1_41_files(self) -> None: + from _v0_1_42 import before_0_1_42 + + for relative in MIGRATION.FILES: + with self.subTest(file=str(relative)): + self.assertEqual(before_0_1_42(relative, live(relative)), previous(relative)) + older = before_0_1_42(ENVIRONMENT, live(ENVIRONMENT)).decode("utf-8") + self.assertEqual(older, lf(ROOT / ENVIRONMENT).replace(f"- {MIGRATION.MENUINST_NEW}\n", f"- {MIGRATION.MENUINST_OLD}\n")) + self.assertEqual(before_0_1_42(ENVIRONMENT, ENVIRONMENT_0_1_42.replace("\n", "\r\n").encode()), ENVIRONMENT_0_1_41.replace("\n", "\r\n").encode()) + self.assertEqual(before_0_1_42("construct.yaml", b"x"), b"x") + + +class BumpConclusionTests(unittest.TestCase): + """bump_construct_text of the live bump_version.py on the conclusion_text forms construct.yaml has.""" + + def bump(self, conclusion: str, old: str = "0.0.2", new: str = "0.0.3") -> str: + text = f"name: LabConstrictor-CAREamics\nversion: {old}\n{conclusion}icon_image: app/logo/logo.png\n" + updated = BUMP.bump_construct_text(text, old, new) + self.assertIn(f"version: {new}\n", updated) + self.assertTrue(updated.startswith("name: LabConstrictor-CAREamics\n")) + self.assertTrue(updated.endswith("icon_image: app/logo/logo.png\n")) + return updated.split("\n")[2] + "\n" + + def test_a_wrapped_plain_scalar_is_joined_on_one_line_with_the_new_version(self) -> None: + wrapped = "conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics\n 0.0.2.\n" + self.assertEqual(self.bump(wrapped), "conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics 0.0.3.\n") + + def test_a_scalar_wrapped_from_the_key_line_and_over_three_lines(self) -> None: + wrapped = "conclusion_text:\n Thank you! You have successfully\n installed Demo\n 0.0.2.\n" + self.assertEqual(self.bump(wrapped), "conclusion_text: Thank you! You have successfully installed Demo 0.0.3.\n") + + def test_crlf_is_kept(self) -> None: + text = "version: 0.0.2\r\nconclusion_text: Thank you! Installed Demo\r\n 0.0.2.\r\nicon_image: a.png\r\n" + self.assertEqual( + BUMP.bump_construct_text(text, "0.0.2", "0.0.3"), + "version: 0.0.3\r\nconclusion_text: Thank you! Installed Demo 0.0.3.\r\nicon_image: a.png\r\n", + ) + + def test_a_one_line_quoted_value_is_bumped_as_before(self) -> None: + self.assertEqual(self.bump("conclusion_text: 'Thank you! Installed Demo 0.0.2.'\n"), "conclusion_text: 'Thank you! Installed Demo 0.0.3.'\n") + self.assertEqual(self.bump('conclusion_text: "Thank you! Installed Demo 0.0.2." # end\n'), 'conclusion_text: "Thank you! Installed Demo 0.0.3." # end\n') + + def test_a_one_line_bare_value_is_bumped_as_before(self) -> None: + self.assertEqual(self.bump("conclusion_text: Thank you! Installed Demo 0.0.2.\n"), "conclusion_text: Thank you! Installed Demo 0.0.3.\n") + + def test_the_version_placeholder_is_filled_in(self) -> None: + conclusion = "conclusion_text: 'Thank you! You have successfully installed Demo VERSION_NUMBER.'\n" + self.assertEqual(self.bump(conclusion, "0.0.0", "0.0.1"), "conclusion_text: 'Thank you! You have successfully installed Demo 0.0.1.'\n") + wrapped = "conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics\n VERSION_NUMBER.\n" + self.assertEqual(self.bump(wrapped, "0.0.0", "0.0.1"), "conclusion_text: Thank you! You have successfully installed LabConstrictor-CAREamics 0.0.1.\n") + + def test_a_block_scalar_and_the_template_line_are_left_to_the_one_line_update(self) -> None: + block = "conclusion_text: >\n Thank you! Installed Demo 0.0.2.\n" + self.assertEqual(BUMP.join_wrapped_conclusion(block), block) + template = lf(ROOT / "construct.yaml") + self.assertEqual(BUMP.join_wrapped_conclusion(template), template) + + def test_the_previous_script_missed_the_wrapped_value(self) -> None: + # run from its source, without a __pycache__ next to the frozen copy (the resources are compared file by file) + source = MIGRATION.PREVIOUS_ROOT / MIGRATION.BUMP + old: dict[str, object] = {"__name__": "bump_version_0_1_41", "__file__": str(source)} + exec(compile(source.read_text(encoding="utf-8"), str(source), "exec"), old) + bump_construct_text = old["bump_construct_text"] + assert callable(bump_construct_text) + text = "version: 0.0.2\nconclusion_text: Thank you! Installed LabConstrictor-CAREamics\n 0.0.2.\n" + self.assertIn("\n 0.0.2.\n", bump_construct_text(text, "0.0.2", "0.0.3")) + + +class MigrationTests(unittest.TestCase): + def setUp(self) -> None: + self.repo = Path(tempfile.mkdtemp(prefix="lc_0_1_42_")) + self.put(ENVIRONMENT, ENVIRONMENT_0_1_41.encode()) + 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: + self.assertEqual(lf(self.repo / ENVIRONMENT), ENVIRONMENT_0_1_42) + 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_41_gets_the_changes_and_a_second_run_changes_nothing(self) -> None: + log = self.run_migration() + self.assert_template_state() + self.assertIn(f"{ENVIRONMENT}: updated: `menuinst>=2` changed to `menuinst>=2,!=2.5.2`", log) + self.assertIn(f"{MIGRATION.BUMP}: updated: replaced by the 0.1.42 file", log) + self.assertIn("done: 2 file(s) changed", log) + again = self.run_migration() + self.assertIn(f"{ENVIRONMENT}: unchanged: already up to date", again) + self.assertIn("no repository changes were required", again) + self.assert_template_state() + + def test_only_the_menuinst_line_of_a_customised_environment_changes(self) -> None: + own = ENVIRONMENT_0_1_41.replace(" - certifi\n", " - certifi\n - napari=0.5 # our own\n").replace(" - menuinst>=2\n", " - menuinst>=2 # menus\n") + self.put(ENVIRONMENT, own.encode()) + self.run_migration() + self.assertEqual(lf(self.repo / ENVIRONMENT), own.replace(" - menuinst>=2 # menus\n", " - menuinst>=2,!=2.5.2 # menus\n")) + + def test_crlf_is_kept(self) -> None: + self.put(ENVIRONMENT, ENVIRONMENT_0_1_41.replace("\n", "\r\n").encode()) + 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 (ENVIRONMENT, *MIGRATION.FILES): + with self.subTest(file=str(relative)): + self.assertNotIn(b"\n", (self.repo / relative).read_bytes().replace(b"\r\n", b"")) + + def test_another_menuinst_requirement_is_skipped_with_what_to_do_by_hand(self) -> None: + for spec in ("menuinst>=2.1", "menuinst", "conda-forge::menuinst>=2", "menuinst=2.5.1"): + with self.subTest(spec=spec): + own = ENVIRONMENT_0_1_41.replace(" - menuinst>=2\n", f" - {spec}\n") + path = self.put(ENVIRONMENT, own.encode()) + log = self.run_migration() + self.assertIn(f"{ENVIRONMENT}: SKIPPED: customised menuinst requirement ({spec})", log) + self.assertIn("exclude menuinst 2.5.2", log) + self.assertEqual(path.read_text(encoding="utf-8"), own) + + def test_an_environment_without_menuinst_gets_a_note_and_no_line(self) -> None: + own = ENVIRONMENT_0_1_41.replace(" - menuinst>=2\n", "") + path = self.put(ENVIRONMENT, own.encode()) + log = self.run_migration() + self.assertIn(f"{ENVIRONMENT}: unchanged: no menuinst requirement (nothing was added)", log) + self.assertEqual(path.read_text(encoding="utf-8"), own) + self.assertNotIn("SKIPPED", log) + + def test_a_customised_bump_version_is_skipped_with_what_to_do_by_hand(self) -> None: + own = previous(MIGRATION.BUMP) + b"\n# our own change\n" + path = self.put(MIGRATION.BUMP, own) + log = self.run_migration() + self.assertIn(f"{MIGRATION.BUMP}: SKIPPED: customised (not the 0.1.41 template file)", log) + self.assertIn("join_wrapped_conclusion", log) + self.assertEqual(path.read_bytes(), own) + self.assertIn("done: 1 file(s) changed", log) + + def test_missing_files_are_not_created(self) -> None: + for relative in (ENVIRONMENT, *MIGRATION.FILES): + (self.repo / relative).unlink() + log = self.run_migration() + for relative in (ENVIRONMENT, *MIGRATION.FILES): + self.assertIn(f"{relative}: not present in this repository (nothing was created)", log) + self.assertEqual([p for p in self.repo.rglob("*") if p.is_file()], []) + + def test_an_unreadable_file_is_skipped_and_the_migration_does_not_raise(self) -> None: + self.put(ENVIRONMENT, b"\xff\xfe not utf-8\n") + log = self.run_migration() + self.assertIn(f"{ENVIRONMENT}: SKIPPED:", log) + self.assertIn(f"{MIGRATION.BUMP}: updated", log) + + 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.42"), encoding="utf-8") + command = [ + sys.executable, str(self.repo / ".template_sync/sync.py"), "--from-version", start, "--to-version", "0.1.42", + "--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_41(self) -> None: + result = self.sync("0.1.41") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("[migration 0.1.42]", result.stdout) + self.assert_template_state() + again = self.sync("0.1.41") + self.assertIn("[migration 0.1.42] done: no repository changes were required", again.stdout) + + +if __name__ == "__main__": + unittest.main()