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
11 changes: 10 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.31
template_version: 0.1.34
migrations:
- from: 0.0.0
to: 0.0.1
Expand Down Expand Up @@ -99,3 +99,12 @@ migrations:
- from: 0.1.30
to: 0.1.31
script: migrations/v0_1_30_to_v0_1_31.py
- from: 0.1.31
to: 0.1.32
script: migrations/v0_1_31_to_v0_1_32.py
- 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
132 changes: 132 additions & 0 deletions .template_sync/migrations/v0_1_31_to_v0_1_32.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""Template 0.1.31 -> 0.1.32: the user docs link to the guide that owns a topic instead of repeating it.

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

Each topic of the LabConstrictor documentation is written on one page, and every other page links to it. The plugins' install steps belong
to the plugin guides on the website, and how to write tools belongs to LabConstrictor-Tools. The template keeps what is its own: where an
app declares its tools and what the installer does with them.

What this changes in an app repository (every step is independent, idempotent and never deletes anything):

1. .tools/docs/tools_bridge.md is replaced by the 0.1.32 guide when it is still the 0.1.31 template file. The guide no longer repeats the
plugins' install steps, the list of form markers and the test commands of LabConstrictor-Tools, or the version of the Tools pin; it links
to the owner guides instead. A file the app changed itself stays as it is (SKIPPED).
2. .tools/docs/install.md: "Where the app is listed" writes napari in lower case and links to the guide that says how to run the tools.
3. .tools/docs/README.md: the entry of the tools guide writes napari in lower case.

Steps 2 and 3 replace one exact piece of template text each and leave a file alone when that text is not there (SKIPPED). The line endings
of each file are kept. The changes reach users with the app's next release.
"""
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_32.md"
TAG = "[migration 0.1.32]"
RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_31_to_v0_1_32"
PREVIOUS_ROOT = RESOURCE_ROOT / "previous"

TOOLS_DOC = Path(".tools/docs/tools_bridge.md")
INSTALL_DOC = Path(".tools/docs/install.md")
DOCS_INDEX = Path(".tools/docs/README.md")

SITE = "https://cellmigrationlab.github.io/LabConstrictor-Site/"

# Files replaced whole, only when they are the 0.1.31 template file (compared with LF line endings).
WHOLE_FILES = (TOOLS_DOC,)

# (old, new) pairs, written with LF line endings; a file with CRLF line endings gets them with CRLF.
EDITS: dict[Path, tuple[tuple[str, str], ...]] = {
INSTALL_DOC: (
("If the app ships tools for Napari, Fiji or QuPath, the installer registers them with LabConstrictor Tools",
"If the app ships tools for napari, Fiji or QuPath, the installer registers them with LabConstrictor Tools"),
("with `hosts: [notebook, napari]` the app is listed in Napari, and not in Fiji or QuPath.",
"with `hosts: [notebook, napari]` the app is listed in napari, and not in Fiji or QuPath."),
("so it is listed in every host; ...`).\n",
"so it is listed in every host; ...`).\n"
"\n"
"To run the tools, install the plugin for your image software once: see"
f" [Use apps inside napari, Fiji and QuPath]({SITE}guides/image-software/).\n"),
),
DOCS_INDEX: (
("- [Expose tools to Napari, Fiji and QuPath (experimental)](tools_bridge.md)\n",
"- [Expose tools to napari, Fiji and QuPath (experimental)](tools_bridge.md)\n"),
),
}
FILES = (*WHOLE_FILES, *EDITS)


def log(message: str) -> None:
print(f"{TAG} {message}")


def apply_edits(text_lf: str, edits: tuple[tuple[str, str], ...]) -> tuple[str, int, int]:
"""`text_lf` with each pair applied whose old text occurs exactly once and whose new text is not there yet. Returns the text, the
pairs applied and the pairs not found (neither the old text once nor the new text present)."""
applied = missing = 0
for old, new in edits:
if new in text_lf:
continue
if text_lf.count(old) == 1:
text_lf = text_lf.replace(old, new)
applied += 1
else:
missing += 1
return text_lf, applied, missing


def replaced_file(relative: Path, text_lf: str) -> tuple[str, str]:
"""The 0.1.32 text of a whole-file step, and what was done. The text is unchanged when the file is not the 0.1.31 template file."""
new = (RESOURCE_ROOT / relative).read_bytes().decode("utf-8").replace("\r\n", "\n")
if text_lf == new:
return text_lf, "already up to date"
previous = (PREVIOUS_ROOT / relative).read_bytes().decode("utf-8").replace("\r\n", "\n")
if text_lf != previous:
return text_lf, f"SKIPPED: customised (not the 0.1.31 template file), so it was left unchanged; compare it with the template's file. See {DOCS_URL}"
return new, "replaced by the 0.1.32 guide"


def edited_file(relative: Path, text_lf: str) -> tuple[str, str]:
"""The text after the exact-text edits of `relative`, and what was done."""
edits = EDITS[relative]
text, applied, missing = apply_edits(text_lf, edits)
if not missing:
return text, f"{applied} text change(s)" if applied else "already up to date"
if missing == len(edits):
return text, f"SKIPPED: customised (the 0.1.31 text was not found), so it was left unchanged. See {DOCS_URL}"
skipped = f"SKIPPED {missing} passage(s) that differ from the template text (left as they are). See {DOCS_URL}"
return text, f"{applied} text change(s); {skipped}" if applied else f"the other changes are there; {skipped}"


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 relative in WHOLE_FILES else edited_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.32 documentation changes (idempotent, surgical, never raises for a customised file)."""
_ = 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 changes reach users with the next release of the app.")
else:
log("done: no repository changes were required.")
118 changes: 118 additions & 0 deletions .template_sync/migrations/v0_1_32_to_v0_1_33.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""Template 0.1.32 -> 0.1.33: Tools v0.3.0-alpha.3 (Fiji opens results of 3 or 4 planes); the Windows Apps list shows the right version and icon.

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

