Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .template_sync/manifest.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
template_version: 0.1.33
template_version: 0.1.34
migrations:
- from: 0.0.0
to: 0.0.1
Expand Down Expand Up @@ -105,3 +105,6 @@ migrations:
- from: 0.1.32
to: 0.1.33
script: migrations/v0_1_32_to_v0_1_33.py
- from: 0.1.33
to: 0.1.34
script: migrations/v0_1_33_to_v0_1_34.py
86 changes: 86 additions & 0 deletions .template_sync/migrations/v0_1_33_to_v0_1_34.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Template 0.1.33 -> 0.1.34: the installers use LabConstrictor-Tools v0.3.0-alpha.4, with which Fiji opens results as hyperstacks.

Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_34.md

Tools v0.3.0-alpha.4 (feature result_axes_v1, LabConstrictor-Tools #165) writes a result whose axes are known (declared with Axes, or
returned with WithAxes) as an ImageJ hyperstack, so Fiji opens a time-lapse with its time points and slices instead of one long stack.
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.3` to `v0.3.0-alpha.4`, 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_34.md"
TAG = "[migration 0.1.34]"
OLD_PIN = "v0.3.0-alpha.3"
NEW_PIN = "v0.3.0-alpha.4"
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.4 (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.")
18 changes: 18 additions & 0 deletions .tools/docs/migration_0_1_34.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Template 0.1.34: installers use LabConstrictor-Tools v0.3.0-alpha.4

Design note for the 0.1.34 migration (`.template_sync/migrations/v0_1_33_to_v0_1_34.py`). Context: [LabConstrictor-Tools #165](https://github.com/CellMigrationLab/LabConstrictor-Tools/pull/165).

## Why

With LabConstrictor-Tools v0.3.0-alpha.3, every result image reached Fiji as plain TIFF pages: a corrected 3D time-lapse opened as one long
stack (time points x slices) and had to be turned back into a hyperstack by hand. v0.3.0-alpha.4 writes a result whose axes are known, declared
with `Axes(...)` or returned with the new `WithAxes(array, axes)`, as an ImageJ hyperstack when its axes are in ImageJ order (T, Z, C, Y, X):
Fiji opens it with its time points, slices and channels. The array is never reordered, so napari and notebooks read the same data as before.
A tool uses it by returning its image with `WithAxes`; nothing changes for tools that do not.

## 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.3` to `v0.3.0-alpha.4`, 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.
2 changes: 1 addition & 1 deletion app/bash_bat_scripts/post_install.bat
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,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.3"
SET "LC_TOOLS_PIN=v0.3.0-alpha.4"
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
Expand Down
2 changes: 1 addition & 1 deletion app/bash_bat_scripts/post_install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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.3"
LC_TOOLS_PIN="v0.3.0-alpha.4"
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
Expand Down
3 changes: 3 additions & 0 deletions tests/_v0_1_33.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import importlib.util
from pathlib import Path

from _v0_1_34 import before_0_1_34

PIN_0_1_28 = "v0.3.0-alpha.2"
PIN_0_1_33 = "v0.3.0-alpha.3"
PINNED_FILES = (Path("app/bash_bat_scripts/post_install.sh"), Path("app/bash_bat_scripts/post_install.bat"))
Expand All @@ -31,6 +33,7 @@ def _apps_list_blocks() -> tuple[str, str, str, str]:

def before_0_1_33(relative: Path | str, data: bytes) -> bytes:
"""`data` (a live template file at `relative`) with the 0.1.33 pin moved back and the old Apps-list block; any other file as it is."""
data = before_0_1_34(relative, data)
if Path(relative) not in PINNED_FILES:
return data
data = data.replace(PIN_0_1_33.encode(), PIN_0_1_28.encode())
Expand Down
20 changes: 20 additions & 0 deletions tests/_v0_1_34.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Helper of the tests: a live template file as it was before template 0.1.34.

