diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml index 0c5dabe..ad9389a 100644 --- a/.template_sync/manifest.yaml +++ b/.template_sync/manifest.yaml @@ -1,4 +1,4 @@ -template_version: 0.1.45 +template_version: 0.1.46 migrations: - from: 0.0.0 to: 0.0.1 @@ -141,3 +141,6 @@ migrations: - from: 0.1.44 to: 0.1.45 script: migrations/v0_1_44_to_v0_1_45.py + - from: 0.1.45 + to: 0.1.46 + script: migrations/v0_1_45_to_v0_1_46.py diff --git a/.template_sync/migrations/v0_1_45_to_v0_1_46.py b/.template_sync/migrations/v0_1_45_to_v0_1_46.py new file mode 100644 index 0000000..7e35fdc --- /dev/null +++ b/.template_sync/migrations/v0_1_45_to_v0_1_46.py @@ -0,0 +1,86 @@ +"""Template 0.1.45 -> 0.1.46: the installers use LabConstrictor-Tools v0.3.0-alpha.6, which adds @tool(run_again=False). + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_46.md + +Tools v0.3.0-alpha.6 (LabConstrictor-Tools #177) lets a tool say that its form is not shown again after a completed run in a host that brings +it back (Fiji v0.1.0-alpha.11), for a tool seldom run twice in a row such as a long training. Nothing changes for other tools. +What this changes in an app repository (idempotent, never deletes anything): + +1. `LC_TOOLS_PIN` in app/bash_bat_scripts/post_install.sh and post_install.bat moves from `v0.3.0-alpha.5` to `v0.3.0-alpha.6`, ONLY when the + line still holds exactly the old template value. An app with its own pin, a script without a pin line or without the Tools hook stays as it is, + with a note. + +The pin reaches 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_46.md" +TAG = "[migration 0.1.46]" +OLD_PIN = "v0.3.0-alpha.5" +NEW_PIN = "v0.3.0-alpha.6" +POST_INSTALL_SH = Path("app/bash_bat_scripts/post_install.sh") +POST_INSTALL_BAT = Path("app/bash_bat_scripts/post_install.bat") +SH_PIN_LINE = re.compile(r'^([ \t]*LC_TOOLS_PIN=")([^"]*)(".*)$') +BAT_PIN_LINE = re.compile(r'^([ \t]*SET "LC_TOOLS_PIN=)([^"]*)(".*)$', re.IGNORECASE) + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def read(path: Path) -> str: + """The file's text with its line endings as they are (bytes decoded as UTF-8).""" + return path.read_bytes().decode("utf-8") + + +def write(path: Path, text: str) -> None: + path.write_bytes(text.encode("utf-8")) + + +def move_pin(path: Path, pattern: re.Pattern[str]) -> str: + text = read(path) + if "labconstrictor_tools" not in text: + return "has no Tools bridge hook: nothing to move" + lines = text.splitlines(keepends=True) + hits = [(index, match) for index, line in enumerate(lines) if (match := pattern.match(line.rstrip("\r\n")))] + if not hits: + return "has no LC_TOOLS_PIN line (unpinned source or its own Tools source): left as it is" + if len(hits) > 1: + return f"has {len(hits)} LC_TOOLS_PIN lines: left as it is, set the pin by hand to {NEW_PIN}" + index, match = hits[0] + current = match.group(2) + if current == NEW_PIN: + return f"already pins Tools {NEW_PIN}: unchanged" + if current != OLD_PIN: + return f"has its own pin {current}: left as it is (the template pin is now {NEW_PIN})" + ending = lines[index][len(lines[index].rstrip("\r\n")) :] + lines[index] = f"{match.group(1)}{NEW_PIN}{match.group(3)}{ending}" + write(path, "".join(lines)) + return f"updated: Tools pin {OLD_PIN} -> {NEW_PIN}" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Move the Tools pin to v0.3.0-alpha.6 (idempotent, surgical, never raises for a customised file).""" + _ = context + changed = 0 + steps = ((POST_INSTALL_SH, lambda p: move_pin(p, SH_PIN_LINE)), (POST_INSTALL_BAT, lambda p: move_pin(p, BAT_PIN_LINE))) + for relative, step in steps: + path = repo_root / relative + if not path.is_file(): + log(f"{relative}: not present in this repository (nothing was created)") + continue + try: + status = step(path) + 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} change(s). They reach users with the next release of the app. See {DOCS_URL}") + else: + log("done: no repository changes were required.") diff --git a/.tools/docs/migration_0_1_46.md b/.tools/docs/migration_0_1_46.md new file mode 100644 index 0000000..c20faf3 --- /dev/null +++ b/.tools/docs/migration_0_1_46.md @@ -0,0 +1,17 @@ +# Template 0.1.46: installers use LabConstrictor-Tools v0.3.0-alpha.6 + +Design note for the 0.1.46 migration (`.template_sync/migrations/v0_1_45_to_v0_1_46.py`). Context: [LabConstrictor-Tools #177](https://github.com/CellMigrationLab/LabConstrictor-Tools/pull/177). + +## Why + +In Fiji, a tool's form comes back after every run started from the menu, so the same tool can run again without the choosers. After a long +training (LabConstrictor-CAREamics) testers read the form coming back as a fault. LabConstrictor-Tools v0.3.0-alpha.6 adds +`@tool(..., run_again=False)`: Fiji v0.1.0-alpha.11 then does not show that tool's form again after a run that completed (after a failed or +cancelled run it still does). Nothing changes for other tools, and an older Fiji ignores the setting. + +## What changes in an app repository + +* `LC_TOOLS_PIN` in `app/bash_bat_scripts/post_install.sh` and `post_install.bat` moves from `v0.3.0-alpha.5` to `v0.3.0-alpha.6`, only when the + line still holds the template's old value. A pin you set yourself is left as it is, and the sync log says so. + +Nothing else changes. The new pin reaches users with the app's next release. The tag `v0.3.0-alpha.6` must exist before such an installer is used. diff --git a/app/bash_bat_scripts/post_install.bat b/app/bash_bat_scripts/post_install.bat index bb83847..cfd4bf7 100644 --- a/app/bash_bat_scripts/post_install.bat +++ b/app/bash_bat_scripts/post_install.bat @@ -223,7 +223,7 @@ REM This step must never fail the installation: a failure is logged as a WARNING REM LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). REM Default source: the GitHub archive of the labconstrictor-tools release TAG below (a plain zip: no git needed on the user's computer), REM because the package is not on PyPI yet. Once it is, use "labconstrictor-tools" here. To move the pin, change only this tag. -SET "LC_TOOLS_PIN=v0.3.0-alpha.5" +SET "LC_TOOLS_PIN=v0.3.0-alpha.6" IF NOT DEFINED LC_TOOLS_SPEC SET "LC_TOOLS_SPEC=https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/%LC_TOOLS_PIN%.zip" SET "LC_TOOLS_READY=0" "%PYTHON_EXE%" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('PYTHON_PROJ_NAME_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 diff --git a/app/bash_bat_scripts/post_install.sh b/app/bash_bat_scripts/post_install.sh index 9f05cb2..3dfcaff 100644 --- a/app/bash_bat_scripts/post_install.sh +++ b/app/bash_bat_scripts/post_install.sh @@ -76,7 +76,7 @@ if [ -f "$PROJECT_ROOT/setup.py" ]; then # (it never fails the installation by itself). LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). # Default source: the GitHub archive of the labconstrictor-tools release TAG below (a plain zip: no git needed on the user's computer), # because the package is not on PyPI yet. Once it is, use "labconstrictor-tools" here. To move the pin, change only this tag. - LC_TOOLS_PIN="v0.3.0-alpha.5" + LC_TOOLS_PIN="v0.3.0-alpha.6" LC_TOOLS_MODULE="PYTHON_PROJ_NAME_lc_tools" LC_TOOLS_READY=0 if "$PYTHON_EXE" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('$LC_TOOLS_MODULE') else 1)" >> "$LOG_FILE" 2>&1; then diff --git a/tests/_v0_1_45.py b/tests/_v0_1_45.py index 85a3132..8be8242 100644 --- a/tests/_v0_1_45.py +++ b/tests/_v0_1_45.py @@ -10,6 +10,8 @@ from pathlib import Path from types import ModuleType +from _v0_1_46 import before_0_1_46 + ROOT = Path(__file__).resolve().parents[1] MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_44_to_v0_1_45.py" @@ -25,6 +27,7 @@ def _migration() -> ModuleType: def before_0_1_45(relative: Path | str, data: bytes) -> bytes: """`data` (a live template file at `relative`) without the 0.1.45 change; any other file is returned as it is.""" + data = before_0_1_46(relative, data) migration = _migration() relative = Path(relative) text = data.decode("utf-8") diff --git a/tests/_v0_1_46.py b/tests/_v0_1_46.py new file mode 100644 index 0000000..763b376 --- /dev/null +++ b/tests/_v0_1_46.py @@ -0,0 +1,20 @@ +"""Helper of the tests: a live template file as it was before template 0.1.46. + +Template 0.1.46 moves the Tools pin (`LC_TOOLS_PIN` in post_install.sh / .bat) from v0.3.0-alpha.5 to v0.3.0-alpha.6. The tests of the older +migrations compare with the live files; `before_0_1_46` gives the bytes of a live file with the pin moved back, so they keep checking what they +checked. The move itself is tested in test_template_sync_0_1_46.py. +""" +from __future__ import annotations + +from pathlib import Path + +PIN_0_1_45 = "v0.3.0-alpha.5" +PIN_0_1_46 = "v0.3.0-alpha.6" +PINNED_FILES = (Path("app/bash_bat_scripts/post_install.sh"), Path("app/bash_bat_scripts/post_install.bat")) + + +def before_0_1_46(relative: Path | str, data: bytes) -> bytes: + """`data` (a live template file at `relative`) with the 0.1.46 pin moved back; any other file is returned as it is.""" + if Path(relative) not in PINNED_FILES: + return data + return data.replace(PIN_0_1_46.encode(), PIN_0_1_45.encode()) diff --git a/tests/test_template_sync_0_1_43.py b/tests/test_template_sync_0_1_43.py index bd8dd98..7b10ea8 100644 --- a/tests/test_template_sync_0_1_43.py +++ b/tests/test_template_sync_0_1_43.py @@ -32,8 +32,10 @@ def load(path: Path, name: str) -> ModuleType: def live(relative: Path) -> bytes: - """The live template file (0.1.43 is the newest migration).""" - return (ROOT / relative).read_bytes() + """A template file as this migration left it (the pin move of 0.1.46 undone).""" + from _v0_1_46 import before_0_1_46 + + return before_0_1_46(relative, (ROOT / relative).read_bytes()) class TemplateTests(unittest.TestCase): diff --git a/tests/test_template_sync_0_1_45.py b/tests/test_template_sync_0_1_45.py index 9573ada..92cde9a 100644 --- a/tests/test_template_sync_0_1_45.py +++ b/tests/test_template_sync_0_1_45.py @@ -36,7 +36,10 @@ def load(path: Path, name: str) -> ModuleType: def live(relative: Path) -> bytes: - return (ROOT / relative).read_bytes() + """A template file as this migration left it (the pin move of 0.1.46 undone).""" + from _v0_1_46 import before_0_1_46 + + return before_0_1_46(relative, (ROOT / relative).read_bytes()) def filled(data: bytes) -> bytes: diff --git a/tests/test_template_sync_0_1_46.py b/tests/test_template_sync_0_1_46.py new file mode 100644 index 0000000..376447f --- /dev/null +++ b/tests/test_template_sync_0_1_46.py @@ -0,0 +1,119 @@ +"""Tests of the 0.1.46 migration: the Tools pin moves from v0.3.0-alpha.5 to v0.3.0-alpha.6 (@tool(run_again=False), Tools #177).""" +from __future__ import annotations + +import importlib.util +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_45_to_v0_1_46.py" + + +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_46") +SH, BAT = MIGRATION.POST_INSTALL_SH, MIGRATION.POST_INSTALL_BAT +OLD, NEW = MIGRATION.OLD_PIN, MIGRATION.NEW_PIN + + +def live(relative: Path) -> bytes: + """The live template file (0.1.46 is the newest migration).""" + return (ROOT / relative).read_bytes() + + +class TemplateTests(unittest.TestCase): + def test_the_template_pins_the_new_tag_once_per_script(self) -> None: + for relative in (SH, BAT): + text = live(relative).decode("utf-8") + with self.subTest(file=str(relative)): + self.assertEqual(text.count(NEW), 1) + self.assertNotIn(OLD, text) + self.assertIn("\r\n", (ROOT / BAT).read_bytes().decode("utf-8"), "post_install.bat stays CRLF") + + def test_the_manifest_lists_the_migration_and_the_version(self) -> None: + text = (ROOT / ".template_sync/manifest.yaml").read_text(encoding="utf-8") + self.assertRegex(text, r"template_version: 0\.1\.(4[6-9]|[5-9][0-9])\b") + self.assertIn("script: migrations/v0_1_45_to_v0_1_46.py", text) + self.assertTrue((ROOT / ".tools/docs/migration_0_1_46.md").is_file()) + self.assertIn(".tools/docs/migration_0_1_46.md", MIGRATION_PATH.read_text(encoding="utf-8")) + self.assertNotIn("migration_0_1_46.md", (ROOT / ".tools/docs/README.md").read_text(encoding="utf-8")) + + def test_the_older_tests_see_the_0_1_45_pin(self) -> None: + from _v0_1_46 import before_0_1_46 + + for relative in (SH, BAT): + with self.subTest(file=str(relative)): + self.assertEqual(before_0_1_46(relative, live(relative)), live(relative).replace(NEW.encode(), OLD.encode())) + self.assertEqual(before_0_1_46("construct.yaml", NEW.encode()), NEW.encode()) + + +class MigrationTests(unittest.TestCase): + def setUp(self) -> None: + self.repo = Path(tempfile.mkdtemp(prefix="lc_0_1_46_")) + for relative in (SH, BAT): + target = self.repo / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(live(relative).replace(NEW.encode(), OLD.encode())) + + def tearDown(self) -> None: + shutil.rmtree(self.repo, ignore_errors=True) + + def run_migration(self) -> str: + out = StringIO() + with redirect_stdout(out): + MIGRATION.migrate(self.repo, {}) + return out.getvalue() + + def test_an_app_of_0_1_45_gets_the_template_files_and_a_second_run_changes_nothing(self) -> None: + log = self.run_migration() + for relative in (SH, BAT): + with self.subTest(file=str(relative)): + self.assertEqual((self.repo / relative).read_bytes(), live(relative)) + self.assertEqual(log.count(f"updated: Tools pin {OLD} -> {NEW}"), 2, log) + self.assertIn("2 change(s)", log) + self.assertIn("no repository changes were required", self.run_migration()) + + def test_an_own_pin_is_left_alone(self) -> None: + sh = self.repo / SH + sh.write_bytes(sh.read_bytes().replace(OLD.encode(), b"v0.2.0-rc.2")) + before = sh.read_bytes() + log = self.run_migration() + self.assertEqual(sh.read_bytes(), before) + self.assertIn("has its own pin v0.2.0-rc.2: left as it is", log) + + def test_a_script_without_the_hook_or_files_missing_are_left_alone(self) -> None: + (self.repo / SH).write_text("#!/bin/bash\necho hi\n", encoding="utf-8") + (self.repo / BAT).unlink() + log = self.run_migration() + self.assertIn("has no Tools bridge hook", log) + self.assertIn(f"{BAT}: not present in this repository", log) + self.assertFalse((self.repo / BAT).exists()) + + def test_the_sync_script_runs_the_migration_from_0_1_45(self) -> None: + shutil.copytree(ROOT / ".template_sync", self.repo / ".template_sync") + manifest = self.repo / ".template_sync/manifest.yaml" + manifest.write_text(re.sub(r"template_version: [0-9.]+", "template_version: 0.1.46", manifest.read_text(encoding="utf-8")), encoding="utf-8") + command = [sys.executable, str(self.repo / ".template_sync/sync.py"), "--from-version", "0.1.45", "--to-version", "0.1.46", "--repository-root", str(self.repo)] + result = subprocess.run(command, capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("[migration 0.1.46]", result.stdout) + self.assertEqual((self.repo / SH).read_bytes(), live(SH)) + + +if __name__ == "__main__": + unittest.main()