Tools v0.3.0-alpha.2 wrote a result image of 3 or 4 planes (3 channels, 3 timepoints) as one page of colour samples, which Fiji cannot open
unless it is 8-bit (LabConstrictor-Tools #163); v0.3.0-alpha.3 writes it as grey pages. What this changes in an app repository (each step is
independent, idempotent and 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.2` to `v0.3.0-alpha.3`, 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.

2. post_install.bat registered the app in the Windows Apps list with the version written at initialisation (`DISPLAY_VERSION`; no
release ever changed it) and the icon `logo.ico`, a file no installer contains. The version is now read at install time from the
bundled construct.yaml (the setup-time value stays as a fallback), and the icon is the first .ico the installer copied into the app
folder; without one, no icon entry is written. Only the template's exact lines are replaced; a changed script stays as it is, with a note.

Since template 0.1.32 the Tools guide no longer names the pin, so no document changes. Both 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_33.md"
TAG = "[migration 0.1.33]"
OLD_PIN = "v0.3.0-alpha.2"
NEW_PIN = "v0.3.0-alpha.3"
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=")([^"]*)(".*)$')
# The Windows Apps list block of post_install.bat (CRLF in the script; matched without line endings). The app's own setup-time version is kept.
OLD_ARP = re.compile(r'^SET "DISPLAY_ICON=%PROJECT_ROOT%\\logo\.ico"\r?\nSET "DISPLAY_VERSION=([^"\r\n]*)"(?=\r?\n)', re.MULTILINE)
NEW_ARP_LINES = (
"REM Windows Apps list: the version of this installer (the version: line of the bundled construct.yaml, written by each release),",
"REM and the app icon the installer copied (the first .ico in the app folder); no icon entry when there is none.",
'SET "DISPLAY_VERSION={version}"',
'IF EXIST "%PROJECT_ROOT%\\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\\construct.yaml"`) DO SET "DISPLAY_VERSION=%%~B"',
'SET "DISPLAY_ICON="',
'FOR %%I IN ("%PROJECT_ROOT%\\*.ico") DO IF NOT DEFINED DISPLAY_ICON SET "DISPLAY_ICON=%%~fI"',
)
OLD_ICON_REG = 'reg add "%ARP_KEY%" /v DisplayIcon /d "%DISPLAY_ICON%" /f >> "%LOG_FILE%" 2>&1'
NEW_ICON_REG = "IF DEFINED DISPLAY_ICON " + OLD_ICON_REG
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 fix_apps_list(path: Path) -> str:
text = read(path)
if NEW_ICON_REG in text:
return "already reads the Apps-list version and icon at install time: unchanged"
match = OLD_ARP.search(text)
if match is None or text.count(OLD_ICON_REG) != 1:
return "has no template Apps-list block (changed by hand): left as it is"
newline = "\r\n" if "\r\n" in text else "\n"
block = newline.join(NEW_ARP_LINES).replace("{version}", match.group(1))
text = text[: match.start()] + block + text[match.end() :]
write(path, text.replace(OLD_ICON_REG, NEW_ICON_REG))
return "updated: the Windows Apps list shows the installed version and the app icon"


def migrate(repo_root: Path, context: dict[str, Any]) -> None:
"""Move the Tools pin to v0.3.0-alpha.3 and fix the Windows Apps-list entry (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)),
(POST_INSTALL_BAT, fix_apps_list))
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.")
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.")
Loading
Loading