Template 0.1.34 moves the Tools pin (`LC_TOOLS_PIN` in post_install.sh / .bat) from v0.3.0-alpha.3 to v0.3.0-alpha.4. The tests of the older
migrations compare with the live files; `before_0_1_34` 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_34.py.
"""
from __future__ import annotations

from pathlib import Path

PIN_0_1_33 = "v0.3.0-alpha.3"
PIN_0_1_34 = "v0.3.0-alpha.4"
PINNED_FILES = (Path("app/bash_bat_scripts/post_install.sh"), Path("app/bash_bat_scripts/post_install.bat"))


def before_0_1_34(relative: Path | str, data: bytes) -> bytes:
"""`data` (a live template file at `relative`) with the 0.1.34 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_34.encode(), PIN_0_1_33.encode())
15 changes: 8 additions & 7 deletions tests/test_template_sync_0_1_33.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from types import ModuleType

from _v0_1_33 import before_0_1_33
from _v0_1_34 import before_0_1_34


ROOT = Path(__file__).resolve().parents[1]
Expand All @@ -34,29 +35,29 @@ def load(path: Path, name: str) -> ModuleType:


def live(relative: Path) -> bytes:
"""The live template file (0.1.33 is the newest migration)."""
return (ROOT / relative).read_bytes()
"""The live template file without the later pin move of 0.1.34 (tests/_v0_1_34.py)."""
return before_0_1_34(relative, (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 = (ROOT / relative).read_bytes().decode("utf-8")
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.assertIn("template_version: 0.1.33", text) # the newest migration: update when a later one is added
self.assertRegex(text, r"template_version: 0\.1\.(3[3-9]|[4-9][0-9])\b") # the current version is checked by the test of the newest migration
self.assertIn("script: migrations/v0_1_32_to_v0_1_33.py", text)
self.assertTrue((ROOT / ".tools/docs/migration_0_1_33.md").is_file())


class AppsListTemplateTests(unittest.TestCase):
def test_the_bat_reads_the_version_and_icon_at_install_time(self) -> None:
text = (ROOT / BAT).read_bytes().decode("utf-8")
text = live(BAT).decode("utf-8")
self.assertNotIn("logo.ico", text)
self.assertEqual(text.count(MIGRATION.NEW_ICON_REG), 1)
self.assertIn('findstr /B /C:"version:" "%PROJECT_ROOT%\\construct.yaml"`) DO SET "DISPLAY_VERSION=%%~B"', text)
Expand Down Expand Up @@ -125,8 +126,8 @@ def test_the_sync_script_runs_the_migration_from_0_1_32(self) -> None:
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.33]", result.stdout)
self.assertEqual((self.repo / SH).read_bytes(), (ROOT / SH).read_bytes())
self.assertEqual((self.repo / BAT).read_bytes(), (ROOT / BAT).read_bytes().replace(b"VERSION_NUMBER", b"0.1.3"))
self.assertEqual((self.repo / SH).read_bytes(), live(SH))
self.assertEqual((self.repo / BAT).read_bytes(), live(BAT).replace(b"VERSION_NUMBER", b"0.1.3"))


if __name__ == "__main__":
Expand Down
109 changes: 109 additions & 0 deletions tests/test_template_sync_0_1_34.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""Tests of the 0.1.34 migration: the Tools pin moves from v0.3.0-alpha.3 to v0.3.0-alpha.4 (Fiji opens results as hyperstacks, Tools #165)."""
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_33_to_v0_1_34.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_34")
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.34 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.assertIn("template_version: 0.1.34", text) # the newest migration: update when a later one is added
self.assertIn("script: migrations/v0_1_33_to_v0_1_34.py", text)
self.assertTrue((ROOT / ".tools/docs/migration_0_1_34.md").is_file())


class MigrationTests(unittest.TestCase):
def setUp(self) -> None:
self.repo = Path(tempfile.mkdtemp(prefix="lc_0_1_34_"))
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_33_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_33(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.34", manifest.read_text(encoding="utf-8")), encoding="utf-8")
command = [sys.executable, str(self.repo / ".template_sync/sync.py"), "--from-version", "0.1.33", "--to-version", "0.1.34", "--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.34]", result.stdout)
self.assertEqual((self.repo / SH).read_bytes(), live(SH))


if __name__ == "__main__":
unittest.main()
Loading