From e5afa5f51e12f5b34a97c82fced6559181c033e6 Mon Sep 17 00:00:00 2001 From: IvanHCenalmor <47150974+IvanHCenalmor@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:21:59 +0000 Subject: [PATCH] Sync template to version 0.1.32 --- .github/workflows/release_constructor.yml | 5 + .../workflows/update_on_notebook_change.yml | 4 +- .template_sync/manifest.yaml | 20 +- .../migrations/v0_1_26_to_v0_1_27.py | 99 +++ .../migrations/v0_1_27_to_v0_1_28.py | 97 +++ .../migrations/v0_1_28_to_v0_1_29.py | 141 ++++ .../migrations/v0_1_29_to_v0_1_30.py | 124 +++ .../migrations/v0_1_30_to_v0_1_31.py | 505 ++++++++++++ .../migrations/v0_1_31_to_v0_1_32.py | 132 +++ .../schema/labconstrictor-app.schema.json | 19 + .../docs/app_manifest_host_requirements.md | 18 + .../schema/labconstrictor-app.schema.json | 91 +++ .../.tools/python/merge_requirements.py | 755 ++++++++++++++++++ .../.tools/python/merge_requirements.py | 543 +++++++++++++ .../.tools/docs/tools_bridge.md | 81 ++ .../previous/.tools/docs/tools_bridge.md | 59 ++ .tools/docs/README.md | 2 +- .tools/docs/app_manifest.md | 27 +- .tools/docs/tools_bridge.md | 107 ++- .tools/docs/use_cases.md | 4 +- .tools/python/merge_requirements.py | 500 ++++++++---- .tools/python/update_changelog.py | 5 +- .tools/requirements.txt | 2 + .tools/schema/labconstrictor-app.schema.json | 23 +- .tools/templates/Welcome_template.ipynb | 147 +++- app/bash_bat_scripts/post_install.bat | 4 +- app/bash_bat_scripts/post_install.sh | 4 +- labconstrictor-app.yaml | 2 +- 28 files changed, 3272 insertions(+), 248 deletions(-) create mode 100644 .template_sync/migrations/v0_1_26_to_v0_1_27.py create mode 100644 .template_sync/migrations/v0_1_27_to_v0_1_28.py create mode 100644 .template_sync/migrations/v0_1_28_to_v0_1_29.py create mode 100644 .template_sync/migrations/v0_1_29_to_v0_1_30.py create mode 100644 .template_sync/migrations/v0_1_30_to_v0_1_31.py create mode 100644 .template_sync/migrations/v0_1_31_to_v0_1_32.py create mode 100644 .template_sync/resources/v0_1_26_to_v0_1_27/.tools/docs/app_manifest_host_requirements.md create mode 100644 .template_sync/resources/v0_1_26_to_v0_1_27/.tools/schema/labconstrictor-app.schema.json create mode 100644 .template_sync/resources/v0_1_30_to_v0_1_31/.tools/python/merge_requirements.py create mode 100644 .template_sync/resources/v0_1_30_to_v0_1_31/previous/.tools/python/merge_requirements.py create mode 100644 .template_sync/resources/v0_1_31_to_v0_1_32/.tools/docs/tools_bridge.md create mode 100644 .template_sync/resources/v0_1_31_to_v0_1_32/previous/.tools/docs/tools_bridge.md diff --git a/.github/workflows/release_constructor.yml b/.github/workflows/release_constructor.yml index fe5ec41..fffa59f 100644 --- a/.github/workflows/release_constructor.yml +++ b/.github/workflows/release_constructor.yml @@ -68,6 +68,11 @@ jobs: "check_placeholders.py" \ .tools/python/check_placeholders.py \ python .tools/python/check_placeholders.py + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "merge_requirements.py --check" \ + .tools/python/merge_requirements.py \ + python .tools/python/merge_requirements.py --source-dir notebooks --output requirements.txt --check - name: Commit updated versioned files diff --git a/.github/workflows/update_on_notebook_change.yml b/.github/workflows/update_on_notebook_change.yml index 4a8c03b..9c779a5 100644 --- a/.github/workflows/update_on_notebook_change.yml +++ b/.github/workflows/update_on_notebook_change.yml @@ -7,6 +7,7 @@ on: - 'notebooks/**/*.ipynb' - 'notebooks/notebook_latest_versions.yaml' - 'notebooks/**/requirements.yaml' + - 'requirements_overrides.yaml' workflow_dispatch: # One run of this workflow at a time per branch. The src workflow has its own group: the two can run at the same time, @@ -45,6 +46,7 @@ jobs: notebooks/**/*.ipynb notebooks/notebook_latest_versions.yaml notebooks/**/requirements.yaml + requirements_overrides.yaml - name: Syncronize notebook versions if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') @@ -92,7 +94,7 @@ jobs: python .tools/python/bump_notebook_README.py - name: Run merge script - if: github.event_name == 'workflow_dispatch' || contains(steps.changed-files.outputs.all_changed_files, 'requirements.yaml') + if: github.event_name == 'workflow_dispatch' || contains(steps.changed-files.outputs.all_changed_files, 'requirements.yaml') || contains(steps.changed-files.outputs.all_changed_files, 'requirements_overrides.yaml') run: | bash .tools/bash/run_with_context.sh \ artifacts/error_log_document.log \ diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml index 316674c..7de3f90 100644 --- a/.template_sync/manifest.yaml +++ b/.template_sync/manifest.yaml @@ -1,4 +1,4 @@ -template_version: 0.1.26 +template_version: 0.1.32 migrations: - from: 0.0.0 to: 0.0.1 @@ -84,3 +84,21 @@ migrations: - from: 0.1.25 to: 0.1.26 script: migrations/v0_1_25_to_v0_1_26.py + - from: 0.1.26 + to: 0.1.27 + script: migrations/v0_1_26_to_v0_1_27.py + - from: 0.1.27 + to: 0.1.28 + script: migrations/v0_1_27_to_v0_1_28.py + - from: 0.1.28 + to: 0.1.29 + script: migrations/v0_1_28_to_v0_1_29.py + - from: 0.1.29 + to: 0.1.30 + script: migrations/v0_1_29_to_v0_1_30.py + - 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 diff --git a/.template_sync/migrations/v0_1_26_to_v0_1_27.py b/.template_sync/migrations/v0_1_26_to_v0_1_27.py new file mode 100644 index 0000000..546548e --- /dev/null +++ b/.template_sync/migrations/v0_1_26_to_v0_1_27.py @@ -0,0 +1,99 @@ +"""Template 0.1.26 -> 0.1.27: an app can say which napari, Fiji or QuPath plugin version its tools need (host_requirements). + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_27.md +Proposal: https://github.com/CellMigrationLab/LabConstrictor-Tools/issues/155 + +The App Centre schema gained an optional field, host_requirements. The template's copy of the schema rejects fields it does not +know, so without this migration an app that adds the field fails its "Check App Centre manifest" workflow. What this changes in an +app repository (each step is independent, idempotent and never deletes anything): + +1. .tools/schema/labconstrictor-app.schema.json: replaced by the template's copy (the template owns it; it must equal the App Centre's + schema). A missing schema is not created: the app has no manifest check to update. +2. .tools/docs/app_manifest.md: the section "Plugin versions your tools need (optional)" goes before "## The automatic check". A page + that already has the section is unchanged; a page without that heading gets it before its Previous / Home / Next links, or at + its end. Line endings are kept. + +labconstrictor-app.yaml belongs to the app and is never created or changed. +""" +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_27.md" +TAG = "[migration 0.1.27]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_26_to_v0_1_27" + +SCHEMA = Path(".tools/schema/labconstrictor-app.schema.json") +MANIFEST_PAGE = Path(".tools/docs/app_manifest.md") +SECTION = Path(".tools/docs/app_manifest_host_requirements.md") + +SECTION_HEADING = "## Plugin versions your tools need (optional)" +ANCHOR = "## The automatic check" +FOOTER = re.compile(r'^---[ \t]*\n(?:[ \t]*\n)*
.*?
[ \t]*(?:\n|$)', re.MULTILINE | re.DOTALL) + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def resource_bytes(relative: Path) -> bytes: + return (RESOURCE_ROOT / relative).read_bytes() + + +def with_section(text_lf: str, section: str) -> str: + """The page with the section before "## The automatic check", else before its links, else at its end.""" + lines = text_lf.split("\n") + for index, line in enumerate(lines): + if line.rstrip() == ANCHOR: + before = "\n".join(lines[:index]).rstrip("\n") + return before + "\n\n" + section.rstrip("\n") + "\n\n" + "\n".join(lines[index:]) + footers = list(FOOTER.finditer(text_lf)) + if footers: + start = footers[-1].start() + return text_lf[:start].rstrip("\n") + "\n\n" + section.rstrip("\n") + "\n\n" + text_lf[start:] + return text_lf.rstrip("\n") + "\n\n" + section + + +def update_schema(repo_root: Path) -> str: + path = repo_root / SCHEMA + if not path.is_file(): + return "not present in this repository (nothing was created)" + data = resource_bytes(SCHEMA) + if path.read_bytes() == data: + return "unchanged: already the template's copy" + path.write_bytes(data) + return "updated: the template's copy (accepts host_requirements)" + + +def update_page(repo_root: Path) -> str: + path = repo_root / MANIFEST_PAGE + if not path.is_file(): + return "not present in this repository (nothing was created)" + raw = path.read_bytes().decode("utf-8") + newline = "\r\n" if "\r\n" in raw else "\n" + text_lf = raw.replace("\r\n", "\n") + if SECTION_HEADING in (line.rstrip() for line in text_lf.split("\n")): + return "unchanged: already has the section on plugin versions" + section = resource_bytes(SECTION).decode("utf-8").replace("\r\n", "\n") + path.write_bytes(with_section(text_lf, section).replace("\n", newline).encode("utf-8")) + return "updated: added the section on plugin versions" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Refresh the schema copy and document host_requirements (idempotent, never deletes).""" + _ = context + changed = 0 + for name, step in ((SCHEMA, update_schema), (MANIFEST_PAGE, update_page)): + try: + status = step(repo_root) + except (OSError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + changed += status.startswith("updated") + log(f"{name}: {status}") + if changed: + log(f"done: {changed} file(s) changed. See {DOCS_URL}") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_27_to_v0_1_28.py b/.template_sync/migrations/v0_1_27_to_v0_1_28.py new file mode 100644 index 0000000..83266b8 --- /dev/null +++ b/.template_sync/migrations/v0_1_27_to_v0_1_28.py @@ -0,0 +1,97 @@ +"""Template 0.1.27 -> 0.1.28: the installers use LabConstrictor-Tools v0.3.0-alpha.2, which registers an app's host_requirements. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_28.md + +Tools v0.3.0-alpha.2 (feature host_requirements_v1, LabConstrictor-Tools #155) copies the `host_requirements:` block of labconstrictor-app.yaml +into the registry entry, so napari, Fiji and QuPath can tell a person with an older plugin to update it. Older Tools ignore the block. 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.1` to `v0.3.0-alpha.2`, 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. `.tools/docs/tools_bridge.md`: the tag name `v0.3.0-alpha.1` is replaced by `v0.3.0-alpha.2` (the guide names the pinned tag). + +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_28.md" +TAG = "[migration 0.1.28]" +OLD_PIN = "v0.3.0-alpha.1" +NEW_PIN = "v0.3.0-alpha.2" +POST_INSTALL_SH = Path("app/bash_bat_scripts/post_install.sh") +POST_INSTALL_BAT = Path("app/bash_bat_scripts/post_install.bat") +TOOLS_DOC = Path(".tools/docs/tools_bridge.md") +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 refresh_guide(path: Path) -> str: + text = read(path) + if OLD_PIN not in text: + return "does not name the old tag: unchanged" + write(path, text.replace(OLD_PIN, NEW_PIN)) + return f"updated: names {NEW_PIN}" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Move the Tools pin to v0.3.0-alpha.2 and refresh the Tools guide (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)), + (TOOLS_DOC, refresh_guide)) + 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} file(s) changed. The pin reaches users with the next release of the app. See {DOCS_URL}") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_28_to_v0_1_29.py b/.template_sync/migrations/v0_1_28_to_v0_1_29.py new file mode 100644 index 0000000..c426e78 --- /dev/null +++ b/.template_sync/migrations/v0_1_28_to_v0_1_29.py @@ -0,0 +1,141 @@ +"""Template 0.1.28 -> 0.1.29: text corrections, and the notebook changelog no longer quotes commit trailers. + +What this changes in an app repository. Every change replaces one exact piece of template text and is skipped when that text is not +there (a file the app changed itself stays as it is, with a note). Each step is independent and idempotent; nothing is created or deleted. + +1. .tools/python/update_changelog.py: the notebook CHANGELOG.md quotes the subject line of the commit (`--pretty=%s`) instead of the whole + message (`--pretty=%B`), so trailers such as Co-authored-by are no longer published with the app. +2. app/bash_bat_scripts/post_install.sh and post_install.bat: the installer log says the tools are registered "for Napari, Fiji and QuPath". +3. .tools/docs/tools_bridge.md: the guide names QuPath next to Napari and Fiji, links the plugins' current repositories + (LabConstrictor-napari, LabConstrictor-Fiji, LabConstrictor-QuPath) and says what is known about Windows. +4. .tools/docs/app_manifest.md: the host_requirements example names plugin version 0.1.0-alpha.7. +5. .tools/docs/use_cases.md: the VLab4Mic logo and app badge point to CellMigrationLab/LabConstrictor-VLab4Mic. +6. .tools/docs/README.md: the tools guide entry names QuPath, and the per-version design notes (migration_0_1_*.md) are no longer listed + as user documentation (the files stay; the migrations link to them). + +The changes reach users with the app's next release. +""" +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + + +TAG = "[migration 0.1.29]" + +UPDATE_CHANGELOG = Path(".tools/python/update_changelog.py") +POST_INSTALL_SH = Path("app/bash_bat_scripts/post_install.sh") +POST_INSTALL_BAT = Path("app/bash_bat_scripts/post_install.bat") +TOOLS_DOC = Path(".tools/docs/tools_bridge.md") +MANIFEST_DOC = Path(".tools/docs/app_manifest.md") +USE_CASES_DOC = Path(".tools/docs/use_cases.md") +DOCS_INDEX = Path(".tools/docs/README.md") + +# (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], ...]] = { + UPDATE_CHANGELOG: ( + (' """Get current commit hash and message"""\n', + ' """Get current commit hash and message (the subject line only: the body and its trailers, such as\n' + ' Co-authored-by, do not belong in the notebook\'s changelog)"""\n'), + ("subprocess.check_output(['git', 'log', '-1', '--pretty=%B'])", "subprocess.check_output(['git', 'log', '-1', '--pretty=%s'])"), + ), + POST_INSTALL_SH: ( + (' for Napari and Fiji"\n', ' for Napari, Fiji and QuPath"\n'), + ), + POST_INSTALL_BAT: ( + (' for Napari and Fiji. >> "%LOG_FILE%"\n', ' for Napari, Fiji and QuPath. >> "%LOG_FILE%"\n'), + ), + TOOLS_DOC: ( + ("# Expose your app's tools to Napari and Fiji (optional, experimental)\n", + "# Expose your app's tools to Napari, Fiji and QuPath (optional, experimental)\n"), + ("as **tools**. After installation they appear in a generic **Napari** widget and a generic **Fiji** command, and work from the\n", + "as **tools**. After installation they appear in a generic **Napari** widget, a generic **Fiji** command and a generic **QuPath** command," + " and work from the\n"), + ("4. Install the Napari plugin (`napari-labconstrictor`) or the Fiji plugin (`labconstrictor-fiji`) once per machine. Neither is on PyPI or a" + " Fiji update site yet: see the READMEs of\n" + " [napari-labconstrictor](https://github.com/CellMigrationLab/napari-labconstrictor) and" + " [LabConstrictor-Fiji](https://github.com/CellMigrationLab/LabConstrictor-Fiji) for the install commands.\n", + "4. Install the Napari plugin (`napari-labconstrictor`), the Fiji plugin (`labconstrictor-fiji`) or the QuPath extension once per machine." + " None of them is on PyPI or an update site yet:\n" + " see the READMEs of [LabConstrictor-napari](https://github.com/CellMigrationLab/LabConstrictor-napari),\n" + " [LabConstrictor-Fiji](https://github.com/CellMigrationLab/LabConstrictor-Fiji) and" + " [LabConstrictor-QuPath](https://github.com/CellMigrationLab/LabConstrictor-QuPath) for the install steps.\n"), + ("The Windows hook (`post_install.bat`) has not yet been run on a real Windows computer; if you can help, follow the\n" + "[human test protocol](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/HUMAN_TEST_PROTOCOL.md).\n", + "The Windows hook (`post_install.bat`) runs in the template's automated tests on a Windows\n" + "machine, but it has not yet been tested by a person on Windows.\n"), + ), + MANIFEST_DOC: ( + (" min_version: 0.1.0-alpha.6 # a release tag of the plugin, with or without v\n", + " min_version: 0.1.0-alpha.7 # a release tag of the plugin, with or without v\n"), + (" fiji:\n min_version: 0.1.0-alpha.6\n", " fiji:\n min_version: 0.1.0-alpha.7\n"), + ), + USE_CASES_DOC: ( + ("https://raw.githubusercontent.com/HenriquesLab/LabConstrictor-VLab4Mic/main/src/logo/logo.png", + "https://raw.githubusercontent.com/CellMigrationLab/LabConstrictor-VLab4Mic/main/src/logo/logo.png"), + ("-181717?logo=github)](https://github.com/HenriquesLab/LabConstrictor-VLab4Mic)", + "-181717?logo=github)](https://github.com/CellMigrationLab/LabConstrictor-VLab4Mic)"), + ), + DOCS_INDEX: ( + ("- [Expose tools to Napari and Fiji (experimental)](tools_bridge.md)\n", + "- [Expose tools to Napari, Fiji and QuPath (experimental)](tools_bridge.md)\n"), + ), +} +DESIGN_NOTE_ENTRY = re.compile(r"^- \[Template 0\.1\.\d+: [^\n]*\]\(migration_0_1_\d+\.md\)[ \t]*\n", re.MULTILINE) + + +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 whose old text occurs exactly once replaced. 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 text_lf.count(old) == 1: + text_lf = text_lf.replace(old, new) + applied += 1 + elif new not in text_lf: + missing += 1 + return text_lf, applied, missing + + +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, applied, missing = apply_edits(original, EDITS[relative]) + notes = [f"{applied} text correction(s)"] if applied else [] + if relative == DOCS_INDEX: + text, removed = DESIGN_NOTE_ENTRY.subn("", text) + if removed: + notes.append(f"{removed} design note entries removed from the list") + if missing: + notes.append(f"{missing} passage(s) differ from the template text and were left as they are") + if text == original: + return "unchanged: " + ("; ".join(notes) if notes else "already up to date") + path.write_bytes(text.replace("\n", newline).encode("utf-8")) + return "updated: " + "; ".join(notes) + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Apply the 0.1.29 text corrections (idempotent, surgical, never raises for a customised file).""" + _ = context + changed = 0 + for relative in EDITS: + 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" + 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.") diff --git a/.template_sync/migrations/v0_1_29_to_v0_1_30.py b/.template_sync/migrations/v0_1_29_to_v0_1_30.py new file mode 100644 index 0000000..a813d9d --- /dev/null +++ b/.template_sync/migrations/v0_1_29_to_v0_1_30.py @@ -0,0 +1,124 @@ +"""Template 0.1.29 -> 0.1.30: the website's address is its GitHub Pages address, and two text corrections. + +What this changes in an app repository. Every change replaces one exact piece of text and is skipped when that text is not there (a file +the app changed itself stays as it is, with a note). Each step is independent and idempotent; nothing is created or deleted. + +1. The address https://labconstrictor.cellmig.org/ becomes https://cellmigrationlab.github.io/LabConstrictor-Site/ (the site stays at + its GitHub Pages address) in the template's files: .tools/docs/app_manifest.md, .tools/docs/install.md, .tools/schema/README.md and + .tools/schema/labconstrictor-app.schema.json (its `$id` and the line it tells editors to add). +2. In the app's own labconstrictor-app.yaml and docs/labconstrictor-project.yaml only the editor line + (`# yaml-language-server: $schema=...`) gets the new address, so editors can load the schema again. Nothing else in them is touched. +3. .tools/docs/use_cases.md: the VLab4Mic logo is loaded from app/logo/logo.png (the copy under src/logo/ was removed). +4. .tools/docs/tools_bridge.md: people have installed apps on Windows and macOS from a clean system. + +The changes reach users with the app's next release. +""" +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + + +TAG = "[migration 0.1.30]" + +OLD_URL = "https://labconstrictor.cellmig.org/" +NEW_URL = "https://cellmigrationlab.github.io/LabConstrictor-Site/" + +MANIFEST_DOC = Path(".tools/docs/app_manifest.md") +INSTALL_DOC = Path(".tools/docs/install.md") +SCHEMA_README = Path(".tools/schema/README.md") +SCHEMA = Path(".tools/schema/labconstrictor-app.schema.json") +USE_CASES_DOC = Path(".tools/docs/use_cases.md") +TOOLS_DOC = Path(".tools/docs/tools_bridge.md") +APP_MANIFEST = Path("labconstrictor-app.yaml") +PROJECT_FILE = Path("docs/labconstrictor-project.yaml") + +# Template files: every occurrence of the old address is replaced. +ADDRESS_FILES = (MANIFEST_DOC, INSTALL_DOC, SCHEMA_README, SCHEMA) +# The app's own files: only the editor line is rewritten. +EDITOR_LINE_FILES = (APP_MANIFEST, PROJECT_FILE) +EDITOR_LINE = re.compile(r"^(# yaml-language-server: \$schema=)" + re.escape(OLD_URL), re.MULTILINE) + +# (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], ...]] = { + USE_CASES_DOC: ( + ("https://raw.githubusercontent.com/CellMigrationLab/LabConstrictor-VLab4Mic/main/src/logo/logo.png", + "https://raw.githubusercontent.com/CellMigrationLab/LabConstrictor-VLab4Mic/main/app/logo/logo.png"), + ), + TOOLS_DOC: ( + ("machine, but it has not yet been tested by a person on Windows.\n", + "machine, and people have installed apps on Windows and macOS from a clean system.\n"), + ), +} +FILES = (*ADDRESS_FILES, *EDITOR_LINE_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 whose old text occurs exactly once replaced. 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 text_lf.count(old) == 1: + text_lf = text_lf.replace(old, new) + applied += 1 + elif new not in text_lf: + missing += 1 + return text_lf, applied, missing + + +def changed_text(relative: Path, text_lf: str) -> tuple[str, list[str]]: + """The text of the file at `relative` after this migration, and what was done to it.""" + notes: list[str] = [] + if relative in ADDRESS_FILES: + count = text_lf.count(OLD_URL) + text_lf = text_lf.replace(OLD_URL, NEW_URL) + if count: + notes.append(f"{count} address(es) changed") + elif relative in EDITOR_LINE_FILES: + text_lf, count = EDITOR_LINE.subn(lambda match: match.group(1) + NEW_URL, text_lf) + if count: + notes.append("the editor line names the new address") + else: + text_lf, applied, missing = apply_edits(text_lf, EDITS[relative]) + if applied: + notes.append(f"{applied} text correction(s)") + if missing: + notes.append(f"{missing} passage(s) differ from the template text and were left as they are") + return text_lf, notes + + +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, notes = changed_text(relative, original) + if text == original: + return "unchanged: " + ("; ".join(notes) if notes else "already up to date") + path.write_bytes(text.replace("\n", newline).encode("utf-8")) + return "updated: " + "; ".join(notes) + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Apply the 0.1.30 address change and text corrections (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" + 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.") diff --git a/.template_sync/migrations/v0_1_30_to_v0_1_31.py b/.template_sync/migrations/v0_1_30_to_v0_1_31.py new file mode 100644 index 0000000..69cedf1 --- /dev/null +++ b/.template_sync/migrations/v0_1_30_to_v0_1_31.py @@ -0,0 +1,505 @@ +"""Template 0.1.30 -> 0.1.31: no silent change of a notebook's package versions (#48), no lost work when a notebook is updated (#49). + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_31.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. #48, the requirements merge replaced one notebook's pin with another notebook's higher one (`numpy==1.26.4` and `numpy==2.0.0` gave + `numpy==2.0.0`), and wrote every requirement as `==` (`numpy<2.0` became `numpy==2.0`), without a word. + * .tools/python/merge_requirements.py is replaced by the 0.1.31 file when it is still the 0.1.30 template file: requirements are kept + as written and combined, and requirements that disagree stop the merge, naming every notebook, unless requirements_overrides.yaml + decides, with the reason. `--check` only looks for conflicts. + * .tools/requirements.txt installs `packaging` (the merge compares versions as pip does). + * requirements_overrides.yaml is created when the notebooks already pin a package to different versions: it records the version the + merge chose until now (the newest), so the app installs what it installed before, but now as a visible decision to check. + * .github/workflows/update_on_notebook_change.yml runs the merge again when requirements_overrides.yaml changes. + * .github/workflows/release_constructor.yml runs `merge_requirements.py --check` before a release, after check_placeholders.py. +2. #49, the Update button of the Welcome notebook wrote the new notebook over the user's copy, with their changes and outputs, without a + word. .tools/templates/Welcome_template.ipynb (the Welcome notebook of the next release is made from it): the button asks first, keeps + the current copy as .backup-.ipynb, writes the new notebook atomically, and records the new version only after that. + +Rules this migration keeps: surgical (whole files only when they are the 0.1.30 template files, otherwise known blocks), idempotent (a +second run reports no changes), never raises for a customised file (the sync pull request must still be created), the line endings of +each file are kept, nothing is deleted. +""" +from __future__ import annotations + +import importlib.util +import json +import re +from functools import partial +from pathlib import Path +from types import ModuleType +from typing import Any, Callable + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_31.md" +TAG = "[migration 0.1.31]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_30_to_v0_1_31" +PREVIOUS_ROOT = RESOURCE_ROOT / "previous" + +MERGE = Path(".tools/python/merge_requirements.py") +TOOLS_REQUIREMENTS = Path(".tools/requirements.txt") +OVERRIDES = Path("requirements_overrides.yaml") +NOTEBOOKS = Path("notebooks") +NOTEBOOK_WORKFLOW = Path(".github/workflows/update_on_notebook_change.yml") +RELEASE_WORKFLOW = Path(".github/workflows/release_constructor.yml") +WELCOME_TEMPLATE = Path(".tools/templates/Welcome_template.ipynb") + +PACKAGING_PIN = "packaging==25.0" +PACKAGING_LINES = "# merge_requirements.py (versions compared as pip compares them)\n" + PACKAGING_PIN + "\n" +PACKAGING_LINE = re.compile(r"^\s*packaging\s*([=<>!~;\[]|$)", re.IGNORECASE) + +# -------------------------------------------------------------------------------------------------------------------------------- +# update_on_notebook_change.yml: a change of requirements_overrides.yaml runs the merge again. (0.1.30 text, 0.1.31 text), each once. +# -------------------------------------------------------------------------------------------------------------------------------- +NOTEBOOK_WORKFLOW_BLOCKS: tuple[tuple[str, str], ...] = ( + (" - 'notebooks/**/requirements.yaml'\n", " - 'notebooks/**/requirements.yaml'\n - 'requirements_overrides.yaml'\n"), + (" notebooks/**/requirements.yaml\n", " notebooks/**/requirements.yaml\n requirements_overrides.yaml\n"), + ( + " if: github.event_name == 'workflow_dispatch' || contains(steps.changed-files.outputs.all_changed_files, 'requirements.yaml')\n", + " if: github.event_name == 'workflow_dispatch' || contains(steps.changed-files.outputs.all_changed_files, 'requirements.yaml')" + " || contains(steps.changed-files.outputs.all_changed_files, 'requirements_overrides.yaml')\n", + ), +) + +# -------------------------------------------------------------------------------------------------------------------------------- +# release_constructor.yml: `merge_requirements.py --check` right after check_placeholders.py in the bump-version job (the first one). +# -------------------------------------------------------------------------------------------------------------------------------- +PLACEHOLDER_STEP = re.compile( + r"(?P[ ]+)bash \.tools/bash/run_with_context\.sh \\\n" + r"(?P=indent) (?P\S+) \\\n" + r"(?P=indent) \"check_placeholders\.py\" \\\n" + r"(?P=indent) \.tools/python/check_placeholders\.py \\\n" + r"(?P=indent) python \.tools/python/check_placeholders\.py\n" +) +REQUIREMENTS_CHECK_STEP = ( + "{indent}bash .tools/bash/run_with_context.sh \\\n" + "{indent} {log} \\\n" + '{indent} "merge_requirements.py --check" \\\n' + "{indent} .tools/python/merge_requirements.py \\\n" + "{indent} python .tools/python/merge_requirements.py --source-dir notebooks --output requirements.txt --check\n" +) + +# -------------------------------------------------------------------------------------------------------------------------------- +# Welcome_template.ipynb (#49), in the code cell that defines the notebook table. Blocks are compared line by line without trailing +# spaces (the template's lines carry some); the new text replaces the lines of the old block. +# -------------------------------------------------------------------------------------------------------------------------------- +HELPER_ANCHOR = "def apply_grid_layout(grid):\n" +HELPER = '''def replace_notebook_with_backup(notebook_path: Path, new_content: str): + """Replace a notebook by its update, keeping the current file (with the user's changes and outputs) as a backup. + + The new content must be a notebook. It is written to a temporary file next to the notebook and then moved into place, so a failed + download or write never leaves a broken notebook. Returns the path of the backup, or None when there was no notebook yet. + """ + import os + from datetime import datetime + + if not isinstance(json.loads(new_content), dict): + raise ValueError("the downloaded file is not a notebook") + notebook_path.parent.mkdir(parents=True, exist_ok=True) + backup_path = None + if notebook_path.exists(): + stamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + backup_path = notebook_path.with_name(f"{notebook_path.stem}.backup-{stamp}{notebook_path.suffix}") + number = 1 + while backup_path.exists(): + number += 1 + backup_path = notebook_path.with_name(f"{notebook_path.stem}.backup-{stamp}-{number}{notebook_path.suffix}") + shutil.copy2(notebook_path, backup_path) + temporary_path = notebook_path.with_name(f".{notebook_path.name}.update") + try: + temporary_path.write_text(new_content, encoding="utf-8") + os.replace(temporary_path, notebook_path) + finally: + if temporary_path.exists(): + temporary_path.unlink() + return backup_path + + +''' +HANDLER_OLD = ''' def button_update(main_folder, subfolder, row_idx): + def show(button): + button.disabled = True + button.description = "Updating..." + + # Download the notebook + notebook_url = f"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/notebooks/{main_folder}/{subfolder}.ipynb?ref={github_branch}" + if private_repository: + if github_token.value: + notebook_response = requests.get(notebook_url, headers={"Authorization": f"token {github_token.value}"}) + else: + grip_output.value = "❌ Please check your Presonal Access Token" + else: + notebook_response = requests.get(notebook_url) + + if notebook_response.status_code == 200: + try: + # Decode the notebook content + notebook_content = base64.b64decode( + notebook_response.json()['content'] + ).decode('utf-8') + + # Save to local path + local_notebook_path = Path(".") / main_folder / f"{subfolder}.ipynb" + local_notebook_path.parent.mkdir(parents=True, exist_ok=True) + local_notebook_path.write_text(notebook_content, encoding='utf-8') + + # Update the local version YAML + local_latest_versions[main_folder][subfolder] = online_latest_versions[main_folder][subfolder] + local_latest_version_path.write_text(yaml.dump(local_latest_versions, default_flow_style=False)) + + grip_output.value = f"✅ Updated {subfolder} to version {online_latest_versions[main_folder][subfolder]}" + + # Update the grid to show up-to-date + grid[row_idx, 3] = table_cell(online_latest_versions[main_folder][subfolder]) + grid[row_idx, 4] = table_cell("✅ Up-to-date") + grid[row_idx, 5] = table_cell("-") + apply_grid_layout(grid) + + except Exception as e: + grip_output.value = f"❌ Error saving notebook: {e}" + button.disabled = False + button.description = "Update" + else: + grip_output.value = f"❌ Failed to download notebook (HTTP {notebook_response.status_code})" + display(notebook_response.text[:300]) + button.disabled = False + button.description = "Update" + + return show +''' +HANDLER_NEW = ''' def button_update(main_folder, subfolder, row_idx): + # Updating replaces the user's copy of the notebook: ask first, keep that copy as a backup, and change the + # recorded version only once the new notebook is in place (CellMigrationLab/LabConstrictor#49). + local_notebook_path = Path(".") / main_folder / f"{subfolder}.ipynb" + new_version = online_latest_versions[main_folder][subfolder] + + def reset(button): + button.disabled = False + button.description = "Update" + + def do_update(button): + button.description = "Updating..." + notebook_url = f"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/notebooks/{main_folder}/{subfolder}.ipynb?ref={github_branch}" + headers = {} + if private_repository: + if not github_token.value: + grip_output.value = "❌ Please check your Personal Access Token. Your notebook was not changed." + reset(button) + return + headers = {"Authorization": f"token {github_token.value}"} + try: + notebook_response = requests.get(notebook_url, headers=headers, timeout=60) + except requests.RequestException as e: + grip_output.value = f"❌ Failed to download notebook: {e}. Your notebook was not changed." + reset(button) + return + if notebook_response.status_code != 200: + grip_output.value = f"❌ Failed to download notebook (HTTP {notebook_response.status_code}). Your notebook was not changed." + display(notebook_response.text[:300]) + reset(button) + return + try: + notebook_content = base64.b64decode(notebook_response.json()['content']).decode('utf-8') + backup_path = replace_notebook_with_backup(local_notebook_path, notebook_content) + except Exception as e: + grip_output.value = f"❌ Error saving notebook: {e}. Your notebook was not changed." + reset(button) + return + + # The new notebook is in place: only now record its version + local_latest_versions[main_folder][subfolder] = new_version + local_latest_version_path.write_text(yaml.dump(local_latest_versions, default_flow_style=False)) + saved = f" Your previous copy is saved as {backup_path.name}, next to it." if backup_path else "" + grip_output.value = f"✅ Updated {subfolder} to version {new_version}.{saved}" + + # Update the grid to show up-to-date + grid[row_idx, 3] = table_cell(new_version) + grid[row_idx, 4] = table_cell("✅ Up-to-date") + grid[row_idx, 5] = table_cell("-") + apply_grid_layout(grid) + + def show(button): + button.disabled = True + button.description = "Confirm below" + question = widgets.HTML( + f"Update {subfolder} to version {new_version}?
" + f"The new version replaces {local_notebook_path.as_posix()}. Your current copy, with your changes " + f"and outputs, is first saved as {subfolder}.backup-<date>.ipynb in the same folder.
" + "If the notebook is open in a tab, close that tab first: otherwise JupyterLab can save the old copy over the update." + ) + confirm = widgets.Button(description="Back up and update", button_style="warning", layout=widgets.Layout(width="auto")) + cancel = widgets.Button(description="Cancel") + dialog = widgets.VBox([question, widgets.HBox([confirm, cancel])]) + + def on_confirm(_): + dialog.close() + do_update(button) + + def on_cancel(_): + dialog.close() + grip_output.value = f"Update of {subfolder} cancelled: nothing was changed." + reset(button) + + confirm.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_confirm)) + cancel.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_cancel)) + display(dialog) + + return show +''' +WELCOME_DONE = "def replace_notebook_with_backup(" + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load(name: str, alias: str) -> ModuleType: + path = Path(__file__).resolve().parent / name + spec = importlib.util.spec_from_file_location(alias, path) + if spec is None or spec.loader is None: + raise RuntimeError(f"Unable to load {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _lf(text: str) -> tuple[str, str]: + return text.replace("\r\n", "\n"), ("\r\n" if "\r\n" in text else "\n") + + +def apply_blocks(text_lf: str, blocks: tuple[tuple[str, str], ...]) -> str | None: + """The text with every block changed, or None when a 0.1.30 block is not there exactly once (a customised file).""" + for old, new in blocks: + if text_lf.count(old) != 1: + return None + text_lf = text_lf.replace(old, new, 1) + return text_lf + + +# -------------------------------------------------------------------------------------------------------------------------------- +# #48 +# -------------------------------------------------------------------------------------------------------------------------------- +def _replace_merge(helpers: Any, repo_root: Path) -> str: + path = repo_root / MERGE + current, newline = _lf(helpers.read_text(path)) + new = (RESOURCE_ROOT / MERGE).read_text(encoding="utf-8") + if current == new: + return "already the 0.1.31 template file: unchanged" + if current != (PREVIOUS_ROOT / MERGE).read_text(encoding="utf-8"): + return f"SKIPPED: customised (not the 0.1.30 template file), so it was left unchanged; apply the 0.1.31 change by hand, see {DOCS_URL}" + helpers.write_text(path, new.replace("\n", newline)) + return "updated: replaced by the 0.1.31 template file (requirements that disagree stop the merge)" + + +def _add_packaging(helpers: Any, repo_root: Path) -> str: + path = repo_root / TOOLS_REQUIREMENTS + current = helpers.read_text(path) + if any(PACKAGING_LINE.match(line) for line in current.splitlines()): + return "already installs packaging: unchanged" + newline = "\r\n" if "\r\n" in current else "\n" + text = current if not current or current.endswith(("\n", "\r")) else current + newline + helpers.write_text(path, text + PACKAGING_LINES.replace("\n", newline)) + return f"updated: added {PACKAGING_PIN}" + + +def _canonical(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower() + + +def _version_key(version: str) -> tuple[tuple[int, Any], ...]: + """The order the merge used until 0.1.30 for plain versions (numbers compared as numbers).""" + parts = re.split(r"[.\-+_]|(?=[a-zA-Z])", version) + return tuple((0, int(p)) if p.isdigit() else (1, p) for p in parts if p) + + +def notebook_dependencies(text: str) -> list[str]: + """The `dependencies` list of a requirements.yaml (PyYAML when it is installed, else the simple list forms the template uses).""" + try: + import yaml + except ImportError: + pass + else: + data = yaml.safe_load(text) or {} + found = data.get("dependencies") if isinstance(data, dict) else None + return [str(item) for item in found or []] + items: list[str] = [] + inside = False + for raw in text.splitlines(): + line = raw.split("#", 1)[0].rstrip() + key = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", line) + if key: + inside = key.group(1) == "dependencies" + value = key.group(2).strip() + if inside and value.startswith("[") and value.endswith("]"): + items += [part.strip().strip("'\"") for part in value[1:-1].split(",") if part.strip()] + inside = False + continue + item = re.match(r"^\s*-\s+(.*)$", line) + if inside and item: + items.append(item.group(1).strip().strip("'\"")) + return items + + +EXACT_PIN = re.compile(r"^(?P[A-Za-z0-9][A-Za-z0-9_.-]*)(\[[^\]]*\])?\s*==\s*(?P[A-Za-z0-9_.+!-]+)$") + + +def pin_conflicts(repo_root: Path, helpers: Any) -> dict[str, list[tuple[str, str]]]: + """Packages that the notebooks' `dependencies` pin (==, without a marker) to different versions: {name: [(file, version)]}.""" + pins: dict[str, list[tuple[str, str]]] = {} + root = repo_root / NOTEBOOKS + files = sorted({*root.rglob("requirements.yaml"), *root.rglob("requirements.yml")}) if root.is_dir() else [] + for path in files: + for dependency in notebook_dependencies(helpers.read_text(path)): + match = EXACT_PIN.match(dependency.split("#", 1)[0].strip()) + if match: + pins.setdefault(_canonical(match.group("name")), []).append((path.relative_to(repo_root).as_posix(), match.group("version"))) + return {name: found for name, found in sorted(pins.items()) if len({version for _, version in found}) > 1} + + +def overrides_text(conflicts: dict[str, list[tuple[str, str]]]) -> str: + def quoted(text: str) -> str: + return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"' + + lines = [ + "# Decisions for packages that the notebooks pin to different versions (template 0.1.31, CellMigrationLab/LabConstrictor#48).", + "# The requirements merge (.tools/python/merge_requirements.py) stops when notebooks disagree and no entry here decides. Each entry", + "# gives the requirement every notebook gets (use) and why (reason); both are written at the top of the generated requirements files.", + f"# See {DOCS_URL}", + "overrides:", + ] + for name, found in conflicts.items(): + newest = max((version for _, version in found), key=_version_key) + asked = ", ".join(f"{file} =={version}" for file, version in found) + reason = ( + "Recorded by the template 0.1.31 migration: the version the requirements merge chose until then (the newest pin), so the app " + f"installs what it installed before. The notebooks ask for: {asked}. Check every notebook with this version, then write here why it is right." + ) + lines += [f" {name}:", f" use: {quoted('==' + newest)}", f" reason: {quoted(reason)}"] + return "\n".join(lines) + "\n" + + +def _seed_overrides(helpers: Any, repo_root: Path) -> str: + conflicts = pin_conflicts(repo_root, helpers) + path = repo_root / OVERRIDES + if path.is_file(): + return "already exists: unchanged (the merge says which conflicts it does not decide yet)" + if not conflicts: + return "not needed: no package is pinned to different versions by the notebooks (nothing was created)" + with path.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(overrides_text(conflicts)) + return f"updated: created; it records the version used until now for {', '.join(conflicts)}. Check each one (see {DOCS_URL})" + + +def add_requirements_check(text_lf: str) -> str | None: + """The release workflow with `merge_requirements.py --check` after the first check_placeholders.py step; None without that step.""" + match = PLACEHOLDER_STEP.search(text_lf) + if match is None: + return None + step = REQUIREMENTS_CHECK_STEP.format(indent=match.group("indent"), log=match.group("log")) + return text_lf[: match.end()] + step + text_lf[match.end() :] + + +def _update_release_workflow(helpers: Any, repo_root: Path, path: Path) -> str: + current, newline = _lf(helpers.read_text(path)) + if "merge_requirements.py --source-dir notebooks --output requirements.txt --check" in current: + return "unchanged: already checks the requirements" + merge = repo_root / MERGE + if not merge.is_file() or '"--check"' not in helpers.read_text(merge): + return f"SKIPPED: the repository's merge_requirements.py has no --check (it was not replaced), so the release does not run it. See {DOCS_URL}" + new = add_requirements_check(current) + if new is None: + return f"SKIPPED: the check_placeholders.py command was not found (customised workflow); add the requirements check by hand. See {DOCS_URL}" + helpers.write_text(path, new.replace("\n", newline)) + return "updated: the release stops when the notebooks' requirements conflict (merge_requirements.py --check)" + + +def _blocks_step(helpers: Any, path: Path, blocks: tuple[tuple[str, str], ...], what: str, skipped_hint: str) -> str: + current, newline = _lf(helpers.read_text(path)) + if all(new in current for _, new in blocks): + return f"unchanged: already {what}" + new = apply_blocks(current, blocks) + if new is None: + return f"SKIPPED: customised (a 0.1.30 block was not found), so it was left unchanged; {skipped_hint} See {DOCS_URL}" + helpers.write_text(path, new.replace("\n", newline)) + return f"updated: {what}" + + +# -------------------------------------------------------------------------------------------------------------------------------- +# #49 +# -------------------------------------------------------------------------------------------------------------------------------- +def _replace_lines(source: str, old: str, new: str) -> str | None: + """`source` with the lines of `old` (compared without trailing spaces) replaced by `new`; None when they are not there exactly once.""" + lines = source.splitlines(keepends=True) + wanted = [line.rstrip() for line in old.splitlines()] + stripped = [line.rstrip() for line in lines] + starts = [i for i in range(len(lines) - len(wanted) + 1) if stripped[i : i + len(wanted)] == wanted] + if len(starts) != 1: + return None + start = starts[0] + return "".join(lines[:start]) + new + "".join(lines[start + len(wanted) :]) + + +def update_welcome_source(source: str) -> str | None: + """The table cell with the safe update (#49), or None when the 0.1.30 handler or the helper's anchor is not found.""" + if source.count(HELPER_ANCHOR) != 1: + return None + replaced = _replace_lines(source, HANDLER_OLD, HANDLER_NEW) + if replaced is None: + return None + return replaced.replace(HELPER_ANCHOR, HELPER + HELPER_ANCHOR, 1) + + +def _update_welcome(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + notebook = json.loads(text) + cells = [cell for cell in notebook.get("cells", []) if cell.get("cell_type") == "code"] + sources = ["".join(cell["source"]) if isinstance(cell.get("source"), list) else cell.get("source", "") for cell in cells] + if any(WELCOME_DONE in source for source in sources): + return "unchanged: the Update button already keeps a backup" + for cell, source in zip(cells, sources): + new = update_welcome_source(source.replace("\r\n", "\n")) + if new is None: + continue + cell["source"] = new.splitlines(keepends=True) if isinstance(cell.get("source"), list) else new + rendered = json.dumps(notebook, ensure_ascii=False, indent=1) + if text.endswith(("\n", "\r\n")): + rendered += "\n" + helpers.write_text(path, rendered.replace("\n", newline)) + return "updated: the Update button asks first and keeps the current notebook as a backup" + return f"SKIPPED: the update code of the notebook table was not found (customised); apply the 0.1.31 change by hand. See {DOCS_URL}" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Requirements that disagree stop the merge (#48); the notebook update asks first and keeps a backup (#49). Idempotent, surgical.""" + _ = context + helpers = _load("v0_1_9_to_v0_1_10.py", "template_sync_helpers_0_1_31") + changed = 0 + + def report(name: Path, step: Callable[[], str], must_exist: bool = True) -> None: + nonlocal changed + if must_exist and not (repo_root / name).is_file(): + log(f"{name}: not present in this repository (nothing was created)") + return + try: + status = step() + except (OSError, ValueError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + if status.startswith("updated"): + changed += 1 + log(f"{name}: {status}") + + report(MERGE, partial(_replace_merge, helpers, repo_root)) + report(TOOLS_REQUIREMENTS, partial(_add_packaging, helpers, repo_root)) + report(OVERRIDES, partial(_seed_overrides, helpers, repo_root), must_exist=False) + report(NOTEBOOK_WORKFLOW, partial(_blocks_step, helpers, repo_root / NOTEBOOK_WORKFLOW, NOTEBOOK_WORKFLOW_BLOCKS, + "runs the merge when requirements_overrides.yaml changes", + "after a change of requirements_overrides.yaml, run Updates on notebook change by hand.")) + report(RELEASE_WORKFLOW, partial(_update_release_workflow, helpers, repo_root, repo_root / RELEASE_WORKFLOW)) + report(WELCOME_TEMPLATE, partial(_update_welcome, helpers, repo_root / WELCOME_TEMPLATE)) + + if changed: + log(f"done: {changed} file(s) changed. Review the pull request before merging; the fixes reach users with the next release of the app.") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_31_to_v0_1_32.py b/.template_sync/migrations/v0_1_31_to_v0_1_32.py new file mode 100644 index 0000000..7b1d817 --- /dev/null +++ b/.template_sync/migrations/v0_1_31_to_v0_1_32.py @@ -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.") diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/schema/labconstrictor-app.schema.json b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/schema/labconstrictor-app.schema.json index 536d91e..30ae4ae 100644 --- a/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/schema/labconstrictor-app.schema.json +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/schema/labconstrictor-app.schema.json @@ -21,6 +21,15 @@ "items": {"enum": ["notebook", "napari", "fiji", "qupath"]}, "description": "Where the app's tools can be used besides its own window (the LabConstrictor-Tools bridge)." }, + "host_requirements": { + "type": "object", "additionalProperties": false, + "description": "The oldest LabConstrictor plugin of each host the app needs. labconstrictor-tools register copies it into the app's registry entry; a host whose plugin is older lists the app with a sentence saying which plugin to update (or refuses it with required: true). The notebook needs no plugin.", + "properties": { + "napari": {"$ref": "#/$defs/hostRequirement"}, + "fiji": {"$ref": "#/$defs/hostRequirement"}, + "qupath": {"$ref": "#/$defs/hostRequirement"} + } + }, "distribution": { "type": "object", "additionalProperties": false, "anyOf": [{"required": ["installer"]}, {"required": ["colab"]}, {"required": ["pip"]}], @@ -57,6 +66,16 @@ } }, "$defs": { + "hostRequirement": { + "type": "object", "additionalProperties": false, + "anyOf": [{"required": ["min_version"]}, {"required": ["features"]}], + "properties": { + "min_version": {"type": "string", "pattern": "^v?[0-9]+(\\.[0-9]+)*([-_.]?(a|alpha|b|beta|c|rc|pre|preview)[-_.]?[0-9]*)?([-_.]?(post|rev|r)[-_.]?[0-9]*)?([-_.]?dev[-_.]?[0-9]*)?$", "description": "A release tag of the plugin, with or without v (0.1.0-alpha.6, v0.1.0, 0.2.0rc1). Quote it if YAML could read it as a number (\"0.2\")."}, + "features": {"type": "array", "uniqueItems": true, "minItems": 1, "items": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"}, "description": "Host feature ids the app needs (LabConstrictor-Tools docs/HOST_FEATURES.md), for example shapes_owner_v1."}, + "why": {"type": "string", "minLength": 3, "maxLength": 160, "pattern": "^[^\\n]+$", "description": "One line shown to the person, saying what the newer plugin brings."}, + "required": {"type": "boolean", "description": "true: an older plugin refuses the app's tools instead of warning. Use it only when the tools really fail."} + } + }, "facts": {"type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "string", "minLength": 5, "maxLength": 200}}, "https": {"type": "string", "pattern": "^https://[^\\s/@]+(/[^\\s]*)?$(?!\\n)"}, "repoPath": {"type": "string", "pattern": "^(?!/)(?!.*\\.\\.)[A-Za-z0-9_./ -]+\\.(png|jpg|jpeg|gif)$(?!\\n)", "description": "Path inside the repository, no leading slash."}, diff --git a/.template_sync/resources/v0_1_26_to_v0_1_27/.tools/docs/app_manifest_host_requirements.md b/.template_sync/resources/v0_1_26_to_v0_1_27/.tools/docs/app_manifest_host_requirements.md new file mode 100644 index 0000000..4277621 --- /dev/null +++ b/.template_sync/resources/v0_1_26_to_v0_1_27/.tools/docs/app_manifest_host_requirements.md @@ -0,0 +1,18 @@ +## Plugin versions your tools need (optional) + +If your tools rely on a fix or a feature of the napari, Fiji or QuPath plugin that older plugins lack, say so with `host_requirements`. People with an older plugin keep seeing your app, with one sentence saying which plugin to update and where; your app page on the App Centre lists the versions under "Plugin versions". + +```yaml +host_requirements: + qupath: + min_version: 0.1.0-alpha.6 # a release tag of the plugin, with or without v + features: [shapes_owner_v1] # optional: a host feature id + why: Replace keeps your own annotations # optional: one line shown to the person + fiji: + min_version: 0.1.0-alpha.6 +``` + +- Name only `napari`, `fiji` or `qupath`: the notebook ships with your app and needs no plugin. +- Each needs `min_version`, `features`, or both. `required: true` makes an older plugin refuse your tools instead of warning; use it only when they really fail there. +- Write it as a block, as above. The installer passes this file to `labconstrictor-tools register`, which refuses a malformed block (a misspelt host or key, a version like `latest`); `labconstrictor-tools check --module _lc_tools --app-manifest labconstrictor-app.yaml` shows what it read. +- The feature ids and the rule are in the [LabConstrictor-Tools documentation](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/PROTOCOL.md#host-requirements-which-plugin-an-app-needs). diff --git a/.template_sync/resources/v0_1_26_to_v0_1_27/.tools/schema/labconstrictor-app.schema.json b/.template_sync/resources/v0_1_26_to_v0_1_27/.tools/schema/labconstrictor-app.schema.json new file mode 100644 index 0000000..30ae4ae --- /dev/null +++ b/.template_sync/resources/v0_1_26_to_v0_1_27/.tools/schema/labconstrictor-app.schema.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json", + "title": "labconstrictor-app.yaml", + "description": "Manifest that an app keeps in the root of its own repository so that it can be listed in the LabConstrictor App Centre. Edit it with schema support: add `# yaml-language-server: $schema=https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json` as the first line.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "name", "summary", "kind", "distribution"], + "properties": { + "schema": {"const": 1, "description": "Manifest format version."}, + "name": {"type": "string", "minLength": 2, "maxLength": 60, "description": "Display name, as users know the app."}, + "summary": {"type": "string", "minLength": 20, "maxLength": 200, "description": "One sentence shown on the app card. Plain text."}, + "description": {"type": "string", "maxLength": 2000, "description": "A few plain-text paragraphs shown on the app page; separate paragraphs with a blank line. No HTML or Markdown."}, + "quickstart": { + "type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "string", "minLength": 5, "maxLength": 200}, + "description": "Up to six short plain-text steps for a first run, shown on the app page. Link to fuller documentation with docs_url." + }, + "kind": {"enum": ["analysis", "segmentation", "simulation", "game", "training", "utility"], "description": "What the app is for; drives the filter on the App Centre."}, + "hosts": { + "type": "array", "uniqueItems": true, + "items": {"enum": ["notebook", "napari", "fiji", "qupath"]}, + "description": "Where the app's tools can be used besides its own window (the LabConstrictor-Tools bridge)." + }, + "host_requirements": { + "type": "object", "additionalProperties": false, + "description": "The oldest LabConstrictor plugin of each host the app needs. labconstrictor-tools register copies it into the app's registry entry; a host whose plugin is older lists the app with a sentence saying which plugin to update (or refuses it with required: true). The notebook needs no plugin.", + "properties": { + "napari": {"$ref": "#/$defs/hostRequirement"}, + "fiji": {"$ref": "#/$defs/hostRequirement"}, + "qupath": {"$ref": "#/$defs/hostRequirement"} + } + }, + "distribution": { + "type": "object", "additionalProperties": false, + "anyOf": [{"required": ["installer"]}, {"required": ["colab"]}, {"required": ["pip"]}], + "dependentRequired": {"platforms": ["installer"]}, + "description": "How people get the app. At least one route is required.", + "properties": { + "installer": {"const": true, "description": "The latest GitHub release carries LabConstrictor installers (Name-version-OS-arch.ext)."}, + "colab": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/link"}, "description": "Google Colab notebooks."}, + "platforms": { + "type": "array", "minItems": 1, "uniqueItems": true, "items": {"enum": ["windows-x86_64", "windows-arm64", "macos-arm64", "macos-x86_64", "linux-x86_64", "linux-arm64"]}, + "description": "The systems you support. Only these installers are offered; leave it out to offer every installer of your release." + }, + "pip": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$(?!\\n)", "description": "Name of the package on PyPI."} + } + }, + "authors": {"type": "array", "items": {"$ref": "#/$defs/author"}}, + "license": {"type": "string", "minLength": 1, "description": "SPDX identifier, for example MIT."}, + "inputs": {"$ref": "#/$defs/facts", "description": "What the app accepts, as a short list (file formats, dimensions, units it needs). A summary, not README copy; use docs_url for the rest."}, + "outputs": {"$ref": "#/$defs/facts", "description": "What the app produces, as a short list (images, masks, tables, plots). A summary, not README copy; use docs_url for the rest."}, + "limitations": {"$ref": "#/$defs/facts", "description": "What the app cannot do or where it may be unreliable, as a short list."}, + "status": {"enum": ["Experimental", "Available", "Deprecated"], "description": "How mature the app is, in the same words the Ecosystem page uses for projects."}, + "categories": {"type": "array", "uniqueItems": true, "maxItems": 6, "items": {"type": "string", "maxLength": 30}, "description": "Words a scientist would search for: tasks, synonyms, methods, tools."}, + "doi": {"type": "string", "pattern": "^10\\.\\d{4,9}/\\S+$(?!\\n)", "description": "DOI of the paper to cite (not a software archive)."}, + "homepage": {"$ref": "#/$defs/https"}, + "docs_url": {"$ref": "#/$defs/https"}, + "icon": {"$ref": "#/$defs/repoPath", "description": "Square PNG in the repository (SVG is not accepted: it can carry scripts)."}, + "screenshots": { + "type": "array", "minItems": 1, "maxItems": 6, + "items": { + "type": "object", "additionalProperties": false, "required": ["path", "caption"], + "properties": {"path": {"$ref": "#/$defs/repoPath"}, "caption": {"type": "string", "minLength": 3, "maxLength": 140}} + }, + "description": "Images in the repository; captions double as alt text." + } + }, + "$defs": { + "hostRequirement": { + "type": "object", "additionalProperties": false, + "anyOf": [{"required": ["min_version"]}, {"required": ["features"]}], + "properties": { + "min_version": {"type": "string", "pattern": "^v?[0-9]+(\\.[0-9]+)*([-_.]?(a|alpha|b|beta|c|rc|pre|preview)[-_.]?[0-9]*)?([-_.]?(post|rev|r)[-_.]?[0-9]*)?([-_.]?dev[-_.]?[0-9]*)?$", "description": "A release tag of the plugin, with or without v (0.1.0-alpha.6, v0.1.0, 0.2.0rc1). Quote it if YAML could read it as a number (\"0.2\")."}, + "features": {"type": "array", "uniqueItems": true, "minItems": 1, "items": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"}, "description": "Host feature ids the app needs (LabConstrictor-Tools docs/HOST_FEATURES.md), for example shapes_owner_v1."}, + "why": {"type": "string", "minLength": 3, "maxLength": 160, "pattern": "^[^\\n]+$", "description": "One line shown to the person, saying what the newer plugin brings."}, + "required": {"type": "boolean", "description": "true: an older plugin refuses the app's tools instead of warning. Use it only when the tools really fail."} + } + }, + "facts": {"type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "string", "minLength": 5, "maxLength": 200}}, + "https": {"type": "string", "pattern": "^https://[^\\s/@]+(/[^\\s]*)?$(?!\\n)"}, + "repoPath": {"type": "string", "pattern": "^(?!/)(?!.*\\.\\.)[A-Za-z0-9_./ -]+\\.(png|jpg|jpeg|gif)$(?!\\n)", "description": "Path inside the repository, no leading slash."}, + "link": { + "type": "object", "additionalProperties": false, "required": ["label", "url"], + "properties": {"label": {"type": "string", "minLength": 2, "maxLength": 60}, "url": {"type": "string", "pattern": "^https://colab\\.research\\.google\\.com/[^\\s]+$(?!\\n)"}} + }, + "author": { + "type": "object", "additionalProperties": false, "required": ["name"], + "properties": {"name": {"type": "string", "minLength": 2}, "orcid": {"type": "string", "pattern": "^\\d{4}-\\d{4}-\\d{4}-\\d{3}[\\dX]$(?!\\n)"}} + } + } +} diff --git a/.template_sync/resources/v0_1_30_to_v0_1_31/.tools/python/merge_requirements.py b/.template_sync/resources/v0_1_30_to_v0_1_31/.tools/python/merge_requirements.py new file mode 100644 index 0000000..fe22142 --- /dev/null +++ b/.template_sync/resources/v0_1_30_to_v0_1_31/.tools/python/merge_requirements.py @@ -0,0 +1,755 @@ +#!/usr/bin/env python3 +"""Merge requirements files under a directory (e.g. notebooks/*) into a single +root requirements file. + +The script supports both classic requirements.txt files and the +requirements.yaml format used by notebooks. For YAML files, it merges the +`python_version` (every notebook must agree) and the `dependencies` list while +discarding per-notebook descriptions. + +It also recognizes optional per-OS fields (`windows_dependencies`, +`linux_dependencies`, `macos_dependencies`) and emits dedicated requirements +outputs for each platform containing only the entries from their OS-specific +lists, in addition to the common file. + +Alongside the common requirements file, it emits a GPU-targeted variant. The +GPU file rewrites `tensorflow` to `tensorflow[and-cuda]` on Linux only (TensorFlow's CUDA +wheels exist only for Linux; other systems keep plain `tensorflow`) and adds the +PyTorch CUDA wheel index when `torch`, `torchvision`, or `torchaudio` are present. + +Version requirements are never changed silently (template 0.1.31, CellMigrationLab/LabConstrictor#48): + * the requirements of a package are kept as written: `numpy>=1.24` stays `numpy>=1.24`, and the + requirements of several notebooks are combined (`numpy<2,>=1.24`); the lock step then finds the versions; + * when notebooks pin a package to different versions (`numpy==1.26.4` and `numpy==2.0.0`), or a pin does not + meet another notebook's requirement, nothing is written and the script fails, naming every notebook and its + requirement. The developer makes the notebooks agree, or decides explicitly in requirements_overrides.yaml + (next to the output), with the reason; the decision is written at the top of every generated file; + * requirements with different environment markers (`; sys_platform == "win32"`) are kept as separate lines; + * package names are compared as pip compares them (`NumPy`, `numpy` and `num_py` are one package). +`python merge_requirements.py --check` only looks for conflicts: it writes nothing (the release runs it). + +It preserves non-package lines (pip options, VCS/URLs) and supports simple `-r` includes. + +It also automatically adds ipywidgets if missing, with a version determined by +Python, JupyterLab, and matplotlib versions from environment.yaml. +""" +import argparse +import re +import sys +from collections import OrderedDict +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path + +import yaml +from packaging.requirements import InvalidRequirement, Requirement +from packaging.specifiers import InvalidSpecifier, SpecifierSet +from packaging.utils import canonicalize_name +from packaging.version import InvalidVersion, Version + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_31.md" +OVERRIDES_FILE = "requirements_overrides.yaml" + +# Regex to capture name, optional extras, operator and version, and optional markers (used for the GPU rewrite of final lines) +pkg_re = re.compile(r"^(?P[A-Za-z0-9_.+-]+)(?P\[[^\]]+\])?\s*(?P==|>=|<=|~=|!=|>|<)\s*(?P[^;\s]+)(?P\s*;.*)?$") + +OS_FIELD_MAP = { + "windows": "windows_dependencies", + "linux": "linux_dependencies", + "macos": "macos_dependencies", +} +OS_DISPLAY_NAMES = { + "windows": "Windows", + "linux": "Linux", + "macos": "macOS", +} +GPU_DISPLAY_NAME = "NVIDIA GPU" +GPU_TORCH_EXTRA_INDEX_URL = "--extra-index-url https://download.pytorch.org/whl/cu128" +TORCH_GPU_PACKAGES = {"torch", "torchvision", "torchaudio"} +PLAIN_PKG_RE = re.compile( + r"^(?P[A-Za-z0-9_.+-]+)(?P\[[^\]]+\])?(?P\s*;.*)?$" +) +ADDED_BY_SCRIPT = "added by merge_requirements.py" + + +@dataclass +class Entry: + """One requirement line of one file, as written.""" + + source: str + line: str + name: str + extras: tuple[str, ...] + spec: str + marker: str + + +@dataclass +class Override: + """A decision of requirements_overrides.yaml: every notebook gets `use` for this package.""" + + name: str + use: str + reason: str + used: bool = False + + +@dataclass +class Resolved: + """The line written for one package (and marker), and how it was decided.""" + + entries: list[Entry] + spec: str + extras: list[str] + override: Override | None = None + + @property + def name(self) -> str: + return self.entries[0].name + + @property + def marker(self) -> str: + return self.entries[0].marker + + def line(self) -> str: + extras = f"[{','.join(self.extras)}]" if self.extras else "" + marker = f" ; {self.marker}" if self.marker else "" + return f"{self.name}{extras}{self.spec}{marker}" + + +@dataclass +class RequirementContext: + groups: OrderedDict[tuple[str, str], list[Entry]] = field(default_factory=OrderedDict) + other_lines: OrderedDict[str, None] = field(default_factory=OrderedDict) + errors: list[str] = field(default_factory=list) + + +class Conflict(Exception): + """Requirements of one package that no single version meets, or that the script will not choose between.""" + + def __init__(self, package: str, reason: str, entries: list[Entry], where: str = ""): + super().__init__(reason) + self.package = package + self.reason = reason + self.entries = entries + self.where = where + + +def normalize_line(line: str) -> str: + # Remove inline comments and surrounding whitespace. + if "#" in line: + line = line.split("#", 1)[0] + return line.strip() + + +def display_path(path: Path) -> str: + try: + return path.resolve().relative_to(Path.cwd().resolve()).as_posix() + except ValueError: + return path.as_posix() + + +def merge_python_version(filepath: str | Path | None, current: str | None, candidate: str | None): + """Every notebook that names a python_version must name the same one.""" + if not candidate: + return current + if current is None: + return candidate + if current == candidate: + return current + else: + raise ValueError(f"Conflicting python_version found {current} vs {candidate} when processing {filepath}") + + +def process_requirement_line(line: str, ctx: RequirementContext, source: str, base_dir: Path | None = None): + """Handle a single requirement line (shared between txt and yaml inputs).""" + if not line: + return + + parts = line.split(maxsplit=1) + if parts[0] in ("-r", "--requirement") and len(parts) == 2: + include_path = Path(parts[1]) if base_dir is None else (base_dir / parts[1]) + include = include_path.resolve() + if include.exists(): + read_requirements_file(include, ctx) + return + + # Keep pip option lines (indexes, find-links, etc.) as-is + if line.startswith("--") or line.startswith("-f ") or line.startswith("-i ") or line.startswith("-e "): + ctx.other_lines.setdefault(line, None) + return + + # VCS or URL lines (git+, http(s)://, file:) keep as-is + if any(line.startswith(prefix) for prefix in ("git+", "http://", "https://", "file:", "ssh://")): + ctx.other_lines.setdefault(line, None) + return + + try: + requirement = Requirement(line) + except InvalidRequirement as exc: + ctx.errors.append(f"{source}: '{line}' is not a valid requirement ({exc})") + return + if requirement.url: + # name @ url: installed from that address, as written + ctx.other_lines.setdefault(line, None) + return + marker = str(requirement.marker) if requirement.marker else "" + entry = Entry(source, line, requirement.name, tuple(sorted(requirement.extras)), str(requirement.specifier), marker) + ctx.groups.setdefault((canonicalize_name(requirement.name), marker), []).append(entry) + + +def read_requirements_file(path: Path, ctx: RequirementContext): + try: + text = path.read_text(encoding="utf-8") + except Exception: + return + + for raw in text.splitlines(): + line = normalize_line(raw) + process_requirement_line(line, ctx, display_path(path), base_dir=path.parent) + + +def read_requirements_yaml(path: Path, ctx: RequirementContext, os_contexts: dict[str, RequirementContext]) -> str | None: + """Read requirements.yaml and return its python_version if present.""" + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except Exception: + return None + + python_version = data.get("python_version") + dependencies = data.get("dependencies", []) or [] + source = display_path(path) + + for dep in dependencies: + line = normalize_line(str(dep)) + process_requirement_line(line, ctx, source, base_dir=path.parent) + + for os_name, field_name in OS_FIELD_MAP.items(): + os_deps = data.get(field_name) or [] + if not os_deps: + continue + os_ctx = os_contexts.get(os_name) + if os_ctx is None: + continue + for dep in os_deps: + line = normalize_line(str(dep)) + process_requirement_line(line, os_ctx, f"{source} ({field_name})", base_dir=path.parent) + + return python_version + + +def find_requirements_files(source_dir): + if not source_dir.exists(): + return [] + + patterns = ["requirements.yaml", "requirements.yml", "requirements*.txt"] + + files = [] + for pattern in patterns: + files.extend(source_dir.rglob(pattern)) + return sorted({f.resolve() for f in files}) + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Deciding the requirement of each package +# -------------------------------------------------------------------------------------------------------------------------------- +def load_overrides(path: Path) -> dict[str, Override]: + """The decisions of requirements_overrides.yaml, by package name as pip compares them (none when the file is absent).""" + if not path.is_file(): + return {} + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except yaml.YAMLError as exc: + raise ValueError(f"{display_path(path)} is not valid YAML: {exc}") from exc + entries = data.get("overrides") if isinstance(data, dict) else None + if entries is None: + return {} + if not isinstance(entries, dict): + raise ValueError(f"{display_path(path)}: `overrides` must map package names to {{use: ..., reason: ...}}") + overrides: dict[str, Override] = {} + for name, value in entries.items(): + use = value.get("use") if isinstance(value, dict) else None + reason = value.get("reason") if isinstance(value, dict) else None + if not isinstance(use, str) or not use.strip(): + raise ValueError(f"{display_path(path)}: {name} needs `use`, the requirement every notebook gets, for example \"==2.0.0\"") + if not isinstance(reason, str) or not reason.strip(): + raise ValueError(f"{display_path(path)}: {name} needs `reason`, why this requirement is right for every notebook that uses {name}") + try: + SpecifierSet(use.strip()) + except InvalidSpecifier as exc: + raise ValueError(f"{display_path(path)}: {name}: `use: {use}` is not a version requirement such as \"==2.0.0\" or \">=1.24,<2\" ({exc})") from exc + overrides[canonicalize_name(str(name))] = Override(str(name), use.strip(), " ".join(reason.split())) + return overrides + + +def _exact_versions(entry: Entry) -> list[str]: + return [s.version for s in SpecifierSet(entry.spec) if s.operator in ("==", "===") and "*" not in s.version] + + +def _same_version(a: str, b: str) -> bool: + try: + return Version(a) == Version(b) + except InvalidVersion: + return a == b + + +def _union_extras(entries: list[Entry]) -> list[str]: + extras: list[str] = [] + for entry in entries: + extras.extend(extra for extra in entry.extras if extra not in extras) + return extras + + +def resolve_group(package: str, entries: list[Entry], checked_with: list[Entry], override: Override | None, where: str = "") -> Resolved: + """The requirement written for `entries` (one package, one marker); `checked_with` are other requirements that apply too. + + An override decides. Otherwise the requirements are combined: several different exact pins, or a pin that does not meet another + requirement, raise Conflict (whatever the order of the files). Without a pin, the combined ranges are written as they are. + """ + extras = _union_extras(entries) + if override is not None: + override.used = True + return Resolved(entries, override.use, extras, override) + everything = entries + checked_with + pins: list[tuple[str, Entry]] = [(version, entry) for entry in everything for version in _exact_versions(entry)] + distinct: list[str] = [] + for version, _ in pins: + if not any(_same_version(version, seen) for seen in distinct): + distinct.append(version) + if len(distinct) > 1: + raise Conflict(package, f"pinned to different versions ({', '.join(sorted(distinct))})", everything, where) + if distinct: + pin = distinct[0] + for entry in everything: + if entry.spec and not SpecifierSet(entry.spec).contains(pin, prereleases=True): + raise Conflict(package, f"the pin =={pin} does not meet {entry.name}{entry.spec} of {entry.source}", everything, where) + elif not satisfiable(SpecifierSet(",".join(entry.spec for entry in everything if entry.spec))): + raise Conflict(package, "no version meets all of these requirements", everything, where) + # The line keeps the requirements of its own entries; `checked_with` (the common requirements of an OS file) only had to agree. + own_pins = [version for entry in entries for version in _exact_versions(entry)] + if own_pins: + return Resolved(entries, f"=={own_pins[0]}", extras) + return Resolved(entries, str(SpecifierSet(",".join(entry.spec for entry in entries if entry.spec))), extras) + + +def satisfiable(specifiers: SpecifierSet) -> bool: + """Whether some version meets every specifier (`<2,>=2.1` does not). + + Every version a specifier names is tried, and versions just above it (2.1, 2.1.1, 2.1.0.1, 2.1.0.0.1): a range that only versions + closer than that could meet is reported as unsatisfiable, which stops the merge (an override then decides) instead of guessing. + """ + if not len(specifiers): + return True + candidates: list[str] = [] + for specifier in specifiers: + version = specifier.version.removesuffix(".*") + candidates += [version, f"{version}.1", f"{version}.0.1", f"{version}.0.0.1"] + for candidate in candidates: + try: + if specifiers.contains(candidate, prereleases=True): + return True + except InvalidVersion: + continue + return False + + +def resolve_context(ctx: RequirementContext, overrides: dict[str, Override], conflicts: list[Conflict], + base: RequirementContext | None = None, where: str = "") -> list[Resolved]: + """Resolve every package of a context; an OS context is also checked against the common requirements that apply on that OS.""" + resolved: list[Resolved] = [] + for (package, marker), entries in ctx.groups.items(): + checked_with: list[Entry] = [] + if base is not None: + for (base_package, base_marker), base_entries in base.groups.items(): + if base_package == package and base_marker in ("", marker): + checked_with.extend(base_entries) + try: + resolved.append(resolve_group(package, entries, checked_with, overrides.get(package), where)) + except Conflict as conflict: + conflicts.append(conflict) + return resolved + + +def conflict_report(conflicts: list[Conflict], errors: list[str], overrides_path: Path) -> str: + lines = ["The notebooks ask for incompatible package versions, so no requirements file was written.", ""] + for error in errors: + lines.append(f" {error}") + for conflict in sorted(conflicts, key=lambda c: (c.package, c.where)): + where = f" ({conflict.where})" if conflict.where else "" + lines.append(f" {conflict.package}{where}: {conflict.reason}") + for entry in sorted(conflict.entries, key=lambda e: (e.source, e.line)): + lines.append(f" {entry.source}: {entry.line}") + if conflicts: + example = sorted(conflicts, key=lambda c: c.package)[0].package + lines += [ + "", + f"Make the notebooks agree (edit their requirements.yaml), or decide in {display_path(overrides_path)} which requirement every", + "notebook gets, and why. It is written at the top of the generated requirements files. For example:", + "", + "overrides:", + f" {example}:", + ' use: "=="', + f' reason: ""', + ] + lines += ["", f"See {DOCS_URL}"] + return "\n".join(lines) + + +def override_header(resolved: list[Resolved]) -> list[str]: + lines = [] + for item in resolved: + if item.override is None: + continue + asked = "; ".join(f"{entry.source}: {entry.line}" for entry in item.entries if entry.source != ADDED_BY_SCRIPT) + lines.append(f"# Decided in {OVERRIDES_FILE}: {item.line()} (the notebooks ask for: {asked}). Reason: {item.override.reason}") + return lines + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Packages the app always needs +# -------------------------------------------------------------------------------------------------------------------------------- +def resolve_ipywidgets_version(py_version, jl_version): + """Resolve ipywidgets version based on Python, JupyterLab versions. + + Returns a version spec string like ">=7.0.0,<8.0.0" or a pinned version. + """ + + # Simple heuristic: ipywidgets 8.x for modern stacks, 7.x for older + try: + py_major, py_minor = map(int, py_version.split(".")[:2]) + jl_major = int(jl_version.split(".")[0]) + + if jl_major >= 4 and py_major >= 3 and py_minor >= 9: + return "8.1.7" # Latest stable for modern Python + JupyterLab 4 + elif py_major >= 3 and py_minor >= 7: + return "8.1.6" # Good for Python 3.7+ + else: + return "7.7.2" # Fallback for older environments + except Exception: + return ">=7.0.0" # Safe fallback + + +def _has_package(ctx: RequirementContext, package: str) -> bool: + return any(name == package for name, _ in ctx.groups) + + +def _add_package(ctx: RequirementContext, name: str, spec: str) -> None: + ctx.groups[(canonicalize_name(name), "")] = [Entry(ADDED_BY_SCRIPT, f"{name}{spec}", name, (), spec, "")] + + +def determine_jupyterlab_version(resolved: list[Resolved], default: str = "4.4.0") -> str: + for item in resolved: + if canonicalize_name(item.name) == "jupyterlab" and not item.marker and item.spec.startswith("==") and "," not in item.spec: + return item.spec[2:] + return default + + +def ensure_jl_hidecode(ctx: RequirementContext): + if _has_package(ctx, "jl-hidecode"): + return + _add_package(ctx, "jl-hidecode", "==0.0.1") + print("Added jl-hidecode==0.0.1 (enforced)") + + +def ensure_ipywidgets(ctx: RequirementContext, python_version: str | None, jl_ver: str) -> bool: + if _has_package(ctx, "ipywidgets"): + return False + iw_version = resolve_ipywidgets_version(python_version, jl_ver) + spec = iw_version if iw_version[:1] in "<>=!~" else f"=={iw_version}" + _add_package(ctx, "ipywidgets", spec) + print(f"Added ipywidgets{spec} (resolved)") + return True + + +def build_final_lines(ctx: RequirementContext, resolved: list[Resolved], sort: bool) -> list[str]: + final_lines: list[str] = list(ctx.other_lines.keys()) + items = sorted(resolved, key=lambda item: item.name.casefold()) if sort else resolved + final_lines.extend(item.line() for item in items) + return final_lines + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Output files +# -------------------------------------------------------------------------------------------------------------------------------- +def get_os_output_path(output: Path, os_name: str) -> Path: + suffix = output.suffix + stem = output.stem + return output.with_name(f"{stem}-{os_name}{suffix}") + + +def get_gpu_output_path(output: Path) -> Path: + suffix = output.suffix + stem = output.stem + return output.with_name(f"{stem}_gpu{suffix}") + + +def merge_requirement_extras(extras: str, extra_name: str) -> str: + if not extras: + return f"[{extra_name}]" + + extras_content = extras[1:-1] + parts = [part.strip() for part in extras_content.split(",") if part.strip()] + if extra_name not in parts: + parts.append(extra_name) + return "[" + ",".join(parts) + "]" + + +def rewrite_tensorflow_for_gpu(line: str) -> str: + match = pkg_re.match(line) + if match: + name = match.group("name") + if name.lower() != "tensorflow": + return line + extras = merge_requirement_extras(match.group("extras") or "", "and-cuda") + marker = match.group("marker") or "" + return f"{name}{extras}{match.group('op')}{match.group('ver')}{marker}" + + match = PLAIN_PKG_RE.match(line) + if match and match.group("name").lower() == "tensorflow": + extras = merge_requirement_extras(match.group("extras") or "", "and-cuda") + marker = match.group("marker") or "" + return f"{match.group('name')}{extras}{marker}" + + return line + + +# TensorFlow's `and-cuda` extra pulls nvidia-* wheels that exist only for Linux (nvidia-nccl-cu12 has never had a Windows or macOS +# wheel), and the extra itself carries no platform marker. Without a marker the universal lock of requirements_gpu.txt pins them for +# every system, so `pip install` fails on a Windows computer with an NVIDIA driver (the installer picks the GPU file there). TensorFlow +# has had no native Windows GPU build since 2.10, so Windows and macOS keep plain `tensorflow` in the GPU file. +GPU_TENSORFLOW_PLATFORM = 'sys_platform == "linux"' +NON_GPU_TENSORFLOW_PLATFORM = 'sys_platform != "linux"' + + +def _with_platform(marker: str, platform: str) -> str: + """Return ` ; `, combined with the line's own marker (`; `) when it has one.""" + existing = marker.split(";", 1)[1].strip() if ";" in marker else "" + return f" ; ({existing}) and {platform}" if existing else f" ; {platform}" + + +def tensorflow_gpu_lines(line: str) -> list[str]: + """Return the GPU-file lines for a tensorflow requirement: `[and-cuda]` on Linux, the plain requirement elsewhere. + + A line that is not a tensorflow requirement is returned unchanged (as a one-item list). + """ + match = pkg_re.match(line) + if match: + if match.group("name").lower() != "tensorflow": + return [line] + name, extras = match.group("name"), match.group("extras") or "" + spec = f"{match.group('op')}{match.group('ver')}" + else: + match = PLAIN_PKG_RE.match(line) + if not match or match.group("name").lower() != "tensorflow": + return [line] + name, extras, spec = match.group("name"), match.group("extras") or "", "" + marker = match.group("marker") or "" + cuda_extras = merge_requirement_extras(extras, "and-cuda") + return [ + f"{name}{cuda_extras}{spec}{_with_platform(marker, GPU_TENSORFLOW_PLATFORM)}", + f"{name}{extras}{spec}{_with_platform(marker, NON_GPU_TENSORFLOW_PLATFORM)}", + ] + + +def build_gpu_lines(final_lines: list[str]) -> list[str]: + gpu_lines: list[str] = [] + has_torch_package = False + has_torch_index = False + + for line in final_lines: + if "download.pytorch.org/whl" in line: + has_torch_index = True + + match = pkg_re.match(line) or PLAIN_PKG_RE.match(line) + if match: + package_name = match.group("name").lower() + if package_name in TORCH_GPU_PACKAGES: + has_torch_package = True + if package_name == "tensorflow": + gpu_lines.extend(tensorflow_gpu_lines(line)) + continue + + gpu_lines.append(line) + + if has_torch_package and not has_torch_index: + insertion_index = 0 + while insertion_index < len(gpu_lines) and gpu_lines[insertion_index].startswith("-"): + insertion_index += 1 + gpu_lines.insert(insertion_index, GPU_TORCH_EXTRA_INDEX_URL) + + return gpu_lines + + +def write_requirements_output( + path: Path, + files: list[Path], + final_lines: list[str], + target_os: str | None = None, + target_accelerator: str | None = None, + decisions: list[str] | None = None, +): + generated = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + header_lines = [ + f"# Generated by .tools/python/merge_requirements.py on {generated}Z", + f"# Source files: {', '.join(str(p) for p in files)}", + ] + if target_os: + header_lines.append(f"# Target OS: {OS_DISPLAY_NAMES.get(target_os, target_os.capitalize())}") + if target_accelerator: + header_lines.append(f"# Target accelerator: {target_accelerator}") + header_lines.extend(decisions or []) + header_lines.append("# ---") + + content = "\n".join(header_lines) + "\n" + if final_lines: + content += "\n".join(final_lines) + if not content.endswith("\n"): + content += "\n" + + path.write_text(content, encoding="utf-8") + + +def main(argv: list[str] | None = None): + parser = argparse.ArgumentParser(description="Merge multiple requirements files (txt or yaml) into one.") + parser.add_argument("--source-dir", default="notebooks", help="Directory to scan for requirements files") + parser.add_argument("--output", default="requirements.txt", help="Output requirements file to write") + parser.add_argument("--sort", action="store_true", help="Sort final requirements alphabetically") + parser.add_argument("--overrides", help=f"Decisions for conflicting requirements (default: {OVERRIDES_FILE} next to the output)") + parser.add_argument("--check", action="store_true", help="Only check that the notebooks' requirements do not conflict; write nothing") + args = parser.parse_args(argv) + + source = Path(args.source_dir) + output = Path(args.output) + overrides_path = Path(args.overrides) if args.overrides else output.with_name(OVERRIDES_FILE) + + discovered_files = find_requirements_files(source) + + skip_outputs = {output.resolve()} + skip_outputs.add(get_gpu_output_path(output).resolve()) + for os_name in OS_FIELD_MAP: + skip_outputs.add(get_os_output_path(output, os_name).resolve()) + + files = [f for f in discovered_files if f.resolve() not in skip_outputs] + if not files: + if args.check: + print(f"No requirements files found under {source}: nothing to check.") + return 0 + print(f"No requirements files found under {source}, writing empty {output}") + output.write_text("# Generated requirements (none found)\n", encoding="utf-8") + gpu_output = get_gpu_output_path(output) + gpu_output.write_text("# Generated GPU requirements (none found)\n", encoding="utf-8") + return 0 + + base_ctx = RequirementContext() + os_contexts = {name: RequirementContext() for name in OS_FIELD_MAP} + python_version = None + + for f in files: + if f.suffix.lower() in {".yaml", ".yml"}: + candidate_py = read_requirements_yaml(f, base_ctx, os_contexts) + python_version = merge_python_version(f, python_version, candidate_py) + else: + read_requirements_file(f, base_ctx) + + try: + overrides = load_overrides(overrides_path) + except ValueError as exc: + print(f"{exc}\nSee {DOCS_URL}", file=sys.stderr) + return 1 + + ensure_jl_hidecode(base_ctx) + conflicts: list[Conflict] = [] + base_resolved = resolve_context(base_ctx, overrides, conflicts) + jl_ver = determine_jupyterlab_version(base_resolved) + if ensure_ipywidgets(base_ctx, python_version, jl_ver): + key = next(reversed(base_ctx.groups)) + base_resolved.append(resolve_group(key[0], base_ctx.groups[key], [], overrides.get(key[0]))) + os_resolved = { + os_name: resolve_context(ctx, overrides, conflicts, base=base_ctx, where=f"{OS_FIELD_MAP[os_name]}, with the common dependencies") + for os_name, ctx in os_contexts.items() + } + errors = base_ctx.errors + [error for ctx in os_contexts.values() for error in ctx.errors] + if conflicts or errors: + print(conflict_report(conflicts, errors, overrides_path), file=sys.stderr) + return 1 + for override in overrides.values(): + if not override.used: + print(f"Note: {display_path(overrides_path)} decides {override.name}, which no notebook requires any more; the entry can be removed.") + if args.check: + print(f"The requirements of {len(files)} file(s) do not conflict" + + (f" ({sum(o.used for o in overrides.values())} decision(s) from {display_path(overrides_path)})." if overrides else ".")) + return 0 + + decisions = override_header(base_resolved) + base_final_lines = build_final_lines(base_ctx, base_resolved, args.sort) + write_requirements_output(output, files, base_final_lines, decisions=decisions) + print(f"Wrote {output} with {len(base_final_lines)} entries (from {len(files)} files)") + + gpu_output = get_gpu_output_path(output) + gpu_final_lines = build_gpu_lines(base_final_lines) + write_requirements_output( + gpu_output, + files, + gpu_final_lines, + target_accelerator=GPU_DISPLAY_NAME, + decisions=decisions, + ) + print(f"Wrote {gpu_output} with {len(gpu_final_lines)} entries (from {len(files)} files, target {GPU_DISPLAY_NAME})") + + for os_name, ctx in os_contexts.items(): + if not ctx.groups and not ctx.other_lines: + continue + os_final_lines = build_final_lines(ctx, os_resolved[os_name], args.sort) + os_output = get_os_output_path(output, os_name) + write_requirements_output(os_output, files, os_final_lines, target_os=os_name, decisions=override_header(os_resolved[os_name])) + print(f"Wrote {os_output} with {len(os_final_lines)} entries (from {len(files)} files, target {os_name})") + + # Create the environment.yaml if not present + env_path = Path("environment.yaml") + if not env_path.exists(): + print(f"{env_path} not found, please be sure to create one.") + raise FileNotFoundError(f"{env_path} not found.") + else: + data = yaml.safe_load(env_path.read_text(encoding="utf-8")) + dependencies = data.get("dependencies", []) + python_updated = False + jl_updated = False + for i, dep in enumerate(dependencies): + if not isinstance(dep, str): + continue + if python_version and dep.startswith("python="): + dependencies[i] = f"python={python_version}" + python_updated = True + if dep.startswith("jupyterlab="): + dependencies[i] = f"jupyterlab={jl_ver}" + jl_updated = True + data["dependencies"] = dependencies + env_path.write_text(yaml.dump(data, sort_keys=False), encoding="utf-8") + if python_updated or jl_updated: + parts = [] + if python_updated: + parts.append(f"python={python_version}") + if jl_updated: + parts.append(f"jupyterlab={jl_ver}") + print(f"Updated {env_path} with {', '.join(parts)}") + else: + print(f"No python/jupyterlab entries updated in {env_path}") + + # Replace on setup.py the Python version + setup_path = Path("setup.py") + if setup_path.exists() and python_version: + setup_text = setup_path.read_text(encoding="utf-8") + # Require only the major.minor series: environment.yaml pins the exact + # patch release for the installer, but a source install should accept + # any patch release of that series (e.g. 3.12.3 for 3.12.13). + python_series = ".".join(str(python_version).split(".")[:2]) + pattern = r'python_requires\s*=\s*["\'][><=\.0-9 ]+(PYTHON\_VERSION)?["\']' + new_setup_text = re.sub(pattern, f'python_requires=">={python_series}"', setup_text) + setup_path.write_text(new_setup_text, encoding="utf-8") + print(f"Updated {setup_path} with python_requires>={python_series}") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_30_to_v0_1_31/previous/.tools/python/merge_requirements.py b/.template_sync/resources/v0_1_30_to_v0_1_31/previous/.tools/python/merge_requirements.py new file mode 100644 index 0000000..1fccecb --- /dev/null +++ b/.template_sync/resources/v0_1_30_to_v0_1_31/previous/.tools/python/merge_requirements.py @@ -0,0 +1,543 @@ +#!/usr/bin/env python3 +"""Merge requirements files under a directory (e.g. notebooks/*) into a single +root requirements file. + +The script now supports both classic requirements.txt files and the new +requirements.yaml format used by notebooks. For YAML files, it merges the +`python_version` (picking the newest) and the `dependencies` list while +discarding per-notebook descriptions. + +It also recognizes optional per-OS fields (`windows_dependencies`, +`linux_dependencies`, `macos_dependencies`) and emits dedicated requirements +outputs for each platform containing only the entries from their OS-specific +lists, in addition to the common file. + +Alongside the common requirements file, it emits a GPU-targeted variant. The +GPU file rewrites `tensorflow` to `tensorflow[and-cuda]` on Linux only (TensorFlow's CUDA +wheels exist only for Linux; other systems keep plain `tensorflow`) and adds the +PyTorch CUDA wheel index when `torch`, `torchvision`, or `torchaudio` are present. + +It resolves simple version conflicts by choosing the newest version seen for a +given package (and emits a pinned `pkg==`). It still preserves +non-package lines (pip options, VCS/URLs) and supports simple `-r` includes. + +It also automatically adds ipywidgets if missing, with a version determined by +Python, JupyterLab, and matplotlib versions from environment.yaml. +""" +from pathlib import Path +import argparse +import sys +from collections import OrderedDict +from datetime import datetime +import re +import yaml + + +# Regex to capture name, optional extras, operator and version, and optional markers +pkg_re = re.compile(r"^(?P[A-Za-z0-9_.+-]+)(?P\[[^\]]+\])?\s*(?P==|>=|<=|~=|!=|>|<)\s*(?P[^;\s]+)(?P\s*;.*)?$") + +OS_FIELD_MAP = { + "windows": "windows_dependencies", + "linux": "linux_dependencies", + "macos": "macos_dependencies", +} +OS_DISPLAY_NAMES = { + "windows": "Windows", + "linux": "Linux", + "macos": "macOS", +} +GPU_DISPLAY_NAME = "NVIDIA GPU" +GPU_TORCH_EXTRA_INDEX_URL = "--extra-index-url https://download.pytorch.org/whl/cu128" +TORCH_GPU_PACKAGES = {"torch", "torchvision", "torchaudio"} +PLAIN_PKG_RE = re.compile( + r"^(?P[A-Za-z0-9_.+-]+)(?P\[[^\]]+\])?(?P\s*;.*)?$" +) + + +class RequirementContext: + def __init__(self): + self.pkg_order: list[str] = [] + self.pkgs: dict[str, dict] = {} + self.other_lines: OrderedDict[str, None] = OrderedDict() + + +def normalize_line(line: str) -> str: + # Remove inline comments and surrounding whitespace. + if "#" in line: + line = line.split("#", 1)[0] + return line.strip() + + +try: + # Prefer packaging.version for robust version comparison + from packaging.version import Version, InvalidVersion + + def parse_version(v: str): + try: + return Version(v) + except InvalidVersion: + return v + + def is_version_greater(a, b): + try: + return Version(a) > Version(b) + except Exception: + return str(a) > str(b) + +except Exception: + # Fallback: simple numeric-aware comparator + def _split_parts(v: str): + parts = re.split(r"[.\-+_]|(?=[a-zA-Z])", v) + key = [] + for p in parts: + if not p: + continue + if p.isdigit(): + key.append((0, int(p))) + else: + key.append((1, p)) + return tuple(key) + + def parse_version(v: str): + return _split_parts(v) + + def is_version_greater(a, b): + return parse_version(a) > parse_version(b) + + +def merge_python_version(filepath: str | None, current: str | None, candidate: str | None): + """Pick the newest python_version string, if provided.""" + if not candidate: + return current + if current is None: + return candidate + if current == candidate: + return current + else: + raise ValueError(f"Conflicting python_version found {current} vs {candidate} when processing {filepath}") + + +def process_requirement_line(line: str, pkg_order: list, pkgs: dict, other_lines: OrderedDict, base_dir: Path | None = None): + """Handle a single requirement line (shared between txt and yaml inputs).""" + if not line: + return + + parts = line.split(maxsplit=1) + if parts[0] in ("-r", "--requirement") and len(parts) == 2: + include_path = Path(parts[1]) if base_dir is None else (base_dir / parts[1]) + include = include_path.resolve() + if include.exists(): + read_requirements_file(include, pkg_order, pkgs, other_lines) + return + + # Keep pip option lines (indexes, find-links, etc.) as-is + if line.startswith("--") or line.startswith("-f ") or line.startswith("-i ") or line.startswith("-e "): + other_lines.setdefault(line, None) + return + + # VCS or URL lines (git+, http(s)://, file:) keep as-is + if any(line.startswith(prefix) for prefix in ("git+", "http://", "https://", "file:", "ssh://")): + other_lines.setdefault(line, None) + return + + m = pkg_re.match(line) + if not m: + # plain package (unpinned) or marker-only spec + key = line.split(";", 1)[0].strip().lower() + if key not in pkgs: + pkgs[key] = {"name": line, "pinned": False, "ver": None} + pkg_order.append(key) + return + + name = m.group("name") + extras = m.group("extras") or "" + ver = m.group("ver") + marker = m.group("marker") or "" + + base = name.lower() + if base not in pkgs: + pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} + pkg_order.append(base) + else: + existing = pkgs[base] + if not existing.get("pinned"): + pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} + else: + try: + if is_version_greater(ver, existing.get("ver")): + pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} + except Exception: + if str(ver) > str(existing.get("ver")): + pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} + + +def read_requirements_file(path: Path, pkg_order: list, pkgs: dict, other_lines: OrderedDict): + try: + text = path.read_text(encoding="utf-8") + except Exception: + return + + for raw in text.splitlines(): + line = normalize_line(raw) + process_requirement_line(line, pkg_order, pkgs, other_lines, base_dir=path.parent) + + +def read_requirements_yaml(path: Path, pkg_order: list, pkgs: dict, other_lines: OrderedDict, os_contexts: dict[str, RequirementContext]) -> str | None: + """Read requirements.yaml and return its python_version if present.""" + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except Exception: + return None + + python_version = data.get("python_version") + dependencies = data.get("dependencies", []) or [] + + for dep in dependencies: + line = normalize_line(str(dep)) + process_requirement_line(line, pkg_order, pkgs, other_lines, base_dir=path.parent) + + for os_name, field in OS_FIELD_MAP.items(): + os_deps = data.get(field) or [] + if not os_deps: + continue + ctx = os_contexts.get(os_name) + if ctx is None: + continue + for dep in os_deps: + line = normalize_line(str(dep)) + process_requirement_line(line, ctx.pkg_order, ctx.pkgs, ctx.other_lines, base_dir=path.parent) + + return python_version + + +def find_requirements_files(source_dir): + if not source_dir.exists(): + return [] + + patterns = ["requirements.yaml", "requirements.yml", "requirements*.txt"] + + files = [] + for pattern in patterns: + files.extend(source_dir.rglob(pattern)) + return sorted({f.resolve() for f in files}) + + +def resolve_ipywidgets_version(py_version, jl_version): + """Resolve ipywidgets version based on Python, JupyterLab versions. + + Returns a version spec string like ">=7.0.0,<8.0.0" or a pinned version. + """ + + # Simple heuristic: ipywidgets 8.x for modern stacks, 7.x for older + try: + py_major, py_minor = map(int, py_version.split(".")[:2]) + jl_major = int(jl_version.split(".")[0]) + + if jl_major >= 4 and py_major >= 3 and py_minor >= 9: + return "8.1.7" # Latest stable for modern Python + JupyterLab 4 + elif py_major >= 3 and py_minor >= 7: + return "8.1.6" # Good for Python 3.7+ + else: + return "7.7.2" # Fallback for older environments + except Exception: + return ">=7.0.0" # Safe fallback + + +def determine_jupyterlab_version(pkgs: dict, default: str = "4.4.0") -> str: + jl_info = pkgs.get("jupyterlab") + if jl_info and jl_info.get("pinned") and jl_info.get("ver"): + return jl_info["ver"] + return default + + +def ensure_jl_hidecode(ctx: RequirementContext): + if "jl-hidecode" in ctx.pkgs: + return + ctx.pkgs["jl-hidecode"] = { + "name": "jl-hidecode", + "pinned": True, + "ver": "0.0.1", + "marker": "", + } + ctx.pkg_order.append("jl-hidecode") + print("Added jl-hidecode==0.0.1 (enforced)") + + +def ensure_ipywidgets(ctx: RequirementContext, python_version: str | None, jl_ver: str): + if "ipywidgets" in ctx.pkgs: + return + iw_version = resolve_ipywidgets_version(python_version, jl_ver) + ctx.pkgs["ipywidgets"] = { + "name": "ipywidgets", + "pinned": True, + "ver": iw_version, + "marker": "", + } + ctx.pkg_order.append("ipywidgets") + print(f"Added ipywidgets=={iw_version} (resolved)") + + +def build_final_lines(ctx: RequirementContext, sort: bool) -> list[str]: + final_lines: list[str] = [] + for ol in ctx.other_lines.keys(): + final_lines.append(ol) + + pkg_keys = sorted(ctx.pkg_order, key=str.casefold) if sort else ctx.pkg_order + + for key in pkg_keys: + info = ctx.pkgs.get(key) + if not info: + continue + if info.get("pinned") and info.get("ver"): + final_lines.append(f"{info['name']}=={info['ver']}{info.get('marker','')}") + else: + final_lines.append(info["name"]) + return final_lines + + +def get_os_output_path(output: Path, os_name: str) -> Path: + suffix = output.suffix + stem = output.stem + return output.with_name(f"{stem}-{os_name}{suffix}") + + +def get_gpu_output_path(output: Path) -> Path: + suffix = output.suffix + stem = output.stem + return output.with_name(f"{stem}_gpu{suffix}") + + +def merge_requirement_extras(extras: str, extra_name: str) -> str: + if not extras: + return f"[{extra_name}]" + + extras_content = extras[1:-1] + parts = [part.strip() for part in extras_content.split(",") if part.strip()] + if extra_name not in parts: + parts.append(extra_name) + return "[" + ",".join(parts) + "]" + + +def rewrite_tensorflow_for_gpu(line: str) -> str: + match = pkg_re.match(line) + if match: + name = match.group("name") + if name.lower() != "tensorflow": + return line + extras = merge_requirement_extras(match.group("extras") or "", "and-cuda") + marker = match.group("marker") or "" + return f"{name}{extras}{match.group('op')}{match.group('ver')}{marker}" + + match = PLAIN_PKG_RE.match(line) + if match and match.group("name").lower() == "tensorflow": + extras = merge_requirement_extras(match.group("extras") or "", "and-cuda") + marker = match.group("marker") or "" + return f"{match.group('name')}{extras}{marker}" + + return line + + +# TensorFlow's `and-cuda` extra pulls nvidia-* wheels that exist only for Linux (nvidia-nccl-cu12 has never had a Windows or macOS +# wheel), and the extra itself carries no platform marker. Without a marker the universal lock of requirements_gpu.txt pins them for +# every system, so `pip install` fails on a Windows computer with an NVIDIA driver (the installer picks the GPU file there). TensorFlow +# has had no native Windows GPU build since 2.10, so Windows and macOS keep plain `tensorflow` in the GPU file. +GPU_TENSORFLOW_PLATFORM = 'sys_platform == "linux"' +NON_GPU_TENSORFLOW_PLATFORM = 'sys_platform != "linux"' + + +def _with_platform(marker: str, platform: str) -> str: + """Return ` ; `, combined with the line's own marker (`; `) when it has one.""" + existing = marker.split(";", 1)[1].strip() if ";" in marker else "" + return f" ; ({existing}) and {platform}" if existing else f" ; {platform}" + + +def tensorflow_gpu_lines(line: str) -> list[str]: + """Return the GPU-file lines for a tensorflow requirement: `[and-cuda]` on Linux, the plain requirement elsewhere. + + A line that is not a tensorflow requirement is returned unchanged (as a one-item list). + """ + match = pkg_re.match(line) + if match: + if match.group("name").lower() != "tensorflow": + return [line] + name, extras = match.group("name"), match.group("extras") or "" + spec = f"{match.group('op')}{match.group('ver')}" + else: + match = PLAIN_PKG_RE.match(line) + if not match or match.group("name").lower() != "tensorflow": + return [line] + name, extras, spec = match.group("name"), match.group("extras") or "", "" + marker = match.group("marker") or "" + cuda_extras = merge_requirement_extras(extras, "and-cuda") + return [ + f"{name}{cuda_extras}{spec}{_with_platform(marker, GPU_TENSORFLOW_PLATFORM)}", + f"{name}{extras}{spec}{_with_platform(marker, NON_GPU_TENSORFLOW_PLATFORM)}", + ] + + +def build_gpu_lines(final_lines: list[str]) -> list[str]: + gpu_lines: list[str] = [] + has_torch_package = False + has_torch_index = False + + for line in final_lines: + if "download.pytorch.org/whl" in line: + has_torch_index = True + + match = pkg_re.match(line) or PLAIN_PKG_RE.match(line) + if match: + package_name = match.group("name").lower() + if package_name in TORCH_GPU_PACKAGES: + has_torch_package = True + if package_name == "tensorflow": + gpu_lines.extend(tensorflow_gpu_lines(line)) + continue + + gpu_lines.append(line) + + if has_torch_package and not has_torch_index: + insertion_index = 0 + while insertion_index < len(gpu_lines) and gpu_lines[insertion_index].startswith("-"): + insertion_index += 1 + gpu_lines.insert(insertion_index, GPU_TORCH_EXTRA_INDEX_URL) + + return gpu_lines + + +def write_requirements_output( + path: Path, + files: list[Path], + final_lines: list[str], + target_os: str | None = None, + target_accelerator: str | None = None, +): + header_lines = [ + f"# Generated by .tools/python/merge_requirements.py on {datetime.utcnow().isoformat()}Z", + f"# Source files: {', '.join(str(p) for p in files)}", + ] + if target_os: + header_lines.append(f"# Target OS: {OS_DISPLAY_NAMES.get(target_os, target_os.capitalize())}") + if target_accelerator: + header_lines.append(f"# Target accelerator: {target_accelerator}") + header_lines.append("# ---") + + content = "\n".join(header_lines) + "\n" + if final_lines: + content += "\n".join(final_lines) + if not content.endswith("\n"): + content += "\n" + + path.write_text(content, encoding="utf-8") + + +def main(): + parser = argparse.ArgumentParser(description="Merge multiple requirements files (txt or yaml) into one.") + parser.add_argument("--source-dir", default="notebooks", help="Directory to scan for requirements files") + parser.add_argument("--output", default="requirements.txt", help="Output requirements file to write") + parser.add_argument("--sort", action="store_true", help="Sort final requirements alphabetically") + args = parser.parse_args() + + source = Path(args.source_dir) + output = Path(args.output) + + discovered_files = find_requirements_files(source) + + skip_outputs = {output.resolve()} + skip_outputs.add(get_gpu_output_path(output).resolve()) + for os_name in OS_FIELD_MAP: + skip_outputs.add(get_os_output_path(output, os_name).resolve()) + + files = [f for f in discovered_files if f.resolve() not in skip_outputs] + if not files: + print(f"No requirements files found under {source}, writing empty {output}") + output.write_text("# Generated requirements (none found)\n", encoding="utf-8") + gpu_output = get_gpu_output_path(output) + gpu_output.write_text("# Generated GPU requirements (none found)\n", encoding="utf-8") + return 0 + + base_ctx = RequirementContext() + os_contexts = {name: RequirementContext() for name in OS_FIELD_MAP} + python_version = None + + for f in files: + if f.suffix.lower() in {".yaml", ".yml"}: + candidate_py = read_requirements_yaml(f, base_ctx.pkg_order, base_ctx.pkgs, base_ctx.other_lines, os_contexts) + python_version = merge_python_version(f, python_version, candidate_py) + else: + read_requirements_file(f, base_ctx.pkg_order, base_ctx.pkgs, base_ctx.other_lines) + + ensure_jl_hidecode(base_ctx) + jl_ver = determine_jupyterlab_version(base_ctx.pkgs) + ensure_ipywidgets(base_ctx, python_version, jl_ver) + + base_final_lines = build_final_lines(base_ctx, args.sort) + write_requirements_output(output, files, base_final_lines) + print(f"Wrote {output} with {len(base_final_lines)} entries (from {len(files)} files)") + + gpu_output = get_gpu_output_path(output) + gpu_final_lines = build_gpu_lines(base_final_lines) + write_requirements_output( + gpu_output, + files, + gpu_final_lines, + target_accelerator=GPU_DISPLAY_NAME, + ) + print(f"Wrote {gpu_output} with {len(gpu_final_lines)} entries (from {len(files)} files, target {GPU_DISPLAY_NAME})") + + for os_name, ctx in os_contexts.items(): + if not ctx.pkg_order and not ctx.other_lines: + continue + os_final_lines = build_final_lines(ctx, args.sort) + os_output = get_os_output_path(output, os_name) + write_requirements_output(os_output, files, os_final_lines, target_os=os_name) + print(f"Wrote {os_output} with {len(os_final_lines)} entries (from {len(files)} files, target {os_name})") + + # Create the environment.yaml if not present + env_path = Path("environment.yaml") + if not env_path.exists(): + print(f"{env_path} not found, please be sure to create one.") + raise FileNotFoundError(f"{env_path} not found.") + else: + data = yaml.safe_load(env_path.read_text(encoding="utf-8")) + dependencies = data.get("dependencies", []) + python_updated = False + jl_updated = False + for i, dep in enumerate(dependencies): + if not isinstance(dep, str): + continue + if python_version and dep.startswith("python="): + dependencies[i] = f"python={python_version}" + python_updated = True + if dep.startswith("jupyterlab="): + dependencies[i] = f"jupyterlab={jl_ver}" + jl_updated = True + data["dependencies"] = dependencies + env_path.write_text(yaml.dump(data, sort_keys=False), encoding="utf-8") + if python_updated or jl_updated: + parts = [] + if python_updated: + parts.append(f"python={python_version}") + if jl_updated: + parts.append(f"jupyterlab={jl_ver}") + print(f"Updated {env_path} with {', '.join(parts)}") + else: + print(f"No python/jupyterlab entries updated in {env_path}") + + # Replace on setup.py the Python version + setup_path = Path("setup.py") + if setup_path.exists() and python_version: + setup_text = setup_path.read_text(encoding="utf-8") + # Require only the major.minor series: environment.yaml pins the exact + # patch release for the installer, but a source install should accept + # any patch release of that series (e.g. 3.12.3 for 3.12.13). + python_series = ".".join(str(python_version).split(".")[:2]) + pattern = r'python_requires\s*=\s*["\'][><=\.0-9 ]+(PYTHON\_VERSION)?["\']' + new_setup_text = re.sub(pattern, f'python_requires=">={python_series}"', setup_text) + setup_path.write_text(new_setup_text, encoding="utf-8") + print(f"Updated {setup_path} with python_requires>={python_series}") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_31_to_v0_1_32/.tools/docs/tools_bridge.md b/.template_sync/resources/v0_1_31_to_v0_1_32/.tools/docs/tools_bridge.md new file mode 100644 index 0000000..9599e53 --- /dev/null +++ b/.template_sync/resources/v0_1_31_to_v0_1_32/.tools/docs/tools_bridge.md @@ -0,0 +1,81 @@ +# Expose your app's tools to napari, Fiji and QuPath (optional, experimental) + +If your repository ships Python code (see [Upload external code](external_code_upload.md)), you can declare some of its functions +as **tools**. After installation, people can run them in napari, Fiji and QuPath and from the command line, with forms made from the +function signatures. Nothing changes for apps that do not declare tools. + +This page covers what the template does: where you declare the tools and what the installer does with them. Two other guides cover the rest: + +- [Writing tools](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/AUTHORING.md), in LabConstrictor-Tools: the inputs + and outputs a tool can have, how to lay out its form, what each program supports, and how to test a tool. +- [Use apps inside napari, Fiji and QuPath](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/image-software/): what the people + who install your app do to run its tools, with the install steps of the + [napari plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/napari/), the + [Fiji plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/fiji/) and the + [QuPath extension](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/qupath/). + +## Declare your tools + +1. Add a module named `_lc_tools` next to your package under `src/` (so `src/mytool_lc_tools/__init__.py` for + the package `mytool`). The installer registers tools only from a module with exactly this name. Declare tools in it with typed + functions, and import your science code **inside** the functions: + + ```python + from typing import Annotated + from labconstrictor_tools import Image, ImageOut, Min, tool + + @tool("Gaussian blur") + def blur(image: Image, sigma: Annotated[float, Min(0)] = 2.0) -> ImageOut: + from mytool.filters import gaussian + return gaussian(image, sigma) + ``` + + Keep the module light: it is imported to read the tool list, so heavy imports at the top slow every start. +2. Import `labconstrictor_tools` only in `_lc_tools`, or inside functions, if you can. The rest of your package then also works + where LabConstrictor Tools is not installed: a notebook run on Google Colab, a copy of the package used elsewhere, or an installation where + Tools failed to install. An import at the top of your package does not stop the installation, because the installer installs Tools before + it checks that your package can be imported. +3. Name the programs your tools work in under `hosts:` in `labconstrictor-app.yaml`: see [Describe your app for the App Centre](app_manifest.md). +4. Test your tools before you publish a release, as [Writing tools](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/AUTHORING.md) + shows (`labconstrictor-tools check` and `labconstrictor-tools test`). + +## What the installer does + +The installer's `post_install` step: + +1. installs your package; +2. if your package has a `_lc_tools` module, installs LabConstrictor Tools; +3. checks that your package can be imported; +4. registers the app (`labconstrictor-tools register ...`) with the version from the `version:` line of `construct.yaml` and the hosts of + `labconstrictor-app.yaml`. + +When the app is uninstalled, `pre_uninstall` unregisters it. + +A failure in step 2 or 4 is written as a `WARNING` to `menuinst_debug.log` in the install folder, the registration is skipped, and the +installation goes on. The one exception is a package that needs Tools to be imported: then the import check of step 3 fails, as it should. + +The Windows step (`post_install.bat`) runs in the template's automated tests on a Windows machine, and people have installed apps on Windows +and macOS from a clean system. + +### Which LabConstrictor Tools the installer installs + +LabConstrictor Tools is not on PyPI yet. The installer downloads the GitHub archive of one release tag of LabConstrictor-Tools, a plain zip +file, so the user's computer does not need git. The tag is pinned: two installers built from the same app release install the same Tools, +and a change to Tools does not reach new installations until the pin is moved on purpose. Template updates move the pin in your app. + +The tag is the value of `LC_TOOLS_PIN` in both scripts: +[app/bash_bat_scripts/post_install.sh](../../app/bash_bat_scripts/post_install.sh) (`LC_TOOLS_PIN="..."`) and +[app/bash_bat_scripts/post_install.bat](../../app/bash_bat_scripts/post_install.bat) (`SET "LC_TOOLS_PIN=..."`). + +To install Tools from somewhere else, set the environment variable `LC_TOOLS_SPEC` when the installer runs: a wheel, a git URL, a mirror, or +the name `labconstrictor-tools` once it is on PyPI. It replaces the pin completely. + +**Move the pin (template maintainers).** Create and test the tag in LabConstrictor-Tools (the procedure is in its `docs/OPERATIONS.md`). +Change `LC_TOOLS_PIN` in both scripts of the template, and in the copies under `.template_sync/resources/` of the latest migration if it has +them (the test `test_resources_are_identical_to_the_template_files` fails when they differ). Then write a migration that changes the string in +the apps' scripts, and bump `template_version`. + +## If something does not work + +- `menuinst_debug.log` in the app's install folder says what the installer did with your tools. +- `labconstrictor-tools doctor` checks the Tools installation, and `labconstrictor-tools logs` shows its log. diff --git a/.template_sync/resources/v0_1_31_to_v0_1_32/previous/.tools/docs/tools_bridge.md b/.template_sync/resources/v0_1_31_to_v0_1_32/previous/.tools/docs/tools_bridge.md new file mode 100644 index 0000000..c557edb --- /dev/null +++ b/.template_sync/resources/v0_1_31_to_v0_1_32/previous/.tools/docs/tools_bridge.md @@ -0,0 +1,59 @@ +# Expose your app's tools to Napari, Fiji and QuPath (optional, experimental) + +If your repository ships Python code (see [Upload external code](external_code_upload.md)), you can declare some of its functions +as **tools**. After installation they appear in a generic **Napari** widget, a generic **Fiji** command and a generic **QuPath** command, and work from the +command line, with forms generated automatically from the function signatures. Nothing changes for apps that do not declare tools. + +1. Add a module named `_lc_tools` next to your package under `src/` (so `src/mytool_lc_tools/__init__.py` for + the package `mytool`). Declare tools in it with typed functions, importing your science code **inside** the functions: + + ```python + from typing import Annotated + from labconstrictor_tools import Image, ImageOut, Min, tool + + @tool("Gaussian blur") + def blur(image: Image, sigma: Annotated[float, Min(0)] = 2.0) -> ImageOut: + from mytool.filters import gaussian + return gaussian(image, sigma) + ``` + + Keep the module light: it is imported to read the tool list, so heavy imports at the top slow every start. + **Import `labconstrictor_tools` only in the tools module if you can.** Since template 0.1.17 the installer installs `labconstrictor-tools` *before* it checks that + your package can be imported, so a package that imports `labconstrictor_tools` at module level no longer stops the installation. It is still better practice to import it lazily (inside functions) + or only in `_lc_tools`: the rest of your package then also works where Tools is not installed (a notebook run on Colab, a copy of the package used elsewhere, a failed Tools install). +2. The installer (`post_install`) detects the module, installs `labconstrictor-tools` and registers the app + (`labconstrictor-tools register ...`). `pre_uninstall` unregisters it. A failure in this step is logged to + `menuinst_debug.log` and never fails the installation. + **Order in `post_install`.** (1) your package is installed, (2) if it ships `_lc_tools`, `labconstrictor-tools` is installed, (3) the package import check runs, (4) the app is registered. + Installing Tools before the import check is what lets your package import `labconstrictor_tools` at module level. A failed Tools install is a `WARNING` in `menuinst_debug.log` + and the registration is skipped; the installation continues, unless your package needs Tools to be imported (then the import check fails, as it should). + **Where `labconstrictor-tools` comes from.** It is not on PyPI yet, so by default the installer downloads the GitHub archive of a **pinned release tag**, + `https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/v0.3.0-alpha.2.zip` (a plain zip: git is not needed on the user's computer). + Set the environment variable `LC_TOOLS_SPEC` when the installer runs to install it from somewhere else (a wheel, a git URL, a mirror, or the + name `labconstrictor-tools` once it is published on PyPI); it overrides the pin completely. + **Pinned (important).** Two installers built from the same app release get the same version of the tools package, and a change to Tools `main` + does not reach new installations until the pin is moved on purpose. + **How to move the pin.** The tag name is written in one place per script: the variable `LC_TOOLS_PIN` (`LC_TOOLS_PIN="v0.3.0-alpha.2"` in + `app/bash_bat_scripts/post_install.sh`, `SET "LC_TOOLS_PIN=v0.3.0-alpha.2"` in `post_install.bat`). To use a new release: create and test the tag in + LabConstrictor-Tools (procedure in its `docs/OPERATIONS.md`), change that string in both scripts and in the copies under + `.template_sync/resources/` of the latest migration (the test `test_resources_are_identical_to_the_template_files` fails when they differ), + update the tag in this paragraph, and bump `template_version` so apps receive the change. Apps already migrated need a new migration to change the + string in their own scripts. +3. Test your tools before releasing: `labconstrictor-tools check --module mytool_lc_tools` and + `labconstrictor-tools test --module mytool_lc_tools --cases lc_tests/cases.json`. +4. Install the Napari plugin (`napari-labconstrictor`), the Fiji plugin (`labconstrictor-fiji`) or the QuPath extension once per machine. None of them is on PyPI or an update site yet: + see the READMEs of [LabConstrictor-napari](https://github.com/CellMigrationLab/LabConstrictor-napari), + [LabConstrictor-Fiji](https://github.com/CellMigrationLab/LabConstrictor-Fiji) and [LabConstrictor-QuPath](https://github.com/CellMigrationLab/LabConstrictor-QuPath) for the install steps. +5. Optional: make a long form readable and rich with markers (the authoring guide in the Tools repository lists them all): + - layout: `Group("...")`, `Advanced()`, `Collapsed()`, `EnabledWhen(...)`; + - input widgets: `Widget("slider")` for a bounded number and `Widget("radio")` for a short list of choices; + - `PickChannel()` to let the person choose one channel of a multi-channel image (your function receives that channel as a 2D array); + - `ChoicesFrom("other_tool")` to fill a dropdown from another tool of yours (for example the available devices); + - `RegionOf("image")` (optional labels input) to run on the selection in the host (Napari Shapes layer, Fiji ROI, QuPath annotations); + - outputs: `ImageOut`, `LabelsOut`, `TableOut`, `Scalars`, `MessageOut`, `PointsOut` and `ShapesOut` (polygons: Napari shapes layer, Fiji ROIs, QuPath annotations); + - say "nothing found" with `ToolError("no_match", ...)`. + Napari, Fiji and QuPath do not support every feature in the same way: the table "What each host does with each feature" in `docs/HOST_FEATURES.md` of the Tools repository is the reference. +Documentation and source: https://github.com/CellMigrationLab/LabConstrictor-Tools. +The registered version is read from the `version:` line of `construct.yaml`. The Windows hook (`post_install.bat`) runs in the template's automated tests on a Windows +machine, and people have installed apps on Windows and macOS from a clean system. +Troubleshooting: `labconstrictor-tools doctor`, `labconstrictor-tools logs`, and `~/.labconstrictor/logs/labconstrictor.log`. diff --git a/.tools/docs/README.md b/.tools/docs/README.md index 72ce340..486ccf8 100644 --- a/.tools/docs/README.md +++ b/.tools/docs/README.md @@ -37,7 +37,7 @@ Go from notebook to installer in minutes. #### 1. [**Create a New Repository from this Template**](./create_repository.md) #### 2. [**Initialise your repository**](./initialise_repository.md) #### 3. [*(Optional)* **Upload external code**](./external_code_upload.md) -- [Expose tools to Napari and Fiji (experimental)](tools_bridge.md) +- [Expose tools to napari, Fiji and QuPath (experimental)](tools_bridge.md) #### 4. [**Upload Your Notebooks**](./notebook_upload.md) #### 5. [**Create Executable Installers**](./executable_creation.md) > **Requirements:** You only need a GitHub account and the Jupyter notebooks you want to distribute. diff --git a/.tools/docs/app_manifest.md b/.tools/docs/app_manifest.md index a7308f5..ce3b553 100644 --- a/.tools/docs/app_manifest.md +++ b/.tools/docs/app_manifest.md @@ -1,6 +1,6 @@ # Describe your app for the App Centre -The [LabConstrictor App Centre](https://labconstrictor.cellmig.org/apps/) lists apps built with LabConstrictor, with a page for each one. The App Centre reads a small file from **your** repository, `labconstrictor-app.yaml`, so you describe your app once and keep it up to date yourself. Version numbers and download links always come from your latest GitHub release. +The [LabConstrictor App Centre](https://cellmigrationlab.github.io/LabConstrictor-Site/apps/) lists apps built with LabConstrictor, with a page for each one. The App Centre reads a small file from **your** repository, `labconstrictor-app.yaml`, so you describe your app once and keep it up to date yourself. Version numbers and download links always come from your latest GitHub release. ## How you get the file @@ -9,7 +9,7 @@ The [repository initialiser](initialise_repository.md) asks for a one-sentence s ## What it contains ```yaml -# yaml-language-server: $schema=https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json +# yaml-language-server: $schema=https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json schema: 1 name: My App summary: One sentence that says what it does, for the app card. @@ -36,7 +36,26 @@ distribution: # at least one way to get the app: installer, colab or icon: app/logo/logo.png # optional: a square PNG in your repository ``` -The first line makes editors with YAML support (for example VS Code) check the file as you type. `inputs`, `outputs` and `limitations` are short summaries for the app page (a list of one to six sentences, not README copy). More optional fields exist (authors, DOI, license, screenshots, a quick start); the full list is in the [schema](https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json). Everything is plain text: no HTML or Markdown. +The first line makes editors with YAML support (for example VS Code) check the file as you type. `inputs`, `outputs` and `limitations` are short summaries for the app page (a list of one to six sentences, not README copy). More optional fields exist (authors, DOI, license, screenshots, a quick start); the full list is in the [schema](https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json). Everything is plain text: no HTML or Markdown. + +## Plugin versions your tools need (optional) + +If your tools rely on a fix or a feature of the napari, Fiji or QuPath plugin that older plugins lack, say so with `host_requirements`. People with an older plugin keep seeing your app, with one sentence saying which plugin to update and where; your app page on the App Centre lists the versions under "Plugin versions". + +```yaml +host_requirements: + qupath: + min_version: 0.1.0-alpha.7 # a release tag of the plugin, with or without v + features: [shapes_owner_v1] # optional: a host feature id + why: Replace keeps your own annotations # optional: one line shown to the person + fiji: + min_version: 0.1.0-alpha.7 +``` + +- Name only `napari`, `fiji` or `qupath`: the notebook ships with your app and needs no plugin. +- Each needs `min_version`, `features`, or both. `required: true` makes an older plugin refuse your tools instead of warning; use it only when they really fail there. +- Write it as a block, as above. The installer passes this file to `labconstrictor-tools register`, which refuses a malformed block (a misspelt host or key, a version like `latest`); `labconstrictor-tools check --module _lc_tools --app-manifest labconstrictor-app.yaml` shows what it read. +- The feature ids and the rule are in the [LabConstrictor-Tools documentation](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/PROTOCOL.md#host-requirements-which-plugin-an-app-needs). ## The automatic check @@ -49,7 +68,7 @@ The **Check App Centre manifest** workflow runs when you change the file and whe ## Get listed -Having the file does not list your app by itself. To list it, [submit your repository](https://labconstrictor.cellmig.org/submit/) to the App Centre. +Having the file does not list your app by itself. To list it, [submit your repository](https://cellmigrationlab.github.io/LabConstrictor-Site/submit/) to the App Centre. --- diff --git a/.tools/docs/tools_bridge.md b/.tools/docs/tools_bridge.md index 14e69dc..9599e53 100644 --- a/.tools/docs/tools_bridge.md +++ b/.tools/docs/tools_bridge.md @@ -1,11 +1,24 @@ -# Expose your app's tools to Napari and Fiji (optional, experimental) +# Expose your app's tools to napari, Fiji and QuPath (optional, experimental) If your repository ships Python code (see [Upload external code](external_code_upload.md)), you can declare some of its functions -as **tools**. After installation they appear in a generic **Napari** widget and a generic **Fiji** command, and work from the -command line, with forms generated automatically from the function signatures. Nothing changes for apps that do not declare tools. +as **tools**. After installation, people can run them in napari, Fiji and QuPath and from the command line, with forms made from the +function signatures. Nothing changes for apps that do not declare tools. + +This page covers what the template does: where you declare the tools and what the installer does with them. Two other guides cover the rest: + +- [Writing tools](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/AUTHORING.md), in LabConstrictor-Tools: the inputs + and outputs a tool can have, how to lay out its form, what each program supports, and how to test a tool. +- [Use apps inside napari, Fiji and QuPath](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/image-software/): what the people + who install your app do to run its tools, with the install steps of the + [napari plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/napari/), the + [Fiji plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/fiji/) and the + [QuPath extension](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/qupath/). + +## Declare your tools 1. Add a module named `_lc_tools` next to your package under `src/` (so `src/mytool_lc_tools/__init__.py` for - the package `mytool`). Declare tools in it with typed functions, importing your science code **inside** the functions: + the package `mytool`). The installer registers tools only from a module with exactly this name. Declare tools in it with typed + functions, and import your science code **inside** the functions: ```python from typing import Annotated @@ -18,41 +31,51 @@ command line, with forms generated automatically from the function signatures. N ``` Keep the module light: it is imported to read the tool list, so heavy imports at the top slow every start. - **Import `labconstrictor_tools` only in the tools module if you can.** Since template 0.1.17 the installer installs `labconstrictor-tools` *before* it checks that - your package can be imported, so a package that imports `labconstrictor_tools` at module level no longer stops the installation. It is still better practice to import it lazily (inside functions) - or only in `_lc_tools`: the rest of your package then also works where Tools is not installed (a notebook run on Colab, a copy of the package used elsewhere, a failed Tools install). -2. The installer (`post_install`) detects the module, installs `labconstrictor-tools` and registers the app - (`labconstrictor-tools register ...`). `pre_uninstall` unregisters it. A failure in this step is logged to - `menuinst_debug.log` and never fails the installation. - **Order in `post_install`.** (1) your package is installed, (2) if it ships `_lc_tools`, `labconstrictor-tools` is installed, (3) the package import check runs, (4) the app is registered. - Installing Tools before the import check is what lets your package import `labconstrictor_tools` at module level. A failed Tools install is a `WARNING` in `menuinst_debug.log` - and the registration is skipped; the installation continues, unless your package needs Tools to be imported (then the import check fails, as it should). - **Where `labconstrictor-tools` comes from.** It is not on PyPI yet, so by default the installer downloads the GitHub archive of a **pinned release tag**, - `https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/v0.3.0-alpha.1.zip` (a plain zip: git is not needed on the user's computer). - Set the environment variable `LC_TOOLS_SPEC` when the installer runs to install it from somewhere else (a wheel, a git URL, a mirror, or the - name `labconstrictor-tools` once it is published on PyPI); it overrides the pin completely. - **Pinned (important).** Two installers built from the same app release get the same version of the tools package, and a change to Tools `main` - does not reach new installations until the pin is moved on purpose. - **How to move the pin.** The tag name is written in one place per script: the variable `LC_TOOLS_PIN` (`LC_TOOLS_PIN="v0.3.0-alpha.1"` in - `app/bash_bat_scripts/post_install.sh`, `SET "LC_TOOLS_PIN=v0.3.0-alpha.1"` in `post_install.bat`). To use a new release: create and test the tag in - LabConstrictor-Tools (procedure in its `docs/OPERATIONS.md`), change that string in both scripts and in the copies under - `.template_sync/resources/` of the latest migration (the test `test_resources_are_identical_to_the_template_files` fails when they differ), - update the tag in this paragraph, and bump `template_version` so apps receive the change. Apps already migrated need a new migration to change the - string in their own scripts. -3. Test your tools before releasing: `labconstrictor-tools check --module mytool_lc_tools` and - `labconstrictor-tools test --module mytool_lc_tools --cases lc_tests/cases.json`. -4. Install the Napari plugin (`napari-labconstrictor`) or the Fiji plugin (`labconstrictor-fiji`) once per machine. Neither is on PyPI or a Fiji update site yet: see the READMEs of - [napari-labconstrictor](https://github.com/CellMigrationLab/napari-labconstrictor) and [LabConstrictor-Fiji](https://github.com/CellMigrationLab/LabConstrictor-Fiji) for the install commands. -5. Optional: make a long form readable and rich with markers (the authoring guide in the Tools repository lists them all): - - layout: `Group("...")`, `Advanced()`, `Collapsed()`, `EnabledWhen(...)`; - - input widgets: `Widget("slider")` for a bounded number and `Widget("radio")` for a short list of choices; - - `PickChannel()` to let the person choose one channel of a multi-channel image (your function receives that channel as a 2D array); - - `ChoicesFrom("other_tool")` to fill a dropdown from another tool of yours (for example the available devices); - - `RegionOf("image")` (optional labels input) to run on the selection in the host (Napari Shapes layer, Fiji ROI, QuPath annotations); - - outputs: `ImageOut`, `LabelsOut`, `TableOut`, `Scalars`, `MessageOut`, `PointsOut` and `ShapesOut` (polygons: Napari shapes layer, Fiji ROIs, QuPath annotations); - - say "nothing found" with `ToolError("no_match", ...)`. - Napari, Fiji and QuPath do not support every feature in the same way: the table "What each host does with each feature" in `docs/HOST_FEATURES.md` of the Tools repository is the reference. -Documentation and source: https://github.com/CellMigrationLab/LabConstrictor-Tools. -The registered version is read from the `version:` line of `construct.yaml`. The Windows hook (`post_install.bat`) has not yet been run on a real Windows computer; if you can help, follow the -[human test protocol](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/HUMAN_TEST_PROTOCOL.md). -Troubleshooting: `labconstrictor-tools doctor`, `labconstrictor-tools logs`, and `~/.labconstrictor/logs/labconstrictor.log`. +2. Import `labconstrictor_tools` only in `_lc_tools`, or inside functions, if you can. The rest of your package then also works + where LabConstrictor Tools is not installed: a notebook run on Google Colab, a copy of the package used elsewhere, or an installation where + Tools failed to install. An import at the top of your package does not stop the installation, because the installer installs Tools before + it checks that your package can be imported. +3. Name the programs your tools work in under `hosts:` in `labconstrictor-app.yaml`: see [Describe your app for the App Centre](app_manifest.md). +4. Test your tools before you publish a release, as [Writing tools](https://github.com/CellMigrationLab/LabConstrictor-Tools/blob/main/docs/AUTHORING.md) + shows (`labconstrictor-tools check` and `labconstrictor-tools test`). + +## What the installer does + +The installer's `post_install` step: + +1. installs your package; +2. if your package has a `_lc_tools` module, installs LabConstrictor Tools; +3. checks that your package can be imported; +4. registers the app (`labconstrictor-tools register ...`) with the version from the `version:` line of `construct.yaml` and the hosts of + `labconstrictor-app.yaml`. + +When the app is uninstalled, `pre_uninstall` unregisters it. + +A failure in step 2 or 4 is written as a `WARNING` to `menuinst_debug.log` in the install folder, the registration is skipped, and the +installation goes on. The one exception is a package that needs Tools to be imported: then the import check of step 3 fails, as it should. + +The Windows step (`post_install.bat`) runs in the template's automated tests on a Windows machine, and people have installed apps on Windows +and macOS from a clean system. + +### Which LabConstrictor Tools the installer installs + +LabConstrictor Tools is not on PyPI yet. The installer downloads the GitHub archive of one release tag of LabConstrictor-Tools, a plain zip +file, so the user's computer does not need git. The tag is pinned: two installers built from the same app release install the same Tools, +and a change to Tools does not reach new installations until the pin is moved on purpose. Template updates move the pin in your app. + +The tag is the value of `LC_TOOLS_PIN` in both scripts: +[app/bash_bat_scripts/post_install.sh](../../app/bash_bat_scripts/post_install.sh) (`LC_TOOLS_PIN="..."`) and +[app/bash_bat_scripts/post_install.bat](../../app/bash_bat_scripts/post_install.bat) (`SET "LC_TOOLS_PIN=..."`). + +To install Tools from somewhere else, set the environment variable `LC_TOOLS_SPEC` when the installer runs: a wheel, a git URL, a mirror, or +the name `labconstrictor-tools` once it is on PyPI. It replaces the pin completely. + +**Move the pin (template maintainers).** Create and test the tag in LabConstrictor-Tools (the procedure is in its `docs/OPERATIONS.md`). +Change `LC_TOOLS_PIN` in both scripts of the template, and in the copies under `.template_sync/resources/` of the latest migration if it has +them (the test `test_resources_are_identical_to_the_template_files` fails when they differ). Then write a migration that changes the string in +the apps' scripts, and bump `template_version`. + +## If something does not work + +- `menuinst_debug.log` in the app's install folder says what the installer did with your tools. +- `labconstrictor-tools doctor` checks the Tools installation, and `labconstrictor-tools logs` shows its log. diff --git a/.tools/docs/use_cases.md b/.tools/docs/use_cases.md index a800707..bd72573 100644 --- a/.tools/docs/use_cases.md +++ b/.tools/docs/use_cases.md @@ -6,11 +6,11 @@ Here are some tools that have already been created using LabConstrictor: ## VLab4Mic

- VLab4Mic Logo + VLab4Mic Logo

[![Original GitHub Repo](https://img.shields.io/badge/GitHub-VLab4Mic-181717?logo=github)](https://github.com/HenriquesLab/VLab4Mic) -[![LabConstrictor GitHub Repo](https://img.shields.io/badge/GitHub-LabConstrictor--VLab4Mic-181717?logo=github)](https://github.com/HenriquesLab/LabConstrictor-VLab4Mic) +[![LabConstrictor GitHub Repo](https://img.shields.io/badge/GitHub-LabConstrictor--VLab4Mic-181717?logo=github)](https://github.com/CellMigrationLab/LabConstrictor-VLab4Mic) [![bioRxiv Paper](https://img.shields.io/badge/bioRxiv-Paper-B31B1B)](https://www.biorxiv.org/content/10.64898/2026.06.02.729521v2) **Abstract:** diff --git a/.tools/python/merge_requirements.py b/.tools/python/merge_requirements.py index 1fccecb..fe22142 100644 --- a/.tools/python/merge_requirements.py +++ b/.tools/python/merge_requirements.py @@ -2,9 +2,9 @@ """Merge requirements files under a directory (e.g. notebooks/*) into a single root requirements file. -The script now supports both classic requirements.txt files and the new +The script supports both classic requirements.txt files and the requirements.yaml format used by notebooks. For YAML files, it merges the -`python_version` (picking the newest) and the `dependencies` list while +`python_version` (every notebook must agree) and the `dependencies` list while discarding per-notebook descriptions. It also recognizes optional per-OS fields (`windows_dependencies`, @@ -17,23 +17,40 @@ wheels exist only for Linux; other systems keep plain `tensorflow`) and adds the PyTorch CUDA wheel index when `torch`, `torchvision`, or `torchaudio` are present. -It resolves simple version conflicts by choosing the newest version seen for a -given package (and emits a pinned `pkg==`). It still preserves -non-package lines (pip options, VCS/URLs) and supports simple `-r` includes. +Version requirements are never changed silently (template 0.1.31, CellMigrationLab/LabConstrictor#48): + * the requirements of a package are kept as written: `numpy>=1.24` stays `numpy>=1.24`, and the + requirements of several notebooks are combined (`numpy<2,>=1.24`); the lock step then finds the versions; + * when notebooks pin a package to different versions (`numpy==1.26.4` and `numpy==2.0.0`), or a pin does not + meet another notebook's requirement, nothing is written and the script fails, naming every notebook and its + requirement. The developer makes the notebooks agree, or decides explicitly in requirements_overrides.yaml + (next to the output), with the reason; the decision is written at the top of every generated file; + * requirements with different environment markers (`; sys_platform == "win32"`) are kept as separate lines; + * package names are compared as pip compares them (`NumPy`, `numpy` and `num_py` are one package). +`python merge_requirements.py --check` only looks for conflicts: it writes nothing (the release runs it). + +It preserves non-package lines (pip options, VCS/URLs) and supports simple `-r` includes. It also automatically adds ipywidgets if missing, with a version determined by Python, JupyterLab, and matplotlib versions from environment.yaml. """ -from pathlib import Path import argparse +import re import sys from collections import OrderedDict -from datetime import datetime -import re +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path + import yaml +from packaging.requirements import InvalidRequirement, Requirement +from packaging.specifiers import InvalidSpecifier, SpecifierSet +from packaging.utils import canonicalize_name +from packaging.version import InvalidVersion, Version +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_31.md" +OVERRIDES_FILE = "requirements_overrides.yaml" -# Regex to capture name, optional extras, operator and version, and optional markers +# Regex to capture name, optional extras, operator and version, and optional markers (used for the GPU rewrite of final lines) pkg_re = re.compile(r"^(?P[A-Za-z0-9_.+-]+)(?P\[[^\]]+\])?\s*(?P==|>=|<=|~=|!=|>|<)\s*(?P[^;\s]+)(?P\s*;.*)?$") OS_FIELD_MAP = { @@ -52,13 +69,70 @@ PLAIN_PKG_RE = re.compile( r"^(?P[A-Za-z0-9_.+-]+)(?P\[[^\]]+\])?(?P\s*;.*)?$" ) +ADDED_BY_SCRIPT = "added by merge_requirements.py" + + +@dataclass +class Entry: + """One requirement line of one file, as written.""" + + source: str + line: str + name: str + extras: tuple[str, ...] + spec: str + marker: str + +@dataclass +class Override: + """A decision of requirements_overrides.yaml: every notebook gets `use` for this package.""" + name: str + use: str + reason: str + used: bool = False + + +@dataclass +class Resolved: + """The line written for one package (and marker), and how it was decided.""" + + entries: list[Entry] + spec: str + extras: list[str] + override: Override | None = None + + @property + def name(self) -> str: + return self.entries[0].name + + @property + def marker(self) -> str: + return self.entries[0].marker + + def line(self) -> str: + extras = f"[{','.join(self.extras)}]" if self.extras else "" + marker = f" ; {self.marker}" if self.marker else "" + return f"{self.name}{extras}{self.spec}{marker}" + + +@dataclass class RequirementContext: - def __init__(self): - self.pkg_order: list[str] = [] - self.pkgs: dict[str, dict] = {} - self.other_lines: OrderedDict[str, None] = OrderedDict() + groups: OrderedDict[tuple[str, str], list[Entry]] = field(default_factory=OrderedDict) + other_lines: OrderedDict[str, None] = field(default_factory=OrderedDict) + errors: list[str] = field(default_factory=list) + + +class Conflict(Exception): + """Requirements of one package that no single version meets, or that the script will not choose between.""" + + def __init__(self, package: str, reason: str, entries: list[Entry], where: str = ""): + super().__init__(reason) + self.package = package + self.reason = reason + self.entries = entries + self.where = where def normalize_line(line: str) -> str: @@ -68,45 +142,15 @@ def normalize_line(line: str) -> str: return line.strip() -try: - # Prefer packaging.version for robust version comparison - from packaging.version import Version, InvalidVersion - - def parse_version(v: str): - try: - return Version(v) - except InvalidVersion: - return v - - def is_version_greater(a, b): - try: - return Version(a) > Version(b) - except Exception: - return str(a) > str(b) - -except Exception: - # Fallback: simple numeric-aware comparator - def _split_parts(v: str): - parts = re.split(r"[.\-+_]|(?=[a-zA-Z])", v) - key = [] - for p in parts: - if not p: - continue - if p.isdigit(): - key.append((0, int(p))) - else: - key.append((1, p)) - return tuple(key) - - def parse_version(v: str): - return _split_parts(v) - - def is_version_greater(a, b): - return parse_version(a) > parse_version(b) +def display_path(path: Path) -> str: + try: + return path.resolve().relative_to(Path.cwd().resolve()).as_posix() + except ValueError: + return path.as_posix() -def merge_python_version(filepath: str | None, current: str | None, candidate: str | None): - """Pick the newest python_version string, if provided.""" +def merge_python_version(filepath: str | Path | None, current: str | None, candidate: str | None): + """Every notebook that names a python_version must name the same one.""" if not candidate: return current if current is None: @@ -117,7 +161,7 @@ def merge_python_version(filepath: str | None, current: str | None, candidate: s raise ValueError(f"Conflicting python_version found {current} vs {candidate} when processing {filepath}") -def process_requirement_line(line: str, pkg_order: list, pkgs: dict, other_lines: OrderedDict, base_dir: Path | None = None): +def process_requirement_line(line: str, ctx: RequirementContext, source: str, base_dir: Path | None = None): """Handle a single requirement line (shared between txt and yaml inputs).""" if not line: return @@ -127,51 +171,34 @@ def process_requirement_line(line: str, pkg_order: list, pkgs: dict, other_lines include_path = Path(parts[1]) if base_dir is None else (base_dir / parts[1]) include = include_path.resolve() if include.exists(): - read_requirements_file(include, pkg_order, pkgs, other_lines) + read_requirements_file(include, ctx) return # Keep pip option lines (indexes, find-links, etc.) as-is if line.startswith("--") or line.startswith("-f ") or line.startswith("-i ") or line.startswith("-e "): - other_lines.setdefault(line, None) + ctx.other_lines.setdefault(line, None) return # VCS or URL lines (git+, http(s)://, file:) keep as-is if any(line.startswith(prefix) for prefix in ("git+", "http://", "https://", "file:", "ssh://")): - other_lines.setdefault(line, None) + ctx.other_lines.setdefault(line, None) return - m = pkg_re.match(line) - if not m: - # plain package (unpinned) or marker-only spec - key = line.split(";", 1)[0].strip().lower() - if key not in pkgs: - pkgs[key] = {"name": line, "pinned": False, "ver": None} - pkg_order.append(key) + try: + requirement = Requirement(line) + except InvalidRequirement as exc: + ctx.errors.append(f"{source}: '{line}' is not a valid requirement ({exc})") return - - name = m.group("name") - extras = m.group("extras") or "" - ver = m.group("ver") - marker = m.group("marker") or "" - - base = name.lower() - if base not in pkgs: - pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} - pkg_order.append(base) - else: - existing = pkgs[base] - if not existing.get("pinned"): - pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} - else: - try: - if is_version_greater(ver, existing.get("ver")): - pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} - except Exception: - if str(ver) > str(existing.get("ver")): - pkgs[base] = {"name": name + (extras or ""), "pinned": True, "ver": ver, "marker": marker} + if requirement.url: + # name @ url: installed from that address, as written + ctx.other_lines.setdefault(line, None) + return + marker = str(requirement.marker) if requirement.marker else "" + entry = Entry(source, line, requirement.name, tuple(sorted(requirement.extras)), str(requirement.specifier), marker) + ctx.groups.setdefault((canonicalize_name(requirement.name), marker), []).append(entry) -def read_requirements_file(path: Path, pkg_order: list, pkgs: dict, other_lines: OrderedDict): +def read_requirements_file(path: Path, ctx: RequirementContext): try: text = path.read_text(encoding="utf-8") except Exception: @@ -179,10 +206,10 @@ def read_requirements_file(path: Path, pkg_order: list, pkgs: dict, other_lines: for raw in text.splitlines(): line = normalize_line(raw) - process_requirement_line(line, pkg_order, pkgs, other_lines, base_dir=path.parent) + process_requirement_line(line, ctx, display_path(path), base_dir=path.parent) -def read_requirements_yaml(path: Path, pkg_order: list, pkgs: dict, other_lines: OrderedDict, os_contexts: dict[str, RequirementContext]) -> str | None: +def read_requirements_yaml(path: Path, ctx: RequirementContext, os_contexts: dict[str, RequirementContext]) -> str | None: """Read requirements.yaml and return its python_version if present.""" try: data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} @@ -191,21 +218,22 @@ def read_requirements_yaml(path: Path, pkg_order: list, pkgs: dict, other_lines: python_version = data.get("python_version") dependencies = data.get("dependencies", []) or [] + source = display_path(path) for dep in dependencies: line = normalize_line(str(dep)) - process_requirement_line(line, pkg_order, pkgs, other_lines, base_dir=path.parent) + process_requirement_line(line, ctx, source, base_dir=path.parent) - for os_name, field in OS_FIELD_MAP.items(): - os_deps = data.get(field) or [] + for os_name, field_name in OS_FIELD_MAP.items(): + os_deps = data.get(field_name) or [] if not os_deps: continue - ctx = os_contexts.get(os_name) - if ctx is None: + os_ctx = os_contexts.get(os_name) + if os_ctx is None: continue for dep in os_deps: line = normalize_line(str(dep)) - process_requirement_line(line, ctx.pkg_order, ctx.pkgs, ctx.other_lines, base_dir=path.parent) + process_requirement_line(line, os_ctx, f"{source} ({field_name})", base_dir=path.parent) return python_version @@ -222,17 +250,175 @@ def find_requirements_files(source_dir): return sorted({f.resolve() for f in files}) +# -------------------------------------------------------------------------------------------------------------------------------- +# Deciding the requirement of each package +# -------------------------------------------------------------------------------------------------------------------------------- +def load_overrides(path: Path) -> dict[str, Override]: + """The decisions of requirements_overrides.yaml, by package name as pip compares them (none when the file is absent).""" + if not path.is_file(): + return {} + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except yaml.YAMLError as exc: + raise ValueError(f"{display_path(path)} is not valid YAML: {exc}") from exc + entries = data.get("overrides") if isinstance(data, dict) else None + if entries is None: + return {} + if not isinstance(entries, dict): + raise ValueError(f"{display_path(path)}: `overrides` must map package names to {{use: ..., reason: ...}}") + overrides: dict[str, Override] = {} + for name, value in entries.items(): + use = value.get("use") if isinstance(value, dict) else None + reason = value.get("reason") if isinstance(value, dict) else None + if not isinstance(use, str) or not use.strip(): + raise ValueError(f"{display_path(path)}: {name} needs `use`, the requirement every notebook gets, for example \"==2.0.0\"") + if not isinstance(reason, str) or not reason.strip(): + raise ValueError(f"{display_path(path)}: {name} needs `reason`, why this requirement is right for every notebook that uses {name}") + try: + SpecifierSet(use.strip()) + except InvalidSpecifier as exc: + raise ValueError(f"{display_path(path)}: {name}: `use: {use}` is not a version requirement such as \"==2.0.0\" or \">=1.24,<2\" ({exc})") from exc + overrides[canonicalize_name(str(name))] = Override(str(name), use.strip(), " ".join(reason.split())) + return overrides + + +def _exact_versions(entry: Entry) -> list[str]: + return [s.version for s in SpecifierSet(entry.spec) if s.operator in ("==", "===") and "*" not in s.version] + + +def _same_version(a: str, b: str) -> bool: + try: + return Version(a) == Version(b) + except InvalidVersion: + return a == b + + +def _union_extras(entries: list[Entry]) -> list[str]: + extras: list[str] = [] + for entry in entries: + extras.extend(extra for extra in entry.extras if extra not in extras) + return extras + + +def resolve_group(package: str, entries: list[Entry], checked_with: list[Entry], override: Override | None, where: str = "") -> Resolved: + """The requirement written for `entries` (one package, one marker); `checked_with` are other requirements that apply too. + + An override decides. Otherwise the requirements are combined: several different exact pins, or a pin that does not meet another + requirement, raise Conflict (whatever the order of the files). Without a pin, the combined ranges are written as they are. + """ + extras = _union_extras(entries) + if override is not None: + override.used = True + return Resolved(entries, override.use, extras, override) + everything = entries + checked_with + pins: list[tuple[str, Entry]] = [(version, entry) for entry in everything for version in _exact_versions(entry)] + distinct: list[str] = [] + for version, _ in pins: + if not any(_same_version(version, seen) for seen in distinct): + distinct.append(version) + if len(distinct) > 1: + raise Conflict(package, f"pinned to different versions ({', '.join(sorted(distinct))})", everything, where) + if distinct: + pin = distinct[0] + for entry in everything: + if entry.spec and not SpecifierSet(entry.spec).contains(pin, prereleases=True): + raise Conflict(package, f"the pin =={pin} does not meet {entry.name}{entry.spec} of {entry.source}", everything, where) + elif not satisfiable(SpecifierSet(",".join(entry.spec for entry in everything if entry.spec))): + raise Conflict(package, "no version meets all of these requirements", everything, where) + # The line keeps the requirements of its own entries; `checked_with` (the common requirements of an OS file) only had to agree. + own_pins = [version for entry in entries for version in _exact_versions(entry)] + if own_pins: + return Resolved(entries, f"=={own_pins[0]}", extras) + return Resolved(entries, str(SpecifierSet(",".join(entry.spec for entry in entries if entry.spec))), extras) + + +def satisfiable(specifiers: SpecifierSet) -> bool: + """Whether some version meets every specifier (`<2,>=2.1` does not). + + Every version a specifier names is tried, and versions just above it (2.1, 2.1.1, 2.1.0.1, 2.1.0.0.1): a range that only versions + closer than that could meet is reported as unsatisfiable, which stops the merge (an override then decides) instead of guessing. + """ + if not len(specifiers): + return True + candidates: list[str] = [] + for specifier in specifiers: + version = specifier.version.removesuffix(".*") + candidates += [version, f"{version}.1", f"{version}.0.1", f"{version}.0.0.1"] + for candidate in candidates: + try: + if specifiers.contains(candidate, prereleases=True): + return True + except InvalidVersion: + continue + return False + + +def resolve_context(ctx: RequirementContext, overrides: dict[str, Override], conflicts: list[Conflict], + base: RequirementContext | None = None, where: str = "") -> list[Resolved]: + """Resolve every package of a context; an OS context is also checked against the common requirements that apply on that OS.""" + resolved: list[Resolved] = [] + for (package, marker), entries in ctx.groups.items(): + checked_with: list[Entry] = [] + if base is not None: + for (base_package, base_marker), base_entries in base.groups.items(): + if base_package == package and base_marker in ("", marker): + checked_with.extend(base_entries) + try: + resolved.append(resolve_group(package, entries, checked_with, overrides.get(package), where)) + except Conflict as conflict: + conflicts.append(conflict) + return resolved + + +def conflict_report(conflicts: list[Conflict], errors: list[str], overrides_path: Path) -> str: + lines = ["The notebooks ask for incompatible package versions, so no requirements file was written.", ""] + for error in errors: + lines.append(f" {error}") + for conflict in sorted(conflicts, key=lambda c: (c.package, c.where)): + where = f" ({conflict.where})" if conflict.where else "" + lines.append(f" {conflict.package}{where}: {conflict.reason}") + for entry in sorted(conflict.entries, key=lambda e: (e.source, e.line)): + lines.append(f" {entry.source}: {entry.line}") + if conflicts: + example = sorted(conflicts, key=lambda c: c.package)[0].package + lines += [ + "", + f"Make the notebooks agree (edit their requirements.yaml), or decide in {display_path(overrides_path)} which requirement every", + "notebook gets, and why. It is written at the top of the generated requirements files. For example:", + "", + "overrides:", + f" {example}:", + ' use: "=="', + f' reason: ""', + ] + lines += ["", f"See {DOCS_URL}"] + return "\n".join(lines) + + +def override_header(resolved: list[Resolved]) -> list[str]: + lines = [] + for item in resolved: + if item.override is None: + continue + asked = "; ".join(f"{entry.source}: {entry.line}" for entry in item.entries if entry.source != ADDED_BY_SCRIPT) + lines.append(f"# Decided in {OVERRIDES_FILE}: {item.line()} (the notebooks ask for: {asked}). Reason: {item.override.reason}") + return lines + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Packages the app always needs +# -------------------------------------------------------------------------------------------------------------------------------- def resolve_ipywidgets_version(py_version, jl_version): """Resolve ipywidgets version based on Python, JupyterLab versions. - + Returns a version spec string like ">=7.0.0,<8.0.0" or a pinned version. """ - + # Simple heuristic: ipywidgets 8.x for modern stacks, 7.x for older try: py_major, py_minor = map(int, py_version.split(".")[:2]) jl_major = int(jl_version.split(".")[0]) - + if jl_major >= 4 and py_major >= 3 and py_minor >= 9: return "8.1.7" # Latest stable for modern Python + JupyterLab 4 elif py_major >= 3 and py_minor >= 7: @@ -243,58 +429,48 @@ def resolve_ipywidgets_version(py_version, jl_version): return ">=7.0.0" # Safe fallback -def determine_jupyterlab_version(pkgs: dict, default: str = "4.4.0") -> str: - jl_info = pkgs.get("jupyterlab") - if jl_info and jl_info.get("pinned") and jl_info.get("ver"): - return jl_info["ver"] +def _has_package(ctx: RequirementContext, package: str) -> bool: + return any(name == package for name, _ in ctx.groups) + + +def _add_package(ctx: RequirementContext, name: str, spec: str) -> None: + ctx.groups[(canonicalize_name(name), "")] = [Entry(ADDED_BY_SCRIPT, f"{name}{spec}", name, (), spec, "")] + + +def determine_jupyterlab_version(resolved: list[Resolved], default: str = "4.4.0") -> str: + for item in resolved: + if canonicalize_name(item.name) == "jupyterlab" and not item.marker and item.spec.startswith("==") and "," not in item.spec: + return item.spec[2:] return default def ensure_jl_hidecode(ctx: RequirementContext): - if "jl-hidecode" in ctx.pkgs: + if _has_package(ctx, "jl-hidecode"): return - ctx.pkgs["jl-hidecode"] = { - "name": "jl-hidecode", - "pinned": True, - "ver": "0.0.1", - "marker": "", - } - ctx.pkg_order.append("jl-hidecode") + _add_package(ctx, "jl-hidecode", "==0.0.1") print("Added jl-hidecode==0.0.1 (enforced)") -def ensure_ipywidgets(ctx: RequirementContext, python_version: str | None, jl_ver: str): - if "ipywidgets" in ctx.pkgs: - return +def ensure_ipywidgets(ctx: RequirementContext, python_version: str | None, jl_ver: str) -> bool: + if _has_package(ctx, "ipywidgets"): + return False iw_version = resolve_ipywidgets_version(python_version, jl_ver) - ctx.pkgs["ipywidgets"] = { - "name": "ipywidgets", - "pinned": True, - "ver": iw_version, - "marker": "", - } - ctx.pkg_order.append("ipywidgets") - print(f"Added ipywidgets=={iw_version} (resolved)") - - -def build_final_lines(ctx: RequirementContext, sort: bool) -> list[str]: - final_lines: list[str] = [] - for ol in ctx.other_lines.keys(): - final_lines.append(ol) + spec = iw_version if iw_version[:1] in "<>=!~" else f"=={iw_version}" + _add_package(ctx, "ipywidgets", spec) + print(f"Added ipywidgets{spec} (resolved)") + return True - pkg_keys = sorted(ctx.pkg_order, key=str.casefold) if sort else ctx.pkg_order - for key in pkg_keys: - info = ctx.pkgs.get(key) - if not info: - continue - if info.get("pinned") and info.get("ver"): - final_lines.append(f"{info['name']}=={info['ver']}{info.get('marker','')}") - else: - final_lines.append(info["name"]) +def build_final_lines(ctx: RequirementContext, resolved: list[Resolved], sort: bool) -> list[str]: + final_lines: list[str] = list(ctx.other_lines.keys()) + items = sorted(resolved, key=lambda item: item.name.casefold()) if sort else resolved + final_lines.extend(item.line() for item in items) return final_lines +# -------------------------------------------------------------------------------------------------------------------------------- +# Output files +# -------------------------------------------------------------------------------------------------------------------------------- def get_os_output_path(output: Path, os_name: str) -> Path: suffix = output.suffix stem = output.stem @@ -410,15 +586,18 @@ def write_requirements_output( final_lines: list[str], target_os: str | None = None, target_accelerator: str | None = None, + decisions: list[str] | None = None, ): + generated = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() header_lines = [ - f"# Generated by .tools/python/merge_requirements.py on {datetime.utcnow().isoformat()}Z", + f"# Generated by .tools/python/merge_requirements.py on {generated}Z", f"# Source files: {', '.join(str(p) for p in files)}", ] if target_os: header_lines.append(f"# Target OS: {OS_DISPLAY_NAMES.get(target_os, target_os.capitalize())}") if target_accelerator: header_lines.append(f"# Target accelerator: {target_accelerator}") + header_lines.extend(decisions or []) header_lines.append("# ---") content = "\n".join(header_lines) + "\n" @@ -430,15 +609,18 @@ def write_requirements_output( path.write_text(content, encoding="utf-8") -def main(): +def main(argv: list[str] | None = None): parser = argparse.ArgumentParser(description="Merge multiple requirements files (txt or yaml) into one.") parser.add_argument("--source-dir", default="notebooks", help="Directory to scan for requirements files") parser.add_argument("--output", default="requirements.txt", help="Output requirements file to write") parser.add_argument("--sort", action="store_true", help="Sort final requirements alphabetically") - args = parser.parse_args() + parser.add_argument("--overrides", help=f"Decisions for conflicting requirements (default: {OVERRIDES_FILE} next to the output)") + parser.add_argument("--check", action="store_true", help="Only check that the notebooks' requirements do not conflict; write nothing") + args = parser.parse_args(argv) source = Path(args.source_dir) output = Path(args.output) + overrides_path = Path(args.overrides) if args.overrides else output.with_name(OVERRIDES_FILE) discovered_files = find_requirements_files(source) @@ -449,6 +631,9 @@ def main(): files = [f for f in discovered_files if f.resolve() not in skip_outputs] if not files: + if args.check: + print(f"No requirements files found under {source}: nothing to check.") + return 0 print(f"No requirements files found under {source}, writing empty {output}") output.write_text("# Generated requirements (none found)\n", encoding="utf-8") gpu_output = get_gpu_output_path(output) @@ -461,17 +646,43 @@ def main(): for f in files: if f.suffix.lower() in {".yaml", ".yml"}: - candidate_py = read_requirements_yaml(f, base_ctx.pkg_order, base_ctx.pkgs, base_ctx.other_lines, os_contexts) + candidate_py = read_requirements_yaml(f, base_ctx, os_contexts) python_version = merge_python_version(f, python_version, candidate_py) else: - read_requirements_file(f, base_ctx.pkg_order, base_ctx.pkgs, base_ctx.other_lines) + read_requirements_file(f, base_ctx) + + try: + overrides = load_overrides(overrides_path) + except ValueError as exc: + print(f"{exc}\nSee {DOCS_URL}", file=sys.stderr) + return 1 ensure_jl_hidecode(base_ctx) - jl_ver = determine_jupyterlab_version(base_ctx.pkgs) - ensure_ipywidgets(base_ctx, python_version, jl_ver) + conflicts: list[Conflict] = [] + base_resolved = resolve_context(base_ctx, overrides, conflicts) + jl_ver = determine_jupyterlab_version(base_resolved) + if ensure_ipywidgets(base_ctx, python_version, jl_ver): + key = next(reversed(base_ctx.groups)) + base_resolved.append(resolve_group(key[0], base_ctx.groups[key], [], overrides.get(key[0]))) + os_resolved = { + os_name: resolve_context(ctx, overrides, conflicts, base=base_ctx, where=f"{OS_FIELD_MAP[os_name]}, with the common dependencies") + for os_name, ctx in os_contexts.items() + } + errors = base_ctx.errors + [error for ctx in os_contexts.values() for error in ctx.errors] + if conflicts or errors: + print(conflict_report(conflicts, errors, overrides_path), file=sys.stderr) + return 1 + for override in overrides.values(): + if not override.used: + print(f"Note: {display_path(overrides_path)} decides {override.name}, which no notebook requires any more; the entry can be removed.") + if args.check: + print(f"The requirements of {len(files)} file(s) do not conflict" + + (f" ({sum(o.used for o in overrides.values())} decision(s) from {display_path(overrides_path)})." if overrides else ".")) + return 0 - base_final_lines = build_final_lines(base_ctx, args.sort) - write_requirements_output(output, files, base_final_lines) + decisions = override_header(base_resolved) + base_final_lines = build_final_lines(base_ctx, base_resolved, args.sort) + write_requirements_output(output, files, base_final_lines, decisions=decisions) print(f"Wrote {output} with {len(base_final_lines)} entries (from {len(files)} files)") gpu_output = get_gpu_output_path(output) @@ -481,15 +692,16 @@ def main(): files, gpu_final_lines, target_accelerator=GPU_DISPLAY_NAME, + decisions=decisions, ) print(f"Wrote {gpu_output} with {len(gpu_final_lines)} entries (from {len(files)} files, target {GPU_DISPLAY_NAME})") for os_name, ctx in os_contexts.items(): - if not ctx.pkg_order and not ctx.other_lines: + if not ctx.groups and not ctx.other_lines: continue - os_final_lines = build_final_lines(ctx, args.sort) + os_final_lines = build_final_lines(ctx, os_resolved[os_name], args.sort) os_output = get_os_output_path(output, os_name) - write_requirements_output(os_output, files, os_final_lines, target_os=os_name) + write_requirements_output(os_output, files, os_final_lines, target_os=os_name, decisions=override_header(os_resolved[os_name])) print(f"Wrote {os_output} with {len(os_final_lines)} entries (from {len(files)} files, target {os_name})") # Create the environment.yaml if not present diff --git a/.tools/python/update_changelog.py b/.tools/python/update_changelog.py index c3aba1e..553cd77 100644 --- a/.tools/python/update_changelog.py +++ b/.tools/python/update_changelog.py @@ -13,10 +13,11 @@ import yaml def get_git_commit_info(): - """Get current commit hash and message""" + """Get current commit hash and message (the subject line only: the body and its trailers, such as + Co-authored-by, do not belong in the notebook's changelog)""" try: commit_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip() - commit_message = subprocess.check_output(['git', 'log', '-1', '--pretty=%B']).decode('utf-8').strip() + commit_message = subprocess.check_output(['git', 'log', '-1', '--pretty=%s']).decode('utf-8').strip() commit_author = subprocess.check_output(['git', 'log', '-1', '--pretty=%an']).decode('utf-8').strip() commit_date = subprocess.check_output(['git', 'log', '-1', '--pretty=%ai']).decode('utf-8').strip() diff --git a/.tools/requirements.txt b/.tools/requirements.txt index 8492066..eb02274 100644 --- a/.tools/requirements.txt +++ b/.tools/requirements.txt @@ -3,3 +3,5 @@ pyyaml==6.0.2 nbformat==5.10.4 # lock_requirements.py (requirements*.txt -> requirements*.lock.txt) uv==0.13.3 +# merge_requirements.py (versions compared as pip compares them) +packaging==25.0 diff --git a/.tools/schema/labconstrictor-app.schema.json b/.tools/schema/labconstrictor-app.schema.json index 536d91e..1e67f94 100644 --- a/.tools/schema/labconstrictor-app.schema.json +++ b/.tools/schema/labconstrictor-app.schema.json @@ -1,8 +1,8 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json", + "$id": "https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json", "title": "labconstrictor-app.yaml", - "description": "Manifest that an app keeps in the root of its own repository so that it can be listed in the LabConstrictor App Centre. Edit it with schema support: add `# yaml-language-server: $schema=https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json` as the first line.", + "description": "Manifest that an app keeps in the root of its own repository so that it can be listed in the LabConstrictor App Centre. Edit it with schema support: add `# yaml-language-server: $schema=https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json` as the first line.", "type": "object", "additionalProperties": false, "required": ["schema", "name", "summary", "kind", "distribution"], @@ -21,6 +21,15 @@ "items": {"enum": ["notebook", "napari", "fiji", "qupath"]}, "description": "Where the app's tools can be used besides its own window (the LabConstrictor-Tools bridge)." }, + "host_requirements": { + "type": "object", "additionalProperties": false, + "description": "The oldest LabConstrictor plugin of each host the app needs. labconstrictor-tools register copies it into the app's registry entry; a host whose plugin is older lists the app with a sentence saying which plugin to update (or refuses it with required: true). The notebook needs no plugin.", + "properties": { + "napari": {"$ref": "#/$defs/hostRequirement"}, + "fiji": {"$ref": "#/$defs/hostRequirement"}, + "qupath": {"$ref": "#/$defs/hostRequirement"} + } + }, "distribution": { "type": "object", "additionalProperties": false, "anyOf": [{"required": ["installer"]}, {"required": ["colab"]}, {"required": ["pip"]}], @@ -57,6 +66,16 @@ } }, "$defs": { + "hostRequirement": { + "type": "object", "additionalProperties": false, + "anyOf": [{"required": ["min_version"]}, {"required": ["features"]}], + "properties": { + "min_version": {"type": "string", "pattern": "^v?[0-9]+(\\.[0-9]+)*([-_.]?(a|alpha|b|beta|c|rc|pre|preview)[-_.]?[0-9]*)?([-_.]?(post|rev|r)[-_.]?[0-9]*)?([-_.]?dev[-_.]?[0-9]*)?$", "description": "A release tag of the plugin, with or without v (0.1.0-alpha.6, v0.1.0, 0.2.0rc1). Quote it if YAML could read it as a number (\"0.2\")."}, + "features": {"type": "array", "uniqueItems": true, "minItems": 1, "items": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"}, "description": "Host feature ids the app needs (LabConstrictor-Tools docs/HOST_FEATURES.md), for example shapes_owner_v1."}, + "why": {"type": "string", "minLength": 3, "maxLength": 160, "pattern": "^[^\\n]+$", "description": "One line shown to the person, saying what the newer plugin brings."}, + "required": {"type": "boolean", "description": "true: an older plugin refuses the app's tools instead of warning. Use it only when the tools really fail."} + } + }, "facts": {"type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "string", "minLength": 5, "maxLength": 200}}, "https": {"type": "string", "pattern": "^https://[^\\s/@]+(/[^\\s]*)?$(?!\\n)"}, "repoPath": {"type": "string", "pattern": "^(?!/)(?!.*\\.\\.)[A-Za-z0-9_./ -]+\\.(png|jpg|jpeg|gif)$(?!\\n)", "description": "Path inside the repository, no leading slash."}, diff --git a/.tools/templates/Welcome_template.ipynb b/.tools/templates/Welcome_template.ipynb index f0592b6..68cccdb 100644 --- a/.tools/templates/Welcome_template.ipynb +++ b/.tools/templates/Welcome_template.ipynb @@ -217,6 +217,37 @@ ")\n", "\n", "\n", + "def replace_notebook_with_backup(notebook_path: Path, new_content: str):\n", + " \"\"\"Replace a notebook by its update, keeping the current file (with the user's changes and outputs) as a backup.\n", + "\n", + " The new content must be a notebook. It is written to a temporary file next to the notebook and then moved into place, so a failed\n", + " download or write never leaves a broken notebook. Returns the path of the backup, or None when there was no notebook yet.\n", + " \"\"\"\n", + " import os\n", + " from datetime import datetime\n", + "\n", + " if not isinstance(json.loads(new_content), dict):\n", + " raise ValueError(\"the downloaded file is not a notebook\")\n", + " notebook_path.parent.mkdir(parents=True, exist_ok=True)\n", + " backup_path = None\n", + " if notebook_path.exists():\n", + " stamp = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n", + " backup_path = notebook_path.with_name(f\"{notebook_path.stem}.backup-{stamp}{notebook_path.suffix}\")\n", + " number = 1\n", + " while backup_path.exists():\n", + " number += 1\n", + " backup_path = notebook_path.with_name(f\"{notebook_path.stem}.backup-{stamp}-{number}{notebook_path.suffix}\")\n", + " shutil.copy2(notebook_path, backup_path)\n", + " temporary_path = notebook_path.with_name(f\".{notebook_path.name}.update\")\n", + " try:\n", + " temporary_path.write_text(new_content, encoding=\"utf-8\")\n", + " os.replace(temporary_path, notebook_path)\n", + " finally:\n", + " if temporary_path.exists():\n", + " temporary_path.unlink()\n", + " return backup_path\n", + "\n", + "\n", "def apply_grid_layout(grid):\n", " \"\"\"Apply responsive sizing while allowing long text to wrap safely.\"\"\"\n", " grid.add_class(\"labconstrictor-responsive-grid\")\n", @@ -476,54 +507,82 @@ " grid[idx, 4] = table_cell(f\"❌ Needs Update to {online_version}\")\n", " \n", " def button_update(main_folder, subfolder, row_idx):\n", - " def show(button):\n", - " button.disabled = True\n", + " # Updating replaces the user's copy of the notebook: ask first, keep that copy as a backup, and change the\n", + " # recorded version only once the new notebook is in place (CellMigrationLab/LabConstrictor#49).\n", + " local_notebook_path = Path(\".\") / main_folder / f\"{subfolder}.ipynb\"\n", + " new_version = online_latest_versions[main_folder][subfolder]\n", + "\n", + " def reset(button):\n", + " button.disabled = False\n", + " button.description = \"Update\"\n", + "\n", + " def do_update(button):\n", " button.description = \"Updating...\"\n", - " \n", - " # Download the notebook\n", " notebook_url = f\"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/notebooks/{main_folder}/{subfolder}.ipynb?ref={github_branch}\"\n", + " headers = {}\n", " if private_repository:\n", - " if github_token.value:\n", - " notebook_response = requests.get(notebook_url, headers={\"Authorization\": f\"token {github_token.value}\"})\n", - " else:\n", - " grip_output.value = \"❌ Please check your Presonal Access Token\"\n", - " else:\n", - " notebook_response = requests.get(notebook_url)\n", - " \n", - " if notebook_response.status_code == 200:\n", - " try:\n", - " # Decode the notebook content\n", - " notebook_content = base64.b64decode(\n", - " notebook_response.json()['content']\n", - " ).decode('utf-8')\n", - " \n", - " # Save to local path\n", - " local_notebook_path = Path(\".\") / main_folder / f\"{subfolder}.ipynb\"\n", - " local_notebook_path.parent.mkdir(parents=True, exist_ok=True)\n", - " local_notebook_path.write_text(notebook_content, encoding='utf-8')\n", - " \n", - " # Update the local version YAML\n", - " local_latest_versions[main_folder][subfolder] = online_latest_versions[main_folder][subfolder]\n", - " local_latest_version_path.write_text(yaml.dump(local_latest_versions, default_flow_style=False))\n", - " \n", - " grip_output.value = f\"✅ Updated {subfolder} to version {online_latest_versions[main_folder][subfolder]}\"\n", - " \n", - " # Update the grid to show up-to-date\n", - " grid[row_idx, 3] = table_cell(online_latest_versions[main_folder][subfolder])\n", - " grid[row_idx, 4] = table_cell(\"✅ Up-to-date\")\n", - " grid[row_idx, 5] = table_cell(\"-\")\n", - " apply_grid_layout(grid)\n", - " \n", - " except Exception as e:\n", - " grip_output.value = f\"❌ Error saving notebook: {e}\"\n", - " button.disabled = False\n", - " button.description = \"Update\"\n", - " else:\n", - " grip_output.value = f\"❌ Failed to download notebook (HTTP {notebook_response.status_code})\"\n", + " if not github_token.value:\n", + " grip_output.value = \"❌ Please check your Personal Access Token. Your notebook was not changed.\"\n", + " reset(button)\n", + " return\n", + " headers = {\"Authorization\": f\"token {github_token.value}\"}\n", + " try:\n", + " notebook_response = requests.get(notebook_url, headers=headers, timeout=60)\n", + " except requests.RequestException as e:\n", + " grip_output.value = f\"❌ Failed to download notebook: {e}. Your notebook was not changed.\"\n", + " reset(button)\n", + " return\n", + " if notebook_response.status_code != 200:\n", + " grip_output.value = f\"❌ Failed to download notebook (HTTP {notebook_response.status_code}). Your notebook was not changed.\"\n", " display(notebook_response.text[:300])\n", - " button.disabled = False\n", - " button.description = \"Update\"\n", - " \n", + " reset(button)\n", + " return\n", + " try:\n", + " notebook_content = base64.b64decode(notebook_response.json()['content']).decode('utf-8')\n", + " backup_path = replace_notebook_with_backup(local_notebook_path, notebook_content)\n", + " except Exception as e:\n", + " grip_output.value = f\"❌ Error saving notebook: {e}. Your notebook was not changed.\"\n", + " reset(button)\n", + " return\n", + "\n", + " # The new notebook is in place: only now record its version\n", + " local_latest_versions[main_folder][subfolder] = new_version\n", + " local_latest_version_path.write_text(yaml.dump(local_latest_versions, default_flow_style=False))\n", + " saved = f\" Your previous copy is saved as {backup_path.name}, next to it.\" if backup_path else \"\"\n", + " grip_output.value = f\"✅ Updated {subfolder} to version {new_version}.{saved}\"\n", + "\n", + " # Update the grid to show up-to-date\n", + " grid[row_idx, 3] = table_cell(new_version)\n", + " grid[row_idx, 4] = table_cell(\"✅ Up-to-date\")\n", + " grid[row_idx, 5] = table_cell(\"-\")\n", + " apply_grid_layout(grid)\n", + "\n", + " def show(button):\n", + " button.disabled = True\n", + " button.description = \"Confirm below\"\n", + " question = widgets.HTML(\n", + " f\"Update {subfolder} to version {new_version}?
\"\n", + " f\"The new version replaces {local_notebook_path.as_posix()}. Your current copy, with your changes \"\n", + " f\"and outputs, is first saved as {subfolder}.backup-<date>.ipynb in the same folder.
\"\n", + " \"If the notebook is open in a tab, close that tab first: otherwise JupyterLab can save the old copy over the update.\"\n", + " )\n", + " confirm = widgets.Button(description=\"Back up and update\", button_style=\"warning\", layout=widgets.Layout(width=\"auto\"))\n", + " cancel = widgets.Button(description=\"Cancel\")\n", + " dialog = widgets.VBox([question, widgets.HBox([confirm, cancel])])\n", + "\n", + " def on_confirm(_):\n", + " dialog.close()\n", + " do_update(button)\n", + "\n", + " def on_cancel(_):\n", + " dialog.close()\n", + " grip_output.value = f\"Update of {subfolder} cancelled: nothing was changed.\"\n", + " reset(button)\n", + "\n", + " confirm.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_confirm))\n", + " cancel.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_cancel))\n", + " display(dialog)\n", + "\n", " return show\n", "\n", " update_button = widgets.Button(description=\"Update\", disable=False) \n", diff --git a/app/bash_bat_scripts/post_install.bat b/app/bash_bat_scripts/post_install.bat index aa02286..8aa7948 100644 --- a/app/bash_bat_scripts/post_install.bat +++ b/app/bash_bat_scripts/post_install.bat @@ -130,7 +130,7 @@ SET "LC_APP_MANIFEST=" IF EXIST "%PROJECT_ROOT%\labconstrictor-app.yaml" SET "LC_APP_MANIFEST=%PROJECT_ROOT%\labconstrictor-app.yaml" "%PYTHON_EXE%" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('celltracks_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 IF NOT ERRORLEVEL 1 ( - echo Found celltracks_lc_tools: registering the tools of CellTracksColab for Napari and Fiji. >> "%LOG_FILE%" + echo Found celltracks_lc_tools: registering the tools of CellTracksColab for Napari, Fiji and QuPath. >> "%LOG_FILE%" REM Which hosts list the app (the sentence is the one Tools uses for an app without hosts). Logged before the READY check, which sets the errorlevel. IF NOT DEFINED LC_APP_MANIFEST echo WARNING: labconstrictor-app.yaml was not found in "%PROJECT_ROOT%" ^(add it to extra_files in construct.yaml^), so CellTracksColab is registered without hosts. 'CellTracksColab' declares no hosts, so it is listed in every host; register it with --app-manifest ^(or --hosts^) to choose >> "%LOG_FILE%" IF DEFINED LC_APP_MANIFEST echo Passing the hosts of "%LC_APP_MANIFEST%" to Tools ^(--app-manifest^); Tools logs the same sentence if the file declares no hosts. >> "%LOG_FILE%" @@ -235,7 +235,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.1" +SET "LC_TOOLS_PIN=v0.3.0-alpha.2" 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('celltracks_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 f44b3cb..befe4d4 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.1" + LC_TOOLS_PIN="v0.3.0-alpha.2" LC_TOOLS_MODULE="celltracks_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 @@ -99,7 +99,7 @@ fi # labconstrictor-tools is installed above, before the import check of the package (LC_TOOLS_PIN, LC_TOOLS_MODULE and LC_TOOLS_READY are set there). if [ -f "$PROJECT_ROOT/setup.py" ] && "$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 lc_note() { echo "$*" >> "$LOG_FILE" || :; } # a full or unwritable log must not fail the installation - lc_note "Found $LC_TOOLS_MODULE: registering the tools of CellTracksColab for Napari and Fiji" + lc_note "Found $LC_TOOLS_MODULE: registering the tools of CellTracksColab for Napari, Fiji and QuPath" LC_APP_VERSION="$(sed -n 's/^version: *//p' "$PROJECT_ROOT/construct.yaml" 2>/dev/null | head -1 | tr -d "\"'\r" || true)" if [ -z "$LC_APP_VERSION" ]; then lc_note "WARNING: no version: line at the start of a line in construct.yaml - registering the tools with version 0." diff --git a/labconstrictor-app.yaml b/labconstrictor-app.yaml index 7b27072..b03f3c1 100644 --- a/labconstrictor-app.yaml +++ b/labconstrictor-app.yaml @@ -1,4 +1,4 @@ -# yaml-language-server: $schema=https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json +# yaml-language-server: $schema=https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json schema: 1 name: CellTracksColab summary: Compile, visualise and analyse cell tracking data across fields of view, biological repeats and conditions.