diff --git a/.github/workflows/check_app_manifest.yml b/.github/workflows/check_app_manifest.yml new file mode 100644 index 0000000..113f55f --- /dev/null +++ b/.github/workflows/check_app_manifest.yml @@ -0,0 +1,46 @@ +name: Check App Centre manifest + +# Checks labconstrictor-app.yaml (the description of the app for the LabConstrictor App Centre). +# A missing file is a warning, an invalid file fails this check. It never blocks building installers: +# it runs on its own, also when a release is published. +on: + pull_request: + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + push: + branches: + - main + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + release: + types: + - published + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Check labconstrictor-app.yaml + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install pyyaml==6.0.2 jsonschema==4.23.0 + + - name: Check the manifest + run: python .tools/python/check_app_manifest.py diff --git a/.github/workflows/publish_pypi.yml b/.github/workflows/publish_pypi.yml new file mode 100644 index 0000000..cfd03da --- /dev/null +++ b/.github/workflows/publish_pypi.yml @@ -0,0 +1,79 @@ +name: Publish the Python package to PyPI + +# Publishes the app's own Python code (the package in src/) on PyPI at each release, with the version of the release: the same +# moment and the same version as the installers (release_constructor.yml). +# +# OFF BY DEFAULT: both jobs are skipped unless the repository variable PYPI_PUBLISH is +# true -> publish on PyPI (pypi.org) +# testpypi -> publish on TestPyPI (test.pypi.org), a trial +# No secret or token: PyPI trusted publishing. One-time setup (a pending trusted publisher on pypi.org for this workflow file and the +# environment "pypi", then the variable): .tools/docs/external_code_upload.md. To turn it off, delete the variable. + +on: + release: + types: + - published + +permissions: + contents: read + +jobs: + build: + name: Build the package of src/ + if: vars.PYPI_PUBLISH == 'true' || vars.PYPI_PUBLISH == 'testpypi' + runs-on: ubuntu-latest + outputs: + url: ${{ steps.build.outputs.url }} + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt build==1.3.0 + + # The tag (v1.2.3 or 1.2.3) without the v. The checkout is the tagged commit, before the "Update version" commit of + # release_constructor.yml: pypi_package.py writes this version into setup.py itself (not committed). + - name: Build and check the package (nothing is uploaded yet) + id: build + env: + TAG: ${{ github.event.release.tag_name }} + PYPI_PUBLISH: ${{ vars.PYPI_PUBLISH }} + run: python .tools/python/pypi_package.py --version "${TAG#v}" --index "$PYPI_PUBLISH" --outdir dist --github-output "$GITHUB_OUTPUT" + + - name: Store the distributions + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: python-package-distributions + path: dist/ + if-no-files-found: error + + publish: + name: Upload to ${{ vars.PYPI_PUBLISH == 'testpypi' && 'TestPyPI' || 'PyPI' }} + needs: build + if: vars.PYPI_PUBLISH == 'true' || vars.PYPI_PUBLISH == 'testpypi' + runs-on: ubuntu-latest + # The environment named in the trusted publisher on pypi.org (and test.pypi.org). GitHub creates it on the first run; protection + # rules added to it (Settings > Environments > pypi), such as required reviewers, then apply to every upload. + environment: + name: pypi + url: ${{ needs.build.outputs.url }} + permissions: + id-token: write # trusted publishing: PyPI accepts a short-lived token that GitHub signs for this workflow and environment + steps: + - name: Download the distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: python-package-distributions + path: dist/ + + - name: Upload + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + repository-url: ${{ vars.PYPI_PUBLISH == 'testpypi' && 'https://test.pypi.org/legacy/' || 'https://upload.pypi.org/legacy/' }} diff --git a/.github/workflows/release_constructor.yml b/.github/workflows/release_constructor.yml new file mode 100644 index 0000000..fffa59f --- /dev/null +++ b/.github/workflows/release_constructor.yml @@ -0,0 +1,220 @@ +name: Build Release Installers + +on: + release: + types: + - published + workflow_dispatch: + inputs: + version: + description: "Version to package (e.g. 0.0.4). Defaults to release tag when empty." + required: false + +# This enables to run a single workflow at a time +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: write + +jobs: + bump-version: + name: Bump version on main branch + runs-on: ubuntu-latest + if: github.event_name == 'release' + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Determine release version + id: version + run: | + set -euxo pipefail + RAW="${{ github.event.release.tag_name }}" + # The tag as typed (v1.0.0 or 1.0.0): bump_version.py points the download links to it. + echo "RELEASE_TAG=$RAW" >> "$GITHUB_ENV" + RAW="${RAW#v}" + echo "release_version=$RAW" >> "$GITHUB_OUTPUT" + echo "RELEASE_VERSION=$RAW" >> "$GITHUB_ENV" + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Sync versioned files + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_version.py" \ + .tools/python/bump_version.py \ + python .tools/python/bump_version.py "${RELEASE_VERSION}" + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_constructor.py" \ + .tools/python/bump_constructor.py \ + python .tools/python/bump_constructor.py + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_Welcome_notebook.py" \ + .tools/python/bump_Welcome_notebook.py \ + python .tools/python/bump_Welcome_notebook.py "${{ github.repository_owner }}" "${{ github.event.repository.name }}" + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "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 + uses: stefanzweifel/git-auto-commit-action@b863ae1933cb653a53c021fe36dbb774e1fb9403 # v5 + with: + branch: main + commit_message: GitHub Action - Update version to ${{ github.event.release.tag_name }} + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: release-bump-version-logs + path: artifacts/error_log_document.log + if-no-files-found: ignore + archive: false + + platforms: + name: Installers to build + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Read distribution.platforms of labconstrictor-app.yaml + id: matrix + run: python .tools/python/release_platforms.py --github-output "$GITHUB_OUTPUT" + + build-installers: + name: Build installers (${{ matrix.os_name }}) + runs-on: ${{ matrix.runner }} + needs: [bump-version, platforms] + strategy: + fail-fast: false + # One build per system of distribution.platforms in labconstrictor-app.yaml (every system without it), from the platforms job. + matrix: ${{ fromJSON(needs.platforms.outputs.matrix) }} + defaults: + run: + shell: bash -l {0} + env: + CONSTRUCTOR_ENV: constructor-env + OUTPUT_DIR: dist/${{ matrix.os_name }} + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Determine release version + id: version + run: | + set -euxo pipefail + if [ "${{ github.event_name }}" = "release" ]; then + RAW="${{ github.event.release.tag_name }}" + else + RAW="${{ inputs.version }}" + fi + + if [ -z "$RAW" ]; then + echo "Version is required when running manually." >&2 + exit 1 + fi + + # The tag as typed (v1.0.0 or 1.0.0): bump_version.py points the download links to it. + echo "RELEASE_TAG=$RAW" >> "$GITHUB_ENV" + RAW="${RAW#v}" + echo "release_version=$RAW" >> "$GITHUB_OUTPUT" + echo "RELEASE_VERSION=$RAW" >> "$GITHUB_ENV" + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Sync versioned files and populate Welcome notebook + run: | + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "bump_version.py" \ + .tools/python/bump_version.py \ + python .tools/python/bump_version.py "${RELEASE_VERSION}" + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "bump_constructor.py" \ + .tools/python/bump_constructor.py \ + python .tools/python/bump_constructor.py + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "bump_Welcome_notebook.py" \ + .tools/python/bump_Welcome_notebook.py \ + python .tools/python/bump_Welcome_notebook.py "${{ github.repository_owner }}" "${{ github.event.repository.name }}" + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "check_placeholders.py" \ + .tools/python/check_placeholders.py \ + python .tools/python/check_placeholders.py + + - name: Set up Miniconda + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Create constructor environment + run: | + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document_${{ matrix.os_name }}.log" \ + "create_constructor_environment.sh" \ + .tools/bash/create_constructor_environment.sh \ + bash .tools/bash/create_constructor_environment.sh + + - name: Build installer with constructor + run: | + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document_${{ matrix.os_name }}.log" \ + "build_installer_with_constructor.sh" \ + .tools/bash/build_installer_with_constructor.sh \ + bash .tools/bash/build_installer_with_constructor.sh + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: build-installers-${{ matrix.os_name }}-logs + path: artifacts/error_log_document_${{ matrix.os_name }}.log + if-no-files-found: ignore + archive: false + + - name: Upload installers to release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + files: dist/${{ matrix.os_name }}/* + fail_on_unmatched_files: true diff --git a/.github/workflows/sync_template.yml b/.github/workflows/sync_template.yml new file mode 100644 index 0000000..8ba8f42 --- /dev/null +++ b/.github/workflows/sync_template.yml @@ -0,0 +1,170 @@ +name: Sync with Template Repository + +on: + schedule: + # Run weekly on Monday at 9 AM UTC + - cron: '0 9 * * 1' + workflow_dispatch: + +# This enables only one template synchronization workflow at a time. +concurrency: + group: template-sync-main + cancel-in-progress: false + +permissions: + contents: write + pull-requests: write + +jobs: + sync-template: + name: Sync with template repository + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: main + fetch-depth: 0 + # Do not leave the default GITHUB_TOKEN in the local Git configuration. + # The pull-request step authenticates separately with the repository-scoped + # LABCONSTRICTOR_SYNC_TOKEN secret. + persist-credentials: false + + - name: Configure Git + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Add upstream remote + run: | + git remote add upstream https://github.com/CellMigrationLab/LabConstrictor.git + + - name: Fetch upstream changes + run: | + git fetch upstream main + + - name: Read local template version + id: local-version + run: | + local_version=$(python3 - <<'PY' + from pathlib import Path + + manifest = Path(".template_sync/manifest.yaml") + if not manifest.exists(): + print("0.0.0") + raise SystemExit + + for line in manifest.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if stripped.startswith("template_version:"): + print(stripped.split(":", 1)[1].strip()) + break + else: + raise SystemExit("template_version not found in .template_sync/manifest.yaml") + PY + ) + echo "version=$local_version" >> "$GITHUB_OUTPUT" + + - name: Read upstream template version + id: upstream-version + run: | + upstream_version=$(python3 - <<'PY' + import subprocess + + manifest = subprocess.run( + ["git", "show", "upstream/main:.template_sync/manifest.yaml"], + check=True, + capture_output=True, + text=True, + ).stdout + for line in manifest.splitlines(): + stripped = line.strip() + if stripped.startswith("template_version:"): + print(stripped.split(":", 1)[1].strip()) + break + else: + raise SystemExit( + "template_version not found in upstream .template_sync/manifest.yaml" + ) + PY + ) + echo "version=$upstream_version" >> "$GITHUB_OUTPUT" + + - name: Check whether template sync is needed + id: version-check + env: + LOCAL_VERSION: ${{ steps.local-version.outputs.version }} + UPSTREAM_VERSION: ${{ steps.upstream-version.outputs.version }} + run: | + python3 - <<'PY' + import os + from pathlib import Path + + def parse_version(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + local_version = os.environ["LOCAL_VERSION"] + upstream_version = os.environ["UPSTREAM_VERSION"] + sync_required = parse_version(upstream_version) > parse_version(local_version) + + output_path = Path(os.environ["GITHUB_OUTPUT"]) + with output_path.open("a", encoding="utf-8") as fh: + fh.write(f"sync_required={'true' if sync_required else 'false'}\n") + PY + + - name: Check synchronization token setup + if: steps.version-check.outputs.sync_required == 'true' + env: + LABCONSTRICTOR_SYNC_TOKEN: ${{ secrets.LABCONSTRICTOR_SYNC_TOKEN }} + run: | + if [[ -z "$LABCONSTRICTOR_SYNC_TOKEN" ]]; then + { + echo "## One-time LabConstrictor setup required" + echo + echo "A template update is available, but this repository does not have the" + echo '`LABCONSTRICTOR_SYNC_TOKEN` repository secret configured.' + echo + echo "Follow the beginner-friendly guide in:" + echo + echo '`.tools/docs/template_synchronization.md`' + } >> "$GITHUB_STEP_SUMMARY" + + echo "::error title=Synchronization setup required::Configure the LABCONSTRICTOR_SYNC_TOKEN repository secret by following .tools/docs/template_synchronization.md." + exit 1 + fi + + - name: Fetch template sync bootstrap + if: steps.version-check.outputs.sync_required == 'true' + run: | + git checkout upstream/main -- .template_sync + + - name: Run template migrations + if: steps.version-check.outputs.sync_required == 'true' + run: | + python3 .template_sync/sync.py \ + --from-version "${{ steps.local-version.outputs.version }}" \ + --to-version "${{ steps.upstream-version.outputs.version }}" \ + --repository-root "$GITHUB_WORKSPACE" + + - name: Check for changes + id: check-changes + run: | + if [[ -n "$(git status --short)" ]]; then + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + echo "has_changes=false" >> "$GITHUB_OUTPUT" + fi + + - name: Create pull request + if: steps.check-changes.outputs.has_changes == 'true' + uses: peter-evans/create-pull-request@c5a7806660adbe173f04e3e038b0ccdcd758773c # v6 + with: + token: ${{ secrets.LABCONSTRICTOR_SYNC_TOKEN }} + branch: template-sync-${{ steps.local-version.outputs.version }}-to-${{ steps.upstream-version.outputs.version }} + delete-branch: true + commit-message: Sync template to version ${{ steps.upstream-version.outputs.version }} + title: Sync template to version ${{ steps.upstream-version.outputs.version }} + body: | + This PR updates `.template_sync` from the template repository and applies the migrations needed to move this repository from template version `${{ steps.local-version.outputs.version }}` to `${{ steps.upstream-version.outputs.version }}`. + + The branch is created with the repository-scoped `LABCONSTRICTOR_SYNC_TOKEN` secret so that updates to GitHub workflow files can be included safely. diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 0c2297a..7bcd4e0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -24,8 +24,21 @@ jobs: cache: pip - run: python -m pip install --upgrade pip - run: python -m pip install -e ".[dev]" + # The tools for napari and Fiji (src/fast4dreg_lc_tools) need labconstrictor-tools, and pandas for their tables: + # the version the app installer pins (LC_TOOLS_PIN in app/bash_bat_scripts/post_install.sh). + - name: Install labconstrictor-tools as the app installer does + run: | + pin=$(sed -n 's/^ *LC_TOOLS_PIN="\(.*\)"$/\1/p' app/bash_bat_scripts/post_install.sh) + echo "labconstrictor-tools $pin" + python -m pip install pandas "https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${pin}.zip" - run: python -c "import nanopyx; print(nanopyx.__version__)" - run: python -m pytest -q + - name: Tool cases (the cases the napari and Fiji checks use) + working-directory: lc_tests + run: | + python make_fixtures.py fixtures + labconstrictor-tools check --module fast4dreg_lc_tools + labconstrictor-tools test --module fast4dreg_lc_tools --cases cases.json - if: matrix.python-version == '3.12' run: python -m ruff check src tests benchmarks validation diff --git a/.github/workflows/update_on_notebook_change.yml b/.github/workflows/update_on_notebook_change.yml new file mode 100644 index 0000000..9c779a5 --- /dev/null +++ b/.github/workflows/update_on_notebook_change.yml @@ -0,0 +1,213 @@ +name: Updates on notebook change + +on: + push: + branches: [ main, master ] + paths: + - '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, +# because each one rebases its commit onto the latest branch before it pushes (a shared group kept only one waiting run, so a +# third push cancelled the waiting run of the other workflow). +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon notebook change, update manifests and changelogs + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@2d756ea4c53f7f6b397767d8723b3a10a9f35bf2 # v44 + with: + separator: "," + files: | + 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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "sync_notebook_versions.py" \ + .tools/python/sync_notebook_versions.py \ + python .tools/python/sync_notebook_versions.py + + - name: Update CHANGELOG + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_changelog.py" \ + .tools/python/update_changelog.py \ + python .tools/python/update_changelog.py notebooks/notebook_latest_versions.yaml + + - name: Update last commit in notebook_latest_versions.yaml + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_version_last_commit.py" \ + .tools/python/update_version_last_commit.py \ + python .tools/python/update_version_last_commit.py notebooks/notebook_latest_versions.yaml + + - name: Hide code cells in notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "hide_code_cells.py" \ + app/python_scripts/hide_code_cells.py \ + python app/python_scripts/hide_code_cells.py . + + - name: Index notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_notebook_README.py" \ + .tools/python/bump_notebook_README.py \ + 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') || contains(steps.changed-files.outputs.all_changed_files, 'requirements_overrides.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "merge_requirements.py" \ + .tools/python/merge_requirements.py \ + python .tools/python/merge_requirements.py --source-dir notebooks --output requirements.txt + + # requirements*.txt -> requirements*.lock.txt: every package the installer installs with pip, with its exact version (uv, valid on + # Windows, macOS and Linux). A lock file is rewritten only when its requirements file, Python or JupyterLab version changed. + - name: Lock requirements + run: | + bash .tools/bash/run_with_context.sh artifacts/error_log_document.log "lock_requirements.py" .tools/python/lock_requirements.py python .tools/python/lock_requirements.py + + - name: Check for changes + id: check-changes + run: | + if [ -z "$(git status --porcelain)" ]; then + echo "has_changes=false" >> $GITHUB_OUTPUT + else + echo "has_changes=true" >> $GITHUB_OUTPUT + fi + + - name: Set up Miniconda for requirements test + if: steps.check-changes.outputs.has_changes == 'true' + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Verify merged requirements inside conda + id: test-conda-env + if: steps.check-changes.outputs.has_changes == 'true' + env: + SKIP_CONDA_ENV_TEST: ${{ vars.SKIP_CONDA_ENV_TEST }} + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "test_conda_environment.sh" \ + .tools/bash/test_conda_environment.sh \ + bash .tools/bash/test_conda_environment.sh + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: notebook-debug-bundle + path: artifacts/error_log_document.log + archive: false + + - name: Commit updated files + id: auto-commit + if: steps.check-changes.outputs.has_changes == 'true' && steps.test-conda-env.outcome == 'success' + env: + BRANCH: ${{ github.ref_name }} + COMMIT_MESSAGE: GitHub Action - Updated files because of notebook and/or requirements changes + # The run checked out the commit that triggered it (the scripts above compare it with its parent); the branch may have moved + # since (another workflow committed, or a new push). A rejected push is therefore retried after a rebase onto the latest branch. + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git ls-files -z --modified --deleted --others --exclude-standard -- 'requirements*.txt' environment.yaml 'notebooks/*' setup.py | xargs -0 -r git add -A -- + if git diff --cached --quiet; then + echo "No changes to commit." + exit 0 + fi + git commit -m "$COMMIT_MESSAGE" + for attempt in 1 2 3 4 5; do + if git push origin "HEAD:refs/heads/$BRANCH"; then + exit 0 + fi + echo "The push was rejected (attempt $attempt of 5): rebasing onto the latest $BRANCH." + sleep $((attempt * 5)) + git fetch origin "$BRANCH" + if ! git rebase --autostash "origin/$BRANCH"; then + git rebase --abort || true + echo "::error::The commit of this run conflicts with the latest $BRANCH; run this workflow again (Actions > Run workflow)." + exit 1 + fi + done + echo "::error::The push was rejected 5 times; run this workflow again (Actions > Run workflow)." + exit 1 + + # Only when the merged requirements could not be installed: a failure of any other step (a script, the push) never reverts a commit. + - name: Revert user commit that broke requirements + if: failure() && github.event_name == 'push' && steps.test-conda-env.outcome == 'failure' + env: + BRANCH: ${{ github.ref_name }} + BAD_COMMIT: ${{ github.sha }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git reset --hard + git clean -fd + for attempt in 1 2 3 4 5; do + git fetch origin "$BRANCH" + git checkout -B "$BRANCH" "origin/$BRANCH" + # A merge commit is reverted against its first parent (-m 1); any other commit is reverted as it is. + if [ "$(git rev-list --parents -n 1 "$BAD_COMMIT" | wc -w)" -gt 2 ]; then + REVERT_ARGS=(-m 1) + else + REVERT_ARGS=() + fi + if ! git revert --no-edit "${REVERT_ARGS[@]}" "$BAD_COMMIT"; then + git revert --abort || true + echo "::error::$BAD_COMMIT broke the requirements but could not be reverted automatically (later commits change the same lines): revert it by hand." + exit 1 + fi + if git push origin "HEAD:refs/heads/$BRANCH"; then + exit 0 + fi + echo "The push of the revert was rejected (attempt $attempt of 5): retrying on the latest $BRANCH." + sleep $((attempt * 5)) + done + echo "::error::The revert of $BAD_COMMIT could not be pushed: revert it by hand." + exit 1 diff --git a/.github/workflows/update_on_src_change.yaml b/.github/workflows/update_on_src_change.yaml new file mode 100644 index 0000000..2ab8870 --- /dev/null +++ b/.github/workflows/update_on_src_change.yaml @@ -0,0 +1,66 @@ +name: Updates on external code change + +on: + push: + branches: [ main, master ] + paths: + - 'src/**' + workflow_dispatch: + +# One run of this workflow at a time per branch. The notebook workflow has its own group: the two can run at the same time, +# because each one rebases its commit onto the latest branch before it pushes (a shared group kept only one waiting run, so a +# third push cancelled the waiting run of the other workflow). +concurrency: + group: src-change-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon external code update the code version + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Update src change file + run: | + cat > .tools/meta/src_change.yaml < Run workflow)." + exit 1 + fi + done + echo "::error::The push was rejected 5 times; run this workflow again (Actions > Run workflow)." + exit 1 diff --git a/.gitignore b/.gitignore index b906764..0189e0f 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,215 @@ dist/ *_validation_*.csv .validation-data/ validation-results/ + +# From the LabConstrictor template (installer builds, logs of its workflows) +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Written by lc_tests/make_fixtures.py +lc_tests/fixtures/ diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml new file mode 100644 index 0000000..171f0c7 --- /dev/null +++ b/.template_sync/manifest.yaml @@ -0,0 +1,101 @@ +template_version: 0.1.31 +migrations: + - from: 0.0.0 + to: 0.0.1 + script: migrations/v0_0_0_to_v0_0_1.py + - from: 0.0.1 + to: 0.1.0 + script: migrations/v0_0_1_to_v0_1_0.py + - from: 0.1.0 + to: 0.1.1 + script: migrations/v0_1_0_to_v0_1_1.py + - from: 0.1.1 + to: 0.1.2 + script: migrations/v0_1_1_to_v0_1_2.py + - from: 0.1.2 + to: 0.1.3 + script: migrations/v0_1_2_to_v0_1_3.py + - from: 0.1.3 + to: 0.1.4 + script: migrations/v0_1_3_to_v0_1_4.py + - from: 0.1.4 + to: 0.1.5 + script: migrations/v0_1_4_to_v0_1_5.py + - from: 0.1.5 + to: 0.1.6 + script: migrations/v0_1_5_to_v0_1_6.py + - from: 0.1.6 + to: 0.1.7 + script: migrations/v0_1_6_to_v0_1_7.py + - from: 0.1.7 + to: 0.1.8 + script: migrations/v0_1_7_to_v0_1_8.py + - from: 0.1.8 + to: 0.1.9 + script: migrations/v0_1_8_to_v0_1_9.py + - from: 0.1.9 + to: 0.1.10 + script: migrations/v0_1_9_to_v0_1_10.py + - from: 0.1.10 + to: 0.1.11 + script: migrations/v0_1_10_to_v0_1_11.py + - from: 0.1.11 + to: 0.1.12 + script: migrations/v0_1_11_to_v0_1_12.py + - from: 0.1.12 + to: 0.1.13 + script: migrations/v0_1_12_to_v0_1_13.py + - from: 0.1.13 + to: 0.1.14 + script: migrations/v0_1_13_to_v0_1_14.py + - from: 0.1.14 + to: 0.1.15 + script: migrations/v0_1_14_to_v0_1_15.py + - from: 0.1.15 + to: 0.1.16 + script: migrations/v0_1_15_to_v0_1_16.py + - from: 0.1.16 + to: 0.1.17 + script: migrations/v0_1_16_to_v0_1_17.py + - from: 0.1.17 + to: 0.1.18 + script: migrations/v0_1_17_to_v0_1_18.py + - from: 0.1.18 + to: 0.1.19 + script: migrations/v0_1_18_to_v0_1_19.py + - from: 0.1.19 + to: 0.1.20 + script: migrations/v0_1_19_to_v0_1_20.py + - from: 0.1.20 + to: 0.1.21 + script: migrations/v0_1_20_to_v0_1_21.py + - from: 0.1.21 + to: 0.1.22 + script: migrations/v0_1_21_to_v0_1_22.py + - from: 0.1.22 + to: 0.1.23 + script: migrations/v0_1_22_to_v0_1_23.py + - from: 0.1.23 + to: 0.1.24 + script: migrations/v0_1_23_to_v0_1_24.py + - from: 0.1.24 + to: 0.1.25 + script: migrations/v0_1_24_to_v0_1_25.py + - 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 diff --git a/.template_sync/migrations/v0_0_0_to_v0_0_1.py b/.template_sync/migrations/v0_0_0_to_v0_0_1.py new file mode 100644 index 0000000..64a3208 --- /dev/null +++ b/.template_sync/migrations/v0_0_0_to_v0_0_1.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Register a repository that predates template-sync metadata. + + A missing local manifest is represented by version ``0.0.0`` in the + synchronization workflow. The workflow checks out the current + ``.template_sync`` directory before running migrations, so no repository + files need to be changed in this bootstrap step. Advancing to ``0.0.1`` + connects first-time repositories to the existing migration chain. + """ + + _ = repo_root + _ = context diff --git a/.template_sync/migrations/v0_0_1_to_v0_1_0.py b/.template_sync/migrations/v0_0_1_to_v0_1_0.py new file mode 100644 index 0000000..dbb4071 --- /dev/null +++ b/.template_sync/migrations/v0_0_1_to_v0_1_0.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Bootstrap migration for the versioned template sync flow. + + The workflow already updates `.template_sync` before executing this script. + This migration is intentionally a no-op so the initial PR only contains the + bootstrap files. Future migrations can make targeted repository changes. + """ + + _ = repo_root + _ = context diff --git a/.template_sync/migrations/v0_1_0_to_v0_1_1.py b/.template_sync/migrations/v0_1_0_to_v0_1_1.py new file mode 100644 index 0000000..fc528f5 --- /dev/null +++ b/.template_sync/migrations/v0_1_0_to_v0_1_1.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +SCRIPT_PATH = Path(".tools/bash/test_conda_environment.sh") +WORKFLOW_PATH = Path(".github/workflows/update_on_notebook_change.yml") + +SKIP_GUARD = """is_truthy() { + case "${1:-}" in + 1|true|TRUE|True|yes|YES|Yes|on|ON|On) + return 0 + ;; + *) + return 1 + ;; + esac +} + +if is_truthy "${SKIP_CONDA_ENV_TEST:-}"; then + echo "SKIP_CONDA_ENV_TEST is enabled; skipping conda environment validation." + exit 0 +fi + +""" + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def update_test_script(repo_root: Path) -> bool: + script_path = repo_root / SCRIPT_PATH + if not script_path.exists(): + print(f"Skipping missing file: {SCRIPT_PATH}") + return False + + original_text = script_path.read_text(encoding="utf-8") + if "SKIP_CONDA_ENV_TEST is enabled; skipping conda environment validation." in original_text: + return False + + newline = detect_newline(original_text) + marker = f"set -u # Exit on undefined variables{newline}" + if marker not in original_text: + raise ValueError(f"Unable to find insertion point in {SCRIPT_PATH}") + + guard_block = SKIP_GUARD.replace("\n", newline) + updated_text = original_text.replace(marker, marker + newline + guard_block, 1) + script_path.write_text(updated_text, encoding="utf-8") + print(f"Updated {SCRIPT_PATH}") + return True + + +def update_workflow(repo_root: Path) -> bool: + workflow_path = repo_root / WORKFLOW_PATH + if not workflow_path.exists(): + print(f"Skipping missing file: {WORKFLOW_PATH}") + return False + + original_text = workflow_path.read_text(encoding="utf-8") + if "SKIP_CONDA_ENV_TEST:" in original_text: + return False + + lines = original_text.splitlines(keepends=True) + newline = detect_newline(original_text) + + for index, line in enumerate(lines): + if line.strip() != "id: test-conda-env": + continue + + indent = line[: len(line) - len(line.lstrip())] + run_index = None + for candidate in range(index + 1, len(lines)): + if lines[candidate].strip() == "run: |": + run_index = candidate + break + + if run_index is None: + raise ValueError(f"Unable to find run block for test-conda-env in {WORKFLOW_PATH}") + + env_block = [ + f"{indent}env:{newline}", + f"{indent} SKIP_CONDA_ENV_TEST: ${{{{ vars.SKIP_CONDA_ENV_TEST }}}}{newline}", + ] + updated_lines = lines[:run_index] + env_block + lines[run_index:] + workflow_path.write_text("".join(updated_lines), encoding="utf-8") + print(f"Updated {WORKFLOW_PATH}") + return True + + raise ValueError(f"Unable to find test-conda-env step in {WORKFLOW_PATH}") + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_test_script(repo_root) or changed_any + changed_any = update_workflow(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_10_to_v0_1_11.py b/.template_sync/migrations/v0_1_10_to_v0_1_11.py new file mode 100644 index 0000000..efa7093 --- /dev/null +++ b/.template_sync/migrations/v0_1_10_to_v0_1_11.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Record the first-time migration compatibility hardening release. + + The functional changes are in the migration engine's historical notebook and + documentation handlers. Those handlers now accept initialized repositories + where project placeholders have already been replaced with real values. + """ + + _ = repo_root + _ = context + print("Template migration compatibility hardening is active.") diff --git a/.template_sync/migrations/v0_1_11_to_v0_1_12.py b/.template_sync/migrations/v0_1_11_to_v0_1_12.py new file mode 100644 index 0000000..a5d8a39 --- /dev/null +++ b/.template_sync/migrations/v0_1_11_to_v0_1_12.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +RESOURCE_ROOT = ( + Path(__file__).resolve().parents[1] / "resources" / "v0_1_11_to_v0_1_12" +) +SYNC_WORKFLOW_PATH = Path(".github/workflows/sync_template.yml") +SYNC_GUIDE_PATH = Path(".tools/docs/template_synchronization.md") +ROOT_README_PATH = Path("README.md") +DOCS_INDEX_PATH = Path(".tools/docs/README.md") +BEFORE_GETTING_STARTED_PATH = Path(".tools/docs/before_getting_started.md") +CREATE_REPOSITORY_PATH = Path(".tools/docs/create_repository.md") +INITIALISE_REPOSITORY_PATH = Path(".tools/docs/initialise_repository.md") +PERSONAL_TOKEN_PATH = Path(".tools/docs/personal_access_token.md") +TROUBLESHOOTING_PATH = Path(".tools/docs/troubleshooting.md") +WORKFLOW_STATUS_PATH = Path(".tools/docs/workflow_status.md") +ACCEPT_PR_PATH = Path(".tools/docs/accept_pull_request.md") + +ROOT_GUIDE_LINK = ".tools/docs/template_synchronization.md" +DOC_GUIDE_LINK = "template_synchronization.md" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as handle: + return handle.read() + + +def write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8", newline="") as handle: + handle.write(text) + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def normalize_newlines(text: str, newline: str) -> str: + return text.replace("\r\n", "\n").replace("\n", newline) + + +def copy_resource(repo_root: Path, relative_path: Path) -> bool: + source_path = RESOURCE_ROOT / relative_path + destination_path = repo_root / relative_path + if not source_path.is_file(): + raise ValueError(f"Missing migration resource: {source_path}") + + source_text = read_text(source_path) + if destination_path.exists(): + existing_text = read_text(destination_path) + newline = detect_newline(existing_text) + else: + existing_text = "" + newline = detect_newline(source_text) + + rendered = normalize_newlines(source_text, newline) + if rendered == existing_text: + return False + + write_text(destination_path, rendered) + print(f"Updated {relative_path}") + return True + + +def insert_before_navigation(text: str, block: str, newline: str) -> str: + normalized = text.replace("\r\n", "\n") + normalized_block = block.strip("\n") + markers = ( + "\n---\n\n
", + "\n---\n
", + ) + for marker in markers: + if marker in normalized: + updated = normalized.replace( + marker, + f"\n\n{normalized_block}\n{marker}", + 1, + ) + return updated.replace("\n", newline) + + if normalized and not normalized.endswith("\n"): + normalized += "\n" + return (normalized + "\n" + normalized_block + "\n").replace("\n", newline) + + +def update_file(repo_root: Path, relative_path: Path, updater) -> bool: + path = repo_root / relative_path + if not path.is_file(): + print(f"Skipping missing file: {relative_path}") + return False + + original = read_text(path) + updated = updater(original, detect_newline(original)) + if updated == original: + return False + + write_text(path, updated) + print(f"Updated {relative_path}") + return True + + +def update_root_readme(text: str, newline: str) -> str: + if ROOT_GUIDE_LINK in text: + return text + + block = """## ๐Ÿ”„ Automatic Template Updates + +LabConstrictor can prepare pull requests that keep this repository aligned with improvements in the main template, including updates to GitHub Actions workflows. Complete the one-time [automatic synchronization setup](.tools/docs/template_synchronization.md) to enable these updates.""" + normalized = text.replace("\r\n", "\n") + marker = "\n## ๐Ÿค Contributing" + if marker in normalized: + normalized = normalized.replace(marker, f"\n\n{block}\n{marker}", 1) + return normalized.replace("\n", newline) + return insert_before_navigation(text, block, newline) + + +def update_docs_index(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + + normalized = text.replace("\r\n", "\n") + entry = "- [Configure automatic template synchronization](template_synchronization.md)" + marker = "## GitHub management" + if marker in normalized: + start = normalized.index(marker) + len(marker) + next_heading = normalized.find("\n## ", start) + insert_at = next_heading if next_heading != -1 else len(normalized) + section = normalized[start:insert_at].rstrip() + normalized = normalized[:start] + section + "\n\n" + entry + "\n" + normalized[insert_at:] + return normalized.replace("\n", newline) + + return insert_before_navigation(text, "## GitHub management\n\n" + entry, newline) + + +def update_before_getting_started(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + block = """## ๐Ÿ”„ One-time update setup + +After creating your repository, complete the [automatic template synchronization setup](template_synchronization.md). This allows future template improvements to be delivered as pull requests, including necessary GitHub Actions workflow updates.""" + return insert_before_navigation(text, block, newline) + + +def update_create_repository(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + block = """## Enable future template updates + +Before initialising the project, complete the one-time [automatic template synchronization setup](template_synchronization.md). It lets LabConstrictor prepare safe pull requests when the template receives fixes, including changes to GitHub Actions workflows.""" + return insert_before_navigation(text, block, newline) + + +def add_callout_after_title(text: str, newline: str, callout: str) -> str: + normalized = text.replace("\r\n", "\n") + lines = normalized.splitlines(keepends=True) + if not lines: + return text + insert_at = 1 + while insert_at < len(lines) and not lines[insert_at].strip(): + insert_at += 1 + rendered = "\n" + callout.strip() + "\n\n" + updated = "".join(lines[:insert_at]) + rendered + "".join(lines[insert_at:]) + return updated.replace("\n", newline) + + +def update_initialise_repository(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + return add_callout_after_title( + text, + newline, + "> Before continuing, complete the one-time [automatic template synchronization setup](template_synchronization.md). This allows future template migrations to update workflow files safely.", + ) + + +def update_personal_token(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + return add_callout_after_title( + text, + newline, + "> Looking for the token used by the automatic template update workflow? Follow the dedicated [automatic template synchronization guide](template_synchronization.md). It uses a repository-scoped fine-grained token with a different purpose and secret name.", + ) + + +def update_workflow_status(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + return add_callout_after_title( + text, + newline, + "The template synchronization workflow requires the one-time [`LABCONSTRICTOR_SYNC_TOKEN` setup](template_synchronization.md). Other notebook and installer workflows continue to use GitHub's built-in credentials.", + ) + + +def update_accept_pr(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text: + return text + return add_callout_after_title( + text, + newline, + "LabConstrictor template updates are delivered as pull requests after you complete the [automatic synchronization setup](template_synchronization.md).", + ) + + +def update_troubleshooting(text: str, newline: str) -> str: + if DOC_GUIDE_LINK in text and "LABCONSTRICTOR_SYNC_TOKEN" in text: + return text + + normalized = text.replace("\r\n", "\n") + section = """## Synchronisation is failing on GitHub Actions + +The **Sync with Template Repository** workflow needs the encrypted repository secret `LABCONSTRICTOR_SYNC_TOKEN` because template migrations can update files in `.github/workflows/`. Follow the [automatic template synchronization guide](template_synchronization.md) for the complete beginner-friendly setup. + +### The synchronization token is missing + +Create the token and save it under **Settings โ†’ Secrets and variables โ†’ Actions** with this exact name: + +```text +LABCONSTRICTOR_SYNC_TOKEN +``` + +### GitHub refuses to update a workflow file + +If the error says GitHub is refusing to create or update a workflow without `workflows` permission, ensure the token has all of these repository permissions: + +- **Contents:** Read and write +- **Pull requests:** Read and write +- **Workflows:** Read and write + +Repositories created before template version `0.1.12` also need the one-time workflow edit described in the synchronization guide so the existing workflow starts using the secret. + +### Bad credentials or authentication failed + +The token may have expired or been revoked. Create a replacement token and update the existing `LABCONSTRICTOR_SYNC_TOKEN` secret.""" + + heading = "## Synchronisation is failing on GitHub Actions" + if heading in normalized: + start = normalized.index(heading) + next_heading = normalized.find("\n## ", start + len(heading)) + if next_heading == -1: + normalized = normalized[:start].rstrip() + "\n\n" + section + "\n" + else: + normalized = ( + normalized[:start].rstrip() + + "\n\n" + + section + + "\n\n" + + normalized[next_heading + 1 :] + ) + return normalized.replace("\n", newline) + + marker = "## JupyterLab does not start" + if marker in normalized: + normalized = normalized.replace(marker, section + "\n\n" + marker, 1) + return normalized.replace("\n", newline) + return insert_before_navigation(text, section, newline) + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + changed = False + + changed = copy_resource(repo_root, SYNC_WORKFLOW_PATH) or changed + changed = copy_resource(repo_root, SYNC_GUIDE_PATH) or changed + + updates = ( + (ROOT_README_PATH, update_root_readme), + (DOCS_INDEX_PATH, update_docs_index), + (BEFORE_GETTING_STARTED_PATH, update_before_getting_started), + (CREATE_REPOSITORY_PATH, update_create_repository), + (INITIALISE_REPOSITORY_PATH, update_initialise_repository), + (PERSONAL_TOKEN_PATH, update_personal_token), + (TROUBLESHOOTING_PATH, update_troubleshooting), + (WORKFLOW_STATUS_PATH, update_workflow_status), + (ACCEPT_PR_PATH, update_accept_pr), + ) + for relative_path, updater in updates: + changed = update_file(repo_root, relative_path, updater) or changed + + if not changed: + print("Template synchronization token integration is already up to date.") diff --git a/.template_sync/migrations/v0_1_12_to_v0_1_13.py b/.template_sync/migrations/v0_1_12_to_v0_1_13.py new file mode 100644 index 0000000..f24e51f --- /dev/null +++ b/.template_sync/migrations/v0_1_12_to_v0_1_13.py @@ -0,0 +1,390 @@ +from __future__ import annotations + +import json +import re + +from pathlib import Path +from typing import Any + + +RESOURCE_ROOT = ( + Path(__file__).resolve().parents[1] / "resources" / "v0_1_12_to_v0_1_13" +) +BUMP_VERSION_PATH = Path(".tools/python/bump_version.py") +DOWNLOAD_TEMPLATE_PATH = Path(".tools/templates/download_executable_template.md") +DOWNLOAD_DOC_PATHS = ( + Path(".tools/docs/download_executable.md"), + Path("docs/download_executable.md"), +) +CONSTRUCT_PATH = Path("construct.yaml") +WELCOME_PATHS = ( + Path(".tools/templates/Welcome_template.ipynb"), + Path("app/menuinst/Welcome.ipynb"), +) + +VERSION_LINE_RE = re.compile( + r'^(version:\s*)(?P["\']?)(?P\d+\.\d+\.\d+)(?P=quote)(?P\s*(?:#.*)?)$', + re.MULTILINE, +) +CONCLUSION_LINE_RE = re.compile( + r'^(conclusion_text:\s*)(?:(?P["\'])(?P.*?)(?P=quote)|(?P.*?))(?P\s*(?:#.*)?)$', + re.MULTILINE, +) +RELEASE_VERSION_RE = re.compile(r"/releases/download/(\d+\.\d+\.\d+)/") +SEMVER_RE = re.compile(r"\b\d+\.\d+\.\d+\b") + +GRID_CONFIG = ( + 'GRID_COLUMN_WIDTHS = (\n' + ' "minmax(110px, 1.2fr) "\n' + ' "minmax(90px, 1.0fr) "\n' + ' "minmax(220px, 3.0fr) "\n' + ' "minmax(90px, 0.8fr) "\n' + ' "minmax(110px, 1.4fr) "\n' + ' "minmax(75px, 0.8fr) "\n' + ' "minmax(160px, 1.8fr)"\n' + ')\n\n\n' + 'def apply_grid_layout(grid):\n' + ' """Apply responsive sizing while keeping the table readable on narrow panes."""\n' + ' grid.add_class("labconstrictor-responsive-grid")\n' + ' grid.layout.width = "100%"\n' + ' grid.layout.grid_template_columns = GRID_COLUMN_WIDTHS\n' + ' grid.layout.overflow = "auto"\n\n\n' +) + +WIDGET_OUTPUT_BLOCK = ( + '# Capture stdout, stderr, rich displays, figures, warnings, and tracebacks from widget callbacks.\n' + '_widget_callback_output_cell_1 = widgets.Output()\n\n\n' +) + +RESPONSIVE_CSS = ( + ' .labconstrictor-responsive-grid .widget-html-content {\n' + ' font-size: clamp(12px, 0.9vw, 15px) !important;\n' + ' line-height: 1.35 !important;\n' + ' }\n' + ' .labconstrictor-responsive-grid .widget-button {\n' + ' font-size: clamp(11px, 0.85vw, 14px) !important;\n' + ' }\n' + ' .table-description {\n' + ' text-align: left !important;\n' + ' white-space: normal !important;\n' + ' overflow-wrap: anywhere !important;\n' + ' }\n' +) + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as handle: + return handle.read() + + +def write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8", newline="") as handle: + handle.write(text) + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def normalize_newlines(text: str, newline: str) -> str: + return text.replace("\r\n", "\n").replace("\n", newline) + + +def copy_bump_version(repo_root: Path) -> bool: + source = RESOURCE_ROOT / BUMP_VERSION_PATH + destination = repo_root / BUMP_VERSION_PATH + if not source.is_file(): + raise ValueError(f"Missing migration resource: {source}") + + source_text = read_text(source) + if destination.exists(): + existing_text = read_text(destination) + newline = detect_newline(existing_text) + else: + existing_text = "" + newline = detect_newline(source_text) + + rendered = normalize_newlines(source_text, newline) + if rendered == existing_text: + return False + + write_text(destination, rendered) + print(f"Updated {BUMP_VERSION_PATH}") + return True + + +def normalize_download_template(repo_root: Path) -> bool: + path = repo_root / DOWNLOAD_TEMPLATE_PATH + if not path.is_file(): + print(f"Skipping missing file: {DOWNLOAD_TEMPLATE_PATH}") + return False + + original = read_text(path) + if "VERSION_NUMBER" in original: + return False + + versions = set(RELEASE_VERSION_RE.findall(original)) + if not versions: + print( + f"Skipping {DOWNLOAD_TEMPLATE_PATH}: no release version placeholder " + "or explicit release version was found" + ) + return False + + updated = original + for version in versions: + updated = updated.replace(version, "VERSION_NUMBER") + + if updated == original: + return False + + write_text(path, updated) + print(f"Normalized release version placeholder in {DOWNLOAD_TEMPLATE_PATH}") + return True + + +def read_project_version(repo_root: Path) -> str | None: + path = repo_root / CONSTRUCT_PATH + if not path.is_file(): + return None + match = VERSION_LINE_RE.search(read_text(path)) + return match.group("version") if match else None + + +def align_construct_conclusion(repo_root: Path, project_version: str | None) -> bool: + if not project_version: + return False + + path = repo_root / CONSTRUCT_PATH + if not path.is_file(): + return False + + original = read_text(path) + + def repl(match: re.Match) -> str: + quote = match.group("quote") or "" + body = match.group("quoted_body") if quote else (match.group("bare_body") or "") + if "VERSION_NUMBER" in body: + updated_body = body.replace("VERSION_NUMBER", project_version) + else: + updated_body = SEMVER_RE.sub(project_version, body, count=1) + return ( + f"{match.group(1)}{quote}{updated_body}{quote}" + f"{match.group('trailing')}" + ) + + updated = CONCLUSION_LINE_RE.sub(repl, original, count=1) + if updated == original: + return False + + write_text(path, updated) + print(f"Aligned {CONSTRUCT_PATH} conclusion text to {project_version}") + return True + + +def align_download_docs(repo_root: Path, project_version: str | None) -> bool: + if not project_version: + return False + + changed = False + for relative_path in DOWNLOAD_DOC_PATHS: + path = repo_root / relative_path + if not path.is_file(): + continue + + original = read_text(path) + versions = set(RELEASE_VERSION_RE.findall(original)) + updated = original + for version in versions: + updated = updated.replace(version, project_version) + + if updated != original: + write_text(path, updated) + print(f"Aligned {relative_path} download links to {project_version}") + changed = True + + return changed + + +def update_welcome_notebook(repo_root: Path, relative_path: Path) -> bool: + path = repo_root / relative_path + if not path.is_file(): + print(f"Skipping missing file: {relative_path}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + try: + notebook = json.loads(original_text) + except json.JSONDecodeError as exc: + raise ValueError(f"Unable to parse {relative_path} as JSON") from exc + + notebook_changed = False + found_grid = False + for cell in notebook.get("cells", []): + if cell.get("cell_type") != "code": + continue + + source = cell.get("source", []) + source_is_list = isinstance(source, list) + src = "".join(source) if source_is_list else str(source) + if "grid = GridspecLayout(1 + num_rows, 7)" not in src: + continue + + found_grid = True + normalized = src.replace("\r\n", "\n") + original_normalized = normalized + + load_marker = "def load_table(version_response, project_version_response, notebooks):\n" + load_index = normalized.find(load_marker) + if load_index < 0: + raise ValueError( + f"Unable to find load_table insertion point in {relative_path}" + ) + grid_config_index = normalized.find("GRID_COLUMN_WIDTHS = (") + if 0 <= grid_config_index < load_index: + normalized = normalized[:grid_config_index] + GRID_CONFIG + normalized[load_index:] + else: + normalized = normalized.replace(load_marker, GRID_CONFIG + load_marker, 1) + + if "_widget_callback_output_cell_1 = widgets.Output()" not in normalized: + marker = "# Define notebooks with their metadata\n" + if marker not in normalized: + raise ValueError( + f"Unable to find widget-output insertion point in {relative_path}" + ) + normalized = normalized.replace(marker, WIDGET_OUTPUT_BLOCK + marker, 1) + + normalized = normalized.replace( + "update_src_button.on_click(on_update_src_button_clicked)", + "update_src_button.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_update_src_button_clicked))", + ) + normalized = re.sub( + r"update_button\.on_click\(button_update\((.*?)\)\)", + r"update_button.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(button_update(\1)))", + normalized, + ) + normalized = normalized.replace( + "apply_grid_column_widths(grid)", "apply_grid_layout(grid)" + ) + + lines = normalized.splitlines(keepends=True) + + grid_create_index = next( + (i for i, line in enumerate(lines) + if line.strip() == "grid = GridspecLayout(1 + num_rows, 7)"), + None, + ) + if grid_create_index is None: + raise ValueError(f"Unable to find Welcome table grid in {relative_path}") + next_line = lines[grid_create_index + 1].strip() if grid_create_index + 1 < len(lines) else "" + if next_line != "apply_grid_layout(grid)": + indent = lines[grid_create_index][: len(lines[grid_create_index]) - len(lines[grid_create_index].lstrip())] + lines.insert(grid_create_index + 1, f"{indent}apply_grid_layout(grid)\n") + + callback_apply_present = False + for index, line in enumerate(lines): + if line.strip() != "apply_grid_layout(grid)": + continue + previous = lines[index - 1].strip() if index > 0 else "" + if previous.startswith("grid[row_idx, 5] = widgets.HTML"): + callback_apply_present = True + break + if not callback_apply_present: + for index, line in enumerate(lines): + if line.strip().startswith("grid[row_idx, 5] = widgets.HTML"): + indent = line[: len(line) - len(line.lstrip())] + lines.insert(index + 1, f"{indent}apply_grid_layout(grid)\n") + break + else: + raise ValueError( + f"Unable to find notebook-update grid block in {relative_path}" + ) + + display_index = next( + (i for i, line in enumerate(lines) if line.strip() == "display(grid, grip_output)"), + None, + ) + if display_index is None: + raise ValueError(f"Unable to find grid display in {relative_path}") + previous = lines[display_index - 1].strip() if display_index > 0 else "" + if previous != "apply_grid_layout(grid)": + indent = lines[display_index][: len(lines[display_index]) - len(lines[display_index].lstrip())] + lines.insert(display_index, f"{indent}apply_grid_layout(grid)\n") + + normalized = "".join(lines) + + if "font-size: clamp(12px, 0.9vw, 15px)" not in normalized: + style_close = " \n" + if style_close not in normalized: + raise ValueError(f"Unable to find Welcome CSS block in {relative_path}") + normalized = normalized.replace(style_close, RESPONSIVE_CSS + style_close, 1) + + header_start = normalized.find(" .grid-header {") + if header_start >= 0: + header_end = normalized.find(" }", header_start) + header_block = normalized[header_start:header_end] + if "font-size: clamp(13px, 1vw, 16px)" not in header_block: + header_marker = " font-weight: 600 !important;\n" + marker_index = normalized.find(header_marker, header_start, header_end) + if marker_index >= 0: + insert_at = marker_index + len(header_marker) + normalized = ( + normalized[:insert_at] + + " font-size: clamp(13px, 1vw, 16px) !important;\n" + + normalized[insert_at:] + ) + + normalized = normalized.replace( + "widgets.HTML(f\"
{nb['description']}
\")", + "widgets.HTML(f\"
{nb['description']}
\")", + ) + + if "display(_widget_callback_output_cell_1)" not in normalized: + normalized = ( + normalized.rstrip("\n") + + "\n\n# Display callback-generated output directly below this cell.\n" + + "display(_widget_callback_output_cell_1)\n" + ) + + if normalized != original_normalized: + rendered_source = normalize_newlines(normalized, "\n") + cell["source"] = ( + rendered_source.splitlines(keepends=True) + if source_is_list + else rendered_source + ) + notebook_changed = True + break + + if not found_grid: + print(f"Skipping {relative_path}: expected Welcome table grid was not found") + return False + if not notebook_changed: + return False + + rendered = json.dumps(notebook, ensure_ascii=False, indent=1) + if original_text.endswith(("\n", "\r\n")): + rendered += newline + write_text(path, rendered) + print(f"Updated responsive Welcome table and widget output in {relative_path}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = copy_bump_version(repo_root) or changed_any + changed_any = normalize_download_template(repo_root) or changed_any + + project_version = read_project_version(repo_root) + changed_any = align_construct_conclusion(repo_root, project_version) or changed_any + changed_any = align_download_docs(repo_root, project_version) or changed_any + + for relative_path in WELCOME_PATHS: + changed_any = update_welcome_notebook(repo_root, relative_path) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_13_to_v0_1_14.py b/.template_sync/migrations/v0_1_13_to_v0_1_14.py new file mode 100644 index 0000000..48d4098 --- /dev/null +++ b/.template_sync/migrations/v0_1_13_to_v0_1_14.py @@ -0,0 +1,385 @@ +from __future__ import annotations + +import json +import re + +from pathlib import Path +from typing import Any + + +WELCOME_PATHS = ( + Path(".tools/templates/Welcome_template.ipynb"), + Path("app/menuinst/Welcome.ipynb"), +) + +GRID_HELPERS = r'''GRID_COLUMN_WIDTHS = ( + "minmax(0, 1.4fr) " # Notebook Name + "minmax(0, 1.4fr) " # Notebook Topic + "minmax(0, 2.8fr) " # Description + "minmax(85px, 0.8fr) " # Local Version + "minmax(100px, 1.2fr) " # Status + "minmax(70px, 0.7fr) " # Update? + "minmax(150px, 1.6fr)" # Open Notebook +) + + +def apply_grid_layout(grid): + """Apply responsive sizing while allowing long text to wrap safely.""" + grid.add_class("labconstrictor-responsive-grid") + grid.layout.width = "100%" + grid.layout.min_width = "0" + grid.layout.grid_template_columns = GRID_COLUMN_WIDTHS + grid.layout.grid_auto_rows = "auto" + grid.layout.overflow = "auto" + + +def table_cell(value, align="center", extra_class=""): + """Create a table cell that can shrink and wrap long scientific identifiers.""" + classes = ["labconstrictor-table-cell"] + if align == "left": + classes.append("labconstrictor-table-cell-left") + else: + classes.append("labconstrictor-table-cell-center") + if extra_class: + classes.append(extra_class) + + class_names = " ".join(classes) + + return widgets.HTML( + value=f"
{value}
", + layout=widgets.Layout(width="100%", min_width="0"), + ) + + +def table_header(value): + """Create a responsive table header.""" + return widgets.HTML( + value=f"
{value}
", + layout=widgets.Layout(width="100%", min_width="0"), + ) + + +''' + +WELCOME_CSS_BLOCK = r''' # Add custom CSS for responsive table styling + display(widgets.HTML(""" + + """)) + + +''' + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as handle: + return handle.read() + + +def write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8", newline="") as handle: + handle.write(text) + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def _replace_welcome_assignments(source: str) -> str: + """Replace the 0.1.13 HTML cells with wrapping table helpers.""" + replacements = { + 'grid[idx, 0] = widgets.HTML(f"
{nb[\'name\']}
")': + 'grid[idx, 0] = table_cell(nb["name"])', + 'grid[idx, 1] = widgets.HTML(f"
{main_folder}
")': + 'grid[idx, 1] = table_cell(main_folder)', + 'grid[idx, 2] = widgets.HTML(f"
{nb[\'description\']}
")': + 'grid[idx, 2] = table_cell(nb["description"], align="left")', + 'grid[idx, 2] = widgets.HTML(f"
{nb[\'description\']}
")': + 'grid[idx, 2] = table_cell(nb["description"], align="left")', + 'grid[idx, 2] = widgets.HTML("
-
")': + 'grid[idx, 2] = table_cell("-")', + 'grid[idx, 3] = widgets.HTML(f"
{local_version}
")': + 'grid[idx, 3] = table_cell(local_version)', + 'grid[idx, 4] = widgets.HTML("
โŒ Project Outdated
")': + 'grid[idx, 4] = table_cell("โŒ Project Outdated")', + 'grid[idx, 5] = widgets.HTML("
-
")': + 'grid[idx, 5] = table_cell("-")', + 'grid[idx, 4] = widgets.HTML("
โœ… Up-to-date
")': + 'grid[idx, 4] = table_cell("โœ… Up-to-date")', + 'grid[idx, 4] = widgets.HTML(f"
โŒ Needs Update to {online_version}
")': + 'grid[idx, 4] = table_cell(f"โŒ Needs Update to {online_version}")', + 'grid[row_idx, 3] = widgets.HTML(f"
{online_latest_versions[main_folder][subfolder]}
")': + 'grid[row_idx, 3] = table_cell(online_latest_versions[main_folder][subfolder])', + 'grid[row_idx, 4] = widgets.HTML("
โœ… Up-to-date
")': + 'grid[row_idx, 4] = table_cell("โœ… Up-to-date")', + 'grid[row_idx, 5] = widgets.HTML("
-
")': + 'grid[row_idx, 5] = table_cell("-")', + 'grid[idx, 3] = widgets.HTML("
Not Found
")': + 'grid[idx, 3] = table_cell("Not Found")', + 'grid[idx, 4] = widgets.HTML("
โŒ Missing Notebook
")': + 'grid[idx, 4] = table_cell("โŒ Missing Notebook")', + 'grid[idx, 0] = widgets.HTML(f"
{subfolder}
")': + 'grid[idx, 0] = table_cell(subfolder)', + 'grid[idx, 4] = widgets.HTML("
โŒ Missing Notebook
")': + 'grid[idx, 4] = table_cell("โŒ Missing Notebook")', + 'grid[idx, 6] = widgets.HTML("
-
")': + 'grid[idx, 6] = table_cell("-")', + } + for old, new in replacements.items(): + source = source.replace(old, new) + return source + + +def _upgrade_welcome_source(source: str, relative_path: Path) -> str: + normalized = source.replace("\r\n", "\n") + + load_marker = "def load_table(version_response, project_version_response, notebooks):\n" + load_index = normalized.find(load_marker) + if load_index < 0: + raise ValueError(f"Unable to find load_table insertion point in {relative_path}") + + # Replace the 0.1.13 responsive helpers in place. If a repository already + # received the final helper manually, this simply canonicalizes it. + grid_config_index = normalized.find("GRID_COLUMN_WIDTHS = (") + if 0 <= grid_config_index < load_index: + normalized = normalized[:grid_config_index] + GRID_HELPERS + normalized[load_index:] + else: + normalized = normalized.replace(load_marker, GRID_HELPERS + load_marker, 1) + + # Keep the existing callback-output capture from 0.1.13, while tolerating a + # manually edited repository where it may be absent. + if "_widget_callback_output_cell_1 = widgets.Output()" not in normalized: + marker = "# Define notebooks with their metadata\n" + if marker not in normalized: + raise ValueError(f"Unable to find widget-output insertion point in {relative_path}") + widget_block = ( + "# Capture stdout, stderr, rich displays, figures, warnings, and tracebacks from widget callbacks.\n" + "_widget_callback_output_cell_1 = widgets.Output()\n\n\n" + ) + normalized = normalized.replace(marker, widget_block + marker, 1) + + # Keep the Open control inside its grid column. + normalized = normalized.replace( + 'layout=widgets.Layout(width="auto")', + 'layout=widgets.Layout(width="auto", min_width="140px")', + ) + normalized = normalized.replace( + 'layout=widgets.Layout(align_items="center")', + 'layout=widgets.Layout(width="100%", min_width="0", align_items="center", justify_content="center")', + ) + + # Preserve callback output if the local 0.1.13 file was partially edited. + normalized = normalized.replace( + "update_src_button.on_click(on_update_src_button_clicked)", + "update_src_button.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_update_src_button_clicked))", + ) + normalized = re.sub( + r"update_button\.on_click\(button_update\((.*?)\)\)", + r"update_button.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(button_update(\1)))", + normalized, + ) + + # Replace the complete style block so every text cell, not only the + # description, can wrap long underscore-separated scientific identifiers. + css_marker = " # Add custom CSS for styling\n" + alt_css_marker = " # Add custom CSS for responsive table styling\n" + css_start = normalized.find(css_marker) + if css_start < 0: + css_start = normalized.find(alt_css_marker) + header_start = normalized.find(" grid[0, 0] =", max(css_start, 0)) + if css_start < 0 or header_start < 0: + raise ValueError(f"Unable to find Welcome CSS/header block in {relative_path}") + normalized = normalized[:css_start] + WELCOME_CSS_BLOCK + normalized[header_start:] + + header_replacements = { + 'grid[0, 0] = widgets.HTML("
Notebook Name
")': + 'grid[0, 0] = table_header("Notebook Name")', + 'grid[0, 1] = widgets.HTML("
Notebook Topic
")': + 'grid[0, 1] = table_header("Notebook Topic")', + 'grid[0, 2] = widgets.HTML("
Description
")': + 'grid[0, 2] = table_header("Description")', + 'grid[0, 3] = widgets.HTML("
Local Version
")': + 'grid[0, 3] = table_header("Local Version")', + 'grid[0, 4] = widgets.HTML("
Status
")': + 'grid[0, 4] = table_header("Status")', + 'grid[0, 5] = widgets.HTML("
Update?
")': + 'grid[0, 5] = table_header("Update?")', + 'grid[0, 6] = widgets.HTML("
โฌ‡๏ธ Click to Open the Notebook โฌ‡๏ธ
")': + 'grid[0, 6] = table_header("Open Notebook")', + } + for old, new in header_replacements.items(): + normalized = normalized.replace(old, new) + + normalized = _replace_welcome_assignments(normalized) + + lines = normalized.splitlines(keepends=True) + + grid_create_index = next( + (i for i, line in enumerate(lines) if line.strip() == "grid = GridspecLayout(1 + num_rows, 7)"), + None, + ) + if grid_create_index is None: + raise ValueError(f"Unable to find Welcome table grid in {relative_path}") + next_line = lines[grid_create_index + 1].strip() if grid_create_index + 1 < len(lines) else "" + if next_line != "apply_grid_layout(grid)": + indent = lines[grid_create_index][: len(lines[grid_create_index]) - len(lines[grid_create_index].lstrip())] + lines.insert(grid_create_index + 1, f"{indent}apply_grid_layout(grid)\n") + + # GridspecLayout may recalculate its column template after replacing cells. + callback_apply_present = False + for index, line in enumerate(lines): + if line.strip() != "apply_grid_layout(grid)": + continue + previous = lines[index - 1].strip() if index > 0 else "" + if previous == 'grid[row_idx, 5] = table_cell("-")': + callback_apply_present = True + break + if not callback_apply_present: + for index, line in enumerate(lines): + if line.strip() == 'grid[row_idx, 5] = table_cell("-")': + indent = line[: len(line) - len(line.lstrip())] + lines.insert(index + 1, f"{indent}apply_grid_layout(grid)\n") + break + else: + raise ValueError(f"Unable to find notebook-update grid block in {relative_path}") + + display_index = next( + (i for i, line in enumerate(lines) if line.strip() == "display(grid, grip_output)"), + None, + ) + if display_index is None: + raise ValueError(f"Unable to find grid display in {relative_path}") + previous = lines[display_index - 1].strip() if display_index > 0 else "" + if previous != "apply_grid_layout(grid)": + indent = lines[display_index][: len(lines[display_index]) - len(lines[display_index].lstrip())] + lines.insert(display_index, f"{indent}apply_grid_layout(grid)\n") + + normalized = "".join(lines) + + if "display(_widget_callback_output_cell_1)" not in normalized: + normalized = ( + normalized.rstrip("\n") + + "\n\n# Display callback-generated output directly below this cell.\n" + + "display(_widget_callback_output_cell_1)\n" + ) + + return normalized + + +def update_welcome_notebook(repo_root: Path, relative_path: Path) -> bool: + path = repo_root / relative_path + if not path.is_file(): + print(f"Skipping missing file: {relative_path}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + try: + notebook = json.loads(original_text) + except json.JSONDecodeError as exc: + raise ValueError(f"Unable to parse {relative_path} as JSON") from exc + + notebook_changed = False + found_grid = False + for cell in notebook.get("cells", []): + if cell.get("cell_type") != "code": + continue + + source = cell.get("source", []) + source_is_list = isinstance(source, list) + src = "".join(source) if source_is_list else str(source) + if "grid = GridspecLayout(1 + num_rows, 7)" not in src: + continue + + found_grid = True + normalized = _upgrade_welcome_source(src, relative_path) + original_normalized = src.replace("\r\n", "\n") + if normalized != original_normalized: + cell["source"] = normalized.splitlines(keepends=True) if source_is_list else normalized + notebook_changed = True + break + + if not found_grid: + print(f"Skipping {relative_path}: expected Welcome table grid was not found") + return False + if not notebook_changed: + return False + + rendered = json.dumps(notebook, ensure_ascii=False, indent=1) + if original_text.endswith(("\n", "\r\n")): + rendered += newline + write_text(path, rendered) + print(f"Updated wrapping Welcome table in {relative_path}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + for relative_path in WELCOME_PATHS: + changed_any = update_welcome_notebook(repo_root, relative_path) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_14_to_v0_1_15.py b/.template_sync/migrations/v0_1_14_to_v0_1_15.py new file mode 100644 index 0000000..06b1537 --- /dev/null +++ b/.template_sync/migrations/v0_1_14_to_v0_1_15.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_14_to_v0_1_15" + +# Template-owned files that make up the App Centre manifest check. labconstrictor-app.yaml itself +# belongs to the app: it is never created, changed or removed by this migration. +MANAGED_FILES = ( + Path(".tools/schema/labconstrictor-app.schema.json"), + Path(".tools/python/check_app_manifest.py"), + Path(".tools/docs/app_manifest.md"), + Path(".github/workflows/check_app_manifest.yml"), +) + + +def copy_resource(repo_root: Path, relative_path: Path) -> None: + """Copy one resource file into the repository, replacing the template-owned copy if it exists. + Raises FileNotFoundError when the resource is missing from the template.""" + source = RESOURCE_ROOT / relative_path + if not source.is_file(): + raise FileNotFoundError(f"Template resource not found: {source}") + destination = repo_root / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(source.read_bytes()) + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Add the App Centre manifest check (script, schema copy, workflow and guide) to the repository.""" + for relative_path in MANAGED_FILES: + copy_resource(repo_root, relative_path) diff --git a/.template_sync/migrations/v0_1_15_to_v0_1_16.py b/.template_sync/migrations/v0_1_15_to_v0_1_16.py new file mode 100644 index 0000000..c41457f --- /dev/null +++ b/.template_sync/migrations/v0_1_15_to_v0_1_16.py @@ -0,0 +1,447 @@ +"""Template 0.1.15 -> 0.1.16: add the LabConstrictor Tools bridge hooks to an app repository. + +What this changes (in the app's *repository*, through the template sync pull request; an installed copy of the app is +only ever changed by installing a newer installer, see +https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_16.md): + +* app/bash_bat_scripts/post_install.sh / .bat register the app with the Tools bridge after install +* app/bash_bat_scripts/pre_uninstall.sh / .bat unregister it on uninstall +* app/bash_bat_scripts/uninstall.sh report a failed pre-uninstall or a failed removal +* .tools/docs/tools_bridge.md and its entry in .tools/docs/README.md +* the App Centre manifest check (.tools/schema/labconstrictor-app.schema.json, .tools/python/check_app_manifest.py, .tools/docs/app_manifest.md, + .github/workflows/check_app_manifest.yml), whose 0.1.15 schema copy was stale; labconstrictor-app.yaml itself is never touched + +Rules this migration keeps: + +* It edits surgically: a block is inserted before a known line of the app's own script, so changes the app made to its scripts + stay. A script that already has the hook (it mentions labconstrictor_tools) is left unchanged, so running it twice, or on an + app that carried the hooks before (bridge-test apps), changes nothing. +* A hook that is already there (apps that got it from the bridge-test branch) is not re-inserted. Only if its Tools source is exactly the + old unpinned `.../LabConstrictor-Tools/archive/refs/heads/main.zip` is that source rewritten to the pinned tag form of the template + (an LC_TOOLS_PIN line plus the tag URL); any other text is left alone with a SKIPPED line that says what to do by hand. +* A script that is missing or too different to edit safely is skipped with a message that says what to do by hand. The + migration never raises for that reason: the sync pull request must still be created. +* Nothing is deleted. Only the files listed above are written; notebooks, src/, requirements, construct.yaml and + labconstrictor-app.yaml are not touched. Line endings of each file are kept. +* The hooks are inert for an app without a _lc_tools module (post_install finds no module and skips the step; + pre_uninstall only warns when a registry entry exists), so the migration is applied to every app. +""" +from __future__ import annotations + +import importlib.util +import re +from pathlib import Path +from typing import Any, Callable + + +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_15_to_v0_1_16" +SCRIPTS = Path("app/bash_bat_scripts") +POST_INSTALL_SH = SCRIPTS / "post_install.sh" +POST_INSTALL_BAT = SCRIPTS / "post_install.bat" +PRE_UNINSTALL_SH = SCRIPTS / "pre_uninstall.sh" +PRE_UNINSTALL_BAT = SCRIPTS / "pre_uninstall.bat" +UNINSTALL_SH = SCRIPTS / "uninstall.sh" +TOOLS_DOC = Path(".tools/docs/tools_bridge.md") +DOCS_INDEX = Path(".tools/docs/README.md") + +# Resource files: copies of the template files of 0.1.16 (a test checks they stay identical to the template). +# Scripts are used as the source of the hook blocks; the doc is copied. +# Template-owned App Centre manifest check (as in 0.1.15). The 0.1.15 copy of the schema rejected the fields inputs, outputs, limitations, +# status and distribution.platforms. labconstrictor-app.yaml itself belongs to the app and is never created, changed or removed here. +MANIFEST_CHECK_FILES = ( + Path(".tools/schema/labconstrictor-app.schema.json"), + Path(".tools/python/check_app_manifest.py"), + Path(".tools/docs/app_manifest.md"), + Path(".github/workflows/check_app_manifest.yml"), +) +MANAGED_FILES = (POST_INSTALL_SH, POST_INSTALL_BAT, PRE_UNINSTALL_SH, PRE_UNINSTALL_BAT, UNINSTALL_SH, TOOLS_DOC) + MANIFEST_CHECK_FILES + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_16.md" +TOOLS_ARCHIVE = "https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/" +UNPINNED_URL = TOOLS_ARCHIVE + "heads/main.zip" +INDEX_ENTRY = "- [Expose tools to Napari and Fiji (experimental)](tools_bridge.md)" +HOOK_MARKER = "labconstrictor_tools" +TAG = "[migration 0.1.16]" + +# uninstall.sh of template 0.1.15 and the replacement of 0.1.16 (exact text only: a changed uninstall.sh is left alone). +OLD_UNINSTALL = 'if [ -f "$PREFIX/pre_uninstall.sh" ]; then\n bash "$PREFIX/pre_uninstall.sh"\nfi\nrm -rf "$PREFIX"\n' +NEW_UNINSTALL = ( + 'if [ -f "$PREFIX/pre_uninstall.sh" ]; then\n' + " # best effort: shortcut/registry cleanup must not stop the removal, but a failure must be visible\n" + ' if ! bash "$PREFIX/pre_uninstall.sh"; then\n' + ' echo "WARNING: pre-uninstall cleanup failed (see the messages above); shortcuts or the tools registry entry may remain." >&2\n' + " fi\n" + "fi\n" + 'if ! rm -rf -- "$PREFIX"; then\n' + ' echo "ERROR: could not remove $PREFIX; PROJECT_NAME is only partly uninstalled. Close anything using it and delete that folder manually." >&2\n' + " exit 1\n" + "fi\n" +) + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers(): + """Reuse the rendering helpers of the 0.1.10 migration (token replacement, newline detection, file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_16", 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 _resource_lines(helpers: Any, relative: Path, replacements: dict[str, str]) -> list[str]: + source = RESOURCE_ROOT / relative + if not source.is_file(): + raise FileNotFoundError(f"Template resource not found: {source}") + return helpers.render_template(helpers.read_text(source), replacements, "\n").split("\n") + + +def _find(lines: list[str], predicate: Callable[[str], bool], start: int = 0) -> int | None: + for index in range(start, len(lines)): + if predicate(lines[index]): + return index + return None + + +def _block(resource: list[str], starts: Callable[[str], bool], ends: Callable[[str], bool], lead: int = 0) -> list[str]: + """Lines of the resource from the line where `starts` is true (minus `lead` lines before it) up to, not including, the line where `ends` is true.""" + first = _find(resource, starts) + last = _find(resource, ends, (first or 0) + 1) if first is not None else None + if first is None or last is None: + raise ValueError("the hook block was not found in the template resource") + return resource[first - lead : last] + + +def _insert_before(helpers: Any, path: Path, block: list[str], anchor: Callable[[str], bool], required: list[str]) -> str: + """Insert `block` before the first line of the file at `path` for which `anchor` is true. Returns a status text.""" + text = helpers.read_text(path) + if HOOK_MARKER in text: + return "already has the Tools bridge hook: unchanged" + missing = [item for item in required if item not in text] + if missing: + return f"SKIPPED: the script does not define {', '.join(missing)}, so the hook cannot be added safely; add it by hand from .tools/docs/tools_bridge.md" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + index = _find(lines, anchor) + if index is None: + return "SKIPPED: the line the hook goes before was not found (the script was customised); add the hook by hand from .tools/docs/tools_bridge.md" + if lines[index - 1 : index] and not lines[index - 1].endswith(("\n", "\r")): + lines[index - 1] += newline + lines[index:index] = [line + newline for line in block] + helpers.write_text(path, "".join(lines)) + return "hook added" + + +def _template_pin(resource: list[str]) -> str: + """The tag the template scripts pin Tools to (read from the template resource, so the two cannot drift apart).""" + for line in resource: + match = re.match(r'^(?:LC_TOOLS_PIN="|SET "LC_TOOLS_PIN=)([^"]+)"$', line.strip()) + if match: + return match.group(1) + raise ValueError("LC_TOOLS_PIN was not found in the template resource") + + +def _repin(helpers: Any, path: Path, resource: list[str], batch: bool) -> str: + """For a script that already has the hook: rewrite the known unpinned Tools source to the pinned tag form of the template. + + Only the exact old text is rewritten (the `${LC_TOOLS_SPEC:-}` default in post_install.sh, the `IF NOT DEFINED LC_TOOLS_SPEC SET` + line in post_install.bat); a pin line is added next to it. Anything else is left unchanged. Idempotent, line endings kept.""" + unchanged = "already has the Tools bridge hook: unchanged" + text = helpers.read_text(path) + pin = _template_pin(resource) + if UNPINNED_URL not in text: + if "LC_TOOLS_PIN" in text or "LabConstrictor-Tools/archive/" not in text: + return unchanged + return f"{unchanged}. SKIPPED the pin: its Tools source is not the known unpinned main.zip (customised); keep it or set a tag by hand, see {DOCS_URL}" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + if batch: + exact = 'IF NOT DEFINED LC_TOOLS_SPEC SET "LC_TOOLS_SPEC=' + UNPINNED_URL + '"' + hits = [i for i, l in enumerate(lines) if l.strip() == exact] + new_source = exact.replace(UNPINNED_URL, TOOLS_ARCHIVE + "tags/%LC_TOOLS_PIN%.zip") + pin_lines = [ + "REM Pinned release tag of labconstrictor-tools (moving the pin: change only this tag).", + f'SET "LC_TOOLS_PIN={pin}"', + ] + anchor_prefix = None + else: + exact = "${LC_TOOLS_SPEC:-" + UNPINNED_URL + "}" + hits = [i for i, l in enumerate(lines) if exact in l] + new_source = exact.replace(UNPINNED_URL, TOOLS_ARCHIVE + "tags/${LC_TOOLS_PIN}.zip") + pin_lines = [ + "# Pinned release tag of labconstrictor-tools (moving the pin: change only this tag).", + f'LC_TOOLS_PIN="{pin}"', + ] + anchor_prefix = "LC_TOOLS_MODULE=" + if len(hits) != 1 or text.count(UNPINNED_URL) != 1: + return f"{unchanged}. SKIPPED the pin: the unpinned Tools source is not in the known form (customised); replace refs/heads/main.zip by refs/tags/{pin}.zip by hand, see {DOCS_URL}" + index = hits[0] + insert_at = index + if anchor_prefix: + anchors = [i for i, l in enumerate(lines) if l.startswith(anchor_prefix)] + if len(anchors) != 1 or anchors[0] > index: + return (f"{unchanged}. SKIPPED the pin: no single {anchor_prefix} line before the pip install line (customised); add " + f'LC_TOOLS_PIN="{pin}" and use refs/tags/{pin}.zip by hand, see {DOCS_URL}') + insert_at = anchors[0] + lines[index] = lines[index].replace(exact, new_source) + if lines[insert_at - 1 : insert_at] and not lines[insert_at - 1].endswith(("\n", "\r")): + lines[insert_at - 1] += newline + lines[insert_at:insert_at] = [l + newline for l in pin_lines] + helpers.write_text(path, "".join(lines)) + return f"updated: unpinned Tools source (refs/heads/main.zip) rewritten to the pinned tag {pin}" + + +def _repin_only(helpers: Any, path: Path, resource: list[str], batch: bool) -> str: + if HOOK_MARKER not in helpers.read_text(path): + return "SKIPPED: no hook added (the app's Python package is unknown); add it by hand from .tools/docs/tools_bridge.md" + return _repin(helpers, path, resource, batch) + + +def _migrate_post_install_sh(helpers: Any, repo_root: Path, resource: list[str]) -> str: + path = repo_root / POST_INSTALL_SH + block = _block(resource, lambda l: l.startswith("# --- Optional: expose the app's tools"), lambda l: "include_path.py" in l and "notebook_launcher.json" in l, lead=1) + status = _insert_before( + helpers, path, block, + lambda l: "include_path.py" in l and "notebook_launcher.json" in l, + ['PYTHON_EXE="', 'PROJECT_ROOT="', 'LOG_FILE="'], + ) + return _repin(helpers, path, resource, batch=False) if status.startswith("already has") else status + + +def _migrate_post_install_bat(helpers: Any, repo_root: Path, resource: list[str]) -> str: + path = repo_root / POST_INSTALL_BAT + block = _block(resource, lambda l: l.startswith("REM Optional: expose the app's tools"), lambda l: "include_path.py" in l and "notebook_launcher.json" in l) + status = _insert_before( + helpers, path, block, + lambda l: "include_path.py" in l and "notebook_launcher.json" in l, + ['SET "PYTHON_EXE=', 'SET "PROJECT_ROOT=', 'SET "LOG_FILE='], + ) + if status.startswith("already has"): + return _repin(helpers, path, resource, batch=True) + if status == "hook added": + # The hook reads LC_TOOLS_SPEC and the version into variables: keep a "!" in a value from being re-interpreted. + text = helpers.read_text(path) + old, new = "SETLOCAL EnableExtensions", "SETLOCAL EnableExtensions DisableDelayedExpansion" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + for index, line in enumerate(lines): + if line.strip().upper() == old.upper(): + lines[index] = new + (newline if line.endswith(("\n", "\r")) else "") + helpers.write_text(path, "".join(lines)) + status += " (SETLOCAL now DisableDelayedExpansion)" + break + return status + + +def _migrate_pre_uninstall(helpers: Any, repo_root: Path, resource: list[str], relative: Path, starts: Callable[[str], bool]) -> str: + block = _block(resource, starts, lambda l: "menuinst.api import remove" in l) + return _insert_before( + helpers, repo_root / relative, block, + lambda l: "menuinst.api import remove" in l, + ["BASE_PATH"] if relative.suffix == ".sh" else [], + ) + + +def _migrate_uninstall_sh(helpers: Any, repo_root: Path, replacements: dict[str, str]) -> str: + path = repo_root / UNINSTALL_SH + text = helpers.read_text(path) + newline = helpers.detect_newline(text) + normalised = text.replace("\r\n", "\n") + new = helpers.render_template(NEW_UNINSTALL, replacements, "\n") + if new in normalised: + return "already up to date: unchanged" + if OLD_UNINSTALL not in normalised: + return "SKIPPED: uninstall.sh differs from the template of 0.1.15 (customised); left unchanged. Optional: the new text only reports a failed pre-uninstall or a failed removal, see " + DOCS_URL + helpers.write_text(path, normalised.replace(OLD_UNINSTALL, new, 1).replace("\n", newline)) + return "updated (pre-uninstall failures and a failed removal are reported)" + + +def _migrate_docs(helpers: Any, repo_root: Path, replacements: dict[str, str]) -> list[str]: + results = [] + source = RESOURCE_ROOT / TOOLS_DOC + destination = repo_root / TOOLS_DOC + rendered = helpers.render_template(helpers.read_text(source), replacements, helpers.detect_newline(helpers.read_text(destination)) if destination.exists() else "\n") + if destination.exists() and helpers.read_text(destination) == rendered: + results.append(f"{TOOLS_DOC}: unchanged") + else: + helpers.write_text(destination, rendered) + results.append(f"{TOOLS_DOC}: written") + + index_path = repo_root / DOCS_INDEX + if not index_path.is_file(): + results.append(f"{DOCS_INDEX}: not present, index entry skipped") + return results + text = helpers.read_text(index_path) + if "tools_bridge.md" in text: + results.append(f"{DOCS_INDEX}: entry already present, unchanged") + return results + entry = INDEX_ENTRY + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + anchor = _find(lines, lambda l: "external_code_upload.md" in l) + if entry is None or anchor is None: + results.append(f"{DOCS_INDEX}: SKIPPED (no place for the entry; the page is still reachable as tools_bridge.md)") + return results + if not lines[anchor].endswith(("\n", "\r")): + lines[anchor] += newline + lines.insert(anchor + 1, entry + newline) + helpers.write_text(index_path, "".join(lines)) + results.append(f"{DOCS_INDEX}: entry added") + return results + + +def detect_package(helpers: Any, repo_root: Path) -> str | None: + """The app's Python package name. The 0.1.10 helper gives up when src/ holds two packages, which is exactly the case of an + app that has a _lc_tools module next to its package (and apps may have several shim packages), so the name of the + single _lc_tools module wins, then the single package that is not a tools module, then the 0.1.10 helper (setup.py), then the name in pyproject.toml.""" + src = repo_root / "src" + if src.is_dir(): + # The tools module is the one thing the hook registers, so its name is the best answer when there is exactly one. + tools = [] + for child in src.iterdir(): + module = child.name if child.is_dir() and (child / "__init__.py").is_file() else child.stem if child.suffix == ".py" else "" + if module.endswith("_lc_tools") and len(module) > len("_lc_tools"): + tools.append(module[: -len("_lc_tools")]) + tools = sorted(set(tools)) + if len(tools) == 1: + return tools[0] + candidates = sorted( + child.name + for child in src.iterdir() + if child.is_dir() + and child.name.isidentifier() + and not child.name.endswith("_lc_tools") + and (child / "__init__.py").is_file() + ) + if len(candidates) == 1: + return candidates[0] + name = helpers.detect_python_package_name(repo_root) + if name != "PYTHON_PROJ_NAME": + return name + return _package_from_pyproject(repo_root) + + +def _package_from_pyproject(repo_root: Path) -> str | None: + """Last resort (an app with several packages in src/ and a setup.py shim without a name): the [project] name of pyproject.toml, + hyphens turned into underscores, accepted only if src// exists. The 0.1.10 helper does not read pyproject.toml.""" + path = repo_root / "pyproject.toml" + if not path.is_file(): + return None + try: + text = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + return None + name = None + try: + import tomllib # Python 3.11+ + + project = tomllib.loads(text).get("project", {}) + name = project.get("name") if isinstance(project, dict) else None + except ImportError: + section = re.search(r"^\[project\]\s*$(?P.*?)(?=^\[|\Z)", text, re.MULTILINE | re.DOTALL) + match = re.search(r'^\s*name\s*=\s*["\']([^"\']+)["\']', section.group("body"), re.MULTILINE) if section else None + name = match.group(1) if match else None + except ValueError: # tomllib.TOMLDecodeError: a pyproject.toml that does not parse decides nothing + return None + if not isinstance(name, str) or not name.strip(): + return None + package = name.strip().replace("-", "_") + if package.isidentifier() and (repo_root / "src" / package).is_dir(): + return package + return None + + +def _migrate_manifest_check(repo_root: Path) -> list[str]: + """Bring the template-owned manifest check files to this version (byte copies; unchanged files are not rewritten).""" + results = [] + for relative in MANIFEST_CHECK_FILES: + source = RESOURCE_ROOT / relative + if not source.is_file(): + raise FileNotFoundError(f"Template resource not found: {source}") + destination = repo_root / relative + data = source.read_bytes() + if destination.is_file() and destination.read_bytes() == data: + results.append(f"{relative}: unchanged") + continue + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(data) + results.append(f"{relative}: written") + return results + + +def has_tools_module(repo_root: Path) -> bool: + src = repo_root / "src" + if not src.is_dir(): + return False + return any(src.glob("*_lc_tools/__init__.py")) or any(src.glob("*_lc_tools.py")) + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Add the Tools bridge hooks to the installer scripts of the repository (idempotent, never deletes, never raises for a customised file).""" + _ = context + helpers = _load_helpers() + try: + replacements = helpers.load_replacements(repo_root) + except (OSError, ValueError) as exc: + log(f"SKIPPED: could not read the app name from construct.yaml ({exc}); nothing was changed.") + return + + package = detect_package(helpers, repo_root) + if package: + replacements["PYTHON_PROJ_NAME"] = package + else: + log("could not tell the app's Python package from src/, setup.py or pyproject.toml: the post_install hook is skipped (add it by hand), the other files are migrated.") + + log("app has a _lc_tools module: the hooks will register it." if has_tools_module(repo_root) + else "app has no _lc_tools module: the hooks are added but stay inert until you add one (see .tools/docs/tools_bridge.md).") + + steps: list[tuple[Path, Callable[[], str]]] = [] + resources = {path: _resource_lines(helpers, path, replacements) for path in (POST_INSTALL_SH, POST_INSTALL_BAT, PRE_UNINSTALL_SH, PRE_UNINSTALL_BAT)} + if package: # without the package name the block would carry an unreplaced token and silently do nothing + steps.append((POST_INSTALL_SH, lambda: _migrate_post_install_sh(helpers, repo_root, resources[POST_INSTALL_SH]))) + steps.append((POST_INSTALL_BAT, lambda: _migrate_post_install_bat(helpers, repo_root, resources[POST_INSTALL_BAT]))) + else: # the hook is not added, but a hook that is already there still gets its pin + steps.append((POST_INSTALL_SH, lambda: _repin_only(helpers, repo_root / POST_INSTALL_SH, resources[POST_INSTALL_SH], False))) + steps.append((POST_INSTALL_BAT, lambda: _repin_only(helpers, repo_root / POST_INSTALL_BAT, resources[POST_INSTALL_BAT], True))) + steps.append((PRE_UNINSTALL_SH, lambda: _migrate_pre_uninstall(helpers, repo_root, resources[PRE_UNINSTALL_SH], PRE_UNINSTALL_SH, lambda l: l.startswith("# best effort: a failure must not stop")))) + steps.append((PRE_UNINSTALL_BAT, lambda: _migrate_pre_uninstall(helpers, repo_root, resources[PRE_UNINSTALL_BAT], PRE_UNINSTALL_BAT, lambda l: "labconstrictor_tools unregister" in l))) + steps.append((UNINSTALL_SH, lambda: _migrate_uninstall_sh(helpers, repo_root, replacements))) + + changed = 0 + for relative, step in steps: + if not (repo_root / relative).is_file(): + log(f"{relative}: SKIPPED, file not found in this repository (nothing was created).") + continue + try: + status = step() + except (OSError, ValueError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}" + if status.startswith(("hook added", "updated")): + changed += 1 + log(f"{relative}: {status}") + + try: + for line in _migrate_docs(helpers, repo_root, replacements): + if line.endswith(("written", "entry added")): + changed += 1 + log(line) + except (OSError, ValueError, UnicodeDecodeError) as exc: + log(f"docs SKIPPED: {exc}") + + try: + for line in _migrate_manifest_check(repo_root): + if line.endswith("written"): + changed += 1 + log(line) + except OSError as exc: + log(f"manifest check files SKIPPED: {exc}") + + if changed: + log(f"done: {changed} file(s) changed. Review the pull request before merging; the tools register after a NEW installer of the app is installed.") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_16_to_v0_1_17.py b/.template_sync/migrations/v0_1_16_to_v0_1_17.py new file mode 100644 index 0000000..5ec5f8f --- /dev/null +++ b/.template_sync/migrations/v0_1_16_to_v0_1_17.py @@ -0,0 +1,375 @@ +"""Template 0.1.16 -> 0.1.17: install labconstrictor-tools BEFORE the import check of the app package in post_install. + +Problem: post_install of 0.1.16 ran `import ` right after installing the package and only afterwards installed +labconstrictor-tools, so a package that imports `labconstrictor_tools` at module level failed with ModuleNotFoundError and the installer +aborted. Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_17.md + +New order in app/bash_bat_scripts/post_install.sh / .bat: install the package -> install Tools (only if the package ships a +_lc_tools module; a failure is a logged WARNING) -> import check -> register the app (only if the Tools install worked). + +What this changes (only the two post_install scripts of the app repository, plus the Tools guide): + +* a block that installs Tools is inserted before the import check line (sh) / a `CALL :install_lc_tools` is inserted there and the + subroutine is appended to the file (bat; a subroutine because %VAR% in a parenthesised block is expanded when the block is read); +* the lines that defined the pin / module / Tools source in the registration block are MOVED into that block (a one-line comment stays), + with the app's own values (its module name, its pin, its Tools source: nothing is replaced by a template default); +* the single `pip install` line of the registration block becomes a check of LC_TOOLS_READY. +* .tools/docs/tools_bridge.md is refreshed (it still carries the 0.1.16 text in the app repository). + +Rules this migration keeps: + +* Surgical: only lines of the known hook are touched; a script that does not have the known shape is skipped with a message that says what + to do by hand (it never raises: the sync pull request must still be created); other customisations stay. +* Idempotent: a script that already mentions LC_TOOLS_READY is left unchanged. Nothing is deleted except the moved lines. +* A script without the Tools hook is left alone (the 0.1.16 migration adds the hook, in the old position, when the chain runs both, + and this migration then moves it). Line endings of each file are kept. +""" +from __future__ import annotations + +import importlib.util +import re +from pathlib import Path +from typing import Any, Callable + + +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_16_to_v0_1_17" +SCRIPTS = Path("app/bash_bat_scripts") +POST_INSTALL_SH = SCRIPTS / "post_install.sh" +POST_INSTALL_BAT = SCRIPTS / "post_install.bat" +TOOLS_DOC = Path(".tools/docs/tools_bridge.md") +# Resource files: copies of the template files of 0.1.17 (a test checks they stay identical to the template). +MANAGED_FILES = (POST_INSTALL_SH, POST_INSTALL_BAT, TOOLS_DOC) + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_17.md" +TAG = "[migration 0.1.17]" +DONE_MARKER = "LC_TOOLS_READY" +UNCHANGED = "already installs Tools before the import check: unchanged" + +# Tools source of the template (as in the resources): replaced by the app's own source when that differs. +SH_TEMPLATE_SPEC = '"${LC_TOOLS_SPEC:-https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${LC_TOOLS_PIN}.zip}"' +BAT_PIP_LINE = ( + '"%PYTHON_EXE%" -c "import os, subprocess, sys; sys.exit(subprocess.call([sys.executable, \'-m\', \'pip\', \'install\', ' + "os.environ['LC_TOOLS_SPEC']]))\" >> \"%LOG_FILE%\" 2>&1" +) +# Comment lines of the hook header that move together with the variables they describe. +SH_MOVED_COMMENT = re.compile(r"^# (Default source|because the package|is not on PyPI|Pinned release tag)") +BAT_MOVED_COMMENT = re.compile(r"^REM (Default source|because the package|is not on PyPI|Pinned release tag)") + + +class Unsupported(Exception): + """The script does not have the shape this migration knows: it is skipped with this message.""" + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers(): + """Reuse the rendering helpers of the 0.1.10 migration (token replacement, newline detection, file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_17", 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 _find(lines: list[str], predicate: Callable[[str], bool], start: int = 0, stop: int | None = None) -> int | None: + for index in range(start, len(lines) if stop is None else stop): + if predicate(lines[index]): + return index + return None + + +def _only(lines: list[str], predicate: Callable[[str], bool], what: str, start: int = 0, optional: bool = False) -> int | None: + hits = [i for i in range(start, len(lines)) if predicate(lines[i])] + if len(hits) == 1: + return hits[0] + if not hits and optional: + return None + raise Unsupported(f"{what} was {'not found' if not hits else 'found more than once'}") + + +def _resource_lines(helpers: Any, relative: Path, replacements: dict[str, str]) -> list[str]: + source = RESOURCE_ROOT / relative + if not source.is_file(): + raise FileNotFoundError(f"Template resource not found: {source}") + return helpers.render_template(helpers.read_text(source), replacements, "\n").split("\n") + + +def _resource_line(resource: list[str], predicate: Callable[[str], bool], what: str) -> int: + index = _find(resource, predicate) + if index is None: + raise ValueError(f"{what} was not found in the template resource") + return index + + +def _is_package_import(line: str, bat: bool) -> bool: + return bool(re.match(r'^\s+"(%PYTHON_EXE%|\$PYTHON_EXE)" -c "import [A-Za-z_]\w*;', line)) + + +def _package_install_index(lines: list[str]) -> int: + return _only(lines, lambda l: "pip install --no-deps --no-build-isolation" in l, "the package install line (pip install --no-deps --no-build-isolation)") # type: ignore[return-value] + + +def _mark_moved(stripped: list[str], removed: set[int], index: int, pattern: re.Pattern[str]) -> None: + """Mark line `index` and the moved comment lines directly above it (a run the 0.1.15/0.1.16 hook wrote) as removed.""" + removed.add(index) + j = index - 1 + while j >= 0 and (j in removed or pattern.match(stripped[j])): + removed.add(j) + j -= 1 + + +def _rebuild(lines: list[str], removed: set[int], replaced: dict[int, str], inserted: dict[int, list[str]]) -> list[str]: + """The file after the edits: `inserted` lines go before the given index, `replaced` lines take the place of a line, `removed` lines are dropped.""" + out: list[str] = [] + for index, line in enumerate(lines): + if index in inserted: + if out and not out[-1].endswith(("\n", "\r")): + out[-1] += "\n" + out.extend(inserted[index]) + if index in replaced: + out.append(replaced[index]) + elif index not in removed: + out.append(line) + return out + + +def _with_newlines(lines: list[str], newline: str) -> list[str]: + return [line + newline for line in lines] + + +def _mark_moved(stripped: list[str], removed: set[int], index: int, pattern: re.Pattern[str]) -> None: + """Mark line `index` and the moved comment lines directly above it (a run the 0.1.15/0.1.16 hook wrote) as removed.""" + removed.add(index) + j = index - 1 + while j >= 0 and (j in removed or pattern.match(stripped[j])): + removed.add(j) + j -= 1 + + +def _rebuild(lines: list[str], removed: set[int], replaced: dict[int, str], inserted: dict[int, list[str]]) -> list[str]: + """The file after the edits: `inserted` lines go before the given index, `replaced` lines take the place of a line, `removed` lines are dropped.""" + out: list[str] = [] + for index, line in enumerate(lines): + if index in inserted: + if out and not out[-1].endswith(("\n", "\r")): + out[-1] += "\n" + out.extend(inserted[index]) + if index in replaced: + out.append(replaced[index]) + elif index not in removed: + out.append(line) + return out + + +def _with_newlines(lines: list[str], newline: str) -> list[str]: + return [line + newline for line in lines] + + +def _ensure_ends_with_newline(lines: list[str], index: int, newline: str) -> None: + if 0 <= index - 1 < len(lines) and not lines[index - 1].endswith(("\n", "\r")): + lines[index - 1] += newline + + +# -------------------------------------------------------------------------------------------------------------------------------- +# post_install.sh +# -------------------------------------------------------------------------------------------------------------------------------- +def _migrate_sh(helpers: Any, path: Path, resource: list[str]) -> str: + text = helpers.read_text(path) + if DONE_MARKER in text: + return UNCHANGED + if "labconstrictor_tools" not in text: + return "has no Tools bridge hook: nothing to move" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + + start = _package_install_index(lines) + imp = _find(lines, lambda l: _is_package_import(l, False), start + 1) + if imp is None: + raise Unsupported("the import check line after the package install was not found") + stripped = [l.strip() for l in lines] + module_re = re.compile(r'^LC_TOOLS_MODULE="([^"]+)"$') + mod = _only(stripped, lambda l: bool(module_re.match(l)), "the LC_TOOLS_MODULE=\"...\" line", imp + 1) + assert mod is not None + module = module_re.match(stripped[mod]).group(1) # type: ignore[union-attr] + pin_re = re.compile(r'^LC_TOOLS_PIN="([^"]+)"$') + pin = _only(stripped, lambda l: bool(pin_re.match(l)), "the LC_TOOLS_PIN=\"...\" line", imp + 1, optional=True) + pip_re = re.compile(r'^if "\$PYTHON_EXE" -m pip install ("\$\{LC_TOOLS_SPEC:-.*\}") >> "\$LOG_FILE" 2>&1 \\$') + pip = _only(stripped, lambda l: bool(pip_re.match(l)), "the Tools `pip install ... \\` line of the registration block", mod + 1) + assert pip is not None + if not stripped[pip + 1].startswith('&& "$PYTHON_EXE" -m labconstrictor_tools register'): + raise Unsupported("the line after the Tools pip install is not the `labconstrictor_tools register` line") + spec = pip_re.match(stripped[pip]).group(1) # type: ignore[union-attr] + uses_pin = "LC_TOOLS_PIN" in spec + + # The new block, from the template resource, with the app's own module, pin and Tools source. + first = _resource_line(resource, lambda l: l.startswith(" # Tools first"), "the Tools install block") + last = _resource_line(resource, lambda l: _is_package_import(l, False), "the import check line") + block: list[str] = [] + for line in resource[first:last]: + if line.strip().startswith("LC_TOOLS_MODULE="): + block.append(" " + stripped[mod]) + elif line.strip().startswith("LC_TOOLS_PIN="): + if uses_pin: # an app whose Tools source has no pin variable gets no pin line + block.append(" " + (stripped[pin] if pin is not None else line.strip())) + elif SH_TEMPLATE_SPEC in line: + block.append(line.replace(SH_TEMPLATE_SPEC, spec)) + elif not uses_pin and re.match(r"^\s*# (Default source|because the package)", line): + continue # these comment lines describe the pinned tag the app's source does not use + else: + block.append(line) + comment = resource[_resource_line(resource, lambda l: l.startswith("# labconstrictor-tools is installed above"), "the moved-variables comment")] + ready = resource[_resource_line(resource, lambda l: l.lstrip().startswith('if [ "${LC_TOOLS_READY:-0}" = 1 ]'), "the LC_TOOLS_READY check")] + + removed: set[int] = set() + if pin is not None: + _mark_moved(stripped, removed, pin, SH_MOVED_COMMENT) + _mark_moved(stripped, removed, mod, SH_MOVED_COMMENT) + removed.discard(mod) + indent = lines[pip][: len(lines[pip]) - len(lines[pip].lstrip())] + replaced = {mod: comment + newline, pip: indent + ready.strip() + newline} + lines = _rebuild(lines, removed, replaced, {imp: _with_newlines(block, newline)}) + helpers.write_text(path, "".join(lines)) + return f"updated: Tools are installed before the import check (module {module})" + + +# -------------------------------------------------------------------------------------------------------------------------------- +# post_install.bat +# -------------------------------------------------------------------------------------------------------------------------------- +def _migrate_bat(helpers: Any, path: Path, resource: list[str]) -> str: + text = helpers.read_text(path) + if DONE_MARKER in text: + return UNCHANGED + if "labconstrictor_tools" not in text: + return "has no Tools bridge hook: nothing to move" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + stripped = [l.strip() for l in lines] + last_line = next((s for s in reversed(stripped) if s), "") + if not re.match(r"^(GOTO :EOF|EXIT /B)", last_line, re.IGNORECASE): + raise Unsupported("the file does not end with GOTO :EOF or EXIT /B, so a subroutine cannot be appended safely") + + start = _package_install_index(lines) + imp = _find(lines, lambda l: _is_package_import(l, True), start + 1) + if imp is None: + raise Unsupported("the import check line after the package install was not found") + spec_re = re.compile(r'^IF NOT DEFINED LC_TOOLS_SPEC SET "LC_TOOLS_SPEC=.*"$', re.IGNORECASE) + spec = _only(stripped, lambda l: bool(spec_re.match(l)), "the `IF NOT DEFINED LC_TOOLS_SPEC SET ...` line", imp + 1) + assert spec is not None + pin_re = re.compile(r'^SET "LC_TOOLS_PIN=[^"]+"$', re.IGNORECASE) + pin = _only(stripped, lambda l: bool(pin_re.match(l)), 'the SET "LC_TOOLS_PIN=..." line', imp + 1, optional=True) + uses_pin = "%LC_TOOLS_PIN%" in stripped[spec] + find_re = re.compile(r"""^"%PYTHON_EXE%" -c "import importlib\.util, sys; sys\.exit\(0 if importlib\.util\.find_spec\('([^']+)'\) else 1\)" >> "%LOG_FILE%" 2>&1$""") + find = _only(stripped, lambda l: bool(find_re.match(l)), "the find_spec line of the registration block", spec + 1) + assert find is not None + module = find_re.match(stripped[find]).group(1) # type: ignore[union-attr] + pip = _only(stripped, lambda l: l == BAT_PIP_LINE, "the Tools pip install line (through Python) of the registration block", find + 1) + assert pip is not None + + # Template resource: the call block, the replacement lines and the subroutine. + first = _resource_line(resource, lambda l: l.startswith(" REM Tools first"), "the Tools call block") + last = _resource_line(resource, lambda l: _is_package_import(l, True), "the import check line") + call_block = resource[first:last] + comment = resource[_resource_line(resource, lambda l: l.startswith("REM labconstrictor-tools is installed by :install_lc_tools"), "the moved-variables comment")] + ready_at = _resource_line(resource, lambda l: l.lstrip().startswith("REM labconstrictor-tools was installed before the import check"), "the LC_TOOLS_READY check") + ready = resource[ready_at : ready_at + 2] + sub_first = _resource_line(resource, lambda l: l.strip().lower() == ":install_lc_tools", "the subroutine") + subroutine = resource[sub_first:] + while subroutine and not subroutine[-1].strip(): + subroutine.pop() + sub = [] + for line in subroutine: + if line.startswith("SET \"LC_TOOLS_PIN="): + if uses_pin: + sub.append(stripped[pin] if pin is not None else line) + elif line.startswith("IF NOT DEFINED LC_TOOLS_SPEC SET"): + sub.append(stripped[spec]) + else: + sub.append(line.replace("PYTHON_PROJ_NAME_lc_tools", module)) + if not uses_pin: # no pin variable in the app's source: the comment that talks about "the TAG below" would mislead + sub = [l for l in sub if not l.startswith(("REM Default source", "REM because the package"))] + + # The pin / spec / header comments of the registration block are replaced by one comment, the pip line by the READY check. + removed: set[int] = set() + if pin is not None: + _mark_moved(stripped, removed, pin, BAT_MOVED_COMMENT) + _mark_moved(stripped, removed, spec, BAT_MOVED_COMMENT) + removed.discard(spec) + replaced = {spec: comment + newline, pip: "".join(_with_newlines([" " + r.strip() for r in ready], newline))} + if stripped[pip - 1].startswith("REM LC_TOOLS_SPEC goes to pip as one argument"): + removed.add(pip - 1) + lines = _rebuild(lines, removed, replaced, {imp: _with_newlines(call_block, newline)}) + if lines and not lines[-1].endswith(("\n", "\r")): + lines[-1] += newline + lines.extend(_with_newlines([""] + sub, newline)) + helpers.write_text(path, "".join(lines)) + return f"updated: Tools are installed before the import check (module {module})" + + +def _migrate_docs(helpers: Any, repo_root: Path, replacements: dict[str, str]) -> str: + source = RESOURCE_ROOT / TOOLS_DOC + destination = repo_root / TOOLS_DOC + if not destination.exists(): + return "not present in this repository (nothing was created)" + rendered = helpers.render_template(helpers.read_text(source), replacements, helpers.detect_newline(helpers.read_text(destination))) + if helpers.read_text(destination) == rendered: + return "unchanged" + helpers.write_text(destination, rendered) + return "updated: written" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Install Tools before the import check in the post_install scripts (idempotent, surgical, never raises for a customised file).""" + _ = context + helpers = _load_helpers() + try: + replacements = helpers.load_replacements(repo_root) + except (OSError, ValueError) as exc: + log(f"could not read the app name from construct.yaml ({exc}): messages of the inserted block name the app generically.") + replacements = {"PROJECT_NAME": "the app"} + + changed = 0 + for relative, step in ((POST_INSTALL_SH, _migrate_sh), (POST_INSTALL_BAT, _migrate_bat)): + path = repo_root / relative + if not path.is_file(): + log(f"{relative}: SKIPPED, file not found in this repository (nothing was created).") + continue + try: + # the module name of the hook decides PYTHON_PROJ_NAME in the block, so it is rendered after reading the hook + module = _hook_module(helpers, path) + local = dict(replacements) + if module: + local["PYTHON_PROJ_NAME"] = module + status = step(helpers, path, _resource_lines(helpers, relative, local)) + except Unsupported as exc: + status = f"SKIPPED: {exc}; the script was left unchanged. Move the Tools install before the import check by hand, see {DOCS_URL}" + except (OSError, ValueError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; the script was left unchanged. See {DOCS_URL}" + if status.startswith("updated"): + changed += 1 + log(f"{relative}: {status}") + + try: + status = _migrate_docs(helpers, repo_root, replacements) + if status.startswith("updated"): + changed += 1 + log(f"{TOOLS_DOC}: {status}") + except (OSError, ValueError, UnicodeDecodeError) as exc: + log(f"{TOOLS_DOC}: SKIPPED: {exc}") + + if changed: + log(f"done: {changed} file(s) changed. Review the pull request before merging; the change reaches users with the next release of the app.") + else: + log("done: no repository changes were required.") + + +def _hook_module(helpers: Any, path: Path) -> str | None: + """The package name of the existing hook (its _lc_tools module, minus the suffix), if the hook is there.""" + text = helpers.read_text(path) + match = re.search(r"LC_TOOLS_MODULE=\"(\w+)_lc_tools\"|find_spec\('(\w+)_lc_tools'\)", text) + if not match: + return None + return match.group(1) or match.group(2) diff --git a/.template_sync/migrations/v0_1_17_to_v0_1_18.py b/.template_sync/migrations/v0_1_17_to_v0_1_18.py new file mode 100644 index 0000000..02e39f7 --- /dev/null +++ b/.template_sync/migrations/v0_1_17_to_v0_1_18.py @@ -0,0 +1,423 @@ +"""Template 0.1.17 -> 0.1.18: new Tools pin, GitHub Actions pinned by commit SHA, install rules in the install guide, app hosts for Tools. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_18.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. Tools pin. `LC_TOOLS_PIN` in app/bash_bat_scripts/post_install.sh / .bat moves from the old template value `v0.2.0-rc.1` to the new one + (read from the resource copy of the template script, `v0.3.0-alpha.1`), ONLY when the line still holds exactly the old template value. + An app with its own pin, a script without a pin line (unpinned source, own `LC_TOOLS_SPEC`) or without the hook stays as it is, with a note. +2. Pinned actions. The five template workflows (check_app_manifest.yml, release_constructor.yml, sync_template.yml, + update_on_notebook_change.yml, update_on_src_change.yaml) are replaced by the pinned version ONLY when the app's file is still identical to + the previous template version (the resource with the pins removed; line endings are ignored when comparing and kept when writing). + A file that already is the pinned template file is unchanged; a file that is customised (or pinned in part by the app) is skipped with a + message that lists its still unpinned `uses:` lines. A workflow file that is not in the repository is not created. +3. Install guide. `.tools/docs/install.md`, if it exists, gets the section "Before you install" (path without a space) and the section + "Update an installed app" (macOS/Windows uninstall first, Linux `-u`), inserted before "## Install on Windows" and before "## Next". +4. Tools guide. `.tools/docs/tools_bridge.md` is refreshed (it names the pinned tag) only if it still is the 0.1.17 text. +5. App hosts. The installer passes the app's `hosts:` line to Tools (`register --app-manifest`): `construct.yaml` gets the `extra_files` entry that + bundles `labconstrictor-app.yaml` (only if that file exists in the repository, and only in the known block shape), and the Tools hook of + post_install.sh / .bat gets the lines that pass the bundled file and log when it is missing (only in the known hook shape; the app's own + register arguments stay). A hook that already passes `--app-manifest` or `--hosts` is unchanged; any other shape is SKIPPED with a note. + +Rules this migration keeps: surgical (only known lines or known files), 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 re +from pathlib import Path +from typing import Any + + +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_17_to_v0_1_18" +SCRIPTS = Path("app/bash_bat_scripts") +POST_INSTALL_SH = SCRIPTS / "post_install.sh" +POST_INSTALL_BAT = SCRIPTS / "post_install.bat" +TOOLS_DOC = Path(".tools/docs/tools_bridge.md") +INSTALL_DOC = Path(".tools/docs/install.md") +WORKFLOWS = ( + Path(".github/workflows/check_app_manifest.yml"), + Path(".github/workflows/release_constructor.yml"), + Path(".github/workflows/sync_template.yml"), + Path(".github/workflows/update_on_notebook_change.yml"), + Path(".github/workflows/update_on_src_change.yaml"), +) +# Resource files: copies of the template files of 0.1.18 (a test checks they stay identical to the template). +MANAGED_FILES = (POST_INSTALL_SH, POST_INSTALL_BAT, TOOLS_DOC, INSTALL_DOC, *WORKFLOWS) + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_18.md" +TAG = "[migration 0.1.18]" +OLD_PIN = "v0.2.0-rc.1" +NEW_PIN_RE = re.compile(r'LC_TOOLS_PIN="([^"]+)"') + +# The pinned third-party action lines, `uses: owner/repo@<40 hex> # `; removing the pin gives `uses: owner/repo@`. +PINNED_USES = re.compile(r"^(\s*(?:-\s+)?uses:\s*[\w.-]+/[\w./-]+)@[0-9a-f]{40}[ \t]+#[ \t]*(\S+)[ \t]*$") +ANY_USES = re.compile(r"^\s*(?:-\s+)?uses:\s*([\w.-]+/[\w./-]+)@(\S+)") + +INSTALL_BEFORE_HEADING = "## Before you install" +INSTALL_UPDATE_HEADING = "## Update an installed app" +INSTALL_HOSTS_HEADING = "## Where the app is listed" +INSTALL_BEFORE_ANCHOR = "## Install on Windows" +INSTALL_UPDATE_ANCHOR = "## Next" +CONSTRUCT = Path("construct.yaml") +APP_MANIFEST = Path("labconstrictor-app.yaml") + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers() -> Any: + """Reuse the helpers of the 0.1.10 migration (token replacement, newline detection, file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_18", 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 _resource_text(helpers: Any, relative: Path) -> str: + source = RESOURCE_ROOT / relative + if not source.is_file(): + raise FileNotFoundError(f"Template resource not found: {source}") + return str(helpers.read_text(source)).replace("\r\n", "\n") + + +def new_pin(helpers: Any) -> str: + """The pin of the template (the resource copy of post_install.sh is the single source of the value).""" + match = NEW_PIN_RE.search(_resource_text(helpers, POST_INSTALL_SH)) + if not match: + raise ValueError("LC_TOOLS_PIN was not found in the template resource") + return match.group(1) + + +def _unpin(text: str) -> str: + """The text of a workflow before its actions were pinned (the previous template version).""" + lines = [] + for line in text.split("\n"): + match = PINNED_USES.match(line) + lines.append(f"{match.group(1)}@{match.group(2)}" if match else line) + return "\n".join(lines) + + +# -------------------------------------------------------------------------------------------------------------------------------- +# 1. Tools pin +# -------------------------------------------------------------------------------------------------------------------------------- +SH_PIN_LINE = re.compile(r'^([ \t]*LC_TOOLS_PIN=")([^"]*)(".*)$') +BAT_PIN_LINE = re.compile(r'^([ \t]*SET "LC_TOOLS_PIN=)([^"]*)(".*)$', re.IGNORECASE) + + +def _move_pin(helpers: Any, path: Path, pattern: re.Pattern[str], pin: str) -> str: + text = helpers.read_text(path) + if "labconstrictor_tools" not in text: + return "has no Tools bridge hook: nothing to move" + lines = text.splitlines(keepends=True) + hits = [] + for index, line in enumerate(lines): + match = pattern.match(line.rstrip("\r\n")) + if match: + hits.append((index, match)) + 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 {pin}" + index, match = hits[0] + current = match.group(2) + if current == pin: + return f"already pins Tools {pin}: unchanged" + if current != OLD_PIN: + return f"has its own pin {current}: left as it is (the template pin is now {pin})" + ending = lines[index][len(lines[index].rstrip("\r\n")) :] + lines[index] = f"{match.group(1)}{pin}{match.group(3)}{ending}" + helpers.write_text(path, "".join(lines)) + return f"updated: Tools pin {OLD_PIN} -> {pin}" + + +# -------------------------------------------------------------------------------------------------------------------------------- +# 2. Pinned actions +# -------------------------------------------------------------------------------------------------------------------------------- +def _unpinned_uses(text: str) -> list[str]: + """`uses:` lines of third-party actions that are not pinned by SHA (local `./` actions and `docker://` need no pin).""" + found = [] + for line in text.replace("\r\n", "\n").split("\n"): + match = ANY_USES.match(line) + if match and not re.fullmatch(r"[0-9a-f]{40}", match.group(2)) and not match.group(1).startswith(("./", "docker:")): + found.append(line.strip()) + return found + + +def _migrate_workflow(helpers: Any, repo_root: Path, relative: Path) -> str: + path = repo_root / relative + if not path.is_file(): + return "not present in this repository (nothing was created)" + new = _resource_text(helpers, relative) + current = helpers.read_text(path) + current_lf = current.replace("\r\n", "\n") + if current_lf == new: + return "already the pinned template file: unchanged" + if current_lf == _unpin(new): + newline = helpers.detect_newline(current) + helpers.write_text(path, new.replace("\n", newline)) + return "updated: every third-party action is pinned by commit SHA" + left = _unpinned_uses(current) + if not left: + return "customised and already pinned: left as it is" + shown = "; ".join(left[:6]) + ("; ..." if len(left) > 6 else "") + return f"SKIPPED: customised, so it was left unchanged ({len(left)} third-party action(s) not pinned by SHA: {shown}). Pin them by hand, see {DOCS_URL}" + + +# -------------------------------------------------------------------------------------------------------------------------------- +# 3. Install guide +# -------------------------------------------------------------------------------------------------------------------------------- +def _section(text: str, heading: str) -> str: + """The section of `heading` in the (LF) resource text, up to the next `## ` heading, with its trailing blank line.""" + match = re.search(rf"^{re.escape(heading)}\n.*?(?=^## )", text, re.MULTILINE | re.DOTALL) + if not match: + raise ValueError(f"section {heading!r} was not found in the template resource") + return match.group(0) + + +def _migrate_install_doc(helpers: Any, repo_root: Path) -> str: + path = repo_root / INSTALL_DOC + if not path.is_file(): + return "not present in this repository (nothing was created)" + resource = _resource_text(helpers, INSTALL_DOC) + current = helpers.read_text(path) + newline = helpers.detect_newline(current) + lf = current.replace("\r\n", "\n") + done = [] + for heading, anchor in ( + (INSTALL_BEFORE_HEADING, INSTALL_BEFORE_ANCHOR), + (INSTALL_UPDATE_HEADING, INSTALL_UPDATE_ANCHOR), + (INSTALL_HOSTS_HEADING, INSTALL_UPDATE_ANCHOR), + ): + if re.search(rf"^{re.escape(heading)}\s*$", lf, re.MULTILINE): + continue + position = re.search(rf"^{re.escape(anchor)}\s*$", lf, re.MULTILINE) + if not position: + return f"SKIPPED: no line {anchor!r} to insert {heading!r} before; add the sections by hand from {DOCS_URL}" + lf = lf[: position.start()] + _section(resource, heading) + lf[position.start() :] + done.append(heading[3:]) + if not done: + return "already has the install rules: unchanged" + helpers.write_text(path, lf.replace("\n", newline)) + return "updated: added " + " and ".join(repr(d) for d in done) + + +# -------------------------------------------------------------------------------------------------------------------------------- +# 4. Tools guide +# -------------------------------------------------------------------------------------------------------------------------------- +def _migrate_tools_doc(helpers: Any, repo_root: Path, replacements: dict[str, str], pin: str) -> str: + destination = repo_root / TOOLS_DOC + if not destination.is_file(): + return "not present in this repository (nothing was created)" + current = helpers.read_text(destination) + newline = helpers.detect_newline(current) + new = helpers.render_template(_resource_text(helpers, TOOLS_DOC), replacements, newline) + if current == new: + return "unchanged" + old = helpers.render_template(_resource_text(helpers, TOOLS_DOC).replace(pin, OLD_PIN), replacements, newline) + if current != old: + return "SKIPPED: not the 0.1.17 text (customised), so it was left unchanged; it names the pinned Tools tag " + pin + helpers.write_text(destination, new) + return "updated: written" + + +# -------------------------------------------------------------------------------------------------------------------------------- +# 5. App hosts (labconstrictor-app.yaml bundled by the installer, passed to `register --app-manifest`) +# -------------------------------------------------------------------------------------------------------------------------------- +PASSES_HOSTS = re.compile(r"--app-manifest|--hosts") +EXTRA_FILES_HEAD = re.compile(r"^extra_files:\s*$") +EXTRA_FILES_ITEM = re.compile(r"^- [^\s#][^:]*:\s*\S.*$") +MANIFEST_MAPPING = re.compile(r"^\s*-\s*['\"]?labconstrictor-app\.yaml['\"]?\s*:") +WELCOME_MAPPING = re.compile(r"^- [^:]*Welcome\.ipynb:\s*['\"]?([^/'\"\s]+)/") +REGISTER_NAME = re.compile(r'--name "([^"]+)"') +SH_BLOCK_START = " # Hosts of the app:" +SH_BLOCK_END = ' if [ "${LC_TOOLS_READY:-0}" = 1 ]' +BAT_PRE_START = "REM Hosts of the app:" +BAT_LOGS_START = " REM Which hosts list the app" +BAT_LOGS_END = " REM labconstrictor-tools was installed before" +BAT_SPEC_CALL = "importlib.util.find_spec('PYTHON_PROJ_NAME_lc_tools')" +BAT_REGISTER = re.compile(r'^(\s*IF NOT ERRORLEVEL 1 )("%PYTHON_EXE%" -m labconstrictor_tools register .*?)( >> "%LOG_FILE%" 2>&1)\s*$') +SH_LOG_REDIRECT = ' >> "$LOG_FILE" 2>&1' +SH_HOSTS_ARGS = '${LC_HOSTS_ARGS[@]+"${LC_HOSTS_ARGS[@]}"}' + + +def _slice(resource: list[str], start: str, end: str, what: str) -> list[str]: + """The lines of the template resource from the first line that starts with `start` up to (not including) the next line that starts with `end`.""" + begin = next((i for i, line in enumerate(resource) if line.startswith(start)), None) + if begin is None: + raise ValueError(f"{what}: the block was not found in the template resource") + stop = next((i for i in range(begin, len(resource)) if resource[i].startswith(end)), None) + if stop is None: + raise ValueError(f"{what}: the end of the block was not found in the template resource") + return resource[begin:stop] + + +def _only_line(lines: list[str], pattern: str, what: str) -> int: + hits = [i for i, line in enumerate(lines) if pattern in line] + if len(hits) != 1: + raise ValueError(f"{what} was {'not found' if not hits else 'found more than once'}") + return hits[0] + + +def _app_name(line: str) -> str: + match = REGISTER_NAME.search(line) + if not match: + raise ValueError('the register line has no --name "..." argument') + return match.group(1) + + +def _sh_hook_lines(lines: list[str]) -> tuple[int, int, str]: + """(index of the first line of the register statement, index of the line that ends it, the app name) in a known post_install.sh hook.""" + reg = _only_line(lines, "labconstrictor_tools register", "the register line") + if not any(line.lstrip().startswith("lc_note()") for line in lines[:reg]): + raise ValueError("lc_note is not defined before the register line") + first = reg + while first > 0 and lines[first - 1].rstrip("\r\n").rstrip().endswith("\\"): + first -= 1 + if not lines[first].lstrip().startswith("if "): + raise ValueError("the register command is not the condition of an `if` statement") + last = next((i for i in range(reg, min(reg + 4, len(lines))) if SH_LOG_REDIRECT in lines[i]), None) + if last is None or lines[last].count(SH_LOG_REDIRECT) != 1: + raise ValueError(f"the end of the register command (`{SH_LOG_REDIRECT.strip()}`) was not found") + return first, last, _app_name("".join(lines[first : reg + 1])) + + +def _migrate_hosts_sh(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + if "labconstrictor_tools" not in text: + return "has no Tools bridge hook: nothing to do" + if PASSES_HOSTS.search(text): + return "already passes the hosts of the app to Tools: unchanged" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + first, last, name = _sh_hook_lines(lines) + indent = lines[first][: len(lines[first]) - len(lines[first].lstrip())] + block = _slice(_resource_text(helpers, POST_INSTALL_SH).split("\n"), SH_BLOCK_START, SH_BLOCK_END, "post_install.sh") + inserted = [(indent + line[4:] if line.startswith(" ") else line).replace("PROJECT_NAME", name) + newline for line in block] + lines[last] = lines[last].replace(SH_LOG_REDIRECT, f" {SH_HOSTS_ARGS}{SH_LOG_REDIRECT}", 1) + helpers.write_text(path, "".join(lines[:first] + inserted + lines[first:])) + return "updated: the Tools hook passes --app-manifest and logs when labconstrictor-app.yaml is missing" + + +def _bat_hook_lines(lines: list[str]) -> tuple[int, int, int, re.Match[str]]: + """(index of the line before which the manifest lookup goes, index after which the log lines go, register index, its match) in a known post_install.bat hook.""" + reg = _only_line(lines, "labconstrictor_tools register", "the register line") + match = BAT_REGISTER.match(lines[reg].rstrip("\r\n")) + if not match: + raise ValueError("the register line does not have the known shape (IF NOT ERRORLEVEL 1 ... >> LOG_FILE 2>&1)") + found = max((i for i in range(reg) if re.match(r"^\s*echo Found \S+_lc_tools: registering", lines[i])), default=None) + block = max((i for i in range(reg) if lines[i].rstrip("\r\n") == "IF NOT ERRORLEVEL 1 ("), default=None) + if found is None or block is None or block == 0 or "find_spec(" not in lines[block - 1] or block > found: + raise ValueError("the `IF NOT ERRORLEVEL 1 (` block of the hook after the find_spec check was not found") + return block - 1, found, reg, match + + +def _migrate_hosts_bat(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + if "labconstrictor_tools" not in text: + return "has no Tools bridge hook: nothing to do" + if PASSES_HOSTS.search(text): + return "already passes the hosts of the app to Tools: unchanged" + newline = helpers.detect_newline(text) + lines = text.splitlines(keepends=True) + before, found, reg, match = _bat_hook_lines(lines) + name = _app_name(lines[reg]) + resource = _resource_text(helpers, POST_INSTALL_BAT).split("\n") + pre = _slice(resource, BAT_PRE_START, "\"%PYTHON_EXE%\" -c \"import importlib.util, sys; sys.exit(0 if " + BAT_SPEC_CALL, "post_install.bat") + logs = _slice(resource, BAT_LOGS_START, BAT_LOGS_END, "post_install.bat") + head, command, tail = match.groups() + register = [ + head + "IF DEFINED LC_APP_MANIFEST " + command + ' --app-manifest "%LC_APP_MANIFEST%"' + tail, + head + "IF NOT DEFINED LC_APP_MANIFEST " + command + tail, + ] + + def lines_of(texts: list[str]) -> list[str]: + return [item.replace("PROJECT_NAME", name) + newline for item in texts] + + lines[reg : reg + 1] = lines_of(register) + lines[found + 1 : found + 1] = lines_of(logs) + lines[before:before] = lines_of(pre) + helpers.write_text(path, "".join(lines)) + return "updated: the Tools hook passes --app-manifest and logs when labconstrictor-app.yaml is missing" + + +def _migrate_construct(helpers: Any, repo_root: Path) -> str: + """Add the extra_files entry that bundles labconstrictor-app.yaml (only if the file exists, in the known block shape).""" + path = repo_root / CONSTRUCT + if not path.is_file(): + return "not present in this repository (nothing was created)" + text = helpers.read_text(path) + lines = text.splitlines(keepends=True) + stripped = [line.rstrip("\r\n") for line in lines] + if any(MANIFEST_MAPPING.match(line) for line in stripped): + return "already bundles labconstrictor-app.yaml: unchanged" + if not (repo_root / APP_MANIFEST).is_file(): + return ( + "SKIPPED: the repository has no labconstrictor-app.yaml, so it is not bundled and the app is registered without hosts (listed in every host). " + f"Add the file, then add `- labconstrictor-app.yaml: /labconstrictor-app.yaml` to extra_files. See {DOCS_URL}" + ) + heads = [i for i, line in enumerate(stripped) if EXTRA_FILES_HEAD.match(line)] + if len(heads) != 1: + raise ValueError(f"expected one `extra_files:` block in the usual block shape, found {len(heads)}; add the mapping by hand") + last = heads[0] + while last + 1 < len(stripped) and EXTRA_FILES_ITEM.match(stripped[last + 1]): + last += 1 + folders = {m.group(1) for m in (WELCOME_MAPPING.match(line) for line in stripped[heads[0] + 1 : last + 1]) if m} + if last == heads[0] or len(folders) != 1: + raise ValueError("the project folder could not be read from the Welcome.ipynb entry of extra_files; add the mapping by hand") + newline = helpers.detect_newline(text) + entry = f"- labconstrictor-app.yaml: {folders.pop()}/labconstrictor-app.yaml{newline}" + if not lines[last].endswith(("\n", "\r")): + lines[last] += newline + lines.insert(last + 1, entry) + helpers.write_text(path, "".join(lines)) + return "updated: extra_files bundles labconstrictor-app.yaml" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Move the template Tools pin, pin the workflow actions, add the install rules (idempotent, surgical, never raises for a customised file).""" + _ = context + helpers = _load_helpers() + pin = new_pin(helpers) + try: + replacements = helpers.load_replacements(repo_root) + except (OSError, ValueError) as exc: + log(f"could not read the app name from construct.yaml ({exc}): the guides are written without app names.") + replacements = {} + + changed = 0 + + def report(name: Path, step: Any) -> None: + nonlocal changed + 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}") + + for relative, pattern in ((POST_INSTALL_SH, SH_PIN_LINE), (POST_INSTALL_BAT, BAT_PIN_LINE)): + if not (repo_root / relative).is_file(): + log(f"{relative}: SKIPPED, file not found in this repository (nothing was created).") + continue + report(relative, lambda relative=relative, pattern=pattern: _move_pin(helpers, repo_root / relative, pattern, pin)) + for relative in WORKFLOWS: + report(relative, lambda relative=relative: _migrate_workflow(helpers, repo_root, relative)) + report(CONSTRUCT, lambda: _migrate_construct(helpers, repo_root)) + for relative, step in ((POST_INSTALL_SH, _migrate_hosts_sh), (POST_INSTALL_BAT, _migrate_hosts_bat)): + if (repo_root / relative).is_file(): + report(relative, lambda relative=relative, step=step: step(helpers, repo_root / relative)) + report(INSTALL_DOC, lambda: _migrate_install_doc(helpers, repo_root)) + report(TOOLS_DOC, lambda: _migrate_tools_doc(helpers, repo_root, replacements, pin)) + + if changed: + log(f"done: {changed} file(s) changed. Review the pull request before merging; the pin reaches users with the next release of the app.") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_18_to_v0_1_19.py b/.template_sync/migrations/v0_1_18_to_v0_1_19.py new file mode 100644 index 0000000..fe204a9 --- /dev/null +++ b/.template_sync/migrations/v0_1_18_to_v0_1_19.py @@ -0,0 +1,139 @@ +"""Template 0.1.18 -> 0.1.19: src_change.yaml in every installer, Python series (not patch release) in setup.py. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_19.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. .tools/python/bump_constructor.py. `ensure_extra_files` removed the `.tools/meta/src_change.yaml` mapping from `extra_files` and then + re-added it only if it had not been there before, so every other release built an installer without `src_change.yaml` and the Welcome + notebook of that release could not offer source-code updates. The known block is replaced by one that always re-adds the mapping. +2. .tools/python/merge_requirements.py. It wrote the exact Python release pinned for the installer into setup.py (`python_requires=">=3.12.13"`), + so `pip install -e .` failed on any earlier patch release of the same series. The known block is replaced by one that writes the series + (`>=3.12`); environment.yaml keeps the exact pin. +3. setup.py. A `python_requires=">=X.Y.Z"` written by the old merge_requirements.py becomes `">=X.Y"` (only that exact shape). + +Rules this migration keeps: surgical (only the known blocks and the one known setup.py shape), 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 re +from pathlib import Path +from typing import Any + + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_19.md" +TAG = "[migration 0.1.19]" +BUMP_CONSTRUCTOR = Path(".tools/python/bump_constructor.py") +MERGE_REQUIREMENTS = Path(".tools/python/merge_requirements.py") +SETUP = Path("setup.py") + +# Blocks of the 0.1.18 template scripts and their 0.1.19 replacements (LF; each file's own line endings are used when matching and writing). +BUMP_OLD = """ src_change_dst = f"{project_folder}/src_change.yaml" + if src_change_file not in existing_sources and src_change_dst not in existing_dests: + normalized_items.append({src_change_file: src_change_dst}) + src_added += 1 + debug(f"Included src change marker: {src_change_file} -> {src_change_dst}") + else: + debug("src change marker mapping already present") +""" +BUMP_NEW = """ # The mapping was removed from normalized_items above, so always re-add it here; + # checking existing_sources would drop it on every other release. + src_change_dst = f"{project_folder}/src_change.yaml" + normalized_items.append({src_change_file: src_change_dst}) + src_added += 1 + debug(f"Included src change marker: {src_change_file} -> {src_change_dst}") +""" +MERGE_OLD = """ setup_text = setup_path.read_text(encoding="utf-8") + pattern = r'python_requires\\s*=\\s*["\\'][><=\\.0-9 ]+(PYTHON\\_VERSION)?["\\']' + new_setup_text = re.sub(pattern, f'python_requires=">={python_version}"', setup_text) + setup_path.write_text(new_setup_text, encoding="utf-8") + print(f"Updated {setup_path} with python_requires>={python_version}") +""" +MERGE_NEW = """ 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}") +""" +SETUP_PATCH_PIN = re.compile(r'(python_requires\s*=\s*)(["\'])>=(\d+)\.(\d+)\.\d+\2') +SETUP_SERIES_PIN = re.compile(r'python_requires\s*=\s*(["\'])>=(\d+\.\d+|PYTHON_VERSION)\1') + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers() -> Any: + """Reuse the helpers of the 0.1.10 migration (newline-preserving file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_19", 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 _replace_block(helpers: Any, path: Path, old: str, new: str) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + old_here, new_here = old.replace("\n", newline), new.replace("\n", newline) + if new_here in text: + return "unchanged: already has the 0.1.19 block" + count = text.count(old_here) + if count == 0: + return f"SKIPPED: the 0.1.18 block was not found (customised file); apply the change by hand. See {DOCS_URL}" + if count > 1: + return f"SKIPPED: the 0.1.18 block was found {count} times; apply the change by hand. See {DOCS_URL}" + helpers.write_text(path, text.replace(old_here, new_here, 1)) + return "updated" + + +def _migrate_setup(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + matches = SETUP_PATCH_PIN.findall(text) + if not matches: + if SETUP_SERIES_PIN.search(text): + return "unchanged: python_requires already names a Python series" + return "unchanged: no python_requires=\">=X.Y.Z\" written by merge_requirements.py" + if len(matches) > 1: + return f"SKIPPED: {len(matches)} python_requires lines; set \">=X.Y\" by hand. See {DOCS_URL}" + new_text = SETUP_PATCH_PIN.sub(lambda m: f"{m.group(1)}{m.group(2)}>={m.group(3)}.{m.group(4)}{m.group(2)}", text, count=1) + helpers.write_text(path, new_text) + series = SETUP_SERIES_PIN.search(new_text) + return f"updated: python_requires >={series.group(2) if series else '?'}" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Fix bump_constructor.py, merge_requirements.py and setup.py (idempotent, surgical, never raises for a customised file).""" + _ = context + helpers = _load_helpers() + changed = 0 + + def report(name: Path, step: Any) -> None: + nonlocal changed + if not (repo_root / name).is_file(): + log(f"{name}: SKIPPED, file not found 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(BUMP_CONSTRUCTOR, lambda: _replace_block(helpers, repo_root / BUMP_CONSTRUCTOR, BUMP_OLD, BUMP_NEW)) + report(MERGE_REQUIREMENTS, lambda: _replace_block(helpers, repo_root / MERGE_REQUIREMENTS, MERGE_OLD, MERGE_NEW)) + report(SETUP, lambda: _migrate_setup(helpers, repo_root / SETUP)) + + if changed: + log(f"done: {changed} file(s) changed. Review the pull request before merging; src_change.yaml returns with the next installer build.") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_19_to_v0_1_20.py b/.template_sync/migrations/v0_1_19_to_v0_1_20.py new file mode 100644 index 0000000..b077854 --- /dev/null +++ b/.template_sync/migrations/v0_1_19_to_v0_1_20.py @@ -0,0 +1,356 @@ +"""Template 0.1.19 -> 0.1.20: no lost pushes between the two workflows, lock files for the pip requirements, a launcher that starts fresh. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_20.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. Workflows. update_on_notebook_change.yml and update_on_src_change.yaml are replaced by the 0.1.20 files ONLY when the app's file is still + identical to the 0.1.19 template file (line endings are ignored when comparing and kept when writing). The new files rebase their + commit onto the latest branch and retry a rejected push, have one concurrency group each, revert a commit only when the conda test + failed (a merge commit with -m 1, any other commit as it is), and the notebook workflow runs lock_requirements.py. +2. Lock files. .tools/python/lock_requirements.py is created (requirements*.txt -> requirements*.lock.txt with uv), `uv==` is added to + .tools/requirements.txt, .tools/bash/test_conda_environment.sh (replaced when identical to 0.1.19) tests the lock file, + post_install.sh / .bat install the lock file when the installer bundles one (known blocks only), and bump_constructor.py gets the + function that bundles the lock files (inserted at two known lines). +3. Launcher. app/python_scripts/launch_jupyter.py (replaced when identical to the rendered 0.1.19 file) asks to press Enter when JupyterLab + stops and gives JupyterLab an empty workspace folder at every launch (only the Welcome notebook opens). app/menuinst/notebook_launcher.json + gets a Windows command that ends with `& exit`, so the terminal window closes after Enter (cmd /K kept it open). +4. Notebook usage guide. The sentence on stopping JupyterLab in .tools/docs/notebook_usage.md is replaced when it is still the 0.1.19 text. + +Rules this migration keeps: surgical (only known lines or known files), 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 pathlib import Path +from typing import Any + + +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_19_to_v0_1_20" +PREVIOUS_ROOT = RESOURCE_ROOT / "previous" +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_20.md" +TAG = "[migration 0.1.20]" + +NOTEBOOK_WORKFLOW = Path(".github/workflows/update_on_notebook_change.yml") +SRC_WORKFLOW = Path(".github/workflows/update_on_src_change.yaml") +TEST_CONDA = Path(".tools/bash/test_conda_environment.sh") +LAUNCHER = Path("app/python_scripts/launch_jupyter.py") +LOCK_SCRIPT = Path(".tools/python/lock_requirements.py") +TOOLS_REQUIREMENTS = Path(".tools/requirements.txt") +POST_INSTALL_SH = Path("app/bash_bat_scripts/post_install.sh") +POST_INSTALL_BAT = Path("app/bash_bat_scripts/post_install.bat") +BUMP_CONSTRUCTOR = Path(".tools/python/bump_constructor.py") +MENU = Path("app/menuinst/notebook_launcher.json") +USAGE_DOC = Path(".tools/docs/notebook_usage.md") + +# Files replaced as a whole when the app's file is still the (rendered) 0.1.19 template file. +REPLACED_FILES = (NOTEBOOK_WORKFLOW, SRC_WORKFLOW, TEST_CONDA, LAUNCHER) +# Resource files that are copies of the 0.1.20 template files (a test checks they stay identical to the template). +MANAGED_FILES = (*REPLACED_FILES, LOCK_SCRIPT) + +UV_PIN = "uv==0.13.3" +UV_LINE = re.compile(r"^\s*uv\s*(?:[=<>!~;\[]|$)", re.IGNORECASE) +UV_LINES = "# lock_requirements.py (requirements*.txt -> requirements*.lock.txt)\n" + UV_PIN + "\n" + +# post_install.sh: (0.1.19 text, 0.1.20 text), LF. +SH_BLOCKS = ( + ( + 'echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE"\n' + '"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1\n', + "# A lock file (requirements*.lock.txt next to the requirements file: every package with its exact version, written by\n" + "# .tools/python/lock_requirements.py) is installed instead of the requirements file when the installer bundles one.\n" + "locked_requirements() {\n" + ' if [ -f "${1%.txt}.lock.txt" ]; then echo "${1%.txt}.lock.txt"; else echo "$1"; fi\n' + "}\n" + 'SELECTED_REQUIREMENTS="$(locked_requirements "$SELECTED_REQUIREMENTS")"\n' + 'echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE"\n' + '"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1\n', + ), + ( + ' "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-macos.txt" >> "$LOG_FILE" 2>&1\n', + ' "$PYTHON_EXE" -m pip install -r "$(locked_requirements "$PROJECT_ROOT/requirements-macos.txt")" >> "$LOG_FILE" 2>&1\n', + ), + ( + ' "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-linux.txt" >> "$LOG_FILE" 2>&1\n', + ' "$PYTHON_EXE" -m pip install -r "$(locked_requirements "$PROJECT_ROOT/requirements-linux.txt")" >> "$LOG_FILE" 2>&1\n', + ), +) +SH_DONE = "locked_requirements()" + +BAT_BLOCKS = ( + ( + 'echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%"\n' + '"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1\n', + "REM A lock file (requirements*.lock.txt next to the requirements file: every package with its exact version, written by\n" + "REM .tools/python/lock_requirements.py) is installed instead of the requirements file when the installer bundles one.\n" + 'SET "SELECTED_LOCK=%SELECTED_REQUIREMENTS:~0,-4%.lock.txt"\n' + 'IF EXIST "%SELECTED_LOCK%" SET "SELECTED_REQUIREMENTS=%SELECTED_LOCK%"\n' + 'echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%"\n' + '"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1\n', + ), + ( + 'IF EXIST "%PROJECT_ROOT%\\requirements-windows.txt" (\n' + ' echo Installing Windows-specific requirements. >> "%LOG_FILE%"\n' + ' "%PYTHON_EXE%" -m pip install -r "%PROJECT_ROOT%\\requirements-windows.txt" >> "%LOG_FILE%" 2>&1\n', + 'SET "WINDOWS_REQUIREMENTS=%PROJECT_ROOT%\\requirements-windows.txt"\n' + 'IF EXIST "%PROJECT_ROOT%\\requirements-windows.lock.txt" SET "WINDOWS_REQUIREMENTS=%PROJECT_ROOT%\\requirements-windows.lock.txt"\n' + 'IF EXIST "%PROJECT_ROOT%\\requirements-windows.txt" (\n' + ' echo Installing Windows-specific requirements from "%WINDOWS_REQUIREMENTS%". >> "%LOG_FILE%"\n' + ' "%PYTHON_EXE%" -m pip install -r "%WINDOWS_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1\n', + ), +) +BAT_DONE = "SELECTED_LOCK=" + +BUMP_FUNCTION_ANCHOR = "def ensure_extra_files(" +BUMP_CALL_OLD = " ensure_requirements_in_extra_files(data)\n" +BUMP_CALL_NEW = " ensure_requirements_in_extra_files(data)\n ensure_lock_files_in_extra_files(data)\n" +BUMP_DONE = "def ensure_lock_files_in_extra_files(" +BUMP_NEEDS = ("def extract_project_folder(", "def debug(", "from pathlib import Path") + +WIN_EXIT = ["&", "exit"] + +USAGE_OLD = ( + "When you have, click on the terminal window and press `Ctrl+C` to stop the Jupyter Lab session and close the terminal." +) +USAGE_NEW = ( + "When you have, stop the Jupyter Lab session with **File > Shut Down** in Jupyter Lab (or click on the terminal window and press `Ctrl+C`). " + "The terminal then asks you to press `Enter`, and closes." +) + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers() -> Any: + """Reuse the helpers of the 0.1.10 migration (token replacement, newline detection, file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_20", 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 _resource(root: Path, relative: Path) -> str: + source = root / relative + if not source.is_file(): + raise FileNotFoundError(f"Template resource not found: {source}") + return source.read_bytes().decode("utf-8").replace("\r\n", "\n") + + +def _render(helpers: Any, text: str, replacements: dict[str, str]) -> str: + return str(helpers.render_template(text, replacements, "\n")) + + +def _write_lf(helpers: Any, path: Path, text_lf: str, newline: str) -> None: + helpers.write_text(path, text_lf.replace("\n", newline)) + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Whole files (workflows, conda test, launcher) +# -------------------------------------------------------------------------------------------------------------------------------- +def _replace_file(helpers: Any, repo_root: Path, relative: Path, replacements: dict[str, str]) -> str: + path = repo_root / relative + if not path.is_file(): + return "not present in this repository (nothing was created)" + current = helpers.read_text(path) + current_lf = current.replace("\r\n", "\n") + new = _render(helpers, _resource(RESOURCE_ROOT, relative), replacements) + if current_lf == new: + return "already the 0.1.20 template file: unchanged" + if current_lf != _render(helpers, _resource(PREVIOUS_ROOT, relative), replacements): + return f"SKIPPED: customised (not the 0.1.19 template file), so it was left unchanged; apply the 0.1.20 changes by hand, see {DOCS_URL}" + _write_lf(helpers, path, new, helpers.detect_newline(current)) + return "updated: replaced by the 0.1.20 template file" + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Lock files +# -------------------------------------------------------------------------------------------------------------------------------- +def _create_lock_script(helpers: Any, repo_root: Path) -> str: + path = repo_root / LOCK_SCRIPT + new = _resource(RESOURCE_ROOT, LOCK_SCRIPT) + if path.is_file(): + if helpers.read_text(path).replace("\r\n", "\n") == new: + return "already the 0.1.20 template file: unchanged" + return "SKIPPED: the repository has its own lock_requirements.py, left as it is" + if not path.parent.is_dir(): + return "SKIPPED: the repository has no .tools/python folder (nothing was created)" + with path.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(new) + return "updated: created" + + +def _add_uv(helpers: Any, repo_root: Path) -> str: + path = repo_root / TOOLS_REQUIREMENTS + if not path.is_file(): + return "not present in this repository (nothing was created)" + current = helpers.read_text(path) + if any(UV_LINE.match(line) for line in current.splitlines()): + return "already installs uv: unchanged" + newline = helpers.detect_newline(current) + text = current if not current or current.endswith(("\n", "\r")) else current + newline + helpers.write_text(path, text + UV_LINES.replace("\n", newline)) + return f"updated: added {UV_PIN}" + + +def _replace_blocks(helpers: Any, path: Path, blocks: tuple[tuple[str, str], ...], done: str, what: str) -> str: + current = helpers.read_text(path) + lf = current.replace("\r\n", "\n") + if done in lf: + return f"already {what}: unchanged" + missing = [old.splitlines()[0].strip() for old, _ in blocks if lf.count(old) != 1] + if missing: + shown = "; ".join(missing) + return f"SKIPPED: customised, the known lines were not found once ({shown}); left unchanged, apply the change by hand, see {DOCS_URL}" + for old, new in blocks: + lf = lf.replace(old, new) + _write_lf(helpers, path, lf, helpers.detect_newline(current)) + return f"updated: {what}" + + +def _bump_constructor(helpers: Any, repo_root: Path) -> str: + path = repo_root / BUMP_CONSTRUCTOR + if not path.is_file(): + return "not present in this repository (nothing was created)" + current = helpers.read_text(path) + lf = current.replace("\r\n", "\n") + if BUMP_DONE in lf: + return "already bundles the lock files: unchanged" + if lf.count(BUMP_FUNCTION_ANCHOR) != 1 or lf.count(BUMP_CALL_OLD) != 1 or not all(need in lf for need in BUMP_NEEDS): + return f"SKIPPED: customised (the known lines were not found once), left unchanged; add ensure_lock_files_in_extra_files by hand, see {DOCS_URL}" + lf = lf.replace(BUMP_FUNCTION_ANCHOR, BUMP_SNIPPET + BUMP_FUNCTION_ANCHOR, 1).replace(BUMP_CALL_OLD, BUMP_CALL_NEW, 1) + _write_lf(helpers, path, lf, helpers.detect_newline(current)) + return "updated: bundles the lock files (ensure_lock_files_in_extra_files)" + + +# The LOCK_FILES tuple and ensure_lock_files_in_extra_files of the 0.1.20 bump_constructor.py, with the blank lines before the next function +# (a test checks that the template script holds this text once). +BUMP_SNIPPET = '''LOCK_FILES = ( + "requirements.lock.txt", + "requirements_gpu.lock.txt", + "requirements-linux.lock.txt", + "requirements-windows.lock.txt", + "requirements-macos.lock.txt", +) + + +def ensure_lock_files_in_extra_files(construct_data: dict) -> None: + """Bundle the lock files (requirements*.lock.txt, written by lock_requirements.py) next to their requirements files. + + post_install installs a lock file instead of its requirements file when the installer bundles one. A mapping whose lock file is gone + (the requirements could not be locked) is removed, because constructor fails on a missing file. + """ + extra_files = construct_data.setdefault("extra_files", []) + project_folder = extract_project_folder(extra_files) + for lock_file in LOCK_FILES: + mapped = [item for item in extra_files if isinstance(item, dict) and lock_file in item] + if Path(lock_file).exists(): + if not mapped: + extra_files.append({lock_file: f"{project_folder}/{lock_file}"}) + debug(f"Added mapping for {lock_file}") + else: + debug(f"{lock_file} mapping already present") + elif mapped: + for item in mapped: + extra_files.remove(item) + debug(f"Removed the mapping of {lock_file}: the file does not exist (the installer installs the requirements file instead)") + + +''' + + +# -------------------------------------------------------------------------------------------------------------------------------- +# Launcher shortcut (Windows: close the terminal after Enter) +# -------------------------------------------------------------------------------------------------------------------------------- +def _menu(helpers: Any, repo_root: Path) -> str: + path = repo_root / MENU + if not path.is_file(): + return "not present in this repository (nothing was created)" + current = helpers.read_text(path) + lf = current.replace("\r\n", "\n") + try: + data = json.loads(lf) + except json.JSONDecodeError as exc: + return f"SKIPPED: not valid JSON ({exc}), left unchanged" + items = data.get("menu_items") if isinstance(data, dict) else None + if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict): + return f"SKIPPED: not the template shape (one menu item), left unchanged; see {DOCS_URL}" + item = items[0] + command = item.get("command") + win = (item.get("platforms") or {}).get("win") + if not isinstance(command, list) or not isinstance(win, dict) or not item.get("terminal"): + return f"SKIPPED: not the template shape (a terminal command with a win platform), left unchanged; see {DOCS_URL}" + if "command" in win: + if win["command"] == command + WIN_EXIT: + return "already closes the Windows terminal after Enter: unchanged" + return "SKIPPED: has its own Windows command, left unchanged; end it with \"&\", \"exit\" to close the terminal after Enter" + if json.dumps(data, indent=2, ensure_ascii=False) + "\n" != lf: + return f"SKIPPED: formatted differently from the template, left unchanged; add the Windows command by hand, see {DOCS_URL}" + win["command"] = command + WIN_EXIT + _write_lf(helpers, path, json.dumps(data, indent=2, ensure_ascii=False) + "\n", helpers.detect_newline(current)) + return "updated: the Windows command ends with `& exit` (the terminal closes after Enter)" + + +def _usage_doc(helpers: Any, repo_root: Path) -> str: + path = repo_root / USAGE_DOC + if not path.is_file(): + return "not present in this repository (nothing was created)" + current = helpers.read_text(path) + if USAGE_NEW in current: + return "unchanged" + if current.count(USAGE_OLD) != 1: + return "SKIPPED: the 0.1.19 sentence on stopping Jupyter Lab was not found (customised), left unchanged" + helpers.write_text(path, current.replace(USAGE_OLD, USAGE_NEW)) + return "updated: how to stop Jupyter Lab (File > Shut Down, then Enter)" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Replace the two workflows and the launcher, add the lock files (idempotent, surgical, never raises for a customised file).""" + _ = context + helpers = _load_helpers() + try: + replacements = helpers.load_replacements(repo_root) + except (OSError, ValueError) as exc: + log(f"could not read the app name from construct.yaml ({exc}): the launcher is compared without app names.") + replacements = {} + + changed = 0 + + def report(name: Path, step: Any) -> None: + nonlocal changed + 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}") + + for relative in REPLACED_FILES: + report(relative, lambda relative=relative: _replace_file(helpers, repo_root, relative, replacements)) + report(LOCK_SCRIPT, lambda: _create_lock_script(helpers, repo_root)) + report(TOOLS_REQUIREMENTS, lambda: _add_uv(helpers, repo_root)) + for relative, blocks, done in ((POST_INSTALL_SH, SH_BLOCKS, SH_DONE), (POST_INSTALL_BAT, BAT_BLOCKS, BAT_DONE)): + if not (repo_root / relative).is_file(): + log(f"{relative}: not present in this repository (nothing was created)") + continue + report(relative, lambda relative=relative, blocks=blocks, done=done: _replace_blocks( + helpers, repo_root / relative, blocks, done, "installs the lock file when the installer bundles one" + )) + report(BUMP_CONSTRUCTOR, lambda: _bump_constructor(helpers, repo_root)) + report(MENU, lambda: _menu(helpers, repo_root)) + report(USAGE_DOC, lambda: _usage_doc(helpers, repo_root)) + + if changed: + log( + f"done: {changed} file(s) changed. Review the pull request before merging. The lock files are written by the next run of " + "'Updates on notebook change' (Actions > Run workflow); the launcher 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_1_to_v0_1_2.py b/.template_sync/migrations/v0_1_1_to_v0_1_2.py new file mode 100644 index 0000000..6474ab1 --- /dev/null +++ b/.template_sync/migrations/v0_1_1_to_v0_1_2.py @@ -0,0 +1,284 @@ +from __future__ import annotations + +import json +import re + +from pathlib import Path +from typing import Any + + +SRC_WORKFLOW_PATH = Path(".github/workflows/update_on_src_change.yaml") +BUMP_CONSTRUCTOR_PATH = Path(".tools/python/bump_constructor.py") +WELCOME_TEMPLATE_PATH = Path(".tools/templates/Welcome_template.ipynb") +EXTERNAL_CODE_DOC_PATH = Path(".tools/docs/external_code_upload.md") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def replace_text( + repo_root: Path, + relative_path: Path, + old: str, + new: str, + *, + already_updated: str | None = None, +) -> bool: + path = repo_root / relative_path + if not path.exists(): + print(f"Skipping missing file: {relative_path}") + return False + + original_text = read_text(path) + if old in original_text: + updated_text = original_text.replace(old, new, 1) + write_text(path, updated_text) + print(f"Updated {relative_path}") + return True + + if already_updated and already_updated in original_text: + return False + + raise ValueError(f"Unable to find expected text in {relative_path}") + + +def update_src_change_workflow(repo_root: Path) -> bool: + return replace_text( + repo_root, + SRC_WORKFLOW_PATH, + " - 'src/**/*.py'", + " - 'src/**'", + already_updated=" - 'src/**'", + ) + + +def update_bump_constructor(repo_root: Path) -> bool: + path = repo_root / BUMP_CONSTRUCTOR_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_CONSTRUCTOR_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + updated_text = original_text + + old_dst = ' dst = f"{project_folder}/src/{project_name}/{rel.replace(\'src/\', \'\')}"' + new_dst = ' dst = f"{project_folder}/{rel}"' + if old_dst in updated_text: + updated_text = updated_text.replace(old_dst, new_dst, 1) + elif new_dst not in updated_text: + raise ValueError(f"Unable to find constructor src destination mapping in {BUMP_CONSTRUCTOR_PATH}") + + # Match the small formatting cleanup made in the template update. + updated_text = updated_text.replace( + f"import re{newline}{newline}{newline}def load_construct", + f"import re{newline}{newline}def load_construct", + 1, + ) + + if updated_text == original_text: + return False + + write_text(path, updated_text) + print(f"Updated {BUMP_CONSTRUCTOR_PATH}") + return True + + +def update_welcome_template(repo_root: Path) -> bool: + path = repo_root / WELCOME_TEMPLATE_PATH + if not path.exists(): + print(f"Skipping missing file: {WELCOME_TEMPLATE_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + + try: + notebook = json.loads(original_text) + except json.JSONDecodeError as exc: + raise ValueError(f"Unable to parse {WELCOME_TEMPLATE_PATH} as JSON") from exc + + legacy_assignment = re.compile( + r"^(?P[ \t]*)src_folder\s*=\s*" + r"Path\((?P['\"])\.\.(?P=quote1)\)\s*/\s*" + r"(?P['\"])src(?P=quote2)\s*/\s*" + r"(?P['\"])[^'\"]+(?P=quote3)\s*$" + ) + current_assignment = re.compile( + r"^[ \t]*src_folder\s*=\s*" + r"Path\((?P['\"])\.\.(?P=quote1)\)\s*/\s*" + r"(?P['\"])src(?P=quote2)\s*$" + ) + + found_current = False + changed = False + + for cell in notebook.get("cells", []): + if cell.get("cell_type") != "code": + continue + + source = cell.get("source", []) + source_is_list = isinstance(source, list) + lines = source if source_is_list else str(source).splitlines(keepends=True) + updated_lines = [] + cell_changed = False + + for line in lines: + line_ending = "\r\n" if line.endswith("\r\n") else "\n" if line.endswith("\n") else "" + body = line[:-len(line_ending)] if line_ending else line + + if current_assignment.match(body): + found_current = True + updated_lines.append(line) + continue + + match = legacy_assignment.match(body) + if match: + updated_lines.append( + f'{match.group("indent")}src_folder = Path("..") / "src"{line_ending}' + ) + changed = True + cell_changed = True + continue + + updated_lines.append(line) + + if cell_changed: + cell["source"] = updated_lines if source_is_list else "".join(updated_lines) + + if not changed: + if found_current: + return False + print( + f"Skipping {WELCOME_TEMPLATE_PATH}: no legacy src_folder assignment was found" + ) + return False + + rendered = json.dumps(notebook, ensure_ascii=False, indent=1) + if original_text.endswith(("\n", "\r\n")): + rendered += newline + write_text(path, rendered) + print(f"Updated {WELCOME_TEMPLATE_PATH}") + return True + + +def detect_python_package_name(repo_root: Path, text: str = "") -> str: + src_root = repo_root / "src" + if src_root.is_dir(): + candidates = sorted( + child.name + for child in src_root.iterdir() + if child.is_dir() + and child.name.isidentifier() + and (child / "__init__.py").is_file() + ) + if len(candidates) == 1: + return candidates[0] + + setup_path = repo_root / "setup.py" + if setup_path.is_file(): + setup_text = read_text(setup_path) + match = re.search(r'name\s*=\s*["\']([^"\']+)["\']', setup_text) + if match: + return match.group(1).replace("-", "_") + + import_match = re.search( + r"(?m)^import\s+([A-Za-z_][A-Za-z0-9_]*)\s*$", text + ) + if import_match: + return import_match.group(1) + + return "PYTHON_PROJ_NAME" + + +def update_external_code_docs(repo_root: Path) -> bool: + path = repo_root / EXTERNAL_CODE_DOC_PATH + if not path.exists(): + print(f"Skipping missing file: {EXTERNAL_CODE_DOC_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + package_name = detect_python_package_name(repo_root, original_text) + + changed = False + updated_text = original_text + + old_tree = "\n".join( + [ + "```", + "src", + "|-- __init__.py", + "|-- my_script.py", + "|-- subpackage/", + " |-- __init__.py", + " |-- submodule1.py", + "```", + ] + ).replace("\n", newline) + new_tree = "\n".join( + [ + "```text", + "src/", + f"|-- {package_name}/", + "| |-- __init__.py", + "| |-- my_script.py", + "| |-- subpackage/", + "| |-- __init__.py", + "```", + ] + ).replace("\n", newline) + + if old_tree in updated_text: + updated_text = updated_text.replace(old_tree, new_tree, 1) + changed = True + elif new_tree not in updated_text: + print( + f"Skipping directory tree update in {EXTERNAL_CODE_DOC_PATH}: " + "the document uses a custom structure" + ) + + old_init = "# src/__init__.py" + new_init = f"# src/{package_name}/__init__.py" + if old_init in updated_text: + updated_text = updated_text.replace(old_init, new_init, 1) + changed = True + + old_submodule_pattern = re.compile( + rf"(?m)^from\s+{re.escape(package_name)}\s+import\s+subpackage\s*$" + ) + new_submodule = f"from {package_name}.subpackage import submodule1" + if old_submodule_pattern.search(updated_text): + updated_text = old_submodule_pattern.sub(new_submodule, updated_text, count=1) + changed = True + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {EXTERNAL_CODE_DOC_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_src_change_workflow(repo_root) or changed_any + changed_any = update_bump_constructor(repo_root) or changed_any + changed_any = update_welcome_template(repo_root) or changed_any + changed_any = update_external_code_docs(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_20_to_v0_1_21.py b/.template_sync/migrations/v0_1_20_to_v0_1_21.py new file mode 100644 index 0000000..7f8a212 --- /dev/null +++ b/.template_sync/migrations/v0_1_20_to_v0_1_21.py @@ -0,0 +1,86 @@ +"""Template 0.1.20 -> 0.1.21: build the installer with conda-standalone 26.9.3 or later. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_21.md + +What this changes in an app repository (idempotent, never deletes anything): + +1. .tools/bash/create_constructor_environment.sh. The constructor environment did not pin conda-standalone, the `_conda.exe` that the + installer uses to install the packages. Versions before 26.9.3 write the package records without `paths_data` when constructor disables + conda's safety checks (conda/conda#16856). conda 26.9 and later in the installed app looks up the Windows launcher stub in that metadata, + cannot find it, and treats the error as a permission problem: the Windows uninstaller then asks twice for administrator rights for + python.exe (`conda init --reverse`). The known `conda create` line is replaced by one that adds `"conda-standalone>=26.9.3"`. + +Rules this migration keeps: surgical (only the one known line), 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 the file are kept, nothing is deleted. +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path +from typing import Any + + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_21.md" +TAG = "[migration 0.1.21]" +CREATE_ENV = Path(".tools/bash/create_constructor_environment.sh") + +# The 0.1.20 line and its 0.1.21 replacement (LF; the file's own line endings are used when matching and writing). +CREATE_OLD = 'conda create -y -n "${CONSTRUCTOR_ENV:?}" -c conda-forge -c defaults python=3.11 constructor\n' +CREATE_NEW = """# conda-standalone (the installer's _conda.exe) older than 26.9.3 writes package +# records without paths_data when constructor disables conda's safety checks. +# conda 26.9 and later in the installed app then cannot find the Windows +# launcher stub, and `conda init --reverse` in the uninstaller asks for admin +# rights (conda/conda#16856, fixed in conda 26.9.3). +conda create -y -n "${CONSTRUCTOR_ENV:?}" -c conda-forge -c defaults python=3.11 constructor "conda-standalone>=26.9.3" +""" + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers() -> Any: + """Reuse the helpers of the 0.1.10 migration (newline-preserving file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_21", 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 _pin_conda_standalone(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + old_here, new_here = CREATE_OLD.replace("\n", newline), CREATE_NEW.replace("\n", newline) + if new_here in text: + return "unchanged: already pins conda-standalone>=26.9.3" + count = text.count(old_here) + if count == 0: + if "conda-standalone" in text: + return f"SKIPPED: the file already names conda-standalone (customised); check it allows 26.9.3 or later. See {DOCS_URL}" + return f"SKIPPED: the 0.1.20 conda create line was not found (customised file); add \"conda-standalone>=26.9.3\" by hand. See {DOCS_URL}" + if count > 1: + return f"SKIPPED: the 0.1.20 conda create line was found {count} times; add the pin by hand. See {DOCS_URL}" + helpers.write_text(path, text.replace(old_here, new_here, 1)) + return "updated: conda-standalone>=26.9.3" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Pin conda-standalone in create_constructor_environment.sh (idempotent, surgical, never raises for a customised file).""" + _ = context + path = repo_root / CREATE_ENV + if not path.is_file(): + log(f"{CREATE_ENV}: SKIPPED, file not found in this repository (nothing was created).") + log("done: no repository changes were required.") + return + try: + status = _pin_conda_standalone(_load_helpers(), path) + except (OSError, ValueError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + log(f"{CREATE_ENV}: {status}") + if status.startswith("updated"): + log("done: 1 file changed. Build and release a new installer: installs made with an older installer keep the admin prompt at uninstall.") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_21_to_v0_1_22.py b/.template_sync/migrations/v0_1_21_to_v0_1_22.py new file mode 100644 index 0000000..14969fb --- /dev/null +++ b/.template_sync/migrations/v0_1_21_to_v0_1_22.py @@ -0,0 +1,167 @@ +"""Template 0.1.21 -> 0.1.22: Windows computers with an NVIDIA driver can install TensorFlow apps; the version cell reads the version file. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_22.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. .tools/python/merge_requirements.py. The GPU requirements file rewrote `tensorflow` to `tensorflow[and-cuda]` for every system. The + extra pulls nvidia-* wheels that exist only for Linux and carries no platform marker, so the universal lock pinned them for Windows + too, and `pip install` failed on every Windows computer with an NVIDIA driver (post_install.bat picks the GPU file there). The GPU + file now has `tensorflow[and-cuda]==X ; sys_platform == "linux"` and `tensorflow==X ; sys_platform != "linux"`. Three known blocks + are changed (docstring, a new function before build_gpu_lines, the tensorflow branch of build_gpu_lines). +2. .tools/docs/notebook_upload.md. The version cell snippet looked the notebook up at the top level of notebook_latest_versions.yaml, + which sync_notebook_versions.py writes grouped by folder, so Colab users always read "not listed". The one known line is replaced. + Notebooks that already contain the old snippet are not edited (see the design note). + +Rules this migration keeps: surgical (only 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 +from pathlib import Path +from typing import Any + + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_22.md" +TAG = "[migration 0.1.22]" +MERGE = Path(".tools/python/merge_requirements.py") +UPLOAD_DOC = Path(".tools/docs/notebook_upload.md") + +# merge_requirements.py: (0.1.21 text, 0.1.22 text), LF. +MERGE_DOC_OLD = ( + "GPU file rewrites `tensorflow` to `tensorflow[and-cuda]` and adds the PyTorch\n" + "CUDA wheel index when `torch`, `torchvision`, or `torchaudio` are present.\n" +) +MERGE_DOC_NEW = ( + "GPU file rewrites `tensorflow` to `tensorflow[and-cuda]` on Linux only (TensorFlow's CUDA\n" + "wheels exist only for Linux; other systems keep plain `tensorflow`) and adds the\n" + "PyTorch CUDA wheel index when `torch`, `torchvision`, or `torchaudio` are present.\n" +) +MERGE_ANCHOR = "def build_gpu_lines(final_lines: list[str]) -> list[str]:\n" +MERGE_FUNCTION = ( + "# TensorFlow's `and-cuda` extra pulls nvidia-* wheels that exist only for Linux (nvidia-nccl-cu12 has never had a Windows or macOS\n" + '# wheel), and the extra itself carries no platform marker. Without a marker the universal lock of requirements_gpu.txt pins them for\n' + '# every system, so `pip install` fails on a Windows computer with an NVIDIA driver (the installer picks the GPU file there). TensorFlow\n' + '# has had no native Windows GPU build since 2.10, so Windows and macOS keep plain `tensorflow` in the GPU file.\n' + 'GPU_TENSORFLOW_PLATFORM = \'sys_platform == "linux"\'\n' + 'NON_GPU_TENSORFLOW_PLATFORM = \'sys_platform != "linux"\'\n' + '\n' + '\n' + 'def _with_platform(marker: str, platform: str) -> str:\n' + ' """Return ` ; `, combined with the line\'s own marker (`; `) when it has one."""\n' + ' existing = marker.split(";", 1)[1].strip() if ";" in marker else ""\n' + ' return f" ; ({existing}) and {platform}" if existing else f" ; {platform}"\n' + '\n' + '\n' + 'def tensorflow_gpu_lines(line: str) -> list[str]:\n' + ' """Return the GPU-file lines for a tensorflow requirement: `[and-cuda]` on Linux, the plain requirement elsewhere.\n' + '\n' + ' A line that is not a tensorflow requirement is returned unchanged (as a one-item list).\n' + ' """\n' + ' match = pkg_re.match(line)\n' + ' if match:\n' + ' if match.group("name").lower() != "tensorflow":\n' + ' return [line]\n' + ' name, extras = match.group("name"), match.group("extras") or ""\n' + ' spec = f"{match.group(\'op\')}{match.group(\'ver\')}"\n' + ' else:\n' + ' match = PLAIN_PKG_RE.match(line)\n' + ' if not match or match.group("name").lower() != "tensorflow":\n' + ' return [line]\n' + ' name, extras, spec = match.group("name"), match.group("extras") or "", ""\n' + ' marker = match.group("marker") or ""\n' + ' cuda_extras = merge_requirement_extras(extras, "and-cuda")\n' + ' return [\n' + ' f"{name}{cuda_extras}{spec}{_with_platform(marker, GPU_TENSORFLOW_PLATFORM)}",\n' + ' f"{name}{extras}{spec}{_with_platform(marker, NON_GPU_TENSORFLOW_PLATFORM)}",\n' + ' ]\n' + '\n' + '\n' +) +MERGE_BODY_OLD = ( + ' if package_name == "tensorflow":\n' + " line = rewrite_tensorflow_for_gpu(line)\n" + " if package_name in TORCH_GPU_PACKAGES:\n" + " has_torch_package = True\n" +) +MERGE_BODY_NEW = ( + " if package_name in TORCH_GPU_PACKAGES:\n" + " has_torch_package = True\n" + ' if package_name == "tensorflow":\n' + " gpu_lines.extend(tensorflow_gpu_lines(line))\n" + " continue\n" +) +MERGE_DONE = "def tensorflow_gpu_lines(" + +UPLOAD_OLD = ' latest_version = config.get(notebook_name, "")\n' +UPLOAD_NEW = ( + ' # notebook_latest_versions.yaml groups the notebooks by folder: {"": {"": ""}}\n' + " latest_version = next((str(group[notebook_name]) for group in (config or {}).values()\n" + ' if isinstance(group, dict) and notebook_name in group), "")\n' +) +UPLOAD_DONE = "groups the notebooks by folder" + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def _load_helpers() -> Any: + """Reuse the helpers of the 0.1.10 migration (newline-preserving file IO).""" + path = Path(__file__).resolve().parent / "v0_1_9_to_v0_1_10.py" + spec = importlib.util.spec_from_file_location("template_sync_helpers_0_1_22", 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 _patch_merge(text: str, newline: str) -> tuple[str, str]: + """Return (new text, status) for merge_requirements.py; the code blocks change together or not at all.""" + if MERGE_DONE in text: + return text, "unchanged: the GPU file already limits tensorflow[and-cuda] to Linux" + anchor, body_old, body_new = (s.replace("\n", newline) for s in (MERGE_ANCHOR, MERGE_BODY_OLD, MERGE_BODY_NEW)) + if text.count(anchor) != 1 or text.count(body_old) != 1: + return text, f"SKIPPED: the 0.1.21 build_gpu_lines was not found once (customised file); see {DOCS_URL} for the change to make by hand" + function = MERGE_FUNCTION.replace("\n", newline) + text = text.replace(anchor, function + anchor, 1).replace(body_old, body_new, 1) + doc_old, doc_new = MERGE_DOC_OLD.replace("\n", newline), MERGE_DOC_NEW.replace("\n", newline) + if text.count(doc_old) == 1: + text = text.replace(doc_old, doc_new, 1) + return text, "updated: tensorflow[and-cuda] only on Linux in the GPU file" + + +def _patch_upload(text: str, newline: str) -> tuple[str, str]: + if UPLOAD_DONE in text: + return text, "unchanged: the version cell already reads the grouped version file" + old = UPLOAD_OLD.replace("\n", newline) + if text.count(old) != 1: + return text, f"SKIPPED: the 0.1.21 version lookup line was not found once (customised file). See {DOCS_URL}" + return text.replace(old, UPLOAD_NEW.replace("\n", newline), 1), "updated: the version cell reads the grouped version file" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Apply both changes (idempotent, surgical, never raises for a customised or missing file).""" + _ = context + helpers = _load_helpers() + changed = 0 + for relative, patch in ((MERGE, _patch_merge), (UPLOAD_DOC, _patch_upload)): + path = repo_root / relative + if not path.is_file(): + log(f"{relative}: SKIPPED, file not found in this repository (nothing was created).") + continue + try: + text = helpers.read_text(path) + new_text, status = patch(text, "\r\n" if "\r\n" in text else "\n") + if new_text != text: + helpers.write_text(path, new_text) + changed += 1 + except (OSError, ValueError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + log(f"{relative}: {status}") + if changed: + log(f"done: {changed} file(s) changed. Push a notebook change (or run 'Updates on notebook change') to regenerate the GPU lock, then release a new installer.") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_22_to_v0_1_23.py b/.template_sync/migrations/v0_1_22_to_v0_1_23.py new file mode 100644 index 0000000..486fe92 --- /dev/null +++ b/.template_sync/migrations/v0_1_22_to_v0_1_23.py @@ -0,0 +1,192 @@ +"""Template 0.1.22 -> 0.1.23: no template placeholder in the installer (CellMigrationLab/LabConstrictor#40). + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_23.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. Placeholders the repository initialisation missed are replaced with the app's values, only where they are still there: + - app/bash_bat_scripts/post_install.sh / .bat: PYTHON_PROJ_NAME (the import check and the _lc_tools module). An app + initialised on template 0.1.16 or later with Python code in src/ could not be installed: `No module named 'PYTHON_PROJ_NAME'`. + - app/python_scripts/launch_jupyter.py: PROJECT_NAME (PROJECT_DISPLAY_NAME, the launcher's window titles and error messages). + - .tools/templates/Welcome_template.ipynb: PROJECT_NAME and PYTHON_PROJ_NAME ("Welcome to PROJECT_NAME!" in the Playground). + The package is found as in the 0.1.16 migration (the single _lc_tools module or package in src/, then setup.py, then + pyproject.toml); the app name is the menu name of app/menuinst/notebook_launcher.json, which the initialisation wrote. +2. .tools/python/check_placeholders.py (new) and two lines in .github/workflows/release_constructor.yml that run it after the + versioned files are updated: a release whose installer would still ship a placeholder stops with the file, the line and the fix. + +Rules this migration keeps: surgical (only placeholders, one new file and the known workflow lines), 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_23.md" +TAG = "[migration 0.1.23]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_22_to_v0_1_23" + +POST_INSTALL_SH = Path("app/bash_bat_scripts/post_install.sh") +POST_INSTALL_BAT = Path("app/bash_bat_scripts/post_install.bat") +LAUNCHER = Path("app/python_scripts/launch_jupyter.py") +WELCOME_TEMPLATE = Path(".tools/templates/Welcome_template.ipynb") +NOTEBOOK_LAUNCHER = Path("app/menuinst/notebook_launcher.json") +CHECK_SCRIPT = Path(".tools/python/check_placeholders.py") +RELEASE_WORKFLOW = Path(".github/workflows/release_constructor.yml") + +# Which placeholders each file may still hold, and where their value comes from ("package" or "name"). +PLACEHOLDER_FILES: dict[Path, tuple[tuple[str, str], ...]] = { + POST_INSTALL_SH: (("PYTHON_PROJ_NAME", "package"),), + POST_INSTALL_BAT: (("PYTHON_PROJ_NAME", "package"),), + LAUNCHER: (("PROJECT_NAME", "name"),), + WELCOME_TEMPLATE: (("PYTHON_PROJ_NAME", "package"), ("PROJECT_NAME", "name")), +} + +# The release workflow runs bump_Welcome_notebook.py last in both jobs; the check goes right after it, with the same log file. +WELCOME_STEP = re.compile( + r"(?P[ ]+)bash \.tools/bash/run_with_context\.sh \\\n" + r"(?P=indent) (?P\S+) \\\n" + r"(?P=indent) \"bump_Welcome_notebook\.py\" \\\n" + r"(?P=indent) \.tools/python/bump_Welcome_notebook\.py \\\n" + r"(?P=indent) python \.tools/python/bump_Welcome_notebook\.py [^\n]*\n" +) +CHECK_STEP = ( + "{indent}bash .tools/bash/run_with_context.sh \\\n" + "{indent} {log} \\\n" + '{indent} "check_placeholders.py" \\\n' + "{indent} .tools/python/check_placeholders.py \\\n" + "{indent} python .tools/python/check_placeholders.py\n" +) + + +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 placeholder_pattern(name: str) -> re.Pattern[str]: + """A placeholder on its own or followed by '_' (PYTHON_PROJ_NAME_lc_tools), never inside a longer name (UNDERSCORED_PROJECT_NAME).""" + return re.compile(r"(? str | None: + """The app name the initialisation wrote for PROJECT_NAME: the menu name of notebook_launcher.json, else PROJECT_DISPLAY_NAME.""" + path = repo_root / NOTEBOOK_LAUNCHER + if path.is_file(): + try: + name = json.loads(helpers.read_text(path)).get("menu_name") + except (ValueError, AttributeError): + name = None + if isinstance(name, str) and name.strip() and not placeholder_pattern("PROJECT_NAME").search(name): + return name.strip() + path = repo_root / LAUNCHER + if path.is_file(): + match = re.search(r'^PROJECT_DISPLAY_NAME = "([^"\n]+)"', helpers.read_text(path), re.MULTILINE) + if match and match.group(1) != "PROJECT_NAME": + return match.group(1) + return None + + +def _replace_placeholders(helpers: Any, path: Path, wanted: tuple[tuple[str, str], ...], values: dict[str, str | None]) -> str: + text = helpers.read_text(path) + present = [(name, source) for name, source in wanted if placeholder_pattern(name).search(text)] + if not present: + return "unchanged: no placeholder left" + missing = sorted({source for _, source in present if not values[source]}) + if missing: + what = " and ".join("the Python package (one package in src/, or a name in setup.py)" if m == "package" else "the app name" for m in missing) + names = ", ".join(name for name, _ in present) + return f"SKIPPED: {names} is still there, but {what} could not be found; replace it by hand. See {DOCS_URL}" + done = [] + for name, source in present: + value = values[source] + assert value is not None + text, count = placeholder_pattern(name).subn(value.replace("\\", "\\\\"), text) + done.append(f"{name} -> {value} ({count}x)") + helpers.write_text(path, text) + return "updated: " + ", ".join(done) + + +def _create_check_script(helpers: Any, repo_root: Path) -> str: + path = repo_root / CHECK_SCRIPT + new = (RESOURCE_ROOT / CHECK_SCRIPT).read_text(encoding="utf-8") + if path.is_file(): + if helpers.read_text(path).replace("\r\n", "\n") == new: + return "already the 0.1.23 template file: unchanged" + return "SKIPPED: the repository has its own check_placeholders.py, left as it is" + if not path.parent.is_dir(): + return "SKIPPED: the repository has no .tools/python folder (nothing was created)" + with path.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(new) + return "updated: created" + + +def _add_check_step(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + lf = text.replace("\r\n", "\n") + if "check_placeholders.py" in lf: + return "unchanged: already runs check_placeholders.py" + steps = list(WELCOME_STEP.finditer(lf)) + if not steps: + return f"SKIPPED: the bump_Welcome_notebook.py command was not found (customised workflow); add the check by hand. See {DOCS_URL}" + out, last = [], 0 + for match in steps: + out.append(lf[last : match.end()]) + out.append(CHECK_STEP.format(indent=match.group("indent"), log=match.group("log"))) + last = match.end() + out.append(lf[last:]) + helpers.write_text(path, "".join(out).replace("\n", newline)) + return f"updated: the check runs after bump_Welcome_notebook.py in {len(steps)} job(s)" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Replace the placeholders the initialisation missed and add the release check (idempotent, surgical, never raises for a customised file).""" + _ = context + helpers = _load("v0_1_9_to_v0_1_10.py", "template_sync_helpers_0_1_23") + construct = repo_root / "construct.yaml" + if construct.is_file() and re.search(r"^name:\s*UNDERSCORED_PROJECT_NAME\s*$", helpers.read_text(construct), re.MULTILINE): + log("SKIPPED: this repository is not initialised (construct.yaml still names UNDERSCORED_PROJECT_NAME); nothing was changed.") + return + package = _load("v0_1_15_to_v0_1_16.py", "template_sync_detect_0_1_23").detect_package(helpers, repo_root) + values = {"package": package, "name": app_name(helpers, repo_root)} + changed = 0 + + def report(name: Path, step: Callable[[], str]) -> None: + nonlocal changed + if not (repo_root / name).is_file() and name != CHECK_SCRIPT: + 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}") + + for relative, wanted in PLACEHOLDER_FILES.items(): + report(relative, partial(_replace_placeholders, helpers, repo_root / relative, wanted, values)) + report(CHECK_SCRIPT, lambda: _create_check_script(helpers, repo_root)) + report(RELEASE_WORKFLOW, lambda: _add_check_step(helpers, repo_root / RELEASE_WORKFLOW)) + + 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_23_to_v0_1_24.py b/.template_sync/migrations/v0_1_23_to_v0_1_24.py new file mode 100644 index 0000000..c280357 --- /dev/null +++ b/.template_sync/migrations/v0_1_23_to_v0_1_24.py @@ -0,0 +1,350 @@ +"""Template 0.1.23 -> 0.1.24: download links for "v" tags, installers only for the supported systems, the app's own Jupyter kernel. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_24.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. #41, a release tagged v1.0.0 wrote download links to /releases/download/1.0.0/, which do not exist. The release workflow now exports the + tag as typed (RELEASE_TAG), and .tools/python/bump_version.py points the links to it; the installer names keep the bare version. + bump_version.py reads the tag from the environment, so a workflow without the new line, or an older bump_version.py, still works. +2. #42, every release built the four installers, also for systems an app cannot run on (TensorFlow 2.17+ on Intel Macs). The new + .tools/python/release_platforms.py reads `distribution.platforms` of labconstrictor-app.yaml: the release workflow builds only those + systems (a new `platforms` job writes the build matrix), and the download page has no button for the others. Without the key, + every system is built, as before. A build matrix that is not the template's (an app that removed a system by hand) is left as it is. +3. #43, a user-level "python3" kernelspec (`ipykernel install --user`) won over the app's own kernel, and the notebook ran in another + Python. app/python_scripts/launch_jupyter.py sets JUPYTER_PREFER_ENV_PATH=1 before JupyterLab starts. + +Rules this migration keeps: surgical (only the known blocks, one new file), 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 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_24.md" +TAG = "[migration 0.1.24]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_23_to_v0_1_24" + +BUMP_VERSION = Path(".tools/python/bump_version.py") +PLATFORMS_SCRIPT = Path(".tools/python/release_platforms.py") +RELEASE_WORKFLOW = Path(".github/workflows/release_constructor.yml") +LAUNCHER = Path("app/python_scripts/launch_jupyter.py") + +# -------------------------------------------------------------------------------------------------------------------------------- +# bump_version.py (#41 the tag in the links, #42 no button for a system that is not built): (0.1.23 text, 0.1.24 text), each once. +# -------------------------------------------------------------------------------------------------------------------------------- +BUMP_BLOCKS: tuple[tuple[str, str], ...] = ( + ("import argparse\nimport pathlib\n", "import argparse\nimport os\nimport pathlib\n"), + ( + '''def replace_version_placeholder(text: str, new_version: str) -> str: + """Render the release version in download documentation. + + Handles both pristine templates containing ``VERSION_NUMBER`` and + initialized repositories where that placeholder was already rendered to an + older explicit version such as ``0.0.0``. + """ + explicit_versions = set( + re.findall(r"/releases/download/(\\d+\\.\\d+\\.\\d+)/", text) + ) + + text = text.replace("VERSION_NUMBER", new_version) + for previous_version in explicit_versions: + text = text.replace(previous_version, new_version) + return text +''', + '''# The folder of a release in a download link: /releases/download// (the tag is 1.2.3 or v1.2.3). +DOWNLOAD_PATH_RE = re.compile(r"/releases/download/v?\\d+\\.\\d+\\.\\d+/") +# A button of the download page: +DOWNLOAD_BUTTON_RE = re.compile(r'\\s*]*>\\s*') +NOT_BUILT_NOTE = "> No installer is built for {label}: this app does not support it." + + +def replace_version_placeholder(text: str, new_version: str, tag: str | None = None) -> str: + """Render the release version in download documentation. + + Handles both pristine templates containing ``VERSION_NUMBER`` and + initialized repositories where that placeholder was already rendered to an + older explicit version such as ``0.0.0``. The links point to the release + tag as it was typed (``v1.2.3`` or ``1.2.3``); the installer names carry + the version without ``v`` (CellMigrationLab/LabConstrictor#41). + """ + explicit_versions = set( + re.findall(r"/releases/download/v?(\\d+\\.\\d+\\.\\d+)/", text) + ) + + text = text.replace("VERSION_NUMBER", new_version) + for previous_version in explicit_versions: + text = text.replace(previous_version, new_version) + return DOWNLOAD_PATH_RE.sub(f"/releases/download/{tag or new_version}/", text) + + +def drop_unbuilt_buttons(text: str, not_built: list[tuple[tuple[str, ...], str]]) -> str: + """Replace the download button of each system the release does not build with a note (CellMigrationLab/LabConstrictor#42). + + ``not_built`` holds (installer name endings, label) pairs, from release_platforms.py. The "or" between + two buttons goes when one of them became a note. + """ + if not not_built: + return text + + def _button(match: re.Match) -> str: + link = match.group(0).split('"', 2)[1] + for endings, label in not_built: + if link.endswith(endings): + return NOT_BUILT_NOTE.format(label=label) + return match.group(0) + + lines = DOWNLOAD_BUTTON_RE.sub(_button, text).split("\\n") + note_start = NOT_BUILT_NOTE.split("{", 1)[0] + kept = [] + for index, line in enumerate(lines): + if line.strip() == "or": + before = next((other for other in reversed(lines[:index]) if other.strip()), "") + after = next((other for other in lines[index + 1 :] if other.strip()), "") + if before.startswith(note_start) or after.startswith(note_start): + continue + kept.append(line) + return "\\n".join(kept) + + +def not_built_systems() -> list[tuple[tuple[str, ...], str]]: + """(installer name endings, label) of each system left out of distribution.platforms in labconstrictor-app.yaml.""" + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + import release_platforms + + return [(build.files, build.label) for build in release_platforms.skipped_builds(ROOT)] +''', + ), + ( + "def bump_version_in_download_executable_md(new_version: str) -> None:\n", + "def bump_version_in_download_executable_md(\n" + " new_version: str, tag: str | None = None, not_built: list[tuple[tuple[str, ...], str]] | None = None\n" + ") -> None:\n", + ), + ( + " updated_text = replace_version_placeholder(text, new_version)\n", + " updated_text = drop_unbuilt_buttons(replace_version_placeholder(text, new_version, tag), not_built or [])\n", + ), + ( + " args = parser.parse_args()\n", + """ parser.add_argument( + "--tag", + default=os.environ.get("RELEASE_TAG") or None, + help="The release tag the download links point to: 0.0.4 or v0.0.4 (default: $RELEASE_TAG, else the version)", + ) + args = parser.parse_args() +""", + ), + ( + ' sys.exit("Version must look like X.Y.Z")\n', + """ sys.exit("Version must look like X.Y.Z") + if args.tag and args.tag not in (args.new_version, f"v{args.new_version}"): + sys.exit(f"The release tag {args.tag} does not match the version {args.new_version} (expected {args.new_version} or v{args.new_version})") +""", + ), + ( + " # Update download_executable.md\n bump_version_in_download_executable_md(args.new_version)\n", + " # Update download_executable.md: the links point to the release tag, and a system that is not built has no button\n" + " bump_version_in_download_executable_md(args.new_version, args.tag, not_built_systems())\n", + ), +) + +# -------------------------------------------------------------------------------------------------------------------------------- +# release_constructor.yml +# -------------------------------------------------------------------------------------------------------------------------------- +# #41: both "Determine release version" steps strip the "v" of the tag; the tag as typed is exported first. +STRIP_LINE = re.compile(r'^(?P[ ]+)RAW="\$\{RAW#v\}"\n', re.MULTILINE) +TAG_LINES = ( + "{indent}# The tag as typed (v1.0.0 or 1.0.0): bump_version.py points the download links to it.\n" + '{indent}echo "RELEASE_TAG=$RAW" >> "$GITHUB_ENV"\n' +) +# #42: the build matrix of the template, replaced by the one the platforms job writes; the job goes right before the build job. +MATRIX_OLD = """ needs: bump-version + strategy: + fail-fast: false + matrix: + include: + - os_name: linux + runner: ubuntu-latest + - os_name: macos-arm64 + runner: macos-15 + - os_name: macos-intel + runner: macos-15-intel + - os_name: windows + runner: windows-latest +""" +MATRIX_NEW = """ needs: [bump-version, platforms] + strategy: + fail-fast: false + # One build per system of distribution.platforms in labconstrictor-app.yaml (every system without it), from the platforms job. + matrix: ${{ fromJSON(needs.platforms.outputs.matrix) }} +""" +BUILD_JOB = " build-installers:\n" +PLATFORMS_JOB = """ platforms: + name: Installers to build + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Read distribution.platforms of labconstrictor-app.yaml + id: matrix + run: python .tools/python/release_platforms.py --github-output "$GITHUB_OUTPUT" + +""" + +# -------------------------------------------------------------------------------------------------------------------------------- +# launch_jupyter.py (#43): the variable is set right before JupyterLab is imported, in run_jupyter(). +# -------------------------------------------------------------------------------------------------------------------------------- +LAUNCHER_ANCHOR = """ # Import only after configure_tls() has completed. Tornado creates SSL + # contexts during import on some versions. + from jupyterlab.labapp import main +""" +LAUNCHER_LINES = """ # The app's own kernel must win over a user-level "python3" kernelspec (`ipykernel install --user`), which Jupyter + # otherwise prefers: the notebook would run in another Python and fail with "No module named ". Set, not + # setdefault: a JUPYTER_PREFER_ENV_PATH=0 of the user would bring the problem back. + os.environ["JUPYTER_PREFER_ENV_PATH"] = "1" + +""" +LAUNCHER_BLOCK = (LAUNCHER_ANCHOR, LAUNCHER_LINES + LAUNCHER_ANCHOR) + + +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 apply_blocks(text_lf: str, blocks: tuple[tuple[str, str], ...]) -> str | None: + """The text with every block changed, or None when a 0.1.23 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 + + +def add_tag_lines(text_lf: str) -> tuple[str, int]: + """#41: export RELEASE_TAG before each `RAW="${RAW#v}"`; returns the text and how many were added.""" + return STRIP_LINE.subn(lambda m: TAG_LINES.format(indent=m.group("indent")) + m.group(0), text_lf) + + +def build_from_platforms(text_lf: str) -> str | None: + """#42: the platforms job and its matrix, or None when the build job or its matrix is not the template's.""" + if text_lf.count(MATRIX_OLD) != 1 or text_lf.count(BUILD_JOB) != 1: + return None + return text_lf.replace(BUILD_JOB, PLATFORMS_JOB + BUILD_JOB, 1).replace(MATRIX_OLD, MATRIX_NEW, 1) + + +def _blocks_step(helpers: Any, path: Path, blocks: tuple[tuple[str, str], ...], what: str) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + lf = text.replace("\r\n", "\n") + if all(new in lf for _, new in blocks): + return f"unchanged: already {what}" + new_lf = apply_blocks(lf, blocks) + if new_lf is None: + return f"SKIPPED: customised (a 0.1.23 block was not found), so it was left unchanged; apply the 0.1.24 change by hand, see {DOCS_URL}" + helpers.write_text(path, new_lf.replace("\n", newline)) + return f"updated: {what}" + + +def _create_platforms_script(helpers: Any, repo_root: Path) -> str: + path = repo_root / PLATFORMS_SCRIPT + new = (RESOURCE_ROOT / PLATFORMS_SCRIPT).read_text(encoding="utf-8") + if path.is_file(): + if helpers.read_text(path).replace("\r\n", "\n") == new: + return "already the 0.1.24 template file: unchanged" + return "SKIPPED: the repository has its own release_platforms.py, left as it is" + if not path.parent.is_dir(): + return "SKIPPED: the repository has no .tools/python folder (nothing was created)" + with path.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(new) + return "updated: created" + + +def _update_workflow(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + lf = text.replace("\r\n", "\n") + done, notes = [], [] + if "RELEASE_TAG=" in lf: + notes.append("already exports RELEASE_TAG") + else: + lf, count = add_tag_lines(lf) + if count: + done.append(f"exports RELEASE_TAG in {count} job(s)") + else: + notes.append(f'SKIPPED the release tag: no RAW="${{RAW#v}}" line (customised); the download links keep the bare version, see {DOCS_URL}') + if MATRIX_NEW in lf: + notes.append("already builds the systems of distribution.platforms") + else: + migrated = build_from_platforms(lf) + if migrated is None: + notes.append( + "SKIPPED the build matrix: it is not the template's four builds (customised), so it was left as it is; to build the systems of " + f"distribution.platforms instead, see {DOCS_URL}" + ) + else: + lf = migrated + done.append("builds the systems of distribution.platforms (new platforms job)") + if done: + helpers.write_text(path, lf.replace("\n", newline)) + return "updated: " + "; ".join(done + notes) + if any(note.startswith("SKIPPED") for note in notes): + return "; ".join(notes) + return "unchanged: " + "; ".join(notes) + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Release tag in the download links, installers for the systems of distribution.platforms, the app's own kernel (idempotent, surgical).""" + _ = context + helpers = _load("v0_1_9_to_v0_1_10.py", "template_sync_helpers_0_1_24") + changed = 0 + + def report(name: Path, step: Callable[[], str]) -> None: + nonlocal changed + if not (repo_root / name).is_file() and name != PLATFORMS_SCRIPT: + 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(PLATFORMS_SCRIPT, partial(_create_platforms_script, helpers, repo_root)) + report(BUMP_VERSION, partial(_blocks_step, helpers, repo_root / BUMP_VERSION, BUMP_BLOCKS, "points the download links to the release tag")) + report(RELEASE_WORKFLOW, partial(_update_workflow, helpers, repo_root / RELEASE_WORKFLOW)) + report(LAUNCHER, partial(_blocks_step, helpers, repo_root / LAUNCHER, (LAUNCHER_BLOCK,), "prefers the app's own Jupyter kernel")) + + 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_24_to_v0_1_25.py b/.template_sync/migrations/v0_1_24_to_v0_1_25.py new file mode 100644 index 0000000..cff1608 --- /dev/null +++ b/.template_sync/migrations/v0_1_24_to_v0_1_25.py @@ -0,0 +1,270 @@ +"""Template 0.1.24 -> 0.1.25: publish the app's Python code (src/) on PyPI at each release, off until the developer turns it on. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_25.md + +What this changes in an app repository (every step is independent, idempotent and never deletes anything): + +1. .github/workflows/publish_pypi.yml (new). At a published release it builds the package of src/ and uploads it to PyPI with trusted + publishing (no secret). Both jobs are skipped unless the repository variable PYPI_PUBLISH is "true" (PyPI) or "testpypi" (TestPyPI), + so nothing changes for an app that does not turn it on. It is NOT added to a repository that already uploads to PyPI with a + workflow of its own (NucleiSky): the package would be uploaded twice. The log says what to do instead. +2. .tools/python/pypi_package.py (new): the checks and the build the workflow runs (version not on the index yet, a package in src/, + the release version written into setup.py, name, version and dependencies of the built files). +3. setup.py, when it is still the template's (any name, version and Python series): the package needs what requirements.txt lists, + README.md is its description on PyPI, and the source repository is linked. MANIFEST.in (new) puts requirements.txt in the source + distribution. A setup.py changed by hand is left as it is (it still builds; the workflow uses it as it is). +4. .tools/python/bump_version.py: the release also writes its version into setup.py (it never did). + +Rules this migration keeps: surgical (only the known blocks, the known setup.py, new files), 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 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_25.md" +TAG = "[migration 0.1.25]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_24_to_v0_1_25" + +WORKFLOW = Path(".github/workflows/publish_pypi.yml") +PACKAGE_SCRIPT = Path(".tools/python/pypi_package.py") +SETUP = Path("setup.py") +MANIFEST_IN = Path("MANIFEST.in") +BUMP_VERSION = Path(".tools/python/bump_version.py") +NEW_FILES = (WORKFLOW, PACKAGE_SCRIPT, MANIFEST_IN) + +# Text in a workflow that uploads to PyPI (as in .tools/python/pypi_package.py). +PUBLISH_MARKERS = ("pypa/gh-action-pypi-publish", "twine upload") + +# -------------------------------------------------------------------------------------------------------------------------------- +# setup.py of the template up to 0.1.24; the form (and merge_requirements.py) fill in the three placeholders. +# -------------------------------------------------------------------------------------------------------------------------------- +OLD_SETUP = """from setuptools import setup, find_packages + +setup( + name="PYTHON_PROJ_NAME", + version="VERSION_NUMBER", + package_dir={"": "src"}, + packages=find_packages(where="src"), + python_requires=">=PYTHON_VERSION", + install_requires=[ + ], +) +""" +SETUP_FIELDS = (("PYTHON_PROJ_NAME", "name"), ("VERSION_NUMBER", "version"), ("PYTHON_VERSION", "python")) +REQUIRED_LINE = "include requirements.txt" + +# -------------------------------------------------------------------------------------------------------------------------------- +# bump_version.py: (0.1.24 text, 0.1.25 text), each once. +# -------------------------------------------------------------------------------------------------------------------------------- +BUMP_BLOCKS: tuple[tuple[str, str], ...] = ( + ( + 'POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat"\n', + 'POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat"\n' + "# version=\"1.2.3\" in setup.py: the version of the app's Python package (src/)\n" + 'SETUP = ROOT / "setup.py"\n' + 'SETUP_VERSION_RE = re.compile(r"^(?P[ \\t]*version\\s*=\\s*)(?P[\\"\'])\\d+\\.\\d+\\.\\d+(?P=quote)", re.MULTILINE)\n', + ), + ( + ' print(f"Updated post_install.bat PKG_VERSION to {new_version}")\n', + ''' print(f"Updated post_install.bat PKG_VERSION to {new_version}") + + +def bump_setup_py(new_version: str) -> None: + """The version of the app's Python package in setup.py, when it is written there as X.Y.Z. + + The package in the installer and the one publish_pypi.yml publishes on PyPI then carry the release version. The line + endings of the file are kept. + """ + if not SETUP.exists(): + return + with SETUP.open(encoding="utf-8", newline="") as handle: + text = handle.read() + updated = SETUP_VERSION_RE.sub(lambda m: f"{m.group('head')}{m.group('quote')}{new_version}{m.group('quote')}", text, count=1) + if updated != text: + with SETUP.open("w", encoding="utf-8", newline="") as handle: + handle.write(updated) + print(f"Updated setup.py version to {new_version}") +''', + ), + ( + " # Also bump PKG_VERSION in post_install.bat\n bump_post_install_bat(args.new_version)\n", + " # Also bump PKG_VERSION in post_install.bat\n bump_post_install_bat(args.new_version)\n\n" + " # The version of the app's Python package (setup.py), also the version publish_pypi.yml publishes on PyPI\n" + " bump_setup_py(args.new_version)\n", + ), +) + + +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 resource(relative: Path) -> str: + return (RESOURCE_ROOT / relative).read_text(encoding="utf-8") + + +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.24 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 + + +def setup_pattern(template: str) -> re.Pattern[str]: + """A template setup.py as a pattern: each placeholder is the value the form (or merge_requirements.py) wrote, or the placeholder.""" + pattern = re.escape(template.rstrip()) + for placeholder, group in SETUP_FIELDS: + pattern = pattern.replace(re.escape(placeholder), f'(?P<{group}>[^"\\n]*)', 1) + return re.compile(pattern) + + +def setup_values(text_lf: str, template: str) -> dict[str, str] | None: + """The name, version and Python series of a setup.py that is the given template text with its placeholders filled in, else None.""" + match = setup_pattern(template).fullmatch(text_lf.rstrip()) + return match.groupdict() if match else None + + +def render_setup(template: str, values: dict[str, str]) -> str: + for placeholder, group in SETUP_FIELDS: + template = template.replace(placeholder, values[group], 1) + return template + + +def other_publishers(repo_root: Path) -> list[str]: + """The workflows of the repository, other than publish_pypi.yml, that upload to PyPI.""" + folder = repo_root / WORKFLOW.parent + found = [] + for path in sorted(folder.glob("*.y*ml")) if folder.is_dir() else []: + if path.name != WORKFLOW.name and any(marker in path.read_text(encoding="utf-8", errors="replace") for marker in PUBLISH_MARKERS): + found.append(path.relative_to(repo_root).as_posix()) + return found + + +def _create(helpers: Any, repo_root: Path, relative: Path, what: str) -> str: + """Create a new file from the resource (LF); a different file of the repository at that place is kept.""" + path = repo_root / relative + new = resource(relative) + if path.is_file(): + if helpers.read_text(path).replace("\r\n", "\n") == new: + return "unchanged: already the 0.1.25 template file" + return f"SKIPPED: the repository has its own {relative.name}, left as it is; {what}" + if not path.parent.is_dir(): + return f"SKIPPED: the repository has no {relative.parent.as_posix()} folder (nothing was created)" + with path.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(new) + return "updated: created" + + +def _create_workflow(helpers: Any, repo_root: Path) -> str: + others = other_publishers(repo_root) + if others and not (repo_root / WORKFLOW).is_file(): + return ( + f"SKIPPED: {', '.join(others)} already uploads to PyPI, so the template's publish_pypi.yml was not added (the package would be " + "uploaded twice). Nothing to do to keep publishing that way. To publish with the template's workflow instead (at each release, " + f"with the release version): delete your workflow, add publish_pypi.yml by hand and register it on pypi.org, see {DOCS_URL}" + ) + return _create( + helpers, repo_root, WORKFLOW, "to publish the package at each release, compare it with the template's publish_pypi.yml, see " + DOCS_URL + ) + + +def _update_setup(helpers: Any, repo_root: Path) -> str: + path = repo_root / SETUP + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + lf = text.replace("\r\n", "\n") + new_template = resource(SETUP) + if setup_values(lf, new_template) is not None: + return "unchanged: already reads its dependencies from requirements.txt and its description from README.md" + values = setup_values(lf, OLD_SETUP) + if values is None: + return ( + "SKIPPED: not the template's setup.py (changed by hand, or the package is described in pyproject.toml), left as it is. It is " + f"published as it is if you turn on PyPI publishing: check its dependencies and description, see {DOCS_URL}" + ) + helpers.write_text(path, render_setup(new_template, values).replace("\n", newline)) + return f"updated: {values['name']} now needs what requirements.txt lists and has README.md as its description" + + +def _create_manifest_in(helpers: Any, repo_root: Path) -> str: + path = repo_root / MANIFEST_IN + setup = repo_root / SETUP + reads_requirements = setup.is_file() and setup_values(helpers.read_text(setup).replace("\r\n", "\n"), resource(SETUP)) is not None + if path.is_file(): + if REQUIRED_LINE in helpers.read_text(path).replace("\r\n", "\n").splitlines(): + return "unchanged: already puts requirements.txt in the source distribution" + if reads_requirements: + return f"SKIPPED: the repository has its own MANIFEST.in, left as it is; add the line `{REQUIRED_LINE}` to it, see {DOCS_URL}" + return "unchanged: the repository's own MANIFEST.in" + if not reads_requirements: + return "unchanged: not needed (setup.py is not the template's, so it does not read requirements.txt)" + return _create(helpers, repo_root, MANIFEST_IN, "") + + +def _update_bump_version(helpers: Any, path: Path) -> str: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + lf = text.replace("\r\n", "\n") + if all(new in lf for _, new in BUMP_BLOCKS): + return "unchanged: already writes the release version into setup.py" + new_lf = apply_blocks(lf, BUMP_BLOCKS) + if new_lf is None: + return ( + "SKIPPED: customised (a 0.1.24 block was not found), so it was left unchanged; the release version does not reach setup.py " + f"(publish_pypi.yml writes it in its own copy anyway), see {DOCS_URL}" + ) + helpers.write_text(path, new_lf.replace("\n", newline)) + return "updated: the release also writes its version into setup.py" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Opt-in PyPI publishing of the package in src/: a new workflow and script, setup.py and bump_version.py (idempotent, surgical).""" + _ = context + helpers = _load("v0_1_9_to_v0_1_10.py", "template_sync_helpers_0_1_25") + changed = 0 + + def report(name: Path, step: Callable[[], str]) -> None: + nonlocal changed + if name not in NEW_FILES 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(PACKAGE_SCRIPT, partial(_create, helpers, repo_root, PACKAGE_SCRIPT, "publish_pypi.yml runs the template's, compare them")) + report(WORKFLOW, partial(_create_workflow, helpers, repo_root)) + report(SETUP, partial(_update_setup, helpers, repo_root)) + report(MANIFEST_IN, partial(_create_manifest_in, helpers, repo_root)) + report(BUMP_VERSION, partial(_update_bump_version, helpers, repo_root / BUMP_VERSION)) + + if changed: + log( + f"done: {changed} file(s) changed. Nothing is published until you turn it on (the repository variable PYPI_PUBLISH and a trusted " + f"publisher on pypi.org), see {DOCS_URL}" + ) + else: + log("done: no repository changes were required.") diff --git a/.template_sync/migrations/v0_1_25_to_v0_1_26.py b/.template_sync/migrations/v0_1_25_to_v0_1_26.py new file mode 100644 index 0000000..b4e621b --- /dev/null +++ b/.template_sync/migrations/v0_1_25_to_v0_1_26.py @@ -0,0 +1,134 @@ +"""Template 0.1.25 -> 0.1.26: the app's own documentation explains PyPI publishing (added in 0.1.25). + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_26.md + +The 0.1.25 migration added publish_pypi.yml and pypi_package.py but left the app's documentation as it was, so the one-time setup was +described only in the template's documentation. What this changes in an app repository (each step is independent, idempotent and never +deletes anything): + +1. .tools/docs/external_code_upload.md: the section "4. Publish the code on PyPI (optional)" of the template. A page with a section 4 + of its own is left as it is. +2. .tools/docs/troubleshooting.md: the entry "Publishing to PyPI fails" of the template. + +Each text goes at the end of the page's content, before its Previous / Home / Next links, which stay the last thing on the page (they are +moved there if text followed them). A page without these links gets the text at its end. + +Both texts are the template's, byte for byte (.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/): they have no placeholder, +and they link to the design note of 0.1.25 by its address, so every link works in an app. The line endings of each file are kept. +""" +from __future__ import annotations + +import importlib.util +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_26.md" +TAG = "[migration 0.1.26]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_25_to_v0_1_26" + +EXTERNAL_CODE_PAGE = Path(".tools/docs/external_code_upload.md") +TROUBLESHOOTING_PAGE = Path(".tools/docs/troubleshooting.md") +PYPI_SECTION = Path(".tools/docs/external_code_upload_pypi.md") +PYPI_TROUBLESHOOTING = Path(".tools/docs/troubleshooting_pypi.md") + +SECTION_HEADING = "## 4. Publish the code on PyPI (optional)" +TROUBLESHOOTING_HEADING = "## Publishing to PyPI fails" +# A section 4 of the app's own (the template's page has sections 1 to 3 before 0.1.26). +OWN_SECTION_4 = re.compile(r"^##[ \t]+4\.", re.MULTILINE) +# The Previous / Home / Next links at the bottom of a documentation page: a "---" line, then
...
. +FOOTER = re.compile(r'^---[ \t]*\n(?:[ \t]*\n)*
.*?
[ \t]*(?:\n|$)', re.MULTILINE | re.DOTALL) + + +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 resource(relative: Path) -> str: + return (RESOURCE_ROOT / relative).read_text(encoding="utf-8") + + +def has_line(text_lf: str, line: str) -> bool: + return line in (candidate.rstrip() for candidate in text_lf.split("\n")) + + +def add_section(text_lf: str, section: str) -> str: + """The page with the section at the end of its content, then its Previous / Home / Next links (always last), if it has them.""" + footers = list(FOOTER.finditer(text_lf)) + if not footers: + return text_lf.rstrip("\n") + "\n\n" + section + footer = footers[-1] + before, after = text_lf[: footer.start()].rstrip("\n"), text_lf[footer.end():].strip("\n") + content = f"{before}\n\n{after}" if after else before + return content + "\n\n" + section + "\n" + footer.group(0).rstrip("\n") + "\n" + + +def _update(helpers: Any, path: Path, change: Callable[[str], str]) -> None: + text = helpers.read_text(path) + newline = "\r\n" if "\r\n" in text else "\n" + helpers.write_text(path, change(text.replace("\r\n", "\n")).replace("\n", newline)) + + +def _external_code_page(helpers: Any, path: Path) -> str: + lf = helpers.read_text(path).replace("\r\n", "\n") + if has_line(lf, SECTION_HEADING): + return "unchanged: already explains PyPI publishing" + if OWN_SECTION_4.search(lf): + return ( + "SKIPPED: the page has a section 4 of its own, left as it is; the PyPI section is in the template's page " + f"(.tools/docs/external_code_upload.md), see {DOCS_URL}" + ) + section = resource(PYPI_SECTION) + _update(helpers, path, lambda text: add_section(text, section)) + return "updated: added the section 4. Publish the code on PyPI (optional)" + + +def _troubleshooting_page(helpers: Any, path: Path) -> str: + lf = helpers.read_text(path).replace("\r\n", "\n") + if has_line(lf, TROUBLESHOOTING_HEADING): + return "unchanged: already has the entry Publishing to PyPI fails" + entry = resource(PYPI_TROUBLESHOOTING) + _update(helpers, path, lambda text: add_section(text, entry)) + return "updated: added the entry Publishing to PyPI fails" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """The PyPI section of external_code_upload.md and the PyPI entry of troubleshooting.md (idempotent, surgical).""" + _ = context + helpers = _load("v0_1_9_to_v0_1_10.py", "template_sync_helpers_0_1_26") + changed = 0 + + def report(name: Path, step: Callable[[Path], str]) -> None: + nonlocal changed + path = repo_root / name + if not path.is_file(): + log(f"{name}: not present in this repository (nothing was created)") + return + try: + status = step(path) + 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(EXTERNAL_CODE_PAGE, partial(_external_code_page, helpers)) + report(TROUBLESHOOTING_PAGE, partial(_troubleshooting_page, helpers)) + + if changed: + log(f"done: {changed} file(s) changed (documentation only). See {DOCS_URL}") + else: + log("done: no repository changes were required.") 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_2_to_v0_1_3.py b/.template_sync/migrations/v0_1_2_to_v0_1_3.py new file mode 100644 index 0000000..9edb02b --- /dev/null +++ b/.template_sync/migrations/v0_1_2_to_v0_1_3.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import json + +from pathlib import Path +from typing import Any + + +WELCOME_TEMPLATE_PATH = Path(".tools/templates/Welcome_template.ipynb") +WELCOME_NOTEBOOK_PATH = Path("app/menuinst/Welcome.ipynb") + +OLD_NOTEBOOK_URL = ( + 'f"https://api.github.com/repos/{github_owner}/{github_repo_name}' + '/contents/notebooks/{main_folder}/{subfolder}/{subfolder}.ipynb' + '?ref={github_branch}"' +) +NEW_NOTEBOOK_URL = ( + 'f"https://api.github.com/repos/{github_owner}/{github_repo_name}' + '/contents/notebooks/{main_folder}/{subfolder}.ipynb' + '?ref={github_branch}"' +) + + +def update_notebook_url(repo_root: Path, relative_path: Path) -> bool: + path = repo_root / relative_path + if not path.exists(): + print(f"Skipping missing file: {relative_path}") + return False + + original_text = path.read_text(encoding="utf-8") + try: + notebook = json.loads(original_text) + except json.JSONDecodeError as exc: + raise ValueError(f"Unable to parse {relative_path} as JSON") from exc + + changed = False + found_current = False + for cell in notebook.get("cells", []): + source = cell.get("source", []) + source_is_list = isinstance(source, list) + lines = source if source_is_list else [str(source)] + updated_lines = [] + cell_changed = False + + for line in lines: + if OLD_NOTEBOOK_URL in line: + line = line.replace(OLD_NOTEBOOK_URL, NEW_NOTEBOOK_URL, 1) + changed = True + cell_changed = True + if NEW_NOTEBOOK_URL in line: + found_current = True + updated_lines.append(line) + + if cell_changed: + cell["source"] = updated_lines if source_is_list else updated_lines[0] + + if not changed: + if found_current: + return False + print(f"Skipping {relative_path}: no legacy notebook URL was found") + return False + + newline = "\r\n" if "\r\n" in original_text else "\n" + rendered = json.dumps(notebook, ensure_ascii=False, indent=1) + if original_text.endswith(("\n", "\r\n")): + rendered += newline + path.write_text(rendered, encoding="utf-8", newline="") + print(f"Updated {relative_path}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_notebook_url(repo_root, WELCOME_TEMPLATE_PATH) or changed_any + changed_any = update_notebook_url(repo_root, WELCOME_NOTEBOOK_PATH) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") 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_3_to_v0_1_4.py b/.template_sync/migrations/v0_1_3_to_v0_1_4.py new file mode 100644 index 0000000..6941fbb --- /dev/null +++ b/.template_sync/migrations/v0_1_3_to_v0_1_4.py @@ -0,0 +1,323 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +BUMP_CONSTRUCTOR_PATH = Path(".tools/python/bump_constructor.py") +BUMP_VERSION_PATH = Path(".tools/python/bump_version.py") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def replace_text( + text: str, + old: str, + new: str, + *, + already_updated: str | None = None, +) -> tuple[str, bool]: + if old in text: + return text.replace(old, new, 1), True + + if already_updated and already_updated in text: + return text, False + + raise ValueError("Unable to find expected text to replace") + + +def update_bump_constructor(repo_root: Path) -> bool: + path = repo_root / BUMP_CONSTRUCTOR_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_CONSTRUCTOR_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + updated_text = original_text + changed = False + + old_src_filter = newline.join( + [ + ' if not rel.startswith("src/"):', + " continue", + ] + ) + new_src_filter = newline.join( + [ + " # Avoid any python files that are not in the src/ directory or any __init__.py files that are not in the src/ directory ", + ' if not rel.startswith("src/") or py_file.name == "__init__.py":', + " continue", + ] + ) + # Later template versions deliberately include __init__.py files and track + # whether they are the only source files. Treat that feature as newer than + # this migration instead of rewriting it back to the 0.1.4 intermediate form. + if "only_init_files = True" not in updated_text: + updated_text, did_change = replace_text( + updated_text, + old_src_filter, + new_src_filter, + already_updated=new_src_filter, + ) + changed = did_change or changed + + old_setup_cleanup_anchor = newline.join( + [ + " normalized_items.append({src: dst})", + " included_src_flag = True", + " src_added += 1", + "", + " if included_src_flag:", + ] + ) + new_setup_cleanup_anchor = newline.join( + [ + " normalized_items.append({src: dst})", + " included_src_flag = True", + " src_added += 1", + "", + " # For safety also remove setup.py and src_change.yaml if they exist in the extra_files to avoid duplicates, we will re-add them with correct paths if src/ is included", + ' normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src) in ["setup.py", ".tools/meta/src_change.yaml"] for src in item.keys()))] ', + "", + " if included_src_flag:", + ] + ) + cleanup_feature = 'any(str(src) in ["setup.py", ".tools/meta/src_change.yaml"]' + if cleanup_feature not in updated_text: + updated_text, did_change = replace_text( + updated_text, + old_setup_cleanup_anchor, + new_setup_cleanup_anchor, + already_updated=new_setup_cleanup_anchor, + ) + changed = did_change or changed + + old_else_anchor = newline.join( + [ + " if Path(src_change_file).exists():", + ' src_change_dst = f"{project_folder}/src_change.yaml"', + " if src_change_file not in existing_sources and src_change_dst not in existing_dests:", + " normalized_items.append({src_change_file: src_change_dst})", + " src_added += 1", + "", + " # Optionally sort entries (dicts by their single key) for determinism", + ] + ) + new_else_anchor = newline.join( + [ + " if Path(src_change_file).exists():", + ' src_change_dst = f"{project_folder}/src_change.yaml"', + " if src_change_file not in existing_sources and src_change_dst not in existing_dests:", + " normalized_items.append({src_change_file: src_change_dst})", + " src_added += 1", + " else:", + " # If the user has removed the src/directory, remove the generated setup.py and src_change.yaml", + ' setup_dst = Path(project_folder) / "setup.py"', + " if setup_dst.exists():", + " setup_dst.unlink()", + ' src_change_dst = Path(project_folder) / "src_change.yaml"', + " if src_change_dst.exists():", + " src_change_dst.unlink()", + "", + " # Optionally sort entries (dicts by their single key) for determinism", + ] + ) + removal_feature = 'setup_dst = Path(project_folder) / "setup.py"' + if removal_feature not in updated_text: + updated_text, did_change = replace_text( + updated_text, + old_else_anchor, + new_else_anchor, + already_updated=new_else_anchor, + ) + changed = did_change or changed + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {BUMP_CONSTRUCTOR_PATH}") + return True + + +def update_bump_version(repo_root: Path) -> bool: + path = repo_root / BUMP_VERSION_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_VERSION_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + updated_text = original_text + changed = False + + old_helper_anchor = 'POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat"' + newline + newline + new_helper_anchor = newline.join( + [ + 'POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat"', + "", + "def replace_version_placeholder(text: str, new_version: str) -> str:", + ' """ Replace version placeholders \'VERSION_NUMBER\' in the text with the new version."""', + ' return text.replace("VERSION_NUMBER", new_version)', + "", + ] + ) + helper_signature = "def replace_version_placeholder(text: str, new_version: str) -> str:" + if helper_signature not in updated_text: + if old_helper_anchor not in updated_text: + raise ValueError(f"Unable to find helper insertion point in {BUMP_VERSION_PATH}") + updated_text = updated_text.replace(old_helper_anchor, new_helper_anchor, 1) + changed = True + + old_download_function = newline.join( + [ + "def bump_version_in_download_executable_md(new_version: str) -> None:", + ' download_md = ROOT / "docs" / "download_executable.md"', + " if not download_md.exists():", + " return", + " # This file may contain the version in various formats, so we use the flexible replacement function", + " if replace_version_in_file(download_md, new_version, new_version):", + ' print(f"Updated download_executable.md to version {new_version}")', + " else:", + ' print("No version string found in download_executable.md to update.")', + ] + ) + new_download_function = newline.join( + [ + "def bump_version_in_download_executable_md(new_version: str) -> None:", + ' download_md = ROOT / "docs" / "download_executable.md"', + ' template_md = ROOT / ".tools" / "templates" / "download_executable_template.md"', + "", + " # On the first release replace download_executable.md with the template", + " # (but only if it exists)", + " if template_md.exists():", + " # Remove existing download_executable.md if present", + " if download_md.exists():", + " download_md.unlink()", + " # Copy the template to the docs folder using shutil for cross-platform support", + " shutil.copy(template_md, download_md)", + " else:", + ' print("Template for download_executable.md not found! Skipping creation of download_executable.md")', + " return", + " ", + " # This file contains placeholders, update them with the new version", + ' text = download_md.read_text(encoding="utf-8")', + " updated_text = replace_version_placeholder(text, new_version)", + " if updated_text != text:", + ' download_md.write_text(updated_text, encoding="utf-8")', + ' print(f"Updated download_executable.md to version {new_version}")', + " else:", + ' print("No version string found in download_executable.md to update.")', + ] + ) + if old_download_function in updated_text: + updated_text = updated_text.replace(old_download_function, new_download_function, 1) + changed = True + elif ' template_md = ROOT / ".tools" / "templates" / "download_executable_template.md"' not in updated_text: + # Early initialized repositories did not yet have this helper at all. + main_anchor = "def main() -> None:" + if main_anchor not in updated_text: + raise ValueError(f"Unable to find main() insertion point in {BUMP_VERSION_PATH}") + updated_text = updated_text.replace( + main_anchor, + new_download_function + newline + newline + main_anchor, + 1, + ) + changed = True + + old_main_template_copy = newline.join( + [ + " # On the first release replace download_executable.md with the template", + " # (but only if it exists)", + ' if pathlib.Path(".tools/templates/download_executable_template.md").exists():', + " # Remove existing download_executable.md if present", + ' if pathlib.Path(".tools/docs/download_executable.md").exists():', + ' pathlib.Path(".tools/docs/download_executable.md").unlink()', + " # Copy the template to the docs folder using shutil for cross-platform support", + " shutil.copy(", + ' ".tools/templates/download_executable_template.md",', + ' ".tools/docs/download_executable.md",', + " )", + "", + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_main_template_copy, + "", + already_updated=" text, current = read_current_version()", + ) + changed = did_change or changed + + extra_blank_line = ( + ' sys.exit("Version must look like X.Y.Z")' + + newline + + newline + + newline + + " text, current = read_current_version()" + ) + normalized_spacing = ( + ' sys.exit("Version must look like X.Y.Z")' + + newline + + newline + + " text, current = read_current_version()" + ) + if extra_blank_line in updated_text: + updated_text = updated_text.replace(extra_blank_line, normalized_spacing, 1) + changed = True + + old_download_comment = " # Update download_executable.md if it exists" + new_download_block = newline.join( + [ + " # Update download_executable.md", + " bump_version_in_download_executable_md(args.new_version)", + ] + ) + if old_download_comment in updated_text: + updated_text = updated_text.replace( + old_download_comment, + " # Update download_executable.md", + 1, + ) + changed = True + elif "bump_version_in_download_executable_md(args.new_version)" not in updated_text: + post_install_call = " bump_post_install_bat(args.new_version)" + if post_install_call not in updated_text: + raise ValueError(f"Unable to find post-install call in {BUMP_VERSION_PATH}") + updated_text = updated_text.replace( + post_install_call, + post_install_call + newline + newline + new_download_block, + 1, + ) + changed = True + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {BUMP_VERSION_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_bump_constructor(repo_root) or changed_any + changed_any = update_bump_version(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_4_to_v0_1_5.py b/.template_sync/migrations/v0_1_4_to_v0_1_5.py new file mode 100644 index 0000000..b16961b --- /dev/null +++ b/.template_sync/migrations/v0_1_4_to_v0_1_5.py @@ -0,0 +1,638 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any +import re + + +MERGE_REQUIREMENTS_PATH = Path(".tools/python/merge_requirements.py") +BUMP_CONSTRUCTOR_PATH = Path(".tools/python/bump_constructor.py") +POST_INSTALL_BAT_PATH = Path("app/bash_bat_scripts/post_install.bat") +POST_INSTALL_SH_PATH = Path("app/bash_bat_scripts/post_install.sh") +CONSTRUCT_PATH = Path("construct.yaml") +REQUIREMENTS_GPU_PATH = Path("requirements_gpu.txt") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def detect_project_folder(repo_root: Path) -> str: + construct_path = repo_root / CONSTRUCT_PATH + if construct_path.is_file(): + for raw_line in read_text(construct_path).splitlines(): + stripped = raw_line.strip() + if stripped.startswith("name:"): + value = stripped.split(":", 1)[1].strip().strip("\"'") + if value: + return value + + return "PROJECT_NAME" + + +def replace_text( + text: str, + old: str, + new: str, + *, + already_updated: str | None = None, +) -> tuple[str, bool]: + if old in text: + return text.replace(old, new, 1), True + + if already_updated and already_updated in text: + return text, False + + raise ValueError("Unable to find expected text to replace") + + +def update_merge_requirements(repo_root: Path) -> bool: + path = repo_root / MERGE_REQUIREMENTS_PATH + if not path.exists(): + print(f"Skipping missing file: {MERGE_REQUIREMENTS_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + updated_text = original_text + changed = False + + old_doc = newline.join( + [ + "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.", + "", + "It resolves simple version conflicts by choosing the newest version seen for a", + ] + ) + new_doc = newline.join( + [ + "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]` 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", + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_doc, + new_doc, + already_updated="GPU file rewrites `tensorflow` to `tensorflow[and-cuda]`", + ) + changed = did_change or changed + + old_constants = newline.join( + [ + 'OS_DISPLAY_NAMES = {', + ' "windows": "Windows",', + ' "linux": "Linux",', + ' "macos": "macOS",', + "}", + ] + ) + new_constants = newline.join( + [ + '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*;.*)?$"', + ")", + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_constants, + new_constants, + already_updated='GPU_DISPLAY_NAME = "NVIDIA GPU"', + ) + changed = did_change or changed + + old_helper_block = newline.join( + [ + "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 write_requirements_output(path: Path, files: list[Path], final_lines: list[str], target_os: str | None = None):", + ] + ) + new_helper_block = newline.join( + [ + "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", + "", + "", + "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 == "tensorflow":', + " line = rewrite_tensorflow_for_gpu(line)", + " if package_name in TORCH_GPU_PACKAGES:", + " has_torch_package = True", + "", + " 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,", + "):", + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_helper_block, + new_helper_block, + already_updated="def get_gpu_output_path(output: Path) -> Path:", + ) + changed = did_change or changed + + old_header_block = newline.join( + [ + " if target_os:", + ' header_lines.append(f"# Target OS: {OS_DISPLAY_NAMES.get(target_os, target_os.capitalize())}")', + ' header_lines.append("# ---")', + ] + ) + new_header_block = newline.join( + [ + " 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("# ---")', + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_header_block, + new_header_block, + already_updated=' header_lines.append(f"# Target accelerator: {target_accelerator}")', + ) + changed = did_change or changed + + updated_text, did_change = replace_text( + updated_text, + " skip_outputs = {output.resolve()}", + " skip_outputs = {output.resolve()}" + newline + " skip_outputs.add(get_gpu_output_path(output).resolve())", + already_updated=" skip_outputs.add(get_gpu_output_path(output).resolve())", + ) + changed = did_change or changed + + old_no_files = newline.join( + [ + ' print(f"No requirements files found under {source}, writing empty {output}")', + ' output.write_text("# Generated requirements (none found)\\n", encoding="utf-8")', + " return 0", + ] + ) + new_no_files = newline.join( + [ + ' 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", + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_no_files, + new_no_files, + already_updated=' gpu_output.write_text("# Generated GPU requirements (none found)\\n", encoding="utf-8")', + ) + changed = did_change or changed + + old_gpu_write_block = newline.join( + [ + " 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)")', + "", + " for os_name, ctx in os_contexts.items():", + ] + ) + new_gpu_write_block = newline.join( + [ + " 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():", + ] + ) + updated_text, did_change = replace_text( + updated_text, + old_gpu_write_block, + new_gpu_write_block, + already_updated=" gpu_output = get_gpu_output_path(output)", + ) + changed = did_change or changed + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {MERGE_REQUIREMENTS_PATH}") + return True + + +def update_bump_constructor(repo_root: Path) -> bool: + path = repo_root / BUMP_CONSTRUCTOR_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_CONSTRUCTOR_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + if ' isinstance(item, dict) and "requirements_gpu.txt" in item for item in extra_files' in original_text: + return False + + lines = original_text.splitlines(keepends=True) + project_folder = detect_project_folder(repo_root) + gpu_block = ( + newline.join( + [ + " gpu_requirements_included = any(", + ' isinstance(item, dict) and "requirements_gpu.txt" in item for item in extra_files', + " )", + ' if not gpu_requirements_included and Path("requirements_gpu.txt").exists():', + f' extra_files.append({{"requirements_gpu.txt": "{project_folder}/requirements_gpu.txt"}})', + ] + ) + + newline + ) + func_start = None + func_end = len(lines) + for index, line in enumerate(lines): + stripped = line.strip() + if stripped.startswith("def ensure_requirements_in_extra_files("): + func_start = index + continue + if func_start is not None and stripped.startswith("def ") and not line.startswith((" ", "\t")): + func_end = index + break + + if func_start is None: + raise ValueError(f"Unable to find ensure_requirements_in_extra_files() in {BUMP_CONSTRUCTOR_PATH}") + + insert_at = None + candidate_prefixes = ( + "# Check if requirements-linux.txt", + '# Check if requirements-windows.txt', + '# Check if requirements-macos.txt', + 'if Path("requirements-linux.txt").exists():', + "if Path('requirements-linux.txt').exists():", + 'if Path("requirements-windows.txt").exists():', + "if Path('requirements-windows.txt').exists():", + 'if Path("requirements-macos.txt").exists():', + "if Path('requirements-macos.txt').exists():", + '# Update the construct data with the modified extra_files', + 'construct_data["extra_files"] = extra_files', + "construct_data['extra_files'] = extra_files", + ) + + for index in range(func_start + 1, func_end): + stripped = lines[index].strip() + if stripped.startswith(candidate_prefixes): + insert_at = index + break + + if insert_at is None: + requirements_append_re = re.compile( + r"extra_files\.append\(\{['\"]requirements\.txt['\"]:\s*['\"].*requirements\.txt['\"]\}\)" + ) + for index in range(func_start + 1, func_end): + if requirements_append_re.search(lines[index]): + insert_at = index + 1 + while insert_at < func_end and lines[insert_at].strip() == "": + insert_at += 1 + break + + if insert_at is None: + insert_at = func_end + while insert_at > func_start + 1 and lines[insert_at - 1].strip() == "": + insert_at -= 1 + + lines.insert(insert_at, newline) + lines.insert(insert_at, gpu_block) + updated_text = "".join(lines) + write_text(path, updated_text) + print(f"Updated {BUMP_CONSTRUCTOR_PATH}") + return True + + +def update_post_install_bat(repo_root: Path) -> bool: + path = repo_root / POST_INSTALL_BAT_PATH + if not path.exists(): + print(f"Skipping missing file: {POST_INSTALL_BAT_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + lines = original_text.splitlines(keepends=True) + changed = False + + project_folder = detect_project_folder(repo_root) + gpu_requirements_line = f'SET "GPU_REQUIREMENTS=%PREFIX%\\{project_folder}\\requirements_gpu.txt"' + if gpu_requirements_line not in original_text: + echo_line = 'echo Running post_install > "%PREFIX%\\menuinst_debug.log"' + selected_install_line = '"%PREFIX%\\python.exe" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"' + block_lines = [ + f'SET "BASE_REQUIREMENTS=%PREFIX%\\{project_folder}\\requirements.txt"', + gpu_requirements_line, + 'SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%"', + "", + 'IF EXIST "%GPU_REQUIREMENTS%" (', + " where nvidia-smi >NUL 2>&1", + " IF ERRORLEVEL 1 (", + ' echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + " ) ELSE (", + ' echo NVIDIA GPU detected, installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + ' SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%"', + " )", + ") ELSE (", + ' echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + ")", + "", + ] + + if not any(line.rstrip("\r\n") == "SETLOCAL" for line in lines): + for index, line in enumerate(lines): + if line.rstrip("\r\n") == "@ECHO OFF": + lines.insert(index + 1, "SETLOCAL" + newline) + changed = True + break + + echo_index = None + install_index = None + for index, line in enumerate(lines): + stripped = line.rstrip("\r\n") + if stripped == echo_line: + echo_index = index + if ( + stripped.startswith('"%PREFIX%\\python.exe" -m pip install -r ') + and "requirements.txt" in stripped + and "requirements-windows.txt" not in stripped + and "%SELECTED_REQUIREMENTS%" not in stripped + ): + install_index = index + break + + if echo_index is None or install_index is None: + raise ValueError(f"Unable to find insertion point in {POST_INSTALL_BAT_PATH}") + + insertion = [entry + newline for entry in block_lines] + for offset, entry in enumerate(insertion, start=1): + lines.insert(echo_index + offset, entry) + changed = True + + install_index += len(insertion) + lines[install_index] = selected_install_line + newline + + has_endlocal = any(line.rstrip("\r\n") == "ENDLOCAL" for line in lines) + if not has_endlocal: + replaced = False + for index, line in enumerate(lines): + if line.rstrip("\r\n") == "SetLocal EnableDelayedExpansion": + lines[index] = "ENDLOCAL" + newline + replaced = True + changed = True + break + + if not replaced: + for index, line in enumerate(lines): + if line.rstrip("\r\n") == "echo Post-install completed!": + lines.insert(index + 1, "ENDLOCAL" + newline) + changed = True + replaced = True + break + + if not replaced: + lines.append("ENDLOCAL" + newline) + changed = True + + if not changed: + return False + + updated_text = "".join(lines) + write_text(path, updated_text) + print(f"Updated {POST_INSTALL_BAT_PATH}") + return True + + +def update_post_install_sh(repo_root: Path) -> bool: + path = repo_root / POST_INSTALL_SH_PATH + if not path.exists(): + print(f"Skipping missing file: {POST_INSTALL_SH_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + project_folder = detect_project_folder(repo_root) + gpu_requirements_line = f'GPU_REQUIREMENTS="$PREFIX/{project_folder}/requirements_gpu.txt"' + if gpu_requirements_line in original_text: + return False + + lines = original_text.splitlines(keepends=True) + echo_line = 'echo "Running post_install" > "$PREFIX/menuinst_debug.log"' + selected_install_line = '"$PREFIX/bin/python" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$PREFIX/menuinst_debug.log"' + block_lines = [ + f'BASE_REQUIREMENTS="$PREFIX/{project_folder}/requirements.txt"', + gpu_requirements_line, + 'SELECTED_REQUIREMENTS="$BASE_REQUIREMENTS"', + "", + 'if [ -f "$GPU_REQUIREMENTS" ]; then', + ' if [[ "$OSTYPE" == "darwin"* ]]; then', + ' echo "macOS detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$PREFIX/menuinst_debug.log"', + " elif command -v nvidia-smi >/dev/null 2>&1; then", + ' echo "NVIDIA GPU detected, installing GPU requirements from $GPU_REQUIREMENTS" >> "$PREFIX/menuinst_debug.log"', + ' SELECTED_REQUIREMENTS="$GPU_REQUIREMENTS"', + " else", + ' echo "NVIDIA GPU not detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$PREFIX/menuinst_debug.log"', + " fi", + "else", + ' echo "GPU requirements file not found, installing CPU requirements from $BASE_REQUIREMENTS" >> "$PREFIX/menuinst_debug.log"', + "fi", + "", + ] + + echo_index = None + install_index = None + for index, line in enumerate(lines): + stripped = line.rstrip("\r\n") + if stripped == echo_line: + echo_index = index + if ( + stripped.startswith('"$PREFIX/bin/python" -m pip install -r ') + and 'requirements.txt" >> "$PREFIX/menuinst_debug.log"' in stripped + and "requirements-macos.txt" not in stripped + and "requirements-linux.txt" not in stripped + and "$SELECTED_REQUIREMENTS" not in stripped + ): + install_index = index + break + + if echo_index is None or install_index is None: + raise ValueError(f"Unable to find insertion point in {POST_INSTALL_SH_PATH}") + + insertion = [entry + newline for entry in block_lines] + for offset, entry in enumerate(insertion, start=1): + lines.insert(echo_index + offset, entry) + + install_index += len(insertion) + lines[install_index] = selected_install_line + newline + + updated_text = "".join(lines) + write_text(path, updated_text) + print(f"Updated {POST_INSTALL_SH_PATH}") + return True + + +def update_construct(repo_root: Path) -> bool: + path = repo_root / CONSTRUCT_PATH + if not path.exists(): + print(f"Skipping missing file: {CONSTRUCT_PATH}") + return False + + original_text = read_text(path) + if "- requirements_gpu.txt:" in original_text: + return False + + pattern = re.compile( + r"^(?P\s*-\s*)requirements\.txt:\s*(?P.+?/)?requirements\.txt\s*$", + re.MULTILINE, + ) + match = pattern.search(original_text) + if not match: + raise ValueError(f"Unable to find requirements.txt mapping in {CONSTRUCT_PATH}") + + dst_prefix = match.group("dst_prefix") or "" + replacement = ( + match.group(0) + + detect_newline(original_text) + + f"{match.group('indent')}requirements_gpu.txt: {dst_prefix}requirements_gpu.txt" + ) + updated_text = pattern.sub(replacement, original_text, count=1) + write_text(path, updated_text) + print(f"Updated {CONSTRUCT_PATH}") + return True + + +def ensure_requirements_gpu(repo_root: Path) -> bool: + path = repo_root / REQUIREMENTS_GPU_PATH + if path.exists(): + return False + + write_text(path, "") + print(f"Created {REQUIREMENTS_GPU_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_merge_requirements(repo_root) or changed_any + changed_any = update_bump_constructor(repo_root) or changed_any + changed_any = update_post_install_bat(repo_root) or changed_any + changed_any = update_post_install_sh(repo_root) or changed_any + changed_any = update_construct(repo_root) or changed_any + changed_any = ensure_requirements_gpu(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_5_to_v0_1_6.py b/.template_sync/migrations/v0_1_5_to_v0_1_6.py new file mode 100644 index 0000000..25632d2 --- /dev/null +++ b/.template_sync/migrations/v0_1_5_to_v0_1_6.py @@ -0,0 +1,391 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any +import re + + +BUMP_CONSTRUCTOR_PATH = Path(".tools/python/bump_constructor.py") +BUMP_VERSION_PATH = Path(".tools/python/bump_version.py") +CONSTRUCT_PATH = Path("construct.yaml") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def detect_project_folder(repo_root: Path) -> str: + construct_path = repo_root / CONSTRUCT_PATH + if construct_path.is_file(): + for raw_line in read_text(construct_path).splitlines(): + stripped = raw_line.strip() + if stripped.startswith("name:"): + value = stripped.split(":", 1)[1].strip().strip("\"'") + if value: + return value + return "PROJECT_NAME" + + +def update_bump_constructor(repo_root: Path) -> bool: + path = repo_root / BUMP_CONSTRUCTOR_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_CONSTRUCTOR_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + updated_text = original_text + changed = False + project_folder = detect_project_folder(repo_root) + + if 'DEBUG_PREFIX = "[bump_constructor]"' not in original_text: + helper_anchor = "import re" + newline + helper_block = newline.join( + [ + "import re", + "", + 'DEBUG_PREFIX = "[bump_constructor]"', + "", + "", + "def debug(message: str) -> None:", + ' print(f"{DEBUG_PREFIX} {message}")', + "", + ] + ) + if helper_anchor not in updated_text: + raise ValueError(f"Unable to find import insertion point in {BUMP_CONSTRUCTOR_PATH}") + updated_text = updated_text.replace(helper_anchor, helper_block + newline, 1) + changed = True + + requirements_start = "def ensure_requirements_in_extra_files(construct_data: dict):" + requirements_end = "def ensure_extra_files(construct_data: dict, notebooks_root: Path, src_root: Path) -> int:" + requirements_replacement = newline.join( + [ + "def ensure_requirements_in_extra_files(construct_data: dict):", + ' extra_files = construct_data.get("extra_files")', + " if extra_files is None:", + " extra_files = []", + ' construct_data["extra_files"] = extra_files', + "", + " # Check if requirements.txt is included, if not, add it", + " requirements_included = any(", + ' isinstance(item, dict) and "requirements.txt" in item for item in extra_files', + " )", + " if not requirements_included:", + ' extra_files.append({"requirements.txt": "PROJECT_NAME/requirements.txt"})', + ' debug("Added mapping for requirements.txt")', + " else:", + ' debug("requirements.txt mapping already present")', + "", + " gpu_requirements_included = any(", + ' isinstance(item, dict) and "requirements_gpu.txt" in item for item in extra_files', + " )", + ' if not gpu_requirements_included and Path("requirements_gpu.txt").exists():', + ' extra_files.append({"requirements_gpu.txt": "PROJECT_NAME/requirements_gpu.txt"})', + ' debug("Added mapping for requirements_gpu.txt")', + ' elif Path("requirements_gpu.txt").exists():', + ' debug("requirements_gpu.txt mapping already present")', + " else:", + ' debug("requirements_gpu.txt not found, skipping GPU requirements mapping")', + " ", + " # Check if requirements-linux.txt exists and is included, if not, add it", + ' if Path("requirements-linux.txt").exists():', + " linux_included = any(", + ' isinstance(item, dict) and "requirements-linux.txt" in item for item in extra_files', + " )", + " if not linux_included:", + ' extra_files.append({"requirements-linux.txt": "PROJECT_NAME/requirements-linux.txt"})', + ' debug("Added mapping for requirements-linux.txt")', + " else:", + ' debug("requirements-linux.txt mapping already present")', + " else:", + ' debug("requirements-linux.txt not found, skipping Linux requirements mapping")', + " # Check if requirements-windows.txt exists and is included, if not, add it", + ' if Path("requirements-windows.txt").exists():', + " windows_included = any(", + ' isinstance(item, dict) and "requirements-windows.txt" in item for item in extra_files', + " )", + " if not windows_included:", + ' extra_files.append({"requirements-windows.txt": "PROJECT_NAME/requirements-windows.txt"})', + ' debug("Added mapping for requirements-windows.txt")', + " else:", + ' debug("requirements-windows.txt mapping already present")', + " else:", + ' debug("requirements-windows.txt not found, skipping Windows requirements mapping")', + " ", + " # Check if requirements-macos.txt exists and is included, if not, add it", + ' if Path("requirements-macos.txt").exists():', + " macos_included = any(", + ' isinstance(item, dict) and "requirements-macos.txt" in item for item in extra_files', + " )", + " if not macos_included:", + ' extra_files.append({"requirements-macos.txt": "PROJECT_NAME/requirements-macos.txt"})', + ' debug("Added mapping for requirements-macos.txt")', + " else:", + ' debug("requirements-macos.txt mapping already present")', + " else:", + ' debug("requirements-macos.txt not found, skipping macOS requirements mapping")', + "", + " # Update the construct data with the modified extra_files", + ' construct_data["extra_files"] = extra_files', + "", + ] + ).replace("PROJECT_NAME", project_folder) + + if 'debug("Added mapping for requirements.txt")' not in updated_text: + start_index = updated_text.find(requirements_start) + end_index = updated_text.find(requirements_end) + if start_index == -1 or end_index == -1 or end_index <= start_index: + raise ValueError(f"Unable to replace ensure_requirements_in_extra_files() in {BUMP_CONSTRUCTOR_PATH}") + updated_text = updated_text[:start_index] + requirements_replacement + updated_text[end_index:] + changed = True + + extra_start = "def ensure_extra_files(construct_data: dict, notebooks_root: Path, src_root: Path) -> int:" + extra_end = "def main():" + extra_replacement = newline.join( + [ + "def ensure_extra_files(construct_data: dict, notebooks_root: Path, src_root: Path) -> int:", + ' extra_files = construct_data.get("extra_files")', + " if extra_files is None:", + " extra_files = []", + ' construct_data["extra_files"] = extra_files', + "", + " # Extract the project folder name from existing mappings", + " project_folder = extract_project_folder(extra_files)", + ' debug(f"Using project folder: {project_folder}")', + "", + " # Normalize existing entries into a dict for quick lookup", + " existing_sources = set()", + " existing_dests = set()", + " normalized_items = []", + "", + " for item in extra_files:", + " # Items can be either dicts (k: v) or strings with mapping? Assume dicts per example", + " if isinstance(item, dict):", + " for src, dst in item.items():", + " existing_sources.add(str(src))", + " existing_dests.add(str(dst))", + " normalized_items.append({str(src): str(dst)})", + " else:", + " # If strings are present, keep them", + " normalized_items.append(item)", + "", + " ntbk_added = 0", + ' repo_root = Path(".").resolve()', + "", + " # For safety, remove any existing notebooks/*.ipynb entries to avoid duplicates, we will re-add them with correct paths", + ' normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src).startswith("notebooks/") and src.endswith(".ipynb") for src in item.keys()))]', + "", + " # Include all notebooks under notebooks/ directory", + " for ipynb in notebooks_root.rglob(\"*.ipynb\"):", + " rel = ipynb.relative_to(repo_root).as_posix()", + ' if not rel.startswith("notebooks/"):', + " continue", + " src = rel", + ' dst = f"{project_folder}/{rel}"', + "", + " # if src in existing_sources or dst in existing_dests:", + " # continue", + "", + " normalized_items.append({src: dst})", + " ntbk_added += 1", + ' debug(f"Included notebook: {src} -> {dst}")', + "", + " # First get the name of the package from setup.py", + ' setup_path = repo_root / "setup.py"', + ' project_name = "PROJECT_NAME"', + " if setup_path.exists():", + ' setup_text = setup_path.read_text(encoding="utf-8")', + ' name_match = re.search(r\'name\\s*=\\s*["\\\']([^"\\\']+)["\\\']\', setup_text)', + " if name_match:", + " project_name = name_match.group(1)", + ' debug(f"Detected setup.py package name: {project_name}")', + " else:", + ' debug("setup.py not found at repository root")', + "", + " # For safety, remove any existing src/ entries to avoid duplicates, we will re-add them with correct paths", + ' normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src).startswith("src/") for src in item.keys()))]', + "", + " # Include all the Python scripts under src/ directory", + " src_added = 0", + " included_src_flag = False", + ' for py_file in src_root.rglob("*.py"):', + " rel = py_file.relative_to(repo_root).as_posix()", + " # Avoid any python files that are not in the src/ directory or any __init__.py files that are not in the src/ directory ", + ' if not rel.startswith("src/") or py_file.name == "__init__.py":', + " continue", + " src = rel", + ' dst = f"{project_folder}/{rel}"', + "", + " # if src in existing_sources or dst in existing_dests:", + " # continue", + "", + " normalized_items.append({src: dst})", + " included_src_flag = True", + " src_added += 1", + ' debug(f"Included source file: {src} -> {dst}")', + "", + " # For safety also remove setup.py and src_change.yaml if they exist in the extra_files to avoid duplicates, we will re-add them with correct paths if src/ is included", + ' normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src) in ["setup.py", ".tools/meta/src_change.yaml"] for src in item.keys()))] ', + "", + " if included_src_flag:", + " # Also include the setup.py file at the root if not already included", + ' setup_src = "setup.py"', + ' setup_dst = f"{project_folder}/setup.py"', + " if setup_src not in existing_sources and setup_dst not in existing_dests:", + " normalized_items.append({setup_src: setup_dst})", + " src_added += 1", + ' debug(f"Included setup.py: {setup_src} -> {setup_dst}")', + " else:", + ' debug("setup.py mapping already present")', + "", + " # Include the external code change tracking file if it exists", + ' src_change_file = ".tools/meta/src_change.yaml"', + " if Path(src_change_file).exists():", + ' src_change_dst = f"{project_folder}/src_change.yaml"', + " if src_change_file not in existing_sources and src_change_dst not in existing_dests:", + " normalized_items.append({src_change_file: src_change_dst})", + " src_added += 1", + ' debug(f"Included src change marker: {src_change_file} -> {src_change_dst}")', + " else:", + ' debug("src change marker mapping already present")', + " else:", + ' debug("src change marker not found, skipping")', + " else:", + " # If the user has removed the src/directory, remove the generated setup.py and src_change.yaml", + ' debug("No non-__init__.py files found under src/, skipping setup.py and src change marker packaging")', + ' setup_dst = Path(project_folder) / "setup.py"', + " if setup_dst.exists():", + " setup_dst.unlink()", + ' src_change_dst = Path(project_folder) / "src_change.yaml"', + " if src_change_dst.exists():", + " src_change_dst.unlink()", + "", + " # Optionally sort entries (dicts by their single key) for determinism", + " def sort_key(item):", + " if isinstance(item, dict):", + " # single-key dict", + " k = next(iter(item.keys()))", + " return (0, k)", + " return (1, str(item))", + "", + " normalized_items.sort(key=sort_key)", + ' construct_data["extra_files"] = normalized_items', + ' debug(f"Final extra_files entries: {len(normalized_items)}")', + " for item in normalized_items:", + ' debug(f"extra_files entry: {item}")', + "", + " return ntbk_added, src_added", + "", + ] + ).replace("PROJECT_NAME", project_folder) + + if 'debug(f"Included notebook: {src} -> {dst}")' not in updated_text: + start_index = updated_text.find(extra_start) + end_index = updated_text.find(extra_end) + if start_index == -1 or end_index == -1 or end_index <= start_index: + raise ValueError(f"Unable to replace ensure_extra_files() in {BUMP_CONSTRUCTOR_PATH}") + updated_text = updated_text[:start_index] + extra_replacement + updated_text[end_index:] + changed = True + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {BUMP_CONSTRUCTOR_PATH}") + return True + + +def update_bump_version(repo_root: Path) -> bool: + path = repo_root / BUMP_VERSION_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_VERSION_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + updated_text = original_text + changed = False + + old_regex = 'THANKS_LINE_RE = re.compile(r\'(Thank you! You have successfully installed [^\\n]*)(\\d+\\.\\d+\\.\\d+)(!)\')' + new_regex = newline.join( + [ + "CONCLUSION_LINE_RE = re.compile(", + ' r\'^(conclusion_text:\\s*)(?P["\\\'])(?P.*?)(?P=quote)(?P\\s*(?:#.*)?)$\',', + " re.MULTILINE,", + ")", + ] + ) + if "CONCLUSION_LINE_RE = re.compile(" not in updated_text: + if old_regex not in updated_text: + raise ValueError(f"Unable to find conclusion regex in {BUMP_VERSION_PATH}") + updated_text = updated_text.replace(old_regex, new_regex, 1) + changed = True + + new_function = newline.join( + [ + "def bump_construct_text(text: str, old_version: str, new_version: str) -> str:", + ' """Return updated file text with bumped version, preserving YAML structure/comments.', + "", + " - Updates the `version: \"X.Y.Z\"` line.", + " - Updates the version inside `conclusion_text`, replacing either", + " `VERSION_NUMBER` or the previous explicit version if present.", + ' """', + " # 1) Update the explicit version line", + " def _repl_version(m: re.Match) -> str:", + " # Preserve original quoting and trailing comment/whitespace", + " return f\"{m.group(1)}{m.group('quote')}{new_version}{m.group('quote')}{m.group('trailing')}\"", + "", + " text = VERSION_LINE_RE.sub(_repl_version, text, count=1)", + "", + " # 2) Update the version inside conclusion_text if present.", + " def _repl_conclusion(m: re.Match) -> str:", + " body = m.group(\"body\")", + " if \"VERSION_NUMBER\" in body:", + " updated_body = body.replace(\"VERSION_NUMBER\", new_version)", + " else:", + " updated_body = body.replace(old_version, new_version)", + " return f\"{m.group(1)}{m.group('quote')}{updated_body}{m.group('quote')}{m.group('trailing')}\"", + "", + " text = CONCLUSION_LINE_RE.sub(_repl_conclusion, text, count=1)", + " return text", + ] + ) + newline + + if "text = CONCLUSION_LINE_RE.sub(_repl_conclusion, text, count=1)" not in updated_text: + start_marker = "def bump_construct_text(text: str, old_version: str, new_version: str) -> str:" + end_marker = "def bump_post_install_bat(new_version: str) -> None:" + start_index = updated_text.find(start_marker) + end_index = updated_text.find(end_marker) + if start_index == -1 or end_index == -1 or end_index <= start_index: + raise ValueError(f"Unable to replace bump_construct_text() in {BUMP_VERSION_PATH}") + updated_text = updated_text[:start_index] + new_function + updated_text[end_index:] + changed = True + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {BUMP_VERSION_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_bump_constructor(repo_root) or changed_any + changed_any = update_bump_version(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_6_to_v0_1_7.py b/.template_sync/migrations/v0_1_6_to_v0_1_7.py new file mode 100644 index 0000000..1a014d1 --- /dev/null +++ b/.template_sync/migrations/v0_1_6_to_v0_1_7.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +POST_INSTALL_BAT_PATH = Path("app/bash_bat_scripts/post_install.bat") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def update_post_install_bat(repo_root: Path) -> bool: + path = repo_root / POST_INSTALL_BAT_PATH + if not path.exists(): + print(f"Skipping missing file: {POST_INSTALL_BAT_PATH}") + return False + + original_text = read_text(path) + if "CALL :detect_nvidia_smi" in original_text and ":detect_nvidia_smi" in original_text: + return False + + newline = detect_newline(original_text) + lines = original_text.splitlines(keepends=True) + changed = False + + selected_index = None + install_index = None + endlocal_index = None + + for index, line in enumerate(lines): + stripped = line.rstrip("\r\n") + if stripped == 'SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%"': + selected_index = index + elif stripped == '"%PREFIX%\\python.exe" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"': + install_index = index + elif stripped == "ENDLOCAL": + endlocal_index = index + + if selected_index is None or install_index is None or install_index <= selected_index: + raise ValueError(f"Unable to find GPU requirements selection block in {POST_INSTALL_BAT_PATH}") + + replacement_block = [ + 'SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%"', + 'SET "NVIDIA_SMI="', + "", + 'IF EXIST "%GPU_REQUIREMENTS%" (', + " CALL :detect_nvidia_smi", + " IF DEFINED NVIDIA_SMI (", + ' echo NVIDIA GPU utility detected at "%NVIDIA_SMI%", installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + ' SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%"', + " ) ELSE (", + ' echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + " )", + ") ELSE (", + ' echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + ")", + "", + 'echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%PREFIX%\\menuinst_debug.log"', + ] + + replacement_lines = [line + newline for line in replacement_block] + lines[selected_index:install_index] = replacement_lines + changed = True + + if endlocal_index is None: + raise ValueError(f"Unable to find ENDLOCAL in {POST_INSTALL_BAT_PATH}") + + helper_lines = [ + "ENDLOCAL", + "GOTO :EOF", + "", + ":detect_nvidia_smi", + "FOR %%P IN (", + ' "%ProgramFiles%\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe"', + ' "%ProgramW6432%\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe"', + ' "%SystemRoot%\\System32\\nvidia-smi.exe"', + ' "%SystemRoot%\\Sysnative\\nvidia-smi.exe"', + ") DO (", + ' IF NOT DEFINED NVIDIA_SMI IF EXIST "%%~P" SET "NVIDIA_SMI=%%~P"', + ")", + "IF DEFINED NVIDIA_SMI GOTO :EOF", + "", + "FOR /F \"delims=\" %%I IN ('where.exe nvidia-smi.exe 2^>NUL') DO (", + ' IF NOT DEFINED NVIDIA_SMI SET "NVIDIA_SMI=%%~fI"', + ")", + "GOTO :EOF", + ] + helper_text = newline.join(helper_lines) + newline + + file_text = "".join(lines) + if "GOTO :EOF" not in file_text or ":detect_nvidia_smi" not in file_text: + lines[endlocal_index:] = [helper_text] + changed = True + + if not changed: + return False + + write_text(path, "".join(lines)) + print(f"Updated {POST_INSTALL_BAT_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_post_install_bat(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_7_to_v0_1_8.py b/.template_sync/migrations/v0_1_7_to_v0_1_8.py new file mode 100644 index 0000000..f8a31cd --- /dev/null +++ b/.template_sync/migrations/v0_1_7_to_v0_1_8.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any +import re + + +BUMP_CONSTRUCTOR_PATH = Path(".tools/python/bump_constructor.py") +BUMP_VERSION_PATH = Path(".tools/python/bump_version.py") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def replace_exact_block(text: str, old_block: str, new_block: str, path: Path, description: str) -> tuple[str, bool]: + if old_block in text: + return text.replace(old_block, new_block, 1), True + if new_block in text: + return text, False + raise ValueError(f"Unable to find {description} in {path}") + + +def update_bump_version(repo_root: Path) -> bool: + path = repo_root / BUMP_VERSION_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_VERSION_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + changed = False + + old_conclusion_regex_block = newline.join( + [ + "CONCLUSION_LINE_RE = re.compile(", + ' r\'^(conclusion_text:\\s*)(?P["\\\'])(?P.*?)(?P=quote)(?P\\s*(?:#.*)?)$\',', + " re.MULTILINE,", + ")", + ] + ) + new_conclusion_regex_block = newline.join( + [ + "CONCLUSION_LINE_RE = re.compile(", + ' r\'^(conclusion_text:\\s*)(?:(?P["\\\'])(?P.*?)(?P=quote)|(?P.*?))(?P\\s*(?:#.*)?)$\',', + " re.MULTILINE,", + ")", + ] + ) + + updated_text, block_changed = replace_exact_block( + original_text, + old_conclusion_regex_block, + new_conclusion_regex_block, + path, + "CONCLUSION_LINE_RE block", + ) + changed = changed or block_changed + + old_repl_conclusion_block = newline.join( + [ + " # 2) Update the version inside conclusion_text if present.", + " def _repl_conclusion(m: re.Match) -> str:", + ' body = m.group("body")', + ' if "VERSION_NUMBER" in body:', + ' updated_body = body.replace("VERSION_NUMBER", new_version)', + " else:", + " updated_body = body.replace(old_version, new_version)", + ' return f"{m.group(1)}{m.group(\'quote\')}{updated_body}{m.group(\'quote\')}{m.group(\'trailing\')}"', + ] + ) + new_repl_conclusion_block = newline.join( + [ + " # 2) Update the version inside conclusion_text if present.", + " def _repl_conclusion(m: re.Match) -> str:", + ' quote = m.group("quote") or ""', + ' body = m.group("quoted_body") if quote else (m.group("bare_body") or "")', + ' if "VERSION_NUMBER" in body:', + ' updated_body = body.replace("VERSION_NUMBER", new_version)', + " else:", + " updated_body = body.replace(old_version, new_version)", + ' return f"{m.group(1)}{quote}{updated_body}{quote}{m.group(\'trailing\')}"', + ] + ) + + updated_text, block_changed = replace_exact_block( + updated_text, + old_repl_conclusion_block, + new_repl_conclusion_block, + path, + "_repl_conclusion block", + ) + changed = changed or block_changed + + updated_block = newline.join( + [ + "def bump_version_in_download_executable_md(new_version: str) -> None:", + " possible_download_md_paths = [", + ' ROOT / "docs" / "download_executable.md",', + ' ROOT / ".tools" / "docs" / "download_executable.md"', + " ]", + ' template_md = ROOT / ".tools" / "templates" / "download_executable_template.md"', + "", + " for download_md in possible_download_md_paths:", + " # We only want to update the existing files", + " if download_md.exists():", + " # Replace download_executable.md with the template (but only if it exists)", + " if template_md.exists():", + " # Remove existing download_executable.md if present", + " if download_md.exists():", + " download_md.unlink()", + " # Copy the template to the docs folder using shutil for cross-platform support", + " shutil.copy(template_md, download_md)", + " else:", + ' print("Template for download_executable.md not found! Skipping creation of download_executable.md")', + " return", + "", + " # This file contains placeholders, update them with the new version", + ' text = download_md.read_text(encoding="utf-8")', + " updated_text = replace_version_placeholder(text, new_version)", + " if updated_text != text:", + ' download_md.write_text(updated_text, encoding="utf-8")', + ' print(f"Updated download_executable.md to version {new_version}")', + " else:", + ' print("No version string found in download_executable.md to update.")', + ] + ) + + start_marker = "def bump_version_in_download_executable_md(new_version: str) -> None:" + end_marker = f"{newline}def main() -> None:" + + start = updated_text.find(start_marker) + if start == -1: + raise ValueError(f"Unable to find function start in {BUMP_VERSION_PATH}") + + end = updated_text.find(end_marker, start) + if end == -1: + raise ValueError(f"Unable to find function end before main() in {BUMP_VERSION_PATH}") + + current_block = updated_text[start:end].rstrip("\r\n") + if current_block == updated_block: + if not changed: + return False + write_text(path, updated_text) + print(f"Updated {BUMP_VERSION_PATH}") + return True + + updated_text = updated_text[:start] + updated_block + newline + updated_text[end + len(newline):] + write_text(path, updated_text) + print(f"Updated {BUMP_VERSION_PATH}") + return True + + +def update_bump_constructor(repo_root: Path) -> bool: + path = repo_root / BUMP_CONSTRUCTOR_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_CONSTRUCTOR_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + + updated_block = newline.join( + [ + " normalized_items.append({setup_src: setup_dst})", + " src_added += 1", + ' debug(f"Included setup.py: {setup_src} -> {setup_dst}")', + ] + ) + + if updated_block in original_text and 'if setup_src not in existing_sources and setup_dst not in existing_dests:' not in original_text: + return False + + patterns = [ + re.compile( + r' if setup_src not in existing_sources and setup_dst not in existing_dests:\r?\n' + r' normalized_items\.append\(\{setup_src: setup_dst\}\)\r?\n' + r' src_added \+= 1\r?\n' + r'(?: debug\(f"Included setup\.py: \{setup_src\} -> \{setup_dst\}"\)\r?\n)?' + r' else:\r?\n' + r'(?: debug\("setup\.py mapping already present"\)\r?\n)?' + ), + re.compile( + r' if setup_src not in existing_sources and setup_dst not in existing_dests:\r?\n' + r' normalized_items\.append\(\{setup_src: setup_dst\}\)\r?\n' + r' src_added \+= 1\r?\n' + ), + ] + + replacement = updated_block + newline + updated_text = original_text + changed = False + + for pattern in patterns: + updated_text, replacements = pattern.subn(replacement, updated_text, count=1) + if replacements: + changed = True + break + + if not changed: + raise ValueError(f"Unable to find setup.py conditional block in {BUMP_CONSTRUCTOR_PATH}") + + write_text(path, updated_text) + print(f"Updated {BUMP_CONSTRUCTOR_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_bump_version(repo_root) or changed_any + changed_any = update_bump_constructor(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_8_to_v0_1_9.py b/.template_sync/migrations/v0_1_8_to_v0_1_9.py new file mode 100644 index 0000000..5481105 --- /dev/null +++ b/.template_sync/migrations/v0_1_8_to_v0_1_9.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + + +BUMP_CONSTRUCTOR_PATH = Path(".tools/python/bump_constructor.py") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as fh: + return fh.read() + + +def write_text(path: Path, text: str) -> None: + with path.open("w", encoding="utf-8", newline="") as fh: + fh.write(text) + + +def replace_exact_block(text: str, old_block: str, new_block: str, path: Path, description: str) -> tuple[str, bool]: + if old_block in text: + return text.replace(old_block, new_block, 1), True + if new_block in text: + return text, False + raise ValueError(f"Unable to find {description} in {path}") + + +def update_bump_constructor(repo_root: Path) -> bool: + path = repo_root / BUMP_CONSTRUCTOR_PATH + if not path.exists(): + print(f"Skipping missing file: {BUMP_CONSTRUCTOR_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + + old_block = newline.join( + [ + " # Include all the Python scripts under src/ directory", + " src_added = 0", + " included_src_flag = False", + ' for py_file in src_root.rglob("*.py"):', + " rel = py_file.relative_to(repo_root).as_posix()", + " # Avoid any python files that are not in the src/ directory or any __init__.py files that are not in the src/ directory ", + ' if not rel.startswith("src/") or py_file.name == "__init__.py":', + " continue", + " src = rel", + ' dst = f"{project_folder}/{rel}"', + "", + " # if src in existing_sources or dst in existing_dests:", + " # continue", + "", + " normalized_items.append({src: dst})", + " included_src_flag = True", + " src_added += 1", + ' debug(f"Included source file: {src} -> {dst}")', + "", + ] + ) + + new_block = newline.join( + [ + " # Include all the Python scripts under src/ directory", + " src_added = 0", + " only_init_files = True", + " included_src_flag = False", + ' for py_file in src_root.rglob("*.py"):', + " rel = py_file.relative_to(repo_root).as_posix()", + " ", + " # Avoid any python files that are not in the src/ directory ", + ' if not rel.startswith("src/"):', + " continue", + "", + " # Control if we only have __init__.py files", + ' if not py_file.name == "__init__.py":', + " only_init_files = False", + " ", + " src = rel", + ' dst = f"{project_folder}/{rel}"', + "", + " # if src in existing_sources or dst in existing_dests:", + " # continue", + "", + " normalized_items.append({src: dst})", + " included_src_flag = True", + " src_added += 1", + ' debug(f"Included source file: {src} -> {dst}")', + "", + " if only_init_files:", + ' debug("Only __init__.py files found under src/, skipping setup.py and src change marker packaging")', + " included_src_flag = False", + "", + ] + ) + + updated_text, changed = replace_exact_block( + original_text, + old_block, + new_block, + path, + "src packaging block", + ) + + if not changed: + return False + + write_text(path, updated_text) + print(f"Updated {BUMP_CONSTRUCTOR_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + + changed_any = False + changed_any = update_bump_constructor(repo_root) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/migrations/v0_1_9_to_v0_1_10.py b/.template_sync/migrations/v0_1_9_to_v0_1_10.py new file mode 100644 index 0000000..56c57e7 --- /dev/null +++ b/.template_sync/migrations/v0_1_9_to_v0_1_10.py @@ -0,0 +1,332 @@ +from __future__ import annotations + +import json +import re +import subprocess +from pathlib import Path +from typing import Any + + +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_9_to_v0_1_10" +CONSTRUCT_PATH = Path("construct.yaml") +ENVIRONMENT_PATH = Path("environment.yaml") +POST_INSTALL_BAT_PATH = Path("app/bash_bat_scripts/post_install.bat") +POST_INSTALL_SH_PATH = Path("app/bash_bat_scripts/post_install.sh") +NOTEBOOK_LAUNCHER_PATH = Path("app/menuinst/notebook_launcher.json") +LAUNCH_JUPYTER_PATH = Path("app/python_scripts/launch_jupyter.py") +TROUBLESHOOTING_PATH = Path(".tools/docs/troubleshooting.md") + + +def detect_newline(text: str) -> str: + return "\r\n" if "\r\n" in text else "\n" + + +def read_text(path: Path) -> str: + with path.open("r", encoding="utf-8", newline="") as handle: + return handle.read() + + +def write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8", newline="") as handle: + handle.write(text) + + +def strip_quotes(value: str) -> str: + stripped = value.strip() + if len(stripped) >= 2 and stripped[0] == stripped[-1] and stripped[0] in {"'", '"'}: + return stripped[1:-1] + return stripped + + +def extract_yaml_value(text: str, key: str) -> str | None: + match = re.search(rf"^{re.escape(key)}:\s*(.+?)\s*(?:#.*)?$", text, re.MULTILINE) + if not match: + return None + return strip_quotes(match.group(1)) + + +def extract_project_folder(construct_text: str) -> str | None: + for pattern in ( + r"app/menuinst/Welcome\.ipynb:\s*([^\r\n/]+)/notebooks/Welcome\.ipynb", + r"app/menuinst/notebook_launcher\.json:\s*([^\r\n/]+)/notebook_launcher\.json", + r"requirements\.txt:\s*([^\r\n/]+)/requirements\.txt", + ): + match = re.search(pattern, construct_text) + if match: + return match.group(1).strip() + return None + + +def parse_github_owner(remote_url: str) -> str | None: + normalized = remote_url.strip() + for pattern in ( + r"github\.com[:/](?P[^/]+)/(?P[^/]+?)(?:\.git)?$", + r"^git@github\.com:(?P[^/]+)/(?P[^/]+?)(?:\.git)?$", + ): + match = re.search(pattern, normalized) + if match: + return match.group("owner") + return None + + +def detect_github_owner(repo_root: Path, fallback_text: str = "") -> str: + try: + result = subprocess.run( + ["git", "-C", str(repo_root), "config", "--get", "remote.origin.url"], + check=False, + capture_output=True, + text=True, + ) + owner = parse_github_owner(result.stdout) + if owner: + return owner + except OSError: + pass + + match = re.search(r'^SET\s+"PUBLISHER=([^"]+)"\s*$', fallback_text, re.MULTILINE) + if match and match.group(1) != "GITHUB_OWNER": + return match.group(1) + return "GITHUB_OWNER" + + +def detect_python_package_name(repo_root: Path) -> str: + src_root = repo_root / "src" + if src_root.is_dir(): + candidates = sorted( + child.name + for child in src_root.iterdir() + if child.is_dir() + and child.name.isidentifier() + and (child / "__init__.py").is_file() + ) + if len(candidates) == 1: + return candidates[0] + + setup_path = repo_root / "setup.py" + if setup_path.is_file(): + match = re.search(r'name\s*=\s*["\']([^"\']+)["\']', read_text(setup_path)) + if match: + return match.group(1).replace("-", "_") + return "PYTHON_PROJ_NAME" + + +def normalize_posix(path_value: str) -> str: + return path_value.replace("\\", "/") + + +def derive_icon_paths(repo_root: Path, construct_icon: str, project_name: str) -> dict[str, str]: + existing_icons: dict[str, str] = {} + launcher_path = repo_root / NOTEBOOK_LAUNCHER_PATH + if launcher_path.exists(): + try: + launcher = json.loads(launcher_path.read_text(encoding="utf-8")) + platforms = launcher.get("menu_items", [{}])[0].get("platforms", {}) + for platform_key, placeholder in ( + ("win", "ICON_ICO_IMAGE_PATH"), + ("linux", "ICON_IMAGE_PATH"), + ("osx", "ICON_ICNS_IMAGE_PATH"), + ): + icon = platforms.get(platform_key, {}).get("icon") + if isinstance(icon, str) and icon.strip(): + existing_icons[placeholder] = normalize_posix(icon.strip()) + except (json.JSONDecodeError, IndexError, AttributeError): + pass + + normalized_icon = normalize_posix(construct_icon) + stem = normalized_icon.rsplit(".", 1)[0] if normalized_icon else f"app/logo/{project_name}_logo" + return { + "ICON_IMAGE_PATH": existing_icons.get("ICON_IMAGE_PATH", normalized_icon or f"{stem}.png"), + "ICON_ICO_IMAGE_PATH": existing_icons.get("ICON_ICO_IMAGE_PATH", f"{stem}.ico"), + "ICON_ICNS_IMAGE_PATH": existing_icons.get("ICON_ICNS_IMAGE_PATH", f"{stem}.icns"), + } + + +def load_replacements(repo_root: Path) -> dict[str, str]: + construct_text = read_text(repo_root / CONSTRUCT_PATH) + construct_name = extract_yaml_value(construct_text, "name") or "UNDERSCORED_PROJECT_NAME" + project_name = extract_project_folder(construct_text) or construct_name + version = extract_yaml_value(construct_text, "version") or "VERSION_NUMBER" + construct_icon = extract_yaml_value(construct_text, "icon_image") or "" + + if project_name == "PROJECT_NAME" or construct_name == "UNDERSCORED_PROJECT_NAME": + github_owner = "GITHUB_OWNER" + else: + post_install_path = repo_root / POST_INSTALL_BAT_PATH + post_install_text = read_text(post_install_path) if post_install_path.exists() else "" + github_owner = detect_github_owner(repo_root, post_install_text) + + replacements = { + "PROJECT_NAME": project_name, + "UNDERSCORED_PROJECT_NAME": construct_name, + "VERSION_NUMBER": version, + "GITHUB_OWNER": github_owner, + "PYTHON_PROJ_NAME": detect_python_package_name(repo_root), + } + replacements.update(derive_icon_paths(repo_root, construct_icon, project_name)) + return replacements + + +def render_template(text: str, replacements: dict[str, str], newline: str) -> str: + rendered = text.replace("\r\n", "\n") + for key in sorted(replacements, key=len, reverse=True): + rendered = rendered.replace(key, replacements[key]) + return rendered.replace("\n", newline) + + +def copy_template( + repo_root: Path, + resource_relative_path: str, + destination_relative_path: Path, + replacements: dict[str, str] | None = None, +) -> bool: + source_path = RESOURCE_ROOT / resource_relative_path + if not source_path.exists(): + raise ValueError(f"Missing migration resource: {source_path}") + + destination_path = repo_root / destination_relative_path + source_text = read_text(source_path) + if destination_path.exists(): + existing_text = read_text(destination_path) + newline = detect_newline(existing_text) + else: + existing_text = "" + newline = detect_newline(source_text) + + rendered_text = render_template(source_text, replacements or {}, newline) + if existing_text == rendered_text: + return False + + write_text(destination_path, rendered_text) + print(f"Updated {destination_relative_path}") + return True + + +def _dependency_name(line: str) -> str | None: + stripped = line.strip() + if not stripped.startswith("- "): + return None + value = stripped[2:].split("#", 1)[0].strip() + return re.split(r"[<>=!~\s]", value, maxsplit=1)[0] + + +def update_environment(repo_root: Path) -> bool: + path = repo_root / ENVIRONMENT_PATH + if not path.exists(): + print(f"Skipping missing file: {ENVIRONMENT_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + lines = original_text.splitlines() + if not lines: + raise ValueError(f"Unexpected empty file: {ENVIRONMENT_PATH}") + + changed = False + filtered_lines: list[str] = [] + for line in lines: + if _dependency_name(line) == "pip-system-certs": + changed = True + continue + filtered_lines.append(line) + lines = filtered_lines + + dependency_indices: dict[str, int] = {} + for index, line in enumerate(lines): + name = _dependency_name(line) + if name: + dependency_indices.setdefault(name, index) + + pip_index = dependency_indices.get("pip") + if pip_index is None: + raise ValueError(f"Unable to find pip dependency in {ENVIRONMENT_PATH}") + + indent_match = re.match(r"^(\s*)-", lines[pip_index]) + indent = indent_match.group(1) if indent_match else " " + desired_pip = f"{indent}- pip>=24.2" + if lines[pip_index] != desired_pip: + lines[pip_index] = desired_pip + changed = True + + dependency_indices = { + name: index + for index, line in enumerate(lines) + if (name := _dependency_name(line)) is not None + } + desired = ( + ("setuptools", f"{indent}- setuptools"), + ("wheel", f"{indent}- wheel"), + ("menuinst", f"{indent}- menuinst>=2"), + ("truststore", f"{indent}- truststore>=0.10.4"), + ("certifi", f"{indent}- certifi"), + ) + missing = [line for name, line in desired if name not in dependency_indices] + if missing: + insert_index = dependency_indices.get("jupyterlab", len(lines)) + lines[insert_index:insert_index] = missing + changed = True + + if not changed: + return False + + updated_text = newline.join(lines) + newline + write_text(path, updated_text) + print(f"Updated {ENVIRONMENT_PATH}") + return True + + +def update_construct(repo_root: Path, replacements: dict[str, str]) -> bool: + path = repo_root / CONSTRUCT_PATH + if not path.exists(): + print(f"Skipping missing file: {CONSTRUCT_PATH}") + return False + + original_text = read_text(path) + newline = detect_newline(original_text) + mapping_line = f"- app/python_scripts/launch_jupyter.py: {replacements['PROJECT_NAME']}/launch_jupyter.py" + if mapping_line in original_text: + return False + + lines = original_text.splitlines(keepends=True) + insert_index = None + for marker in ( + "app/python_scripts/include_path.py:", + "app/python_scripts/hide_code_cells.py:", + "notebooks/notebook_latest_versions.yaml:", + ): + for index, line in enumerate(lines): + if marker in line: + insert_index = index + 1 + break + if insert_index is not None: + break + + if insert_index is None: + for index, line in enumerate(lines): + if line.startswith("post_install:"): + insert_index = index + break + if insert_index is None: + raise ValueError(f"Unable to find extra_files insertion point in {CONSTRUCT_PATH}") + + lines.insert(insert_index, mapping_line + newline) + write_text(path, "".join(lines)) + print(f"Updated {CONSTRUCT_PATH}") + return True + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + _ = context + replacements = load_replacements(repo_root) + + changed_any = False + changed_any = update_environment(repo_root) or changed_any + changed_any = update_construct(repo_root, replacements) or changed_any + changed_any = copy_template(repo_root, "app/bash_bat_scripts/post_install.bat", POST_INSTALL_BAT_PATH, replacements) or changed_any + changed_any = copy_template(repo_root, "app/bash_bat_scripts/post_install.sh", POST_INSTALL_SH_PATH, replacements) or changed_any + changed_any = copy_template(repo_root, "app/menuinst/notebook_launcher.json", NOTEBOOK_LAUNCHER_PATH, replacements) or changed_any + changed_any = copy_template(repo_root, "app/python_scripts/launch_jupyter.py", LAUNCH_JUPYTER_PATH, replacements) or changed_any + changed_any = copy_template(repo_root, ".tools/docs/troubleshooting.md", TROUBLESHOOTING_PATH, replacements) or changed_any + + if not changed_any: + print("No repository changes were required for this migration.") diff --git a/.template_sync/resources/v0_1_11_to_v0_1_12/.github/workflows/sync_template.yml b/.template_sync/resources/v0_1_11_to_v0_1_12/.github/workflows/sync_template.yml new file mode 100644 index 0000000..8ba8f42 --- /dev/null +++ b/.template_sync/resources/v0_1_11_to_v0_1_12/.github/workflows/sync_template.yml @@ -0,0 +1,170 @@ +name: Sync with Template Repository + +on: + schedule: + # Run weekly on Monday at 9 AM UTC + - cron: '0 9 * * 1' + workflow_dispatch: + +# This enables only one template synchronization workflow at a time. +concurrency: + group: template-sync-main + cancel-in-progress: false + +permissions: + contents: write + pull-requests: write + +jobs: + sync-template: + name: Sync with template repository + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: main + fetch-depth: 0 + # Do not leave the default GITHUB_TOKEN in the local Git configuration. + # The pull-request step authenticates separately with the repository-scoped + # LABCONSTRICTOR_SYNC_TOKEN secret. + persist-credentials: false + + - name: Configure Git + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Add upstream remote + run: | + git remote add upstream https://github.com/CellMigrationLab/LabConstrictor.git + + - name: Fetch upstream changes + run: | + git fetch upstream main + + - name: Read local template version + id: local-version + run: | + local_version=$(python3 - <<'PY' + from pathlib import Path + + manifest = Path(".template_sync/manifest.yaml") + if not manifest.exists(): + print("0.0.0") + raise SystemExit + + for line in manifest.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if stripped.startswith("template_version:"): + print(stripped.split(":", 1)[1].strip()) + break + else: + raise SystemExit("template_version not found in .template_sync/manifest.yaml") + PY + ) + echo "version=$local_version" >> "$GITHUB_OUTPUT" + + - name: Read upstream template version + id: upstream-version + run: | + upstream_version=$(python3 - <<'PY' + import subprocess + + manifest = subprocess.run( + ["git", "show", "upstream/main:.template_sync/manifest.yaml"], + check=True, + capture_output=True, + text=True, + ).stdout + for line in manifest.splitlines(): + stripped = line.strip() + if stripped.startswith("template_version:"): + print(stripped.split(":", 1)[1].strip()) + break + else: + raise SystemExit( + "template_version not found in upstream .template_sync/manifest.yaml" + ) + PY + ) + echo "version=$upstream_version" >> "$GITHUB_OUTPUT" + + - name: Check whether template sync is needed + id: version-check + env: + LOCAL_VERSION: ${{ steps.local-version.outputs.version }} + UPSTREAM_VERSION: ${{ steps.upstream-version.outputs.version }} + run: | + python3 - <<'PY' + import os + from pathlib import Path + + def parse_version(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + local_version = os.environ["LOCAL_VERSION"] + upstream_version = os.environ["UPSTREAM_VERSION"] + sync_required = parse_version(upstream_version) > parse_version(local_version) + + output_path = Path(os.environ["GITHUB_OUTPUT"]) + with output_path.open("a", encoding="utf-8") as fh: + fh.write(f"sync_required={'true' if sync_required else 'false'}\n") + PY + + - name: Check synchronization token setup + if: steps.version-check.outputs.sync_required == 'true' + env: + LABCONSTRICTOR_SYNC_TOKEN: ${{ secrets.LABCONSTRICTOR_SYNC_TOKEN }} + run: | + if [[ -z "$LABCONSTRICTOR_SYNC_TOKEN" ]]; then + { + echo "## One-time LabConstrictor setup required" + echo + echo "A template update is available, but this repository does not have the" + echo '`LABCONSTRICTOR_SYNC_TOKEN` repository secret configured.' + echo + echo "Follow the beginner-friendly guide in:" + echo + echo '`.tools/docs/template_synchronization.md`' + } >> "$GITHUB_STEP_SUMMARY" + + echo "::error title=Synchronization setup required::Configure the LABCONSTRICTOR_SYNC_TOKEN repository secret by following .tools/docs/template_synchronization.md." + exit 1 + fi + + - name: Fetch template sync bootstrap + if: steps.version-check.outputs.sync_required == 'true' + run: | + git checkout upstream/main -- .template_sync + + - name: Run template migrations + if: steps.version-check.outputs.sync_required == 'true' + run: | + python3 .template_sync/sync.py \ + --from-version "${{ steps.local-version.outputs.version }}" \ + --to-version "${{ steps.upstream-version.outputs.version }}" \ + --repository-root "$GITHUB_WORKSPACE" + + - name: Check for changes + id: check-changes + run: | + if [[ -n "$(git status --short)" ]]; then + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + echo "has_changes=false" >> "$GITHUB_OUTPUT" + fi + + - name: Create pull request + if: steps.check-changes.outputs.has_changes == 'true' + uses: peter-evans/create-pull-request@c5a7806660adbe173f04e3e038b0ccdcd758773c # v6 + with: + token: ${{ secrets.LABCONSTRICTOR_SYNC_TOKEN }} + branch: template-sync-${{ steps.local-version.outputs.version }}-to-${{ steps.upstream-version.outputs.version }} + delete-branch: true + commit-message: Sync template to version ${{ steps.upstream-version.outputs.version }} + title: Sync template to version ${{ steps.upstream-version.outputs.version }} + body: | + This PR updates `.template_sync` from the template repository and applies the migrations needed to move this repository from template version `${{ steps.local-version.outputs.version }}` to `${{ steps.upstream-version.outputs.version }}`. + + The branch is created with the repository-scoped `LABCONSTRICTOR_SYNC_TOKEN` secret so that updates to GitHub workflow files can be included safely. diff --git a/.template_sync/resources/v0_1_11_to_v0_1_12/.tools/docs/template_synchronization.md b/.template_sync/resources/v0_1_11_to_v0_1_12/.tools/docs/template_synchronization.md new file mode 100644 index 0000000..1c512ea --- /dev/null +++ b/.template_sync/resources/v0_1_11_to_v0_1_12/.tools/docs/template_synchronization.md @@ -0,0 +1,82 @@ +# Enable automatic LabConstrictor template updates + +LabConstrictor periodically checks the main template for improvements. When an update is available, the **Sync with Template Repository** workflow prepares the changes in a pull request so you can review and merge them safely. + +You will need to do a one-time GitHub setup to create a token that allows LabConstrictor to update your repository. This token described below is limited to the repository you select. LabConstrictor does not need access to your other repositories. + +## What do I need to do? + +Follow the same instructions that are given in the following video and instructions below. + +## Step 1: Create the synchronization token + +![GIF showing the token creation](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Synchronisation_Token_Creation.gif) + +Follow steps on the GIF or click on [this link](https://github.com/settings/personal-access-tokens/new?name=LabConstrictor+Sync&description=Allows+LabConstrictor+to+prepare+template+update+pull+requests.&expires_in=365&contents=write&pull_requests=write&workflows=write) and follow the steps below: + +1. Under **Resource owner**, select the owner of your LabConstrictor repository. +2. Under **Repository access**, select **Only select repositories**. +3. Select your LabConstrictor repository. +4. Choose an expiration period that suits you. The prefilled suggestion is 365 days. +5. Confirm these repository permissions: + - **Contents:** Read and write + - **Pull requests:** Read and write + - **Workflows:** Read and write +6. Select **Generate token**. +7. Copy the generated token. + +> GitHub shows the complete token only once. Keep the page open until you have saved it in Step 2. + +## Step 2: Save the token as a repository secret + +![GIF showing the secret creation](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Synchronisation_Secret_Creation.gif) + +1. Open your LabConstrictor repository. +2. Select **Settings**. +3. In the left sidebar, select **Secrets and variables**, then **Actions**. +4. Select **New repository secret**. +5. Enter this exact name: + + ```text + LABCONSTRICTOR_SYNC_TOKEN + ``` + +6. Paste the token into the **Secret** field. +7. Select **Add secret**. + +> GitHub encrypts repository secrets. The token will not be displayed in the repository or in normal workflow logs. + +## Step 3 (situational): One-time step for repositories created before template version 0.1.12 + +An older synchronization workflow does not yet reference `LABCONSTRICTOR_SYNC_TOKEN`. If you already saw an error saying that a GitHub App cannot create or update a workflow without `workflows` permission, make this small edit once: + +1. Open [`.github/workflows/sync_template.yml`](../../.github/workflows/sync_template.yml) in your repository. +2. Select the pencil icon to edit the file. +3. Copy and paste all the lines from the [LabConstrictor original workflow](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.github/workflows/sync_template.yml). + +4. Select **Commit changes** and commit directly to the default branch. +5. Run **Sync with Template Repository** again. + +The migration will then install the complete updated workflow automatically. This manual edit is only needed once for repositories whose existing workflow predates token integration. + +## Renewing an expired token + +When the token expires: + +1. Create a replacement token using Step 1. +2. Open **Settings โ†’ Secrets and variables โ†’ Actions**. +3. Select `LABCONSTRICTOR_SYNC_TOKEN`. +4. Select **Update secret** and paste the replacement token. +5. Run synchronization again. + +You do not need to edit the workflow again. + +--- + +
+ +[โ† Create repository](create_repository.md)            +[๐Ÿ  Documentation home](README.md)            +[Initialise repository โ†’](initialise_repository.md) + +
diff --git a/.template_sync/resources/v0_1_12_to_v0_1_13/.tools/python/bump_version.py b/.template_sync/resources/v0_1_12_to_v0_1_13/.tools/python/bump_version.py new file mode 100644 index 0000000..2807615 --- /dev/null +++ b/.template_sync/resources/v0_1_12_to_v0_1_13/.tools/python/bump_version.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +import argparse +import pathlib +import re +import shutil +import sys +import textwrap + +ROOT = pathlib.Path(__file__).resolve().parents[2] +CONSTRUCT = ROOT / "construct.yaml" + +# Match version line with optional quotes and optional trailing comment +VERSION_LINE_RE = re.compile( + r'^(version:\s*)(?P["\']?)(?P\d+\.\d+\.\d+)(?P=quote)(?P\s*(?:#.*)?)$', + re.MULTILINE, +) +CONCLUSION_LINE_RE = re.compile( + r'^(conclusion_text:\s*)(?:(?P["\'])(?P.*?)(?P=quote)|(?P.*?))(?P\s*(?:#.*)?)$', + re.MULTILINE, +) +PKG_VERSION_RE = re.compile(r'^(\s*SET\s+"PKG_VERSION=)(\d+\.\d+\.\d+)("\s*)$', re.MULTILINE) +POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat" + +def replace_version_placeholder(text: str, new_version: str) -> str: + """Render the release version in download documentation. + + Handles both pristine templates containing ``VERSION_NUMBER`` and + initialized repositories where that placeholder was already rendered to an + older explicit version such as ``0.0.0``. + """ + explicit_versions = set( + re.findall(r"/releases/download/(\d+\.\d+\.\d+)/", text) + ) + + text = text.replace("VERSION_NUMBER", new_version) + for previous_version in explicit_versions: + text = text.replace(previous_version, new_version) + return text + +def replace_version_in_file(file_path: pathlib.Path, old_version: str, new_version: str) -> bool: + """Replace all occurrences of old_version with new_version in a file. + + Works for markdown and Python files. Handles various version formats: + - Bare versions: 1.2.3 + - With 'v' prefix: v1.2.3 + - In quotes: "1.2.3" or '1.2.3' + - In version strings: version 1.2.3, __version__ = "1.2.3" + + Args: + file_path: Path to the file to update + old_version: Current version string (X.Y.Z format) + new_version: New version string (X.Y.Z format) + + Returns: + True if any replacements were made, False otherwise + """ + if not file_path.exists(): + return False + + text = file_path.read_text(encoding="utf-8") + original_text = text + + # Escape dots for regex + old_escaped = re.escape(old_version) + + # Pattern matches version with optional surrounding characters but preserves them + # Matches: v1.2.3, "1.2.3", '1.2.3', (1.2.3), [1.2.3], bare 1.2.3 + # Does NOT match partial versions like 1.2.34 or 11.2.3 + pattern = re.compile( + r'(?<=["\'\[(\s>v]|^)' + # Lookbehind: quote, bracket, paren, space, >, v, or start + old_escaped + + r'(?=["\'\])\s<,;]|$)' # Lookahead: quote, bracket, paren, space, <, comma, semicolon, or end + ) + + # Also match v-prefixed versions explicitly + v_pattern = re.compile(r'(v)' + old_escaped + r'(?=["\'\])\s<,;!]|$)') + + # Replace v-prefixed versions + text = v_pattern.sub(r'\g<1>' + new_version, text) + + # Replace other versions + text = pattern.sub(new_version, text) + + if text != original_text: + file_path.write_text(text, encoding="utf-8") + return True + return False + + +def read_current_version() -> tuple[str, str]: + """Read construct.yaml as text and extract current SemVer. + + Returns (file_text, version_string). Exits if not found. + """ + text = CONSTRUCT.read_text(encoding="utf-8") + m = VERSION_LINE_RE.search(text) + if not m: + raise ValueError("Could not find version in construct.yaml") + return text, m.group("version") + + +def bump_construct_text(text: str, old_version: str, new_version: str) -> str: + """Return updated file text with bumped version, preserving YAML structure/comments. + + - Updates the `version: "X.Y.Z"` line. + - Updates the version inside `conclusion_text`, replacing either + `VERSION_NUMBER` or the previous explicit version if present. + """ + # 1) Update the explicit version line + def _repl_version(m: re.Match) -> str: + # Preserve original quoting and trailing comment/whitespace + return f"{m.group(1)}{m.group('quote')}{new_version}{m.group('quote')}{m.group('trailing')}" + + text = VERSION_LINE_RE.sub(_repl_version, text, count=1) + + # 2) Update the version inside conclusion_text if present. + def _repl_conclusion(m: re.Match) -> str: + quote = m.group("quote") or "" + body = m.group("quoted_body") if quote else (m.group("bare_body") or "") + if "VERSION_NUMBER" in body: + updated_body = body.replace("VERSION_NUMBER", new_version) + else: + updated_body = re.sub( + r"\b\d+\.\d+\.\d+\b", + new_version, + body, + count=1, + ) + return f"{m.group(1)}{quote}{updated_body}{quote}{m.group('trailing')}" + + text = CONCLUSION_LINE_RE.sub(_repl_conclusion, text, count=1) + return text + + +def bump_post_install_bat(new_version: str) -> None: + if not POST_INSTALL.exists(): + return + text = POST_INSTALL.read_text(encoding="utf-8") + if not PKG_VERSION_RE.search(text): + return + updated = PKG_VERSION_RE.sub(lambda m: f"{m.group(1)}{new_version}{m.group(3)}", text, count=1) + POST_INSTALL.write_text(updated, encoding="utf-8") + print(f"Updated post_install.bat PKG_VERSION to {new_version}") + +def bump_version_in_download_executable_md(new_version: str) -> None: + possible_download_md_paths = [ + ROOT / "docs" / "download_executable.md", + ROOT / ".tools" / "docs" / "download_executable.md" + ] + template_md = ROOT / ".tools" / "templates" / "download_executable_template.md" + + for download_md in possible_download_md_paths: + # We only want to update the existing files + if download_md.exists(): + # Replace download_executable.md with the template (but only if it exists) + if template_md.exists(): + # Remove existing download_executable.md if present + if download_md.exists(): + download_md.unlink() + # Copy the template to the docs folder using shutil for cross-platform support + shutil.copy(template_md, download_md) + else: + print("Template for download_executable.md not found! Skipping creation of download_executable.md") + return + + # This file contains placeholders, update them with the new version + text = download_md.read_text(encoding="utf-8") + updated_text = replace_version_placeholder(text, new_version) + if updated_text != text: + download_md.write_text(updated_text, encoding="utf-8") + print(f"Updated download_executable.md to version {new_version}") + else: + print("No version string found in download_executable.md to update.") + +def main() -> None: + parser = argparse.ArgumentParser( + description="Update project version across release artifacts.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=textwrap.dedent( + """\ + Example: + python .tools/python/bump_version.py 0.0.4 + python .tools/python/bump_version.py 0.0.4 --files README.md src/__init__.py + """ + ), + ) + parser.add_argument("new_version", help="SemVer version, e.g. 0.0.4") + parser.add_argument( + "--files", + nargs="+", + help="Additional files to update (e.g., README.md, __init__.py)" + ) + args = parser.parse_args() + + if not re.fullmatch(r"\d+\.\d+\.\d+", args.new_version): + sys.exit("Version must look like X.Y.Z") + + text, current = read_current_version() + updated_text = bump_construct_text(text, current, args.new_version) + + if updated_text != text: + CONSTRUCT.write_text(updated_text, encoding="utf-8") + print(f"Bumped {current} -> {args.new_version}") + else: + print( + f"Project version already at {args.new_version}; " + "checking dependent versioned files." + ) + + # Also bump PKG_VERSION in post_install.bat + bump_post_install_bat(args.new_version) + + # Update download_executable.md + bump_version_in_download_executable_md(args.new_version) + + # Update additional files if specified + if args.files: + for file_path in args.files: + full_path = ROOT / file_path + if replace_version_in_file(full_path, current, args.new_version): + print(f"Updated {file_path}") + else: + print(f"No changes in {file_path}") + + +if __name__ == "__main__": + main() diff --git a/.template_sync/resources/v0_1_14_to_v0_1_15/.github/workflows/check_app_manifest.yml b/.template_sync/resources/v0_1_14_to_v0_1_15/.github/workflows/check_app_manifest.yml new file mode 100644 index 0000000..113f55f --- /dev/null +++ b/.template_sync/resources/v0_1_14_to_v0_1_15/.github/workflows/check_app_manifest.yml @@ -0,0 +1,46 @@ +name: Check App Centre manifest + +# Checks labconstrictor-app.yaml (the description of the app for the LabConstrictor App Centre). +# A missing file is a warning, an invalid file fails this check. It never blocks building installers: +# it runs on its own, also when a release is published. +on: + pull_request: + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + push: + branches: + - main + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + release: + types: + - published + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Check labconstrictor-app.yaml + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install pyyaml==6.0.2 jsonschema==4.23.0 + + - name: Check the manifest + run: python .tools/python/check_app_manifest.py diff --git a/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/docs/app_manifest.md b/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/docs/app_manifest.md new file mode 100644 index 0000000..a47e6eb --- /dev/null +++ b/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/docs/app_manifest.md @@ -0,0 +1,54 @@ +# 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. + +## How you get the file + +The [repository initialiser](initialise_repository.md) asks for a one-sentence summary, the kind of app and the software it also works in, and adds the file to the initialisation pull request. Read it in the pull request and edit it if you like. If you skip that section, or your repository was created before it existed, copy the example below to the root of your repository. + +## What it contains + +```yaml +# yaml-language-server: $schema=https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json +schema: 1 +name: My App +summary: One sentence that says what it does, for the app card. +description: |- + A few paragraphs of plain text. + + Separate paragraphs with a blank line. +kind: analysis # analysis, segmentation, simulation, game, training or utility +hosts: [notebook, napari] # where its tools can also run: notebook, napari, fiji, qupath +distribution: # at least one way to get the app + installer: true # the installers LabConstrictor builds for each release + colab: + - label: Notebook + url: https://colab.research.google.com/github/you/my-app/blob/main/notebooks/App/App.ipynb + pip: my-app # the name on PyPI +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. 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 automatic check + +The **Check App Centre manifest** workflow runs when you change the file and when you publish a release: + +- If the file is missing, it shows a warning and passes. +- If the file is invalid, it fails and says what to fix. This never stops your installers from being built. +- It also checks that the icon and screenshots you name exist in the repository. + +## 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. + +--- + +
+ +[โ† Previous](initialise_repository.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](external_code_upload.md) + + +
diff --git a/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/python/check_app_manifest.py b/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/python/check_app_manifest.py new file mode 100644 index 0000000..d6e19b9 --- /dev/null +++ b/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/python/check_app_manifest.py @@ -0,0 +1,104 @@ +"""Check labconstrictor-app.yaml, the optional description of an app for the LabConstrictor App Centre. + + python .tools/python/check_app_manifest.py [--repository-root .] + +Exit status: 0 = the file is valid, or there is no file (a GitHub warning says how to add one); +1 = the file is invalid (every problem is reported as a GitHub error annotation); +2 = the check itself could not run (for example the schema copy is missing). +The check never changes any file. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +import yaml +from jsonschema import Draft202012Validator + +MANIFEST_NAME = "labconstrictor-app.yaml" +SCHEMA_RELATIVE = Path(".tools/schema/labconstrictor-app.schema.json") +DOCS_HINT = "See .tools/docs/app_manifest.md." + + +class CheckError(Exception): + """The check could not run (not a problem with the manifest itself).""" + + +def load_schema(root: Path) -> dict[str, Any]: + """The vendored manifest schema. Raises CheckError when it is missing or not valid JSON.""" + path = root / SCHEMA_RELATIVE + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as err: + raise CheckError(f"cannot read the schema copy {SCHEMA_RELATIVE}: {err}") from err + + +def load_manifest(path: Path) -> Any: + """The parsed manifest. Raises ValueError with the YAML message when the file is not valid YAML.""" + try: + return yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as err: + raise ValueError(f"not valid YAML: {err}") from err + + +def schema_problems(manifest: Any, schema: dict[str, Any]) -> list[str]: + """One "path: message" line per way the manifest breaks the schema; empty when it is valid.""" + errors = sorted(Draft202012Validator(schema).iter_errors(manifest), key=lambda e: list(e.absolute_path)) + return [f"{'/'.join(str(p) for p in e.absolute_path) or 'manifest'}: {e.message}" for e in errors] + + +def referenced_paths(manifest: dict[str, Any]) -> list[str]: + """The repository files the manifest names: its icon and its screenshots.""" + paths = [manifest["icon"]] if "icon" in manifest else [] + return paths + [shot["path"] for shot in manifest.get("screenshots", [])] + + +def file_problems(manifest: dict[str, Any], root: Path) -> list[str]: + """One line per file the manifest names that does not exist in the repository.""" + return [f"{path}: file not found in the repository" for path in referenced_paths(manifest) if not (root / path).is_file()] + + +def annotate(level: str, message: str, title: str) -> None: + """Print a GitHub Actions annotation (shown on the run and on the file).""" + print(f"::{level} file={MANIFEST_NAME},title={title}::{message}") + + +def check(root: Path) -> int: + """Run the check; returns the exit status described at the top of this file.""" + manifest_path = root / MANIFEST_NAME + if not manifest_path.is_file(): + annotate("warning", f"{MANIFEST_NAME} is missing, so this app cannot be listed in the LabConstrictor App Centre. {DOCS_HINT}", "App Centre manifest missing") + return 0 + schema = load_schema(root) + try: + manifest = load_manifest(manifest_path) + except ValueError as err: + annotate("error", str(err), "App Centre manifest invalid") + return 1 + problems = schema_problems(manifest, schema) + if not problems: + problems = file_problems(manifest, root) + for problem in problems: + annotate("error", problem, "App Centre manifest invalid") + print(f"{MANIFEST_NAME}: {'invalid' if problems else 'valid'}") + return 1 if problems else 0 + + +def main() -> int: + """Command-line entry point.""" + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--repository-root", type=Path, default=Path(".")) + args = parser.parse_args() + try: + return check(args.repository_root.resolve()) + except CheckError as err: + print(f"::error title=App Centre check could not run::{err}") + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/schema/labconstrictor-app.schema.json b/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/schema/labconstrictor-app.schema.json new file mode 100644 index 0000000..b1d1c73 --- /dev/null +++ b/.template_sync/resources/v0_1_14_to_v0_1_15/.tools/schema/labconstrictor-app.schema.json @@ -0,0 +1,61 @@ +{ + "$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)." + }, + "distribution": { + "type": "object", "additionalProperties": false, "minProperties": 1, + "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."}, + "pip": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$", "description": "Name of the package on PyPI."} + } + }, + "authors": {"type": "array", "items": {"$ref": "#/$defs/author"}}, + "license": {"type": "string", "description": "SPDX identifier, for example MIT."}, + "categories": {"type": "array", "uniqueItems": true, "maxItems": 6, "items": {"type": "string", "maxLength": 30}}, + "doi": {"type": "string", "pattern": "^10\\.\\d{4,9}/\\S+$", "description": "DOI of the paper or archive to cite."}, + "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", "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": { + "https": {"type": "string", "pattern": "^https://[^\\s]+$"}, + "repoPath": {"type": "string", "pattern": "^(?!/)(?!.*\\.\\.)[A-Za-z0-9_./ -]+\\.(png|jpg|jpeg|gif)$", "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]+$"}} + }, + "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]$"}} + } + } +} diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/.github/workflows/check_app_manifest.yml b/.template_sync/resources/v0_1_15_to_v0_1_16/.github/workflows/check_app_manifest.yml new file mode 100644 index 0000000..113f55f --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/.github/workflows/check_app_manifest.yml @@ -0,0 +1,46 @@ +name: Check App Centre manifest + +# Checks labconstrictor-app.yaml (the description of the app for the LabConstrictor App Centre). +# A missing file is a warning, an invalid file fails this check. It never blocks building installers: +# it runs on its own, also when a release is published. +on: + pull_request: + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + push: + branches: + - main + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + release: + types: + - published + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Check labconstrictor-app.yaml + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install pyyaml==6.0.2 jsonschema==4.23.0 + + - name: Check the manifest + run: python .tools/python/check_app_manifest.py diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/docs/app_manifest.md b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/docs/app_manifest.md new file mode 100644 index 0000000..a7308f5 --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/docs/app_manifest.md @@ -0,0 +1,63 @@ +# 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. + +## How you get the file + +The [repository initialiser](initialise_repository.md) asks for a one-sentence summary, the kind of app and the software it also works in, and adds the file to the initialisation pull request. Read it in the pull request and edit it if you like. If you skip that section, or your repository was created before it existed, copy the example below to the root of your repository. + +## What it contains + +```yaml +# yaml-language-server: $schema=https://labconstrictor.cellmig.org/schema/labconstrictor-app.schema.json +schema: 1 +name: My App +summary: One sentence that says what it does, for the app card. +description: |- + A few paragraphs of plain text. + + Separate paragraphs with a blank line. +kind: analysis # analysis, segmentation, simulation, game, training or utility +hosts: [notebook, napari] # where its tools can also run: notebook, napari, fiji, qupath +status: Available # optional: Experimental, Available or Deprecated +inputs: # optional short lists (1 to 6 items of 5 to 200 characters each) + - TIFF images, one channel per file +outputs: + - Label masks and a CSV table +limitations: + - Not tested on 3D data +distribution: # at least one way to get the app: installer, colab or pip + installer: true # the installers LabConstrictor builds for each release + platforms: [windows-x86_64, macos-arm64, linux-x86_64] # optional, needs installer: offer only these installers + colab: + - label: Notebook + url: https://colab.research.google.com/github/you/my-app/blob/main/notebooks/App/App.ipynb + pip: my-app # the name on PyPI +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 automatic check + +The **Check App Centre manifest** workflow runs when you change the file and when you publish a release: + +- If the file is missing, it shows a warning and passes. +- If the file is invalid, it fails and says what to fix. This never stops your installers from being built. +- It rejects fields it does not know (this catches typos, so the schema is not loosened); the template keeps its copy of the schema in step with the App Centre, see [Keep your app up to date](keep_app_up_to_date.md). +- It also checks that the icon and screenshots you name exist in the repository. + +## 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. + +--- + +
+ +[โ† Previous](initialise_repository.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](external_code_upload.md) + + +
diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/docs/tools_bridge.md b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/docs/tools_bridge.md new file mode 100644 index 0000000..15c7638 --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/docs/tools_bridge.md @@ -0,0 +1,52 @@ +# Expose your app's tools to Napari and Fiji (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. + +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. +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. + **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.2.0-rc.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.2.0-rc.1"` in + `app/bash_bat_scripts/post_install.sh`, `SET "LC_TOOLS_PIN=v0.2.0-rc.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`. diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/python/check_app_manifest.py b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/python/check_app_manifest.py new file mode 100644 index 0000000..d6e19b9 --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/.tools/python/check_app_manifest.py @@ -0,0 +1,104 @@ +"""Check labconstrictor-app.yaml, the optional description of an app for the LabConstrictor App Centre. + + python .tools/python/check_app_manifest.py [--repository-root .] + +Exit status: 0 = the file is valid, or there is no file (a GitHub warning says how to add one); +1 = the file is invalid (every problem is reported as a GitHub error annotation); +2 = the check itself could not run (for example the schema copy is missing). +The check never changes any file. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +import yaml +from jsonschema import Draft202012Validator + +MANIFEST_NAME = "labconstrictor-app.yaml" +SCHEMA_RELATIVE = Path(".tools/schema/labconstrictor-app.schema.json") +DOCS_HINT = "See .tools/docs/app_manifest.md." + + +class CheckError(Exception): + """The check could not run (not a problem with the manifest itself).""" + + +def load_schema(root: Path) -> dict[str, Any]: + """The vendored manifest schema. Raises CheckError when it is missing or not valid JSON.""" + path = root / SCHEMA_RELATIVE + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as err: + raise CheckError(f"cannot read the schema copy {SCHEMA_RELATIVE}: {err}") from err + + +def load_manifest(path: Path) -> Any: + """The parsed manifest. Raises ValueError with the YAML message when the file is not valid YAML.""" + try: + return yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as err: + raise ValueError(f"not valid YAML: {err}") from err + + +def schema_problems(manifest: Any, schema: dict[str, Any]) -> list[str]: + """One "path: message" line per way the manifest breaks the schema; empty when it is valid.""" + errors = sorted(Draft202012Validator(schema).iter_errors(manifest), key=lambda e: list(e.absolute_path)) + return [f"{'/'.join(str(p) for p in e.absolute_path) or 'manifest'}: {e.message}" for e in errors] + + +def referenced_paths(manifest: dict[str, Any]) -> list[str]: + """The repository files the manifest names: its icon and its screenshots.""" + paths = [manifest["icon"]] if "icon" in manifest else [] + return paths + [shot["path"] for shot in manifest.get("screenshots", [])] + + +def file_problems(manifest: dict[str, Any], root: Path) -> list[str]: + """One line per file the manifest names that does not exist in the repository.""" + return [f"{path}: file not found in the repository" for path in referenced_paths(manifest) if not (root / path).is_file()] + + +def annotate(level: str, message: str, title: str) -> None: + """Print a GitHub Actions annotation (shown on the run and on the file).""" + print(f"::{level} file={MANIFEST_NAME},title={title}::{message}") + + +def check(root: Path) -> int: + """Run the check; returns the exit status described at the top of this file.""" + manifest_path = root / MANIFEST_NAME + if not manifest_path.is_file(): + annotate("warning", f"{MANIFEST_NAME} is missing, so this app cannot be listed in the LabConstrictor App Centre. {DOCS_HINT}", "App Centre manifest missing") + return 0 + schema = load_schema(root) + try: + manifest = load_manifest(manifest_path) + except ValueError as err: + annotate("error", str(err), "App Centre manifest invalid") + return 1 + problems = schema_problems(manifest, schema) + if not problems: + problems = file_problems(manifest, root) + for problem in problems: + annotate("error", problem, "App Centre manifest invalid") + print(f"{MANIFEST_NAME}: {'invalid' if problems else 'valid'}") + return 1 if problems else 0 + + +def main() -> int: + """Command-line entry point.""" + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--repository-root", type=Path, default=Path(".")) + args = parser.parse_args() + try: + return check(args.repository_root.resolve()) + except CheckError as err: + print(f"::error title=App Centre check could not run::{err}") + return 2 + + +if __name__ == "__main__": + sys.exit(main()) 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 new file mode 100644 index 0000000..30ae4ae --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/.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_15_to_v0_1_16/app/bash_bat_scripts/post_install.bat b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/post_install.bat new file mode 100644 index 0000000..e234cfd --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/post_install.bat @@ -0,0 +1,213 @@ +@ECHO OFF +SETLOCAL EnableExtensions DisableDelayedExpansion + +SET "LOG_FILE=%PREFIX%\menuinst_debug.log" +SET "PYTHON_EXE=%PREFIX%\python.exe" +SET "PROJECT_ROOT=%PREFIX%\PROJECT_NAME" +SET "BASE_REQUIREMENTS=%PROJECT_ROOT%\requirements.txt" +SET "GPU_REQUIREMENTS=%PROJECT_ROOT%\requirements_gpu.txt" +SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%" +SET "NVIDIA_SMI=" +SET "CA_BUNDLE=" +SET "FAILURE_MESSAGE=" +SET "CERTIFI_PATH_FILE=%TEMP%\labconstrictor_certifi_%RANDOM%_%RANDOM%.txt" + +> "%LOG_FILE%" echo Running post_install + +IF NOT EXIST "%PYTHON_EXE%" ( + SET "FAILURE_MESSAGE=Bundled Python executable was not found at %PYTHON_EXE%." + GOTO :fail +) +IF NOT EXIST "%PROJECT_ROOT%\launch_jupyter.py" ( + SET "FAILURE_MESSAGE=TLS-resilient launcher was not found at %PROJECT_ROOT%\launch_jupyter.py." + GOTO :fail +) +IF NOT EXIST "%BASE_REQUIREMENTS%" ( + SET "FAILURE_MESSAGE=Base requirements file was not found at %BASE_REQUIREMENTS%." + GOTO :fail +) + +REM pip 24.2+ uses the operating-system trust store by default. Some Windows +REM certificate stores contain malformed entries that OpenSSL cannot parse. +REM Keep verification enabled while opting out of system trust for installer +REM pip operations and using an explicit verified CA bundle. +SET "PIP_USE_DEPRECATED=legacy-certs" + +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --print-ca-bundle > "%CERTIFI_PATH_FILE%" 2>> "%LOG_FILE%" +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Unable to locate a verified CA bundle." + GOTO :fail +) +SET /P "CA_BUNDLE="<"%CERTIFI_PATH_FILE%" +DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 + +IF NOT DEFINED CA_BUNDLE ( + SET "FAILURE_MESSAGE=No verified CA bundle could be selected." + GOTO :fail +) +IF NOT EXIST "%CA_BUNDLE%" ( + SET "FAILURE_MESSAGE=Selected CA bundle does not exist: %CA_BUNDLE%" + GOTO :fail +) + +SET "PIP_CERT=%CA_BUNDLE%" +SET "REQUESTS_CA_BUNDLE=%CA_BUNDLE%" +SET "CURL_CA_BUNDLE=%CA_BUNDLE%" +echo Using verified CA bundle for installer network operations: "%CA_BUNDLE%" >> "%LOG_FILE%" + +IF EXIST "%GPU_REQUIREMENTS%" ( + CALL :detect_nvidia_smi + IF DEFINED NVIDIA_SMI ( + echo NVIDIA GPU utility detected, installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%LOG_FILE%" + SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%" + ) ELSE ( + echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" + ) +) ELSE ( + echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" +) + +echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application requirements installation failed." + GOTO :fail +) + +IF EXIST "%PROJECT_ROOT%\requirements-windows.txt" ( + echo Installing Windows-specific requirements. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install -r "%PROJECT_ROOT%\requirements-windows.txt" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Windows-specific requirements installation failed." + GOTO :fail + ) +) + +REM External Python code is optional in LabConstrictor projects. If setup.py is +REM bundled, install it without a temporary build environment and verify that +REM the generated import package is usable. Otherwise continue without it. +IF EXIST "%PROJECT_ROOT%\setup.py" ( + echo Found setup.py, installing PROJECT_NAME package locally without build isolation. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install --no-deps --no-build-isolation "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=PROJECT_NAME package installation failed." + GOTO :fail + ) + + "%PYTHON_EXE%" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Installed PROJECT_NAME package could not be imported as PYTHON_PROJ_NAME." + GOTO :fail + ) +) ELSE ( + echo No setup.py detected; this project does not bundle an optional Python package. >> "%LOG_FILE%" +) + +REM Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge). +REM If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +REM This step must never fail the installation. 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.2.0-rc.1" +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_APP_VERSION=" +IF EXIST "%PROJECT_ROOT%\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\construct.yaml"`) DO SET "LC_APP_VERSION=%%~B" +IF NOT DEFINED LC_APP_VERSION ( + SET "LC_APP_VERSION=0" + echo WARNING: no version: line at the start of a line in construct.yaml - registering the tools with version 0. >> "%LOG_FILE%" +) +"%PYTHON_EXE%" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('PYTHON_PROJ_NAME_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF NOT ERRORLEVEL 1 ( + echo Found PYTHON_PROJ_NAME_lc_tools: registering the tools of PROJECT_NAME for Napari and Fiji. >> "%LOG_FILE%" + REM LC_TOOLS_SPEC goes to pip as one argument through Python: cmd.exe never re-parses it (a quote or & in it cannot run anything). + "%PYTHON_EXE%" -c "import os, subprocess, sys; sys.exit(subprocess.call([sys.executable, '-m', 'pip', 'install', os.environ['LC_TOOLS_SPEC']]))" >> "%LOG_FILE%" 2>&1 + IF NOT ERRORLEVEL 1 "%PYTHON_EXE%" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "%PREFIX%" --module PYTHON_PROJ_NAME_lc_tools --version "%LC_APP_VERSION%" --display-name "PROJECT_NAME" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 echo WARNING: tool registration failed - see the pip and register output above in this file; PROJECT_NAME itself is installed. >> "%LOG_FILE%" +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\include_path.py" --path "%PREFIX%" --files "%PROJECT_ROOT%\notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher path preparation failed." + GOTO :fail +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\hide_code_cells.py" "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Notebook metadata preparation failed." + GOTO :fail +) + +REM Keep conda verification enabled, but avoid the Windows trust store that +REM failed during installation. Conda accepts a CA bundle path for ssl_verify. +echo Configuring conda to use verified CA bundle: "%CA_BUNDLE%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m conda config --system --set ssl_verify "%CA_BUNDLE%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: Could not configure conda with the selected CA bundle. The application launcher still has its own verified fallback. >> "%LOG_FILE%" +) + +REM Validate TLS and Jupyter imports before creating shortcuts or registering +REM the application. +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --self-test >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher preflight failed. See menuinst_debug.log and launcher_debug.log." + GOTO :fail +) +echo Launcher preflight completed successfully. >> "%LOG_FILE%" + +"%PYTHON_EXE%" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Python installation diagnostics failed." + GOTO :fail +) + +"%PYTHON_EXE%" -c "from menuinst.api import install; import os; print(install(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application shortcut creation failed." + GOTO :fail +) + +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" +SET "UNINSTALL_EXE=%PREFIX%\Uninstall-UNDERSCORED_PROJECT_NAME.exe" +SET "DISPLAY_ICON=%PROJECT_ROOT%\logo.ico" +SET "DISPLAY_VERSION=VERSION_NUMBER" +SET "PUBLISHER=GITHUB_OWNER" +echo Registering PROJECT_NAME in Windows Apps list >> "%LOG_FILE%" +reg add "%ARP_KEY%" /v DisplayName /d "PROJECT_NAME" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayVersion /d "%DISPLAY_VERSION%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v Publisher /d "%PUBLISHER%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v InstallLocation /d "%PREFIX%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayIcon /d "%DISPLAY_ICON%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v UninstallString /d "\"%UNINSTALL_EXE%\"" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v QuietUninstallString /d "\"%UNINSTALL_EXE%\" /S" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoModify /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoRepair /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 + +echo Post-install completed successfully. >> "%LOG_FILE%" +echo Post-install completed successfully. +ENDLOCAL +EXIT /B 0 + +:fail +IF EXIST "%CERTIFI_PATH_FILE%" DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 +IF NOT DEFINED FAILURE_MESSAGE SET "FAILURE_MESSAGE=Post-install failed for an unknown reason." +echo ERROR: %FAILURE_MESSAGE% >> "%LOG_FILE%" +echo ERROR: %FAILURE_MESSAGE% +echo See "%LOG_FILE%" for details. +ENDLOCAL +EXIT /B 1 + +:detect_nvidia_smi +FOR %%P IN ( + "%ProgramFiles%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%ProgramW6432%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%SystemRoot%\System32\nvidia-smi.exe" + "%SystemRoot%\Sysnative\nvidia-smi.exe" +) DO ( + IF NOT DEFINED NVIDIA_SMI IF EXIST "%%~P" SET "NVIDIA_SMI=%%~P" +) +IF DEFINED NVIDIA_SMI GOTO :EOF + +FOR /F "delims=" %%I IN ('where.exe nvidia-smi.exe 2^>NUL') DO ( + IF NOT DEFINED NVIDIA_SMI SET "NVIDIA_SMI=%%~fI" +) +GOTO :EOF diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/post_install.sh b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/post_install.sh new file mode 100644 index 0000000..39e24a4 --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/post_install.sh @@ -0,0 +1,121 @@ +#!/bin/bash +set -euo pipefail + +LOG_FILE="$PREFIX/menuinst_debug.log" +PYTHON_EXE="$PREFIX/bin/python" +PROJECT_ROOT="$PREFIX/PROJECT_NAME" +BASE_REQUIREMENTS="$PROJECT_ROOT/requirements.txt" +GPU_REQUIREMENTS="$PROJECT_ROOT/requirements_gpu.txt" +SELECTED_REQUIREMENTS="$BASE_REQUIREMENTS" + +echo "Running post_install" > "$LOG_FILE" + +fail() { + echo "ERROR: $1" | tee -a "$LOG_FILE" >&2 + exit 1 +} + +[ -x "$PYTHON_EXE" ] || fail "Bundled Python executable was not found at $PYTHON_EXE." +[ -f "$PROJECT_ROOT/launch_jupyter.py" ] || fail "TLS-resilient launcher was not found at $PROJECT_ROOT/launch_jupyter.py." +[ -f "$BASE_REQUIREMENTS" ] || fail "Base requirements file was not found at $BASE_REQUIREMENTS." + +# pip 24.2+ uses system certificates by default. Opt out for installer pip +# operations and use an explicit verified CA bundle instead. +export PIP_USE_DEPRECATED=legacy-certs +CA_BUNDLE="$("$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --print-ca-bundle 2>> "$LOG_FILE")" +[ -s "$CA_BUNDLE" ] || fail "No valid verified CA bundle could be selected: $CA_BUNDLE" + +export PIP_CERT="$CA_BUNDLE" +export REQUESTS_CA_BUNDLE="$CA_BUNDLE" +export CURL_CA_BUNDLE="$CA_BUNDLE" +echo "Using verified CA bundle for installer network operations: $CA_BUNDLE" >> "$LOG_FILE" + +if [ -f "$GPU_REQUIREMENTS" ]; then + if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "macOS detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + elif command -v nvidia-smi >/dev/null 2>&1; then + echo "NVIDIA GPU detected, installing GPU requirements from $GPU_REQUIREMENTS" >> "$LOG_FILE" + SELECTED_REQUIREMENTS="$GPU_REQUIREMENTS" + else + echo "NVIDIA GPU not detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + fi +else + echo "GPU requirements file not found, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" +fi + +echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE" +"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1 + +if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "Detected macOS platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-macos.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-macos.txt" >> "$LOG_FILE" 2>&1 + fi +elif [[ "${OSTYPE:-}" == "linux-gnu"* ]]; then + echo "Detected Linux platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-linux.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-linux.txt" >> "$LOG_FILE" 2>&1 + fi +else + echo "Unknown platform: ${OSTYPE:-unset}" >> "$LOG_FILE" +fi + +# External Python code is optional. Verify the generated package only when the +# constructor bundled setup.py and src/. +if [ -f "$PROJECT_ROOT/setup.py" ]; then + echo "Found setup.py, installing PROJECT_NAME package locally without build isolation" >> "$LOG_FILE" + "$PYTHON_EXE" -m pip install --no-deps --no-build-isolation "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + "$PYTHON_EXE" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "$LOG_FILE" 2>&1 +else + echo "No setup.py detected; this project does not bundle an optional Python package." >> "$LOG_FILE" +fi + + +# --- Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge) ------------------- +# If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +# This step must never fail the installation. 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.2.0-rc.1" +LC_TOOLS_MODULE="PYTHON_PROJ_NAME_lc_tools" +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 PROJECT_NAME for Napari and Fiji" + 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." + LC_APP_VERSION=0 + fi + if "$PYTHON_EXE" -m pip install "${LC_TOOLS_SPEC:-https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${LC_TOOLS_PIN}.zip}" >> "$LOG_FILE" 2>&1 \ + && "$PYTHON_EXE" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "$PREFIX" \ + --module "$LC_TOOLS_MODULE" --version "$LC_APP_VERSION" --display-name "PROJECT_NAME" >> "$LOG_FILE" 2>&1; then + lc_note "Tools registered (labconstrictor-tools list shows them)." + else + lc_note "WARNING: tool registration failed - see the pip and register output above in this file; PROJECT_NAME itself is installed." + fi +fi + +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PROJECT_ROOT/notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/pre_uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/hide_code_cells.py" "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + +# Keep conda verification enabled while avoiding the system certificate store +# that failed. Conda accepts a CA bundle path for ssl_verify. +if ! "$PYTHON_EXE" -m conda config --system --set ssl_verify "$CA_BUNDLE" >> "$LOG_FILE" 2>&1; then + echo "WARNING: Could not configure conda with the selected CA bundle. The launcher still has its own verified fallback." >> "$LOG_FILE" +fi + +# Do not create the application shortcut unless launcher preflight succeeds. +"$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --self-test >> "$LOG_FILE" 2>&1 +echo "Launcher preflight completed successfully." >> "$LOG_FILE" + +"$PYTHON_EXE" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" -c "from menuinst.api import install; import os; print(install(os.path.join('$PREFIX', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "$LOG_FILE" 2>&1 + +echo "Post-install completed successfully." >> "$LOG_FILE" + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/pre_uninstall.bat b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/pre_uninstall.bat new file mode 100644 index 0000000..14cdff0 --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/pre_uninstall.bat @@ -0,0 +1,9 @@ +@ECHO ON +echo Running pre-uninstall +"%PREFIX%\python.exe" -m labconstrictor_tools unregister --name "PROJECT_NAME" --prefix "%PREFIX%" >NUL 2>&1 +IF ERRORLEVEL 1 IF EXIST "%USERPROFILE%\.labconstrictor\apps\PROJECT_NAME.json" echo WARNING: could not remove PROJECT_NAME from the LabConstrictor tools list; if Napari or Fiji still list it, delete the files %USERPROFILE%\.labconstrictor\apps\PROJECT_NAME.json and PROJECT_NAME.schema.json. 1>&2 +"%PREFIX%\python.exe" -c "from menuinst.api import remove; import os; remove(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json'))" +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" +reg delete "%ARP_KEY%" /f >NUL 2>&1 +echo Pre-uninstall completed! +SetLocal EnableDelayedExpansion diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/pre_uninstall.sh b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/pre_uninstall.sh new file mode 100644 index 0000000..d3c3c0c --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/pre_uninstall.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e +echo "Running pre_uninstall" +# best effort: a failure must not stop the uninstall, but it is reported (a stale entry can stay in the Napari/Fiji list) +if ! "BASE_PATH/bin/python" -m labconstrictor_tools unregister --name "PROJECT_NAME" --prefix "BASE_PATH" > /dev/null 2>&1; then + LC_ENTRY="${LC_HOME:-$HOME/.labconstrictor}/apps/PROJECT_NAME" + if [ -e "$LC_ENTRY.json" ]; then + echo "WARNING: could not remove PROJECT_NAME from the LabConstrictor tools list; if Napari or Fiji still list it, delete the files $LC_ENTRY.json and $LC_ENTRY.schema.json." >&2 + fi +fi +"BASE_PATH/bin/python" -c "from menuinst.api import remove; import os; remove(os.path.join(r'BASE_PATH', 'PROJECT_NAME', 'notebook_launcher.json'))" diff --git a/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/uninstall.sh b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/uninstall.sh new file mode 100644 index 0000000..cb6d153 --- /dev/null +++ b/.template_sync/resources/v0_1_15_to_v0_1_16/app/bash_bat_scripts/uninstall.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +PREFIX="BASE_PATH" +echo "Uninstalling PROJECT_NAME from $PREFIX" +if [ -f "$PREFIX/pre_uninstall.sh" ]; then + # best effort: shortcut/registry cleanup must not stop the removal, but a failure must be visible + if ! bash "$PREFIX/pre_uninstall.sh"; then + echo "WARNING: pre-uninstall cleanup failed (see the messages above); shortcuts or the tools registry entry may remain." >&2 + fi +fi +if ! rm -rf -- "$PREFIX"; then + echo "ERROR: could not remove $PREFIX; PROJECT_NAME is only partly uninstalled. Close anything using it and delete that folder manually." >&2 + exit 1 +fi + +echo "PROJECT_NAME removed." + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi \ No newline at end of file diff --git a/.template_sync/resources/v0_1_16_to_v0_1_17/.tools/docs/tools_bridge.md b/.template_sync/resources/v0_1_16_to_v0_1_17/.tools/docs/tools_bridge.md new file mode 100644 index 0000000..236e827 --- /dev/null +++ b/.template_sync/resources/v0_1_16_to_v0_1_17/.tools/docs/tools_bridge.md @@ -0,0 +1,58 @@ +# Expose your app's tools to Napari and Fiji (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. + +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.2.0-rc.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.2.0-rc.1"` in + `app/bash_bat_scripts/post_install.sh`, `SET "LC_TOOLS_PIN=v0.2.0-rc.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`. diff --git a/.template_sync/resources/v0_1_16_to_v0_1_17/app/bash_bat_scripts/post_install.bat b/.template_sync/resources/v0_1_16_to_v0_1_17/app/bash_bat_scripts/post_install.bat new file mode 100644 index 0000000..55d9761 --- /dev/null +++ b/.template_sync/resources/v0_1_16_to_v0_1_17/app/bash_bat_scripts/post_install.bat @@ -0,0 +1,236 @@ +@ECHO OFF +SETLOCAL EnableExtensions DisableDelayedExpansion + +SET "LOG_FILE=%PREFIX%\menuinst_debug.log" +SET "PYTHON_EXE=%PREFIX%\python.exe" +SET "PROJECT_ROOT=%PREFIX%\PROJECT_NAME" +SET "BASE_REQUIREMENTS=%PROJECT_ROOT%\requirements.txt" +SET "GPU_REQUIREMENTS=%PROJECT_ROOT%\requirements_gpu.txt" +SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%" +SET "NVIDIA_SMI=" +SET "CA_BUNDLE=" +SET "FAILURE_MESSAGE=" +SET "CERTIFI_PATH_FILE=%TEMP%\labconstrictor_certifi_%RANDOM%_%RANDOM%.txt" + +> "%LOG_FILE%" echo Running post_install + +IF NOT EXIST "%PYTHON_EXE%" ( + SET "FAILURE_MESSAGE=Bundled Python executable was not found at %PYTHON_EXE%." + GOTO :fail +) +IF NOT EXIST "%PROJECT_ROOT%\launch_jupyter.py" ( + SET "FAILURE_MESSAGE=TLS-resilient launcher was not found at %PROJECT_ROOT%\launch_jupyter.py." + GOTO :fail +) +IF NOT EXIST "%BASE_REQUIREMENTS%" ( + SET "FAILURE_MESSAGE=Base requirements file was not found at %BASE_REQUIREMENTS%." + GOTO :fail +) + +REM pip 24.2+ uses the operating-system trust store by default. Some Windows +REM certificate stores contain malformed entries that OpenSSL cannot parse. +REM Keep verification enabled while opting out of system trust for installer +REM pip operations and using an explicit verified CA bundle. +SET "PIP_USE_DEPRECATED=legacy-certs" + +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --print-ca-bundle > "%CERTIFI_PATH_FILE%" 2>> "%LOG_FILE%" +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Unable to locate a verified CA bundle." + GOTO :fail +) +SET /P "CA_BUNDLE="<"%CERTIFI_PATH_FILE%" +DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 + +IF NOT DEFINED CA_BUNDLE ( + SET "FAILURE_MESSAGE=No verified CA bundle could be selected." + GOTO :fail +) +IF NOT EXIST "%CA_BUNDLE%" ( + SET "FAILURE_MESSAGE=Selected CA bundle does not exist: %CA_BUNDLE%" + GOTO :fail +) + +SET "PIP_CERT=%CA_BUNDLE%" +SET "REQUESTS_CA_BUNDLE=%CA_BUNDLE%" +SET "CURL_CA_BUNDLE=%CA_BUNDLE%" +echo Using verified CA bundle for installer network operations: "%CA_BUNDLE%" >> "%LOG_FILE%" + +IF EXIST "%GPU_REQUIREMENTS%" ( + CALL :detect_nvidia_smi + IF DEFINED NVIDIA_SMI ( + echo NVIDIA GPU utility detected, installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%LOG_FILE%" + SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%" + ) ELSE ( + echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" + ) +) ELSE ( + echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" +) + +echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application requirements installation failed." + GOTO :fail +) + +IF EXIST "%PROJECT_ROOT%\requirements-windows.txt" ( + echo Installing Windows-specific requirements. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install -r "%PROJECT_ROOT%\requirements-windows.txt" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Windows-specific requirements installation failed." + GOTO :fail + ) +) + +REM External Python code is optional in LabConstrictor projects. If setup.py is +REM bundled, install it without a temporary build environment and verify that +REM the generated import package is usable. Otherwise continue without it. +IF EXIST "%PROJECT_ROOT%\setup.py" ( + echo Found setup.py, installing PROJECT_NAME package locally without build isolation. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install --no-deps --no-build-isolation "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=PROJECT_NAME package installation failed." + GOTO :fail + ) + + REM Tools first, only for an app whose package ships a tools module: the package may import labconstrictor_tools at module level, + REM so labconstrictor-tools is installed BEFORE the import check below. A failed install is only a WARNING, see :install_lc_tools at the end of this file. + CALL :install_lc_tools + + "%PYTHON_EXE%" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Installed PROJECT_NAME package could not be imported as PYTHON_PROJ_NAME." + GOTO :fail + ) +) ELSE ( + echo No setup.py detected; this project does not bundle an optional Python package. >> "%LOG_FILE%" +) + +REM Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge). +REM If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +REM This step must never fail the installation. LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). +REM labconstrictor-tools is installed by :install_lc_tools, called above before the import check of the package (it sets LC_TOOLS_PIN, LC_TOOLS_SPEC and LC_TOOLS_READY). +SET "LC_APP_VERSION=" +IF EXIST "%PROJECT_ROOT%\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\construct.yaml"`) DO SET "LC_APP_VERSION=%%~B" +IF NOT DEFINED LC_APP_VERSION ( + SET "LC_APP_VERSION=0" + echo WARNING: no version: line at the start of a line in construct.yaml - registering the tools with version 0. >> "%LOG_FILE%" +) +"%PYTHON_EXE%" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('PYTHON_PROJ_NAME_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF NOT ERRORLEVEL 1 ( + echo Found PYTHON_PROJ_NAME_lc_tools: registering the tools of PROJECT_NAME for Napari and Fiji. >> "%LOG_FILE%" + REM labconstrictor-tools was installed before the import check (:install_lc_tools): register only if that worked (errorlevel 1 otherwise). + "%PYTHON_EXE%" -c "import sys; sys.exit(0 if sys.argv[1] == '1' else 1)" "%LC_TOOLS_READY%" >> "%LOG_FILE%" 2>&1 + IF NOT ERRORLEVEL 1 "%PYTHON_EXE%" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "%PREFIX%" --module PYTHON_PROJ_NAME_lc_tools --version "%LC_APP_VERSION%" --display-name "PROJECT_NAME" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 echo WARNING: tool registration failed - see the pip and register output above in this file; PROJECT_NAME itself is installed. >> "%LOG_FILE%" +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\include_path.py" --path "%PREFIX%" --files "%PROJECT_ROOT%\notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher path preparation failed." + GOTO :fail +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\hide_code_cells.py" "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Notebook metadata preparation failed." + GOTO :fail +) + +REM Keep conda verification enabled, but avoid the Windows trust store that +REM failed during installation. Conda accepts a CA bundle path for ssl_verify. +echo Configuring conda to use verified CA bundle: "%CA_BUNDLE%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m conda config --system --set ssl_verify "%CA_BUNDLE%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: Could not configure conda with the selected CA bundle. The application launcher still has its own verified fallback. >> "%LOG_FILE%" +) + +REM Validate TLS and Jupyter imports before creating shortcuts or registering +REM the application. +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --self-test >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher preflight failed. See menuinst_debug.log and launcher_debug.log." + GOTO :fail +) +echo Launcher preflight completed successfully. >> "%LOG_FILE%" + +"%PYTHON_EXE%" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Python installation diagnostics failed." + GOTO :fail +) + +"%PYTHON_EXE%" -c "from menuinst.api import install; import os; print(install(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application shortcut creation failed." + GOTO :fail +) + +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" +SET "UNINSTALL_EXE=%PREFIX%\Uninstall-UNDERSCORED_PROJECT_NAME.exe" +SET "DISPLAY_ICON=%PROJECT_ROOT%\logo.ico" +SET "DISPLAY_VERSION=VERSION_NUMBER" +SET "PUBLISHER=GITHUB_OWNER" +echo Registering PROJECT_NAME in Windows Apps list >> "%LOG_FILE%" +reg add "%ARP_KEY%" /v DisplayName /d "PROJECT_NAME" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayVersion /d "%DISPLAY_VERSION%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v Publisher /d "%PUBLISHER%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v InstallLocation /d "%PREFIX%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayIcon /d "%DISPLAY_ICON%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v UninstallString /d "\"%UNINSTALL_EXE%\"" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v QuietUninstallString /d "\"%UNINSTALL_EXE%\" /S" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoModify /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoRepair /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 + +echo Post-install completed successfully. >> "%LOG_FILE%" +echo Post-install completed successfully. +ENDLOCAL +EXIT /B 0 + +:fail +IF EXIST "%CERTIFI_PATH_FILE%" DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 +IF NOT DEFINED FAILURE_MESSAGE SET "FAILURE_MESSAGE=Post-install failed for an unknown reason." +echo ERROR: %FAILURE_MESSAGE% >> "%LOG_FILE%" +echo ERROR: %FAILURE_MESSAGE% +echo See "%LOG_FILE%" for details. +ENDLOCAL +EXIT /B 1 + +:detect_nvidia_smi +FOR %%P IN ( + "%ProgramFiles%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%ProgramW6432%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%SystemRoot%\System32\nvidia-smi.exe" + "%SystemRoot%\Sysnative\nvidia-smi.exe" +) DO ( + IF NOT DEFINED NVIDIA_SMI IF EXIST "%%~P" SET "NVIDIA_SMI=%%~P" +) +IF DEFINED NVIDIA_SMI GOTO :EOF + +FOR /F "delims=" %%I IN ('where.exe nvidia-smi.exe 2^>NUL') DO ( + IF NOT DEFINED NVIDIA_SMI SET "NVIDIA_SMI=%%~fI" +) +GOTO :EOF + +:install_lc_tools +REM Optional (LabConstrictor tools bridge): install labconstrictor-tools when the app's package ships a module named _lc_tools. +REM Called before the import check of the package, which may import labconstrictor_tools at module level. +REM This step must never fail the installation: a failure is logged as a WARNING and LC_TOOLS_READY stays 0 (no registration later). +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.2.0-rc.1" +IF NOT DEFINED LC_TOOLS_SPEC SET "LC_TOOLS_SPEC=https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/%LC_TOOLS_PIN%.zip" +SET "LC_TOOLS_READY=0" +"%PYTHON_EXE%" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('PYTHON_PROJ_NAME_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 GOTO :EOF +echo Found PYTHON_PROJ_NAME_lc_tools: installing labconstrictor-tools before the import check of PROJECT_NAME. >> "%LOG_FILE%" +REM LC_TOOLS_SPEC goes to pip as one argument through Python: cmd.exe never re-parses it (a quote or & in it cannot run anything). +"%PYTHON_EXE%" -c "import os, subprocess, sys; sys.exit(subprocess.call([sys.executable, '-m', 'pip', 'install', os.environ['LC_TOOLS_SPEC']]))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: labconstrictor-tools could not be installed - see the pip output above in this file; the tools of PROJECT_NAME will not be registered ^(the import check fails only if the package needs labconstrictor-tools at import time^). >> "%LOG_FILE%" + GOTO :EOF +) +SET "LC_TOOLS_READY=1" +GOTO :EOF diff --git a/.template_sync/resources/v0_1_16_to_v0_1_17/app/bash_bat_scripts/post_install.sh b/.template_sync/resources/v0_1_16_to_v0_1_17/app/bash_bat_scripts/post_install.sh new file mode 100644 index 0000000..67d91a2 --- /dev/null +++ b/.template_sync/resources/v0_1_16_to_v0_1_17/app/bash_bat_scripts/post_install.sh @@ -0,0 +1,134 @@ +#!/bin/bash +set -euo pipefail + +LOG_FILE="$PREFIX/menuinst_debug.log" +PYTHON_EXE="$PREFIX/bin/python" +PROJECT_ROOT="$PREFIX/PROJECT_NAME" +BASE_REQUIREMENTS="$PROJECT_ROOT/requirements.txt" +GPU_REQUIREMENTS="$PROJECT_ROOT/requirements_gpu.txt" +SELECTED_REQUIREMENTS="$BASE_REQUIREMENTS" + +echo "Running post_install" > "$LOG_FILE" + +fail() { + echo "ERROR: $1" | tee -a "$LOG_FILE" >&2 + exit 1 +} + +[ -x "$PYTHON_EXE" ] || fail "Bundled Python executable was not found at $PYTHON_EXE." +[ -f "$PROJECT_ROOT/launch_jupyter.py" ] || fail "TLS-resilient launcher was not found at $PROJECT_ROOT/launch_jupyter.py." +[ -f "$BASE_REQUIREMENTS" ] || fail "Base requirements file was not found at $BASE_REQUIREMENTS." + +# pip 24.2+ uses system certificates by default. Opt out for installer pip +# operations and use an explicit verified CA bundle instead. +export PIP_USE_DEPRECATED=legacy-certs +CA_BUNDLE="$("$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --print-ca-bundle 2>> "$LOG_FILE")" +[ -s "$CA_BUNDLE" ] || fail "No valid verified CA bundle could be selected: $CA_BUNDLE" + +export PIP_CERT="$CA_BUNDLE" +export REQUESTS_CA_BUNDLE="$CA_BUNDLE" +export CURL_CA_BUNDLE="$CA_BUNDLE" +echo "Using verified CA bundle for installer network operations: $CA_BUNDLE" >> "$LOG_FILE" + +if [ -f "$GPU_REQUIREMENTS" ]; then + if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "macOS detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + elif command -v nvidia-smi >/dev/null 2>&1; then + echo "NVIDIA GPU detected, installing GPU requirements from $GPU_REQUIREMENTS" >> "$LOG_FILE" + SELECTED_REQUIREMENTS="$GPU_REQUIREMENTS" + else + echo "NVIDIA GPU not detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + fi +else + echo "GPU requirements file not found, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" +fi + +echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE" +"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1 + +if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "Detected macOS platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-macos.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-macos.txt" >> "$LOG_FILE" 2>&1 + fi +elif [[ "${OSTYPE:-}" == "linux-gnu"* ]]; then + echo "Detected Linux platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-linux.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-linux.txt" >> "$LOG_FILE" 2>&1 + fi +else + echo "Unknown platform: ${OSTYPE:-unset}" >> "$LOG_FILE" +fi + +# External Python code is optional. Verify the generated package only when the +# constructor bundled setup.py and src/. +if [ -f "$PROJECT_ROOT/setup.py" ]; then + echo "Found setup.py, installing PROJECT_NAME package locally without build isolation" >> "$LOG_FILE" + "$PYTHON_EXE" -m pip install --no-deps --no-build-isolation "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + # Tools first, only for an app whose package ships a _lc_tools module: the app package may import labconstrictor_tools + # at module level, so labconstrictor-tools must be installed BEFORE the import check below. A failed install is only a WARNING + # (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.2.0-rc.1" + LC_TOOLS_MODULE="PYTHON_PROJ_NAME_lc_tools" + LC_TOOLS_READY=0 + if "$PYTHON_EXE" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('$LC_TOOLS_MODULE') else 1)" >> "$LOG_FILE" 2>&1; then + echo "Found $LC_TOOLS_MODULE: installing labconstrictor-tools before the import check of PROJECT_NAME" >> "$LOG_FILE" || : + if "$PYTHON_EXE" -m pip install "${LC_TOOLS_SPEC:-https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${LC_TOOLS_PIN}.zip}" >> "$LOG_FILE" 2>&1; then + LC_TOOLS_READY=1 + else + echo "WARNING: labconstrictor-tools could not be installed - see the pip output above in this file; the tools of PROJECT_NAME will not be registered (the import check below fails only if the package needs labconstrictor-tools at import time)." >> "$LOG_FILE" || : + fi + fi + "$PYTHON_EXE" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "$LOG_FILE" 2>&1 +else + echo "No setup.py detected; this project does not bundle an optional Python package." >> "$LOG_FILE" +fi + + +# --- Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge) ------------------- +# If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +# This step must never fail the installation. LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). +# 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 PROJECT_NAME for Napari and Fiji" + 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." + LC_APP_VERSION=0 + fi + if [ "${LC_TOOLS_READY:-0}" = 1 ] \ + && "$PYTHON_EXE" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "$PREFIX" \ + --module "$LC_TOOLS_MODULE" --version "$LC_APP_VERSION" --display-name "PROJECT_NAME" >> "$LOG_FILE" 2>&1; then + lc_note "Tools registered (labconstrictor-tools list shows them)." + else + lc_note "WARNING: tool registration failed - see the pip and register output above in this file; PROJECT_NAME itself is installed." + fi +fi + +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PROJECT_ROOT/notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/pre_uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/hide_code_cells.py" "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + +# Keep conda verification enabled while avoiding the system certificate store +# that failed. Conda accepts a CA bundle path for ssl_verify. +if ! "$PYTHON_EXE" -m conda config --system --set ssl_verify "$CA_BUNDLE" >> "$LOG_FILE" 2>&1; then + echo "WARNING: Could not configure conda with the selected CA bundle. The launcher still has its own verified fallback." >> "$LOG_FILE" +fi + +# Do not create the application shortcut unless launcher preflight succeeds. +"$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --self-test >> "$LOG_FILE" 2>&1 +echo "Launcher preflight completed successfully." >> "$LOG_FILE" + +"$PYTHON_EXE" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" -c "from menuinst.api import install; import os; print(install(os.path.join('$PREFIX', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "$LOG_FILE" 2>&1 + +echo "Post-install completed successfully." >> "$LOG_FILE" + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/check_app_manifest.yml b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/check_app_manifest.yml new file mode 100644 index 0000000..113f55f --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/check_app_manifest.yml @@ -0,0 +1,46 @@ +name: Check App Centre manifest + +# Checks labconstrictor-app.yaml (the description of the app for the LabConstrictor App Centre). +# A missing file is a warning, an invalid file fails this check. It never blocks building installers: +# it runs on its own, also when a release is published. +on: + pull_request: + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + push: + branches: + - main + paths: + - labconstrictor-app.yaml + - .tools/schema/** + - .tools/python/check_app_manifest.py + - .github/workflows/check_app_manifest.yml + release: + types: + - published + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Check labconstrictor-app.yaml + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install pyyaml==6.0.2 jsonschema==4.23.0 + + - name: Check the manifest + run: python .tools/python/check_app_manifest.py diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/release_constructor.yml b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/release_constructor.yml new file mode 100644 index 0000000..4e7939b --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/release_constructor.yml @@ -0,0 +1,188 @@ +name: Build Release Installers + +on: + release: + types: + - published + workflow_dispatch: + inputs: + version: + description: "Version to package (e.g. 0.0.4). Defaults to release tag when empty." + required: false + +# This enables to run a single workflow at a time +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: write + +jobs: + bump-version: + name: Bump version on main branch + runs-on: ubuntu-latest + if: github.event_name == 'release' + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Determine release version + id: version + run: | + set -euxo pipefail + RAW="${{ github.event.release.tag_name }}" + RAW="${RAW#v}" + echo "release_version=$RAW" >> "$GITHUB_OUTPUT" + echo "RELEASE_VERSION=$RAW" >> "$GITHUB_ENV" + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Sync versioned files + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_version.py" \ + .tools/python/bump_version.py \ + python .tools/python/bump_version.py "${RELEASE_VERSION}" + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_constructor.py" \ + .tools/python/bump_constructor.py \ + python .tools/python/bump_constructor.py + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_Welcome_notebook.py" \ + .tools/python/bump_Welcome_notebook.py \ + python .tools/python/bump_Welcome_notebook.py "${{ github.repository_owner }}" "${{ github.event.repository.name }}" + + + - name: Commit updated versioned files + uses: stefanzweifel/git-auto-commit-action@b863ae1933cb653a53c021fe36dbb774e1fb9403 # v5 + with: + branch: main + commit_message: GitHub Action - Update version to ${{ github.event.release.tag_name }} + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: release-bump-version-logs + path: artifacts/error_log_document.log + if-no-files-found: ignore + archive: false + + build-installers: + name: Build installers (${{ matrix.os_name }}) + runs-on: ${{ matrix.runner }} + needs: bump-version + strategy: + fail-fast: false + matrix: + include: + - os_name: linux + runner: ubuntu-latest + - os_name: macos-arm64 + runner: macos-15 + - os_name: macos-intel + runner: macos-15-intel + - os_name: windows + runner: windows-latest + defaults: + run: + shell: bash -l {0} + env: + CONSTRUCTOR_ENV: constructor-env + OUTPUT_DIR: dist/${{ matrix.os_name }} + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: Determine release version + id: version + run: | + set -euxo pipefail + if [ "${{ github.event_name }}" = "release" ]; then + RAW="${{ github.event.release.tag_name }}" + else + RAW="${{ inputs.version }}" + fi + + if [ -z "$RAW" ]; then + echo "Version is required when running manually." >&2 + exit 1 + fi + + RAW="${RAW#v}" + echo "release_version=$RAW" >> "$GITHUB_OUTPUT" + echo "RELEASE_VERSION=$RAW" >> "$GITHUB_ENV" + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Sync versioned files and populate Welcome notebook + run: | + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "bump_version.py" \ + .tools/python/bump_version.py \ + python .tools/python/bump_version.py "${RELEASE_VERSION}" + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "bump_constructor.py" \ + .tools/python/bump_constructor.py \ + python .tools/python/bump_constructor.py + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document.log" \ + "bump_Welcome_notebook.py" \ + .tools/python/bump_Welcome_notebook.py \ + python .tools/python/bump_Welcome_notebook.py "${{ github.repository_owner }}" "${{ github.event.repository.name }}" + + - name: Set up Miniconda + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Create constructor environment + run: | + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document_${{ matrix.os_name }}.log" \ + "create_constructor_environment.sh" \ + .tools/bash/create_constructor_environment.sh \ + bash .tools/bash/create_constructor_environment.sh + + - name: Build installer with constructor + run: | + bash .tools/bash/run_with_context.sh \ + "artifacts/error_log_document_${{ matrix.os_name }}.log" \ + "build_installer_with_constructor.sh" \ + .tools/bash/build_installer_with_constructor.sh \ + bash .tools/bash/build_installer_with_constructor.sh + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: build-installers-${{ matrix.os_name }}-logs + path: artifacts/error_log_document_${{ matrix.os_name }}.log + if-no-files-found: ignore + archive: false + + - name: Upload installers to release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + files: dist/${{ matrix.os_name }}/* + fail_on_unmatched_files: true diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/sync_template.yml b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/sync_template.yml new file mode 100644 index 0000000..8ba8f42 --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/sync_template.yml @@ -0,0 +1,170 @@ +name: Sync with Template Repository + +on: + schedule: + # Run weekly on Monday at 9 AM UTC + - cron: '0 9 * * 1' + workflow_dispatch: + +# This enables only one template synchronization workflow at a time. +concurrency: + group: template-sync-main + cancel-in-progress: false + +permissions: + contents: write + pull-requests: write + +jobs: + sync-template: + name: Sync with template repository + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: main + fetch-depth: 0 + # Do not leave the default GITHUB_TOKEN in the local Git configuration. + # The pull-request step authenticates separately with the repository-scoped + # LABCONSTRICTOR_SYNC_TOKEN secret. + persist-credentials: false + + - name: Configure Git + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Add upstream remote + run: | + git remote add upstream https://github.com/CellMigrationLab/LabConstrictor.git + + - name: Fetch upstream changes + run: | + git fetch upstream main + + - name: Read local template version + id: local-version + run: | + local_version=$(python3 - <<'PY' + from pathlib import Path + + manifest = Path(".template_sync/manifest.yaml") + if not manifest.exists(): + print("0.0.0") + raise SystemExit + + for line in manifest.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if stripped.startswith("template_version:"): + print(stripped.split(":", 1)[1].strip()) + break + else: + raise SystemExit("template_version not found in .template_sync/manifest.yaml") + PY + ) + echo "version=$local_version" >> "$GITHUB_OUTPUT" + + - name: Read upstream template version + id: upstream-version + run: | + upstream_version=$(python3 - <<'PY' + import subprocess + + manifest = subprocess.run( + ["git", "show", "upstream/main:.template_sync/manifest.yaml"], + check=True, + capture_output=True, + text=True, + ).stdout + for line in manifest.splitlines(): + stripped = line.strip() + if stripped.startswith("template_version:"): + print(stripped.split(":", 1)[1].strip()) + break + else: + raise SystemExit( + "template_version not found in upstream .template_sync/manifest.yaml" + ) + PY + ) + echo "version=$upstream_version" >> "$GITHUB_OUTPUT" + + - name: Check whether template sync is needed + id: version-check + env: + LOCAL_VERSION: ${{ steps.local-version.outputs.version }} + UPSTREAM_VERSION: ${{ steps.upstream-version.outputs.version }} + run: | + python3 - <<'PY' + import os + from pathlib import Path + + def parse_version(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + local_version = os.environ["LOCAL_VERSION"] + upstream_version = os.environ["UPSTREAM_VERSION"] + sync_required = parse_version(upstream_version) > parse_version(local_version) + + output_path = Path(os.environ["GITHUB_OUTPUT"]) + with output_path.open("a", encoding="utf-8") as fh: + fh.write(f"sync_required={'true' if sync_required else 'false'}\n") + PY + + - name: Check synchronization token setup + if: steps.version-check.outputs.sync_required == 'true' + env: + LABCONSTRICTOR_SYNC_TOKEN: ${{ secrets.LABCONSTRICTOR_SYNC_TOKEN }} + run: | + if [[ -z "$LABCONSTRICTOR_SYNC_TOKEN" ]]; then + { + echo "## One-time LabConstrictor setup required" + echo + echo "A template update is available, but this repository does not have the" + echo '`LABCONSTRICTOR_SYNC_TOKEN` repository secret configured.' + echo + echo "Follow the beginner-friendly guide in:" + echo + echo '`.tools/docs/template_synchronization.md`' + } >> "$GITHUB_STEP_SUMMARY" + + echo "::error title=Synchronization setup required::Configure the LABCONSTRICTOR_SYNC_TOKEN repository secret by following .tools/docs/template_synchronization.md." + exit 1 + fi + + - name: Fetch template sync bootstrap + if: steps.version-check.outputs.sync_required == 'true' + run: | + git checkout upstream/main -- .template_sync + + - name: Run template migrations + if: steps.version-check.outputs.sync_required == 'true' + run: | + python3 .template_sync/sync.py \ + --from-version "${{ steps.local-version.outputs.version }}" \ + --to-version "${{ steps.upstream-version.outputs.version }}" \ + --repository-root "$GITHUB_WORKSPACE" + + - name: Check for changes + id: check-changes + run: | + if [[ -n "$(git status --short)" ]]; then + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + echo "has_changes=false" >> "$GITHUB_OUTPUT" + fi + + - name: Create pull request + if: steps.check-changes.outputs.has_changes == 'true' + uses: peter-evans/create-pull-request@c5a7806660adbe173f04e3e038b0ccdcd758773c # v6 + with: + token: ${{ secrets.LABCONSTRICTOR_SYNC_TOKEN }} + branch: template-sync-${{ steps.local-version.outputs.version }}-to-${{ steps.upstream-version.outputs.version }} + delete-branch: true + commit-message: Sync template to version ${{ steps.upstream-version.outputs.version }} + title: Sync template to version ${{ steps.upstream-version.outputs.version }} + body: | + This PR updates `.template_sync` from the template repository and applies the migrations needed to move this repository from template version `${{ steps.local-version.outputs.version }}` to `${{ steps.upstream-version.outputs.version }}`. + + The branch is created with the repository-scoped `LABCONSTRICTOR_SYNC_TOKEN` secret so that updates to GitHub workflow files can be included safely. diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/update_on_notebook_change.yml b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/update_on_notebook_change.yml new file mode 100644 index 0000000..c5fae88 --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/update_on_notebook_change.yml @@ -0,0 +1,154 @@ +name: Updates on notebook change + +on: + push: + branches: [ main, master ] + paths: + - 'notebooks/**/*.ipynb' + - 'notebooks/notebook_latest_versions.yaml' + - 'notebooks/**/requirements.yaml' + workflow_dispatch: + +# This enables to run a single workflow at a time +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon notebook change, update manifests and changelogs + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@2d756ea4c53f7f6b397767d8723b3a10a9f35bf2 # v44 + with: + separator: "," + files: | + notebooks/**/*.ipynb + notebooks/notebook_latest_versions.yaml + notebooks/**/requirements.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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "sync_notebook_versions.py" \ + .tools/python/sync_notebook_versions.py \ + python .tools/python/sync_notebook_versions.py + + - name: Update CHANGELOG + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_changelog.py" \ + .tools/python/update_changelog.py \ + python .tools/python/update_changelog.py notebooks/notebook_latest_versions.yaml + + - name: Update last commit in notebook_latest_versions.yaml + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_version_last_commit.py" \ + .tools/python/update_version_last_commit.py \ + python .tools/python/update_version_last_commit.py notebooks/notebook_latest_versions.yaml + + - name: Hide code cells in notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "hide_code_cells.py" \ + app/python_scripts/hide_code_cells.py \ + python app/python_scripts/hide_code_cells.py . + + - name: Index notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_notebook_README.py" \ + .tools/python/bump_notebook_README.py \ + 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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "merge_requirements.py" \ + .tools/python/merge_requirements.py \ + python .tools/python/merge_requirements.py --source-dir notebooks --output requirements.txt + + - name: Check for changes + id: check-changes + run: | + if [ -z "$(git status --porcelain)" ]; then + echo "has_changes=false" >> $GITHUB_OUTPUT + else + echo "has_changes=true" >> $GITHUB_OUTPUT + fi + + - name: Set up Miniconda for requirements test + if: steps.check-changes.outputs.has_changes == 'true' + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Verify merged requirements inside conda + id: test-conda-env + if: steps.check-changes.outputs.has_changes == 'true' + env: + SKIP_CONDA_ENV_TEST: ${{ vars.SKIP_CONDA_ENV_TEST }} + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "test_conda_environment.sh" \ + .tools/bash/test_conda_environment.sh \ + bash .tools/bash/test_conda_environment.sh + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: notebook-debug-bundle + path: artifacts/error_log_document.log + archive: false + + - name: Commit updated files + id: auto-commit + if: steps.check-changes.outputs.has_changes == 'true' && steps.test-conda-env.outcome == 'success' + uses: stefanzweifel/git-auto-commit-action@b863ae1933cb653a53c021fe36dbb774e1fb9403 # v5 + with: + commit_message: GitHub Action - Updated files because of notebook and/or requirements changes + file_pattern: requirements*.txt environment.yaml notebooks/* setup.py + + - name: Revert user commit that broke requirements + if: failure() && github.event_name == 'push' + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git reset --hard + git clean -fd + git revert "${{ github.sha }}" -m 1 --no-edit + git push origin HEAD:${{ github.ref_name }} diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/update_on_src_change.yaml b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/update_on_src_change.yaml new file mode 100644 index 0000000..76b90f0 --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/.github/workflows/update_on_src_change.yaml @@ -0,0 +1,41 @@ +name: Updates on external code change + +on: + push: + branches: [ main, master ] + paths: + - 'src/**' + workflow_dispatch: + +# This enables to run a single workflow at a time +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon external code update the code version + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Update src change file + run: | + cat > .tools/meta/src_change.yaml < **Check where it comes from.** The installers are not code-signed yet, so your system will warn you. Download only from the app's own GitHub release (the address starts with `https://github.com/` followed by the app's owner and repository, as shown on the app's page), and run it only if you trust that owner. A listing in the App Centre checks that the files come from the app's repository; it is not a security audit. + +> A command prompt window opens during installation on Windows; this is normal, do not close it. + +## Before you install + +- **Install path.** The install path must contain no space: the installer refuses a path with a space. Use a path such as `C:\LabConstrictor\` on Windows or `~/labconstrictor/` on macOS and Linux. + +## Install on Windows + +1. Download the `.exe` file and double-click it. +2. If Windows shows "Windows protected your PC", click "More info" and then "Run anyway". The installers are not code-signed yet. + + ![Windows protected your PC: click More info, then Run anyway](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Windows_Protected_your_PC.png) + +3. Follow the on-screen prompts. Launch the app from the Start Menu or your desktop. + +## Install on a Mac + +1. Choose your file: open the Apple menu, then About This Mac. If the Chip or Processor says Intel, download the Intel installer; if it says M1, M2 or similar, download the Apple Silicon one. +2. Double-click the `.pkg` file. If macOS refuses to open it, go to System Settings, Privacy & Security, scroll down to the message about the package and click "Open Anyway" (it appears only after you tried to open the file once). If you do not see it, try opening the file again, then check this page again. +3. Follow the prompts (we recommend "Install only for me"). Launch the app from your Applications folder. + +## Install on Linux + +1. Download the `.sh` file. +2. Open a terminal in the download folder and run `bash` followed by the name of the file you downloaded, for example: `bash MyApp-0.1.0-Linux-x86_64.sh` +3. Follow the prompts, then launch the app from your applications menu. + +## Update an installed app + +- **macOS and Windows.** On macOS and Windows, update an app by uninstalling the old version first and then installing the new one: the installer does not install over an existing install. On macOS, if you already ran the new installer over the old version and it stopped or reported a failure at the end, move only the old app shortcut (for example `~/Applications/MyApp.app`) to the Bin, keep the app's folder in your home folder, and run the installer again ([known issue](https://github.com/CellMigrationLab/LabConstrictor/issues/34)). +- **Linux.** On Linux, running the installer with `-u` updates in place only if the previous install finished; otherwise delete `/pkgs` or uninstall the app and install it again. + +## Where the app is listed + +If the app ships tools for Napari, Fiji or QuPath, the installer registers them with LabConstrictor Tools and passes the `hosts:` line of the app's `labconstrictor-app.yaml` (the installer bundles that file). A host lists the app only if the line names it: with `hosts: [notebook, napari]` the app is listed in Napari, and not in Fiji or QuPath. Without the file, or without a `hosts:` line, the app is registered without hosts, every host lists it, and `menuinst_debug.log` in the install folder says so (`'' declares no hosts, so it is listed in every host; ...`). + +## Next + +Open the app and start working: [Use notebooks after installation](notebook_usage.md). If something goes wrong, see [Troubleshooting an installed app](troubleshooting_installed_app.md). diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/.tools/docs/tools_bridge.md b/.template_sync/resources/v0_1_17_to_v0_1_18/.tools/docs/tools_bridge.md new file mode 100644 index 0000000..14e69dc --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/.tools/docs/tools_bridge.md @@ -0,0 +1,58 @@ +# Expose your app's tools to Napari and Fiji (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. + +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.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`. diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/app/bash_bat_scripts/post_install.bat b/.template_sync/resources/v0_1_17_to_v0_1_18/app/bash_bat_scripts/post_install.bat new file mode 100644 index 0000000..4dd92c6 --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/app/bash_bat_scripts/post_install.bat @@ -0,0 +1,245 @@ +@ECHO OFF +SETLOCAL EnableExtensions DisableDelayedExpansion + +SET "LOG_FILE=%PREFIX%\menuinst_debug.log" +SET "PYTHON_EXE=%PREFIX%\python.exe" +SET "PROJECT_ROOT=%PREFIX%\PROJECT_NAME" +SET "BASE_REQUIREMENTS=%PROJECT_ROOT%\requirements.txt" +SET "GPU_REQUIREMENTS=%PROJECT_ROOT%\requirements_gpu.txt" +SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%" +SET "NVIDIA_SMI=" +SET "CA_BUNDLE=" +SET "FAILURE_MESSAGE=" +SET "CERTIFI_PATH_FILE=%TEMP%\labconstrictor_certifi_%RANDOM%_%RANDOM%.txt" + +> "%LOG_FILE%" echo Running post_install + +IF NOT EXIST "%PYTHON_EXE%" ( + SET "FAILURE_MESSAGE=Bundled Python executable was not found at %PYTHON_EXE%." + GOTO :fail +) +IF NOT EXIST "%PROJECT_ROOT%\launch_jupyter.py" ( + SET "FAILURE_MESSAGE=TLS-resilient launcher was not found at %PROJECT_ROOT%\launch_jupyter.py." + GOTO :fail +) +IF NOT EXIST "%BASE_REQUIREMENTS%" ( + SET "FAILURE_MESSAGE=Base requirements file was not found at %BASE_REQUIREMENTS%." + GOTO :fail +) + +REM pip 24.2+ uses the operating-system trust store by default. Some Windows +REM certificate stores contain malformed entries that OpenSSL cannot parse. +REM Keep verification enabled while opting out of system trust for installer +REM pip operations and using an explicit verified CA bundle. +SET "PIP_USE_DEPRECATED=legacy-certs" + +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --print-ca-bundle > "%CERTIFI_PATH_FILE%" 2>> "%LOG_FILE%" +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Unable to locate a verified CA bundle." + GOTO :fail +) +SET /P "CA_BUNDLE="<"%CERTIFI_PATH_FILE%" +DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 + +IF NOT DEFINED CA_BUNDLE ( + SET "FAILURE_MESSAGE=No verified CA bundle could be selected." + GOTO :fail +) +IF NOT EXIST "%CA_BUNDLE%" ( + SET "FAILURE_MESSAGE=Selected CA bundle does not exist: %CA_BUNDLE%" + GOTO :fail +) + +SET "PIP_CERT=%CA_BUNDLE%" +SET "REQUESTS_CA_BUNDLE=%CA_BUNDLE%" +SET "CURL_CA_BUNDLE=%CA_BUNDLE%" +echo Using verified CA bundle for installer network operations: "%CA_BUNDLE%" >> "%LOG_FILE%" + +IF EXIST "%GPU_REQUIREMENTS%" ( + CALL :detect_nvidia_smi + IF DEFINED NVIDIA_SMI ( + echo NVIDIA GPU utility detected, installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%LOG_FILE%" + SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%" + ) ELSE ( + echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" + ) +) ELSE ( + echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" +) + +echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application requirements installation failed." + GOTO :fail +) + +IF EXIST "%PROJECT_ROOT%\requirements-windows.txt" ( + echo Installing Windows-specific requirements. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install -r "%PROJECT_ROOT%\requirements-windows.txt" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Windows-specific requirements installation failed." + GOTO :fail + ) +) + +REM External Python code is optional in LabConstrictor projects. If setup.py is +REM bundled, install it without a temporary build environment and verify that +REM the generated import package is usable. Otherwise continue without it. +IF EXIST "%PROJECT_ROOT%\setup.py" ( + echo Found setup.py, installing PROJECT_NAME package locally without build isolation. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install --no-deps --no-build-isolation "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=PROJECT_NAME package installation failed." + GOTO :fail + ) + + REM Tools first, only for an app whose package ships a tools module: the package may import labconstrictor_tools at module level, + REM so labconstrictor-tools is installed BEFORE the import check below. A failed install is only a WARNING, see :install_lc_tools at the end of this file. + CALL :install_lc_tools + + "%PYTHON_EXE%" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Installed PROJECT_NAME package could not be imported as PYTHON_PROJ_NAME." + GOTO :fail + ) +) ELSE ( + echo No setup.py detected; this project does not bundle an optional Python package. >> "%LOG_FILE%" +) + +REM Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge). +REM If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +REM This step must never fail the installation. LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). +REM labconstrictor-tools is installed by :install_lc_tools, called above before the import check of the package (it sets LC_TOOLS_PIN, LC_TOOLS_SPEC and LC_TOOLS_READY). +SET "LC_APP_VERSION=" +IF EXIST "%PROJECT_ROOT%\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\construct.yaml"`) DO SET "LC_APP_VERSION=%%~B" +IF NOT DEFINED LC_APP_VERSION ( + SET "LC_APP_VERSION=0" + echo WARNING: no version: line at the start of a line in construct.yaml - registering the tools with version 0. >> "%LOG_FILE%" +) +REM Hosts of the app: the app's labconstrictor-app.yaml (bundled by construct.yaml extra_files) goes to Tools with --app-manifest, so that +REM Napari, Fiji and QuPath list the app only in the hosts its hosts: line names. Without the file the app is +REM registered without hosts (every host lists it) and the log says so (see the lines after "Found ... registering" below). +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('PYTHON_PROJ_NAME_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF NOT ERRORLEVEL 1 ( + echo Found PYTHON_PROJ_NAME_lc_tools: registering the tools of PROJECT_NAME for Napari and Fiji. >> "%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 PROJECT_NAME is registered without hosts. 'PROJECT_NAME' 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%" + REM labconstrictor-tools was installed before the import check (:install_lc_tools): register only if that worked (errorlevel 1 otherwise). + "%PYTHON_EXE%" -c "import sys; sys.exit(0 if sys.argv[1] == '1' else 1)" "%LC_TOOLS_READY%" >> "%LOG_FILE%" 2>&1 + IF NOT ERRORLEVEL 1 IF DEFINED LC_APP_MANIFEST "%PYTHON_EXE%" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "%PREFIX%" --module PYTHON_PROJ_NAME_lc_tools --version "%LC_APP_VERSION%" --display-name "PROJECT_NAME" --app-manifest "%LC_APP_MANIFEST%" >> "%LOG_FILE%" 2>&1 + IF NOT ERRORLEVEL 1 IF NOT DEFINED LC_APP_MANIFEST "%PYTHON_EXE%" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "%PREFIX%" --module PYTHON_PROJ_NAME_lc_tools --version "%LC_APP_VERSION%" --display-name "PROJECT_NAME" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 echo WARNING: tool registration failed - see the pip and register output above in this file; PROJECT_NAME itself is installed. >> "%LOG_FILE%" +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\include_path.py" --path "%PREFIX%" --files "%PROJECT_ROOT%\notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher path preparation failed." + GOTO :fail +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\hide_code_cells.py" "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Notebook metadata preparation failed." + GOTO :fail +) + +REM Keep conda verification enabled, but avoid the Windows trust store that +REM failed during installation. Conda accepts a CA bundle path for ssl_verify. +echo Configuring conda to use verified CA bundle: "%CA_BUNDLE%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m conda config --system --set ssl_verify "%CA_BUNDLE%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: Could not configure conda with the selected CA bundle. The application launcher still has its own verified fallback. >> "%LOG_FILE%" +) + +REM Validate TLS and Jupyter imports before creating shortcuts or registering +REM the application. +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --self-test >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher preflight failed. See menuinst_debug.log and launcher_debug.log." + GOTO :fail +) +echo Launcher preflight completed successfully. >> "%LOG_FILE%" + +"%PYTHON_EXE%" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Python installation diagnostics failed." + GOTO :fail +) + +"%PYTHON_EXE%" -c "from menuinst.api import install; import os; print(install(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application shortcut creation failed." + GOTO :fail +) + +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" +SET "UNINSTALL_EXE=%PREFIX%\Uninstall-UNDERSCORED_PROJECT_NAME.exe" +SET "DISPLAY_ICON=%PROJECT_ROOT%\logo.ico" +SET "DISPLAY_VERSION=VERSION_NUMBER" +SET "PUBLISHER=GITHUB_OWNER" +echo Registering PROJECT_NAME in Windows Apps list >> "%LOG_FILE%" +reg add "%ARP_KEY%" /v DisplayName /d "PROJECT_NAME" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayVersion /d "%DISPLAY_VERSION%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v Publisher /d "%PUBLISHER%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v InstallLocation /d "%PREFIX%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayIcon /d "%DISPLAY_ICON%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v UninstallString /d "\"%UNINSTALL_EXE%\"" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v QuietUninstallString /d "\"%UNINSTALL_EXE%\" /S" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoModify /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoRepair /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 + +echo Post-install completed successfully. >> "%LOG_FILE%" +echo Post-install completed successfully. +ENDLOCAL +EXIT /B 0 + +:fail +IF EXIST "%CERTIFI_PATH_FILE%" DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 +IF NOT DEFINED FAILURE_MESSAGE SET "FAILURE_MESSAGE=Post-install failed for an unknown reason." +echo ERROR: %FAILURE_MESSAGE% >> "%LOG_FILE%" +echo ERROR: %FAILURE_MESSAGE% +echo See "%LOG_FILE%" for details. +ENDLOCAL +EXIT /B 1 + +:detect_nvidia_smi +FOR %%P IN ( + "%ProgramFiles%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%ProgramW6432%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%SystemRoot%\System32\nvidia-smi.exe" + "%SystemRoot%\Sysnative\nvidia-smi.exe" +) DO ( + IF NOT DEFINED NVIDIA_SMI IF EXIST "%%~P" SET "NVIDIA_SMI=%%~P" +) +IF DEFINED NVIDIA_SMI GOTO :EOF + +FOR /F "delims=" %%I IN ('where.exe nvidia-smi.exe 2^>NUL') DO ( + IF NOT DEFINED NVIDIA_SMI SET "NVIDIA_SMI=%%~fI" +) +GOTO :EOF + +:install_lc_tools +REM Optional (LabConstrictor tools bridge): install labconstrictor-tools when the app's package ships a module named _lc_tools. +REM Called before the import check of the package, which may import labconstrictor_tools at module level. +REM This step must never fail the installation: a failure is logged as a WARNING and LC_TOOLS_READY stays 0 (no registration later). +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" +IF NOT DEFINED LC_TOOLS_SPEC SET "LC_TOOLS_SPEC=https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/%LC_TOOLS_PIN%.zip" +SET "LC_TOOLS_READY=0" +"%PYTHON_EXE%" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('PYTHON_PROJ_NAME_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 GOTO :EOF +echo Found PYTHON_PROJ_NAME_lc_tools: installing labconstrictor-tools before the import check of PROJECT_NAME. >> "%LOG_FILE%" +REM LC_TOOLS_SPEC goes to pip as one argument through Python: cmd.exe never re-parses it (a quote or & in it cannot run anything). +"%PYTHON_EXE%" -c "import os, subprocess, sys; sys.exit(subprocess.call([sys.executable, '-m', 'pip', 'install', os.environ['LC_TOOLS_SPEC']]))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: labconstrictor-tools could not be installed - see the pip output above in this file; the tools of PROJECT_NAME will not be registered ^(the import check fails only if the package needs labconstrictor-tools at import time^). >> "%LOG_FILE%" + GOTO :EOF +) +SET "LC_TOOLS_READY=1" +GOTO :EOF diff --git a/.template_sync/resources/v0_1_17_to_v0_1_18/app/bash_bat_scripts/post_install.sh b/.template_sync/resources/v0_1_17_to_v0_1_18/app/bash_bat_scripts/post_install.sh new file mode 100644 index 0000000..ebcaf0b --- /dev/null +++ b/.template_sync/resources/v0_1_17_to_v0_1_18/app/bash_bat_scripts/post_install.sh @@ -0,0 +1,147 @@ +#!/bin/bash +set -euo pipefail + +LOG_FILE="$PREFIX/menuinst_debug.log" +PYTHON_EXE="$PREFIX/bin/python" +PROJECT_ROOT="$PREFIX/PROJECT_NAME" +BASE_REQUIREMENTS="$PROJECT_ROOT/requirements.txt" +GPU_REQUIREMENTS="$PROJECT_ROOT/requirements_gpu.txt" +SELECTED_REQUIREMENTS="$BASE_REQUIREMENTS" + +echo "Running post_install" > "$LOG_FILE" + +fail() { + echo "ERROR: $1" | tee -a "$LOG_FILE" >&2 + exit 1 +} + +[ -x "$PYTHON_EXE" ] || fail "Bundled Python executable was not found at $PYTHON_EXE." +[ -f "$PROJECT_ROOT/launch_jupyter.py" ] || fail "TLS-resilient launcher was not found at $PROJECT_ROOT/launch_jupyter.py." +[ -f "$BASE_REQUIREMENTS" ] || fail "Base requirements file was not found at $BASE_REQUIREMENTS." + +# pip 24.2+ uses system certificates by default. Opt out for installer pip +# operations and use an explicit verified CA bundle instead. +export PIP_USE_DEPRECATED=legacy-certs +CA_BUNDLE="$("$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --print-ca-bundle 2>> "$LOG_FILE")" +[ -s "$CA_BUNDLE" ] || fail "No valid verified CA bundle could be selected: $CA_BUNDLE" + +export PIP_CERT="$CA_BUNDLE" +export REQUESTS_CA_BUNDLE="$CA_BUNDLE" +export CURL_CA_BUNDLE="$CA_BUNDLE" +echo "Using verified CA bundle for installer network operations: $CA_BUNDLE" >> "$LOG_FILE" + +if [ -f "$GPU_REQUIREMENTS" ]; then + if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "macOS detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + elif command -v nvidia-smi >/dev/null 2>&1; then + echo "NVIDIA GPU detected, installing GPU requirements from $GPU_REQUIREMENTS" >> "$LOG_FILE" + SELECTED_REQUIREMENTS="$GPU_REQUIREMENTS" + else + echo "NVIDIA GPU not detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + fi +else + echo "GPU requirements file not found, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" +fi + +echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE" +"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1 + +if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "Detected macOS platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-macos.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-macos.txt" >> "$LOG_FILE" 2>&1 + fi +elif [[ "${OSTYPE:-}" == "linux-gnu"* ]]; then + echo "Detected Linux platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-linux.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-linux.txt" >> "$LOG_FILE" 2>&1 + fi +else + echo "Unknown platform: ${OSTYPE:-unset}" >> "$LOG_FILE" +fi + +# External Python code is optional. Verify the generated package only when the +# constructor bundled setup.py and src/. +if [ -f "$PROJECT_ROOT/setup.py" ]; then + echo "Found setup.py, installing PROJECT_NAME package locally without build isolation" >> "$LOG_FILE" + "$PYTHON_EXE" -m pip install --no-deps --no-build-isolation "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + # Tools first, only for an app whose package ships a _lc_tools module: the app package may import labconstrictor_tools + # at module level, so labconstrictor-tools must be installed BEFORE the import check below. A failed install is only a WARNING + # (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_MODULE="PYTHON_PROJ_NAME_lc_tools" + LC_TOOLS_READY=0 + if "$PYTHON_EXE" -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('$LC_TOOLS_MODULE') else 1)" >> "$LOG_FILE" 2>&1; then + echo "Found $LC_TOOLS_MODULE: installing labconstrictor-tools before the import check of PROJECT_NAME" >> "$LOG_FILE" || : + if "$PYTHON_EXE" -m pip install "${LC_TOOLS_SPEC:-https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${LC_TOOLS_PIN}.zip}" >> "$LOG_FILE" 2>&1; then + LC_TOOLS_READY=1 + else + echo "WARNING: labconstrictor-tools could not be installed - see the pip output above in this file; the tools of PROJECT_NAME will not be registered (the import check below fails only if the package needs labconstrictor-tools at import time)." >> "$LOG_FILE" || : + fi + fi + "$PYTHON_EXE" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "$LOG_FILE" 2>&1 +else + echo "No setup.py detected; this project does not bundle an optional Python package." >> "$LOG_FILE" +fi + + +# --- Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge) ------------------- +# If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +# This step must never fail the installation. LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). +# 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 PROJECT_NAME for Napari and Fiji" + 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." + LC_APP_VERSION=0 + fi + # Hosts of the app: the app's labconstrictor-app.yaml (bundled by construct.yaml extra_files) goes to Tools with --app-manifest, so that + # Napari, Fiji and QuPath list the app only in the hosts its hosts: line names. Without the file the app is registered + # without hosts (every host lists it) and the log says so, with the sentence Tools uses for it. Tools itself reads the file: a manifest + # without a hosts: line (or with an invalid one) is answered by Tools, whose message goes to this log. + LC_APP_MANIFEST="$PROJECT_ROOT/labconstrictor-app.yaml" + LC_HOSTS_ARGS=() + LC_NO_HOSTS="'PROJECT_NAME' declares no hosts, so it is listed in every host; register it with --app-manifest (or --hosts) to choose" + if [ ! -f "$LC_APP_MANIFEST" ]; then + lc_note "WARNING: $LC_APP_MANIFEST was not found (add labconstrictor-app.yaml to extra_files in construct.yaml), so PROJECT_NAME is registered without hosts. $LC_NO_HOSTS" + else + LC_HOSTS_ARGS=(--app-manifest "$LC_APP_MANIFEST") + lc_note "Passing the hosts of $LC_APP_MANIFEST to Tools (--app-manifest); Tools logs the same sentence if the file declares no hosts." + fi + if [ "${LC_TOOLS_READY:-0}" = 1 ] \ + && "$PYTHON_EXE" -m labconstrictor_tools register --name "PROJECT_NAME" --prefix "$PREFIX" \ + --module "$LC_TOOLS_MODULE" --version "$LC_APP_VERSION" --display-name "PROJECT_NAME" ${LC_HOSTS_ARGS[@]+"${LC_HOSTS_ARGS[@]}"} >> "$LOG_FILE" 2>&1; then + lc_note "Tools registered (labconstrictor-tools list shows them)." + else + lc_note "WARNING: tool registration failed - see the pip and register output above in this file; PROJECT_NAME itself is installed." + fi +fi + +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PROJECT_ROOT/notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/pre_uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/hide_code_cells.py" "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + +# Keep conda verification enabled while avoiding the system certificate store +# that failed. Conda accepts a CA bundle path for ssl_verify. +if ! "$PYTHON_EXE" -m conda config --system --set ssl_verify "$CA_BUNDLE" >> "$LOG_FILE" 2>&1; then + echo "WARNING: Could not configure conda with the selected CA bundle. The launcher still has its own verified fallback." >> "$LOG_FILE" +fi + +# Do not create the application shortcut unless launcher preflight succeeds. +"$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --self-test >> "$LOG_FILE" 2>&1 +echo "Launcher preflight completed successfully." >> "$LOG_FILE" + +"$PYTHON_EXE" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" -c "from menuinst.api import install; import os; print(install(os.path.join('$PREFIX', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "$LOG_FILE" 2>&1 + +echo "Post-install completed successfully." >> "$LOG_FILE" + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/.github/workflows/update_on_notebook_change.yml b/.template_sync/resources/v0_1_19_to_v0_1_20/.github/workflows/update_on_notebook_change.yml new file mode 100644 index 0000000..4a8c03b --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/.github/workflows/update_on_notebook_change.yml @@ -0,0 +1,211 @@ +name: Updates on notebook change + +on: + push: + branches: [ main, master ] + paths: + - 'notebooks/**/*.ipynb' + - 'notebooks/notebook_latest_versions.yaml' + - 'notebooks/**/requirements.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, +# because each one rebases its commit onto the latest branch before it pushes (a shared group kept only one waiting run, so a +# third push cancelled the waiting run of the other workflow). +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon notebook change, update manifests and changelogs + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@2d756ea4c53f7f6b397767d8723b3a10a9f35bf2 # v44 + with: + separator: "," + files: | + notebooks/**/*.ipynb + notebooks/notebook_latest_versions.yaml + notebooks/**/requirements.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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "sync_notebook_versions.py" \ + .tools/python/sync_notebook_versions.py \ + python .tools/python/sync_notebook_versions.py + + - name: Update CHANGELOG + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_changelog.py" \ + .tools/python/update_changelog.py \ + python .tools/python/update_changelog.py notebooks/notebook_latest_versions.yaml + + - name: Update last commit in notebook_latest_versions.yaml + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_version_last_commit.py" \ + .tools/python/update_version_last_commit.py \ + python .tools/python/update_version_last_commit.py notebooks/notebook_latest_versions.yaml + + - name: Hide code cells in notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "hide_code_cells.py" \ + app/python_scripts/hide_code_cells.py \ + python app/python_scripts/hide_code_cells.py . + + - name: Index notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_notebook_README.py" \ + .tools/python/bump_notebook_README.py \ + 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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "merge_requirements.py" \ + .tools/python/merge_requirements.py \ + python .tools/python/merge_requirements.py --source-dir notebooks --output requirements.txt + + # requirements*.txt -> requirements*.lock.txt: every package the installer installs with pip, with its exact version (uv, valid on + # Windows, macOS and Linux). A lock file is rewritten only when its requirements file, Python or JupyterLab version changed. + - name: Lock requirements + run: | + bash .tools/bash/run_with_context.sh artifacts/error_log_document.log "lock_requirements.py" .tools/python/lock_requirements.py python .tools/python/lock_requirements.py + + - name: Check for changes + id: check-changes + run: | + if [ -z "$(git status --porcelain)" ]; then + echo "has_changes=false" >> $GITHUB_OUTPUT + else + echo "has_changes=true" >> $GITHUB_OUTPUT + fi + + - name: Set up Miniconda for requirements test + if: steps.check-changes.outputs.has_changes == 'true' + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Verify merged requirements inside conda + id: test-conda-env + if: steps.check-changes.outputs.has_changes == 'true' + env: + SKIP_CONDA_ENV_TEST: ${{ vars.SKIP_CONDA_ENV_TEST }} + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "test_conda_environment.sh" \ + .tools/bash/test_conda_environment.sh \ + bash .tools/bash/test_conda_environment.sh + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: notebook-debug-bundle + path: artifacts/error_log_document.log + archive: false + + - name: Commit updated files + id: auto-commit + if: steps.check-changes.outputs.has_changes == 'true' && steps.test-conda-env.outcome == 'success' + env: + BRANCH: ${{ github.ref_name }} + COMMIT_MESSAGE: GitHub Action - Updated files because of notebook and/or requirements changes + # The run checked out the commit that triggered it (the scripts above compare it with its parent); the branch may have moved + # since (another workflow committed, or a new push). A rejected push is therefore retried after a rebase onto the latest branch. + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git ls-files -z --modified --deleted --others --exclude-standard -- 'requirements*.txt' environment.yaml 'notebooks/*' setup.py | xargs -0 -r git add -A -- + if git diff --cached --quiet; then + echo "No changes to commit." + exit 0 + fi + git commit -m "$COMMIT_MESSAGE" + for attempt in 1 2 3 4 5; do + if git push origin "HEAD:refs/heads/$BRANCH"; then + exit 0 + fi + echo "The push was rejected (attempt $attempt of 5): rebasing onto the latest $BRANCH." + sleep $((attempt * 5)) + git fetch origin "$BRANCH" + if ! git rebase --autostash "origin/$BRANCH"; then + git rebase --abort || true + echo "::error::The commit of this run conflicts with the latest $BRANCH; run this workflow again (Actions > Run workflow)." + exit 1 + fi + done + echo "::error::The push was rejected 5 times; run this workflow again (Actions > Run workflow)." + exit 1 + + # Only when the merged requirements could not be installed: a failure of any other step (a script, the push) never reverts a commit. + - name: Revert user commit that broke requirements + if: failure() && github.event_name == 'push' && steps.test-conda-env.outcome == 'failure' + env: + BRANCH: ${{ github.ref_name }} + BAD_COMMIT: ${{ github.sha }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git reset --hard + git clean -fd + for attempt in 1 2 3 4 5; do + git fetch origin "$BRANCH" + git checkout -B "$BRANCH" "origin/$BRANCH" + # A merge commit is reverted against its first parent (-m 1); any other commit is reverted as it is. + if [ "$(git rev-list --parents -n 1 "$BAD_COMMIT" | wc -w)" -gt 2 ]; then + REVERT_ARGS=(-m 1) + else + REVERT_ARGS=() + fi + if ! git revert --no-edit "${REVERT_ARGS[@]}" "$BAD_COMMIT"; then + git revert --abort || true + echo "::error::$BAD_COMMIT broke the requirements but could not be reverted automatically (later commits change the same lines): revert it by hand." + exit 1 + fi + if git push origin "HEAD:refs/heads/$BRANCH"; then + exit 0 + fi + echo "The push of the revert was rejected (attempt $attempt of 5): retrying on the latest $BRANCH." + sleep $((attempt * 5)) + done + echo "::error::The revert of $BAD_COMMIT could not be pushed: revert it by hand." + exit 1 diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/.github/workflows/update_on_src_change.yaml b/.template_sync/resources/v0_1_19_to_v0_1_20/.github/workflows/update_on_src_change.yaml new file mode 100644 index 0000000..2ab8870 --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/.github/workflows/update_on_src_change.yaml @@ -0,0 +1,66 @@ +name: Updates on external code change + +on: + push: + branches: [ main, master ] + paths: + - 'src/**' + workflow_dispatch: + +# One run of this workflow at a time per branch. The notebook workflow has its own group: the two can run at the same time, +# because each one rebases its commit onto the latest branch before it pushes (a shared group kept only one waiting run, so a +# third push cancelled the waiting run of the other workflow). +concurrency: + group: src-change-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon external code update the code version + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Update src change file + run: | + cat > .tools/meta/src_change.yaml < Run workflow)." + exit 1 + fi + done + echo "::error::The push was rejected 5 times; run this workflow again (Actions > Run workflow)." + exit 1 diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/.tools/bash/test_conda_environment.sh b/.template_sync/resources/v0_1_19_to_v0_1_20/.tools/bash/test_conda_environment.sh new file mode 100644 index 0000000..4742aca --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/.tools/bash/test_conda_environment.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# Test script to validate conda environment creation and pip requirements installation +# This script creates a test conda environment from environment.yaml and installs pip requirements + +set -e # Exit on any error +set -u # Exit on undefined variables + +is_truthy() { + case "${1:-}" in + 1|true|TRUE|True|yes|YES|Yes|on|ON|On) + return 0 + ;; + *) + return 1 + ;; + esac +} + +if is_truthy "${SKIP_CONDA_ENV_TEST:-}"; then + echo "SKIP_CONDA_ENV_TEST is enabled; skipping conda environment validation." + exit 0 +fi + +echo "==========================================" +echo "Testing Conda Environment Creation" +echo "==========================================" + +# Define test environment name +TEST_ENV_NAME="potential-potato-test-env" + +# Clean up any existing test environment +echo "Cleaning up any existing test environment..." +mamba env remove -n "$TEST_ENV_NAME" -y 2>/dev/null || true + +# Create conda environment from environment.yaml +echo "" +echo "Creating conda environment from environment.yaml..." +if [ ! -f "environment.yaml" ]; then + echo "ERROR: environment.yaml not found!" + exit 1 +fi + +mamba env create -n "$TEST_ENV_NAME" -f environment.yaml -y + +# Activate the environment +echo "" +echo "Activating test environment..." +# Note: In CI, conda/mamba environments need to be activated via conda run +# or by sourcing the activation script + +# Test pip installation of requirements.txt, or of its lock file (requirements.lock.txt, written by +# .tools/python/lock_requirements.py) when there is one: the installer installs the lock file, so that is what is tested. +if [ ! -f "requirements.txt" ]; then + echo "ERROR: requirements.txt not found!" + mamba env remove -n "$TEST_ENV_NAME" -y + exit 1 +fi +REQUIREMENTS_FILE="requirements.txt" +if [ -f "requirements.lock.txt" ]; then + REQUIREMENTS_FILE="requirements.lock.txt" +fi +echo "" +echo "Installing requirements from $REQUIREMENTS_FILE..." + +# Check if the requirements file is not empty +if [ ! -s "$REQUIREMENTS_FILE" ]; then + echo "WARNING: $REQUIREMENTS_FILE is empty, skipping pip install" +else + echo "Installing packages with pip..." + mamba run -n "$TEST_ENV_NAME" pip install --prefer-binary -r "$REQUIREMENTS_FILE" +fi + +# Report dependency conflicts between the pip packages and the conda packages of the environment. Only a warning: a conflict +# among the conda packages themselves must not block the notebooks. +echo "" +echo "Checking the installed packages for conflicts (pip check)..." +if ! mamba run -n "$TEST_ENV_NAME" pip check; then + echo "::warning::pip check found dependency conflicts in the test environment (see the step log); the installer may behave differently than expected." +fi + +# Verify installation by checking Python and key packages +echo "" +echo "Verifying installation..." +echo "Python version:" +mamba run -n "$TEST_ENV_NAME" python --version + +echo "" +echo "Installed pip packages (sample):" +mamba run -n "$TEST_ENV_NAME" pip list | head -n 20 + +# Clean up test environment +echo "" +echo "Cleaning up test environment..." +mamba env remove -n "$TEST_ENV_NAME" -y + +echo "" +echo "==========================================" +echo "โœ“ Conda environment test completed successfully!" +echo "==========================================" diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/.tools/python/lock_requirements.py b/.template_sync/resources/v0_1_19_to_v0_1_20/.tools/python/lock_requirements.py new file mode 100644 index 0000000..c5834a2 --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/.tools/python/lock_requirements.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Lock the merged requirements files: requirements*.txt -> requirements*.lock.txt. + +merge_requirements.py writes the requirements of the notebooks (requirements.txt, requirements_gpu.txt and the per-OS +requirements-.txt). Those files name the packages the notebooks need, but not the packages these depend on, so two +installations of the same release could get different versions. This script writes, next to each file, a lock file that lists +every package pip installs, each with its exact version, and post_install installs the lock file when the installer bundles one. + +How a lock file is made: +* `uv pip compile --universal`: one lock file that is valid on Windows, macOS and Linux (a package that only one platform needs carries + an environment marker, e.g. `colorama==0.4.6 ; sys_platform == 'win32'`). +* `--python-version` is the Python of environment.yaml. uv reads it as the lowest Python of the resolution, so a few packages can appear + twice with a `python_full_version` marker: pip installs the line that matches the Python of the installer. +* The conda packages of environment.yaml (jupyterlab, pip, setuptools, certifi, ...) are installed by the installer itself, so they are + not written to the lock file (their own dependencies are), and a conda pin such as `jupyterlab=4.4.0` constrains the resolution. +* The per-OS files are resolved with requirements.lock.txt as constraints, so a package that both files need gets the same version. +* Pip options of the requirements file (`--extra-index-url` of the GPU file, ...) are copied to the top of the lock file. + +A lock file is written again only when its requirements file, the Python or JupyterLab version (or this script's lock format) changed: +its header holds a fingerprint of those inputs. Re-running the script without such a change rewrites nothing, so a new release +installs the same versions as the previous one. To move every package to its newest version, delete the lock files and run the +workflow "Updates on notebook change" by hand (Actions > Run workflow). + +If a file cannot be locked (uv is missing, or the requirements cannot be resolved), the script prints a warning, removes the +out-of-date lock file of that file (an installer must never install versions that no longer match the requirements) and goes on: +the installer then installs the plain requirements file. The script itself always exits 0 for such a failure. +""" +from __future__ import annotations + +import argparse +import hashlib +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +import yaml + +# Bump when the uv arguments or the output change, so that every lock file is written again. +LOCK_FORMAT = "1" +BASE_INPUT = "requirements.txt" +GPU_INPUT = "requirements_gpu.txt" +OS_INPUTS = ("requirements-linux.txt", "requirements-windows.txt", "requirements-macos.txt") +INPUTS = (BASE_INPUT, GPU_INPUT, *OS_INPUTS) +FINGERPRINT_PREFIX = "# lock-input: sha256:" +# Pip options that choose where packages come from: copied to the top of the lock file, so pip finds the locked versions where uv found them. +INDEX_OPTION = re.compile(r"^\s*(--index-url|--extra-index-url|-i|--find-links|-f|--trusted-host)(\s|=)") +CONDA_SPEC = re.compile(r"^\s*([A-Za-z0-9_.-]+)\s*(?:(==?)\s*([0-9][A-Za-z0-9_.+!*-]*))?(?:=\S+)?\s*$") +PLACEHOLDER = re.compile(r"^[A-Z_]+$") + + +def lock_path(requirements: Path) -> Path: + """requirements.txt -> requirements.lock.txt (same folder).""" + return requirements.with_name(requirements.stem + ".lock.txt") + + +def read_environment(path: Path) -> tuple[str | None, list[str], list[str]]: + """(Python version, conda package names, pip constraints from exact conda pins) of environment.yaml.""" + if not path.is_file(): + return None, [], [] + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + python_version = None + names: list[str] = [] + constraints: list[str] = [] + for dependency in data.get("dependencies", []) or []: + if not isinstance(dependency, str): + continue # the `pip:` subsection of an environment file + match = CONDA_SPEC.match(dependency) + if match: + name, operator, version = match.group(1), match.group(2), match.group(3) + else: + # a spec with a range or alternatives (`pip>=24.2`): only its name is used + name, operator, version = re.split(r"[\s<>=!|,\[]", dependency.strip(), maxsplit=1)[0], None, None + if not name: + continue + if version and PLACEHOLDER.match(version): + version = None # the template itself (python=PYTHON_VERSION) + if name.lower() == "python": + python_version = version + continue + names.append(name) + if version: + # conda `name=1.2` means any 1.2.* release, `name==1.2` exactly 1.2 + constraints.append(f"{name}=={version}" if operator == "==" else f"{name}=={version.removesuffix('.*')}.*") + return python_version, sorted(set(names), key=str.lower), constraints + + +def normalized_requirements(text: str) -> str: + """The requirement and option lines of a requirements file (comments, such as the timestamp of merge_requirements.py, are ignored).""" + lines = [] + for line in text.replace("\r\n", "\n").split("\n"): + stripped = line.strip() + if stripped and not stripped.startswith("#"): + lines.append(stripped) + return "\n".join(lines) + + +def fingerprint(requirements_text: str, python_version: str, constraints: list[str], no_emit: list[str], extra_constraints: str) -> str: + payload = "\n---\n".join( + [LOCK_FORMAT, normalized_requirements(requirements_text), python_version, "\n".join(constraints), "\n".join(no_emit), extra_constraints] + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def current_fingerprint(lock: Path) -> str | None: + if not lock.is_file(): + return None + for line in lock.read_text(encoding="utf-8").splitlines(): + if line.startswith(FINGERPRINT_PREFIX): + return line[len(FINGERPRINT_PREFIX):].strip() + return None + + +def run_uv(requirements: Path, python_version: str, constraint_files: list[Path], no_emit: list[str]) -> str: + """The resolution of `requirements` (stdout of uv pip compile); raises RuntimeError with uv's message when it fails.""" + command = [ + sys.executable, "-m", "uv", "pip", "compile", str(requirements), + "--universal", "--python-version", python_version, + "--no-header", "--no-annotate", "--no-config", "--quiet", + ] + for constraint in constraint_files: + command += ["--constraint", str(constraint)] + for name in no_emit: + command += ["--no-emit-package", name] + try: + result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", check=False) + except OSError as exc: + raise RuntimeError(f"uv could not be started: {exc}") from exc + if result.returncode != 0: + message = (result.stderr or result.stdout).strip() or f"exit code {result.returncode}" + raise RuntimeError(message) + return result.stdout + + +def uv_version() -> str: + try: + result = subprocess.run([sys.executable, "-m", "uv", "--version"], capture_output=True, text=True, check=False) + except OSError: + return "uv" + # "uv 0.13.3 (502f93ca6 2026-10-19 x86_64-pc-windows-msvc)" -> "uv 0.13.3": the build details differ between computers + return " ".join(result.stdout.split()[:2]) or "uv" + + +def render_lock(requirements: Path, resolved: str, digest: str, python_version: str, uv: str) -> str: + options = [line.strip() for line in requirements.read_text(encoding="utf-8").splitlines() if INDEX_OPTION.match(line)] + packages = [line.rstrip() for line in resolved.replace("\r\n", "\n").split("\n") if line.strip() and not line.lstrip().startswith("#")] + header = [ + f"# Lock file of {requirements.name}: every package the installer installs with pip, with its exact version.", + f"# Written by .tools/python/lock_requirements.py ({uv}, universal resolution for Python {python_version}); do not edit it by hand.", + f"# It is written again only when {requirements.name}, the Python or JupyterLab version changes (see the fingerprint below).", + f"{FINGERPRINT_PREFIX}{digest}", + ] + body = options + ([""] if options else []) + packages + return "\n".join(header + [""] + body) + "\n" + + +def warn(message: str) -> None: + # `::warning::` shows the message on the summary page of the GitHub Actions run. + print(f"::warning::{message}", flush=True) + + +def lock_file( + requirements: Path, + python_version: str, + constraints: list[str], + no_emit: list[str], + base_lock: Path | None, + work_dir: Path, + uv: str, +) -> str: + """Lock one requirements file; returns what happened ("unchanged", "written", "failed").""" + lock = lock_path(requirements) + extra = base_lock.read_text(encoding="utf-8") if base_lock is not None and base_lock.is_file() else "" + digest = fingerprint(requirements.read_text(encoding="utf-8"), python_version, constraints, no_emit, normalized_requirements(extra)) + if current_fingerprint(lock) == digest: + print(f"{lock}: up to date (unchanged)") + return "unchanged" + constraint_files = [] + if constraints: + conda_constraints = work_dir / "conda_constraints.txt" + conda_constraints.write_text("\n".join(constraints) + "\n", encoding="utf-8") + constraint_files.append(conda_constraints) + if extra: + # Only the package lines: the pip options of the base lock are not constraints. + base_constraints = work_dir / "base_constraints.txt" + base_constraints.write_text( + "\n".join(line for line in extra.splitlines() if line.strip() and not line.startswith(("#", "-"))) + "\n", encoding="utf-8" + ) + constraint_files.append(base_constraints) + try: + resolved = run_uv(requirements, python_version, constraint_files, no_emit) + except RuntimeError as exc: + warn(f"{requirements} could not be locked, so the installer installs it without a lock file: {exc}") + if lock.exists(): + lock.unlink() + print(f"{lock}: removed (it no longer matches {requirements})") + return "failed" + with lock.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(render_lock(requirements, resolved, digest, python_version, uv)) + print(f"{lock}: written") + return "written" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Lock requirements*.txt into requirements*.lock.txt (every package with its exact version).") + parser.add_argument("--root", type=Path, default=Path("."), help="Folder with the requirements files and environment.yaml") + parser.add_argument("--environment", type=Path, default=None, help="Conda environment file (default: /environment.yaml)") + args = parser.parse_args(argv) + root: Path = args.root + environment = args.environment or root / "environment.yaml" + + python_version, conda_names, constraints = read_environment(environment) + if not python_version: + print(f"{environment}: no exact Python version (python=X.Y.Z), so nothing is locked.") + return 0 + no_emit = [name for name in conda_names if name.lower() not in {"git"}] + + # A lock file whose requirements file is gone is removed (the installer must not install it). + for name in INPUTS: + requirements = root / name + if not requirements.is_file() and lock_path(requirements).is_file(): + lock_path(requirements).unlink() + print(f"{lock_path(requirements)}: removed ({requirements} does not exist)") + + present = [root / name for name in INPUTS if (root / name).is_file()] + if not present: + print("No requirements files found: nothing to lock.") + return 0 + uv = uv_version() + results = {} + with tempfile.TemporaryDirectory() as temporary: + work_dir = Path(temporary) + for requirements in present: + base_lock = lock_path(root / BASE_INPUT) if requirements.name in OS_INPUTS else None + results[requirements.name] = lock_file(requirements, python_version, constraints, no_emit, base_lock, work_dir, uv) + failed = [name for name, status in results.items() if status == "failed"] + print(f"Lock files: {len(results) - len(failed)} of {len(results)} requirements files locked" + (f"; not locked: {', '.join(failed)}" if failed else "")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/app/python_scripts/launch_jupyter.py b/.template_sync/resources/v0_1_19_to_v0_1_20/app/python_scripts/launch_jupyter.py new file mode 100644 index 0000000..f45ec5f --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/app/python_scripts/launch_jupyter.py @@ -0,0 +1,324 @@ +"""TLS-resilient JupyterLab launcher for PROJECT_NAME. + +Certificate handling is configured before JupyterLab imports Tornado. On +Windows this prevents one malformed certificate-store entry from terminating +the application. Certificate and hostname verification remain enabled in every +supported mode. +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import re +import shutil +import ssl +import sys +import tempfile +import traceback +from datetime import datetime, timezone +from importlib import metadata +from pathlib import Path + +PROJECT_DISPLAY_NAME = "PROJECT_NAME" +SCRIPT_DIR = Path(__file__).resolve().parent +_INSTALLED_LAYOUT = (SCRIPT_DIR / "notebooks").is_dir() +if _INSTALLED_LAYOUT: + APP_ROOT = SCRIPT_DIR + PREFIX = APP_ROOT.parent +else: + # Repository layout: app/python_scripts/launch_jupyter.py + repository_root = SCRIPT_DIR.parents[1] + APP_ROOT = repository_root if (repository_root / "notebooks").is_dir() else SCRIPT_DIR + PREFIX = APP_ROOT +DEFAULT_NOTEBOOK = APP_ROOT / "notebooks" / "Welcome.ipynb" +LOG_PATH = PREFIX / "launcher_debug.log" + + +def _write_log(message: str, *, console: bool = True) -> None: + timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") + line = f"[{timestamp}] {message}" + if console: + print(message, flush=True) + try: + with LOG_PATH.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except OSError: + # Logging must never prevent the application from launching. + pass + + +def _package_version(name: str) -> str: + try: + return metadata.version(name) + except metadata.PackageNotFoundError: + return "not installed" + + +def _project_ca_bundle_environment_variable() -> str: + normalized = re.sub(r"[^A-Za-z0-9]+", "_", PROJECT_DISPLAY_NAME).strip("_").upper() + return f"{normalized or 'LABCONSTRICTOR_APP'}_CA_BUNDLE" + + +def _probe_ssl() -> None: + """Create a verified client context without making a network request.""" + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) + if context.verify_mode != ssl.CERT_REQUIRED: + raise RuntimeError("TLS certificate verification is unexpectedly disabled.") + if not context.check_hostname: + raise RuntimeError("TLS hostname verification is unexpectedly disabled.") + + +def _inject_truststore() -> None: + """Route Python SSL contexts through the operating-system trust API.""" + import truststore + + truststore.inject_into_ssl() + + +def _select_ca_bundle() -> Path: + """Choose an explicit CA bundle for verified installer and runtime fallback.""" + for variable in ( + _project_ca_bundle_environment_variable(), + "LABCONSTRICTOR_CA_BUNDLE", + "SSL_CERT_FILE", + "REQUESTS_CA_BUNDLE", + "CURL_CA_BUNDLE", + ): + candidate = os.environ.get(variable, "").strip() + if candidate: + path = Path(candidate).expanduser() + if path.is_file(): + return path.resolve() + + import certifi + + return Path(certifi.where()).resolve() + + +def _install_bundle_fallback(bundle: Path) -> None: + """Use a verified PEM bundle without enumerating the Windows cert store.""" + original_context_type = ssl.SSLContext + + def create_context( + purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH, + *, + cafile: str | os.PathLike[str] | None = None, + capath: str | os.PathLike[str] | None = None, + cadata: str | bytes | None = None, + ) -> ssl.SSLContext: + if purpose == ssl.Purpose.SERVER_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_CLIENT) + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + elif purpose == ssl.Purpose.CLIENT_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_SERVER) + else: + raise ValueError(purpose) + + if cafile or capath or cadata: + context.load_verify_locations( + cafile=os.fspath(cafile) if cafile else None, + capath=os.fspath(capath) if capath else None, + cadata=cadata, + ) + else: + context.load_verify_locations(cafile=str(bundle)) + + keylogfile = os.environ.get("SSLKEYLOGFILE") + if keylogfile and hasattr(context, "keylog_filename"): + context.keylog_filename = keylogfile + return context + + ssl.create_default_context = create_context # type: ignore[assignment] + ssl._create_default_https_context = create_context # type: ignore[attr-defined] + os.environ["SSL_CERT_FILE"] = str(bundle) + os.environ.setdefault("REQUESTS_CA_BUNDLE", str(bundle)) + os.environ.setdefault("CURL_CA_BUNDLE", str(bundle)) + + +def configure_tls() -> tuple[str, list[str]]: + """Prepare TLS before Jupyter/Tornado imports and return mode plus notes.""" + notes: list[str] = [] + + try: + if "truststore" not in getattr(ssl.SSLContext, "__module__", ""): + _inject_truststore() + _probe_ssl() + return "native truststore", notes + except Exception as exc: + notes.append(f"Native truststore activation failed: {exc}") + + try: + bundle = _select_ca_bundle() + _install_bundle_fallback(bundle) + _probe_ssl() + notes.append(f"Using verified CA bundle fallback: {bundle}") + return "verified CA bundle fallback", notes + except Exception as exc: + notes.append(f"CA bundle fallback failed: {exc}") + raise RuntimeError("Unable to create a verified TLS context. " + " | ".join(notes)) from exc + + +def _diagnostics(tls_mode: str, notes: list[str]) -> dict[str, object]: + return { + "status": "ok", + "application": PROJECT_DISPLAY_NAME, + "tls_mode": tls_mode, + "notes": notes, + "ca_bundle_override_variable": _project_ca_bundle_environment_variable(), + "python": sys.version.split()[0], + "python_executable": sys.executable, + "openssl": ssl.OPENSSL_VERSION, + "platform": platform.platform(), + "jupyterlab": _package_version("jupyterlab"), + "jupyter_server": _package_version("jupyter-server"), + "tornado": _package_version("tornado"), + "truststore": _package_version("truststore"), + "pip_system_certs": _package_version("pip-system-certs"), + "certifi": _package_version("certifi"), + "prefix": str(PREFIX), + "log": str(LOG_PATH), + } + + +def _show_error_dialog(message: str) -> None: + if os.name != "nt": + return + try: + import tkinter as tk + from tkinter import messagebox + + root = tk.Tk() + root.withdraw() + messagebox.showerror(f"{PROJECT_DISPLAY_NAME} could not start", message) + root.destroy() + except Exception: + pass + + +def _wait_for_enter() -> None: + """Keep the terminal window open until the user has read it, then let it close. + + The menu shortcut runs the launcher in a terminal window; without this the window + closes (or stays open, on Windows) as soon as JupyterLab stops. + """ + stream = sys.stdin + if stream is None or not stream.isatty(): + return + try: + input("\nPress Enter to close this window...") + except (EOFError, KeyboardInterrupt): + pass + + +def run_jupyter(notebook: Path) -> int: + if not notebook.is_file(): + raise FileNotFoundError(f"Welcome notebook not found: {notebook}") + + # Import only after configure_tls() has completed. Tornado creates SSL + # contexts during import on some versions. + from jupyterlab.labapp import main + + home = Path.home().resolve() + try: + notebook.resolve().relative_to(home) + root_dir = home + except ValueError: + # All-users installations can live outside the home directory. + root_dir = PREFIX.resolve() + + # A fresh, empty workspace folder for every launch: JupyterLab restores the open + # tabs of its workspaces, and the default folder (~/.jupyter/lab/workspaces) is + # shared by every app, so notebooks of other apps (and of earlier sessions) would + # open next to the Welcome notebook. Settings and themes are kept: they are stored + # in the user settings folder, not in the workspaces. + workspaces_dir = Path(tempfile.mkdtemp(prefix="labconstrictor-workspaces-")) + sys.argv = [ + "jupyter-lab", + str(notebook.resolve()), + "--ServerApp.ip=127.0.0.1", + f"--ServerApp.root_dir={root_dir}", + "--ServerApp.shutdown_no_activity_timeout=30", + "--FileContentsManager.always_delete_dir=True", + f"--LabApp.workspaces_dir={workspaces_dir}", + ] + try: + result = main() + finally: + shutil.rmtree(workspaces_dir, ignore_errors=True) + return int(result or 0) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=f"Launch {PROJECT_DISPLAY_NAME} in its packaged JupyterLab environment safely." + ) + parser.add_argument("notebook", nargs="?", type=Path, default=DEFAULT_NOTEBOOK) + parser.add_argument( + "--self-test", + action="store_true", + help="Validate TLS and Jupyter imports without starting the server.", + ) + parser.add_argument( + "--print-ca-bundle", + action="store_true", + help="Print the selected verified CA bundle path and exit.", + ) + parser.add_argument( + "--no-wait", + action="store_true", + help="Exit when JupyterLab stops, without asking to press Enter.", + ) + args = parser.parse_args(argv) + result = _launch(args) + if not (args.no_wait or args.self_test or args.print_ca_bundle): + _wait_for_enter() + return result + + +def _launch(args: argparse.Namespace) -> int: + try: + if args.print_ca_bundle: + print(_select_ca_bundle(), flush=True) + return 0 + + _write_log("Starting application launcher") + tls_mode, notes = configure_tls() + _write_log(f"TLS mode: {tls_mode}") + for note in notes: + # Recovery details remain available in launcher_debug.log and + # self-test JSON without alarming users during a normal launch. + _write_log(note, console=False) + + import jupyterlab.labapp # noqa: F401 + import tornado.netutil # noqa: F401 + + diagnostics = _diagnostics(tls_mode, notes) + if args.self_test: + print(json.dumps(diagnostics, indent=2), flush=True) + _write_log("Launcher self-test completed successfully") + return 0 + + _write_log(f"Opening notebook: {args.notebook}") + return run_jupyter(args.notebook) + except KeyboardInterrupt: + _write_log("Launcher interrupted by user") + return 130 + except Exception as exc: + details = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + _write_log(details.rstrip()) + friendly = ( + f"{PROJECT_DISPLAY_NAME} could not start, but no certificate-store changes are required.\n\n" + f"A diagnostic log was written to:\n{LOG_PATH}\n\n" + f"Technical message: {exc}" + ) + print("\n" + friendly, file=sys.stderr, flush=True) + _show_error_dialog(friendly) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/previous/.github/workflows/update_on_notebook_change.yml b/.template_sync/resources/v0_1_19_to_v0_1_20/previous/.github/workflows/update_on_notebook_change.yml new file mode 100644 index 0000000..c5fae88 --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/previous/.github/workflows/update_on_notebook_change.yml @@ -0,0 +1,154 @@ +name: Updates on notebook change + +on: + push: + branches: [ main, master ] + paths: + - 'notebooks/**/*.ipynb' + - 'notebooks/notebook_latest_versions.yaml' + - 'notebooks/**/requirements.yaml' + workflow_dispatch: + +# This enables to run a single workflow at a time +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon notebook change, update manifests and changelogs + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@2d756ea4c53f7f6b397767d8723b3a10a9f35bf2 # v44 + with: + separator: "," + files: | + notebooks/**/*.ipynb + notebooks/notebook_latest_versions.yaml + notebooks/**/requirements.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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "sync_notebook_versions.py" \ + .tools/python/sync_notebook_versions.py \ + python .tools/python/sync_notebook_versions.py + + - name: Update CHANGELOG + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_changelog.py" \ + .tools/python/update_changelog.py \ + python .tools/python/update_changelog.py notebooks/notebook_latest_versions.yaml + + - name: Update last commit in notebook_latest_versions.yaml + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "update_version_last_commit.py" \ + .tools/python/update_version_last_commit.py \ + python .tools/python/update_version_last_commit.py notebooks/notebook_latest_versions.yaml + + - name: Hide code cells in notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "hide_code_cells.py" \ + app/python_scripts/hide_code_cells.py \ + python app/python_scripts/hide_code_cells.py . + + - name: Index notebooks + if: contains(steps.changed-files.outputs.all_changed_files, '.ipynb') || contains(steps.changed-files.outputs.all_changed_files, 'notebook_latest_versions.yaml') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "bump_notebook_README.py" \ + .tools/python/bump_notebook_README.py \ + 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') + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "merge_requirements.py" \ + .tools/python/merge_requirements.py \ + python .tools/python/merge_requirements.py --source-dir notebooks --output requirements.txt + + - name: Check for changes + id: check-changes + run: | + if [ -z "$(git status --porcelain)" ]; then + echo "has_changes=false" >> $GITHUB_OUTPUT + else + echo "has_changes=true" >> $GITHUB_OUTPUT + fi + + - name: Set up Miniconda for requirements test + if: steps.check-changes.outputs.has_changes == 'true' + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Verify merged requirements inside conda + id: test-conda-env + if: steps.check-changes.outputs.has_changes == 'true' + env: + SKIP_CONDA_ENV_TEST: ${{ vars.SKIP_CONDA_ENV_TEST }} + run: | + bash .tools/bash/run_with_context.sh \ + artifacts/error_log_document.log \ + "test_conda_environment.sh" \ + .tools/bash/test_conda_environment.sh \ + bash .tools/bash/test_conda_environment.sh + + - name: Upload diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: notebook-debug-bundle + path: artifacts/error_log_document.log + archive: false + + - name: Commit updated files + id: auto-commit + if: steps.check-changes.outputs.has_changes == 'true' && steps.test-conda-env.outcome == 'success' + uses: stefanzweifel/git-auto-commit-action@b863ae1933cb653a53c021fe36dbb774e1fb9403 # v5 + with: + commit_message: GitHub Action - Updated files because of notebook and/or requirements changes + file_pattern: requirements*.txt environment.yaml notebooks/* setup.py + + - name: Revert user commit that broke requirements + if: failure() && github.event_name == 'push' + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git reset --hard + git clean -fd + git revert "${{ github.sha }}" -m 1 --no-edit + git push origin HEAD:${{ github.ref_name }} diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/previous/.github/workflows/update_on_src_change.yaml b/.template_sync/resources/v0_1_19_to_v0_1_20/previous/.github/workflows/update_on_src_change.yaml new file mode 100644 index 0000000..76b90f0 --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/previous/.github/workflows/update_on_src_change.yaml @@ -0,0 +1,41 @@ +name: Updates on external code change + +on: + push: + branches: [ main, master ] + paths: + - 'src/**' + workflow_dispatch: + +# This enables to run a single workflow at a time +concurrency: + group: notebooks-global-lock-${{ github.ref }} + cancel-in-progress: false + +jobs: + updates-version_change: + name: Upon external code update the code version + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Update src change file + run: | + cat > .tools/meta/src_change.yaml </dev/null || true + +# Create conda environment from environment.yaml +echo "" +echo "Creating conda environment from environment.yaml..." +if [ ! -f "environment.yaml" ]; then + echo "ERROR: environment.yaml not found!" + exit 1 +fi + +mamba env create -n "$TEST_ENV_NAME" -f environment.yaml -y + +# Activate the environment +echo "" +echo "Activating test environment..." +# Note: In CI, conda/mamba environments need to be activated via conda run +# or by sourcing the activation script + +# Test pip installation of requirements.txt +echo "" +echo "Installing requirements from requirements.txt..." +if [ ! -f "requirements.txt" ]; then + echo "ERROR: requirements.txt not found!" + mamba env remove -n "$TEST_ENV_NAME" -y + exit 1 +fi + +# Check if requirements.txt is not empty +if [ ! -s "requirements.txt" ]; then + echo "WARNING: requirements.txt is empty, skipping pip install" +else + echo "Installing packages with pip..." + mamba run -n "$TEST_ENV_NAME" pip install --prefer-binary -r requirements.txt +fi + +# Verify installation by checking Python and key packages +echo "" +echo "Verifying installation..." +echo "Python version:" +mamba run -n "$TEST_ENV_NAME" python --version + +echo "" +echo "Installed pip packages (sample):" +mamba run -n "$TEST_ENV_NAME" pip list | head -n 20 + +# Clean up test environment +echo "" +echo "Cleaning up test environment..." +mamba env remove -n "$TEST_ENV_NAME" -y + +echo "" +echo "==========================================" +echo "โœ“ Conda environment test completed successfully!" +echo "==========================================" diff --git a/.template_sync/resources/v0_1_19_to_v0_1_20/previous/app/python_scripts/launch_jupyter.py b/.template_sync/resources/v0_1_19_to_v0_1_20/previous/app/python_scripts/launch_jupyter.py new file mode 100644 index 0000000..0f91726 --- /dev/null +++ b/.template_sync/resources/v0_1_19_to_v0_1_20/previous/app/python_scripts/launch_jupyter.py @@ -0,0 +1,286 @@ +"""TLS-resilient JupyterLab launcher for PROJECT_NAME. + +Certificate handling is configured before JupyterLab imports Tornado. On +Windows this prevents one malformed certificate-store entry from terminating +the application. Certificate and hostname verification remain enabled in every +supported mode. +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import re +import ssl +import sys +import traceback +from datetime import datetime, timezone +from importlib import metadata +from pathlib import Path + +PROJECT_DISPLAY_NAME = "PROJECT_NAME" +SCRIPT_DIR = Path(__file__).resolve().parent +_INSTALLED_LAYOUT = (SCRIPT_DIR / "notebooks").is_dir() +if _INSTALLED_LAYOUT: + APP_ROOT = SCRIPT_DIR + PREFIX = APP_ROOT.parent +else: + # Repository layout: app/python_scripts/launch_jupyter.py + repository_root = SCRIPT_DIR.parents[1] + APP_ROOT = repository_root if (repository_root / "notebooks").is_dir() else SCRIPT_DIR + PREFIX = APP_ROOT +DEFAULT_NOTEBOOK = APP_ROOT / "notebooks" / "Welcome.ipynb" +LOG_PATH = PREFIX / "launcher_debug.log" + + +def _write_log(message: str, *, console: bool = True) -> None: + timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") + line = f"[{timestamp}] {message}" + if console: + print(message, flush=True) + try: + with LOG_PATH.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except OSError: + # Logging must never prevent the application from launching. + pass + + +def _package_version(name: str) -> str: + try: + return metadata.version(name) + except metadata.PackageNotFoundError: + return "not installed" + + +def _project_ca_bundle_environment_variable() -> str: + normalized = re.sub(r"[^A-Za-z0-9]+", "_", PROJECT_DISPLAY_NAME).strip("_").upper() + return f"{normalized or 'LABCONSTRICTOR_APP'}_CA_BUNDLE" + + +def _probe_ssl() -> None: + """Create a verified client context without making a network request.""" + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) + if context.verify_mode != ssl.CERT_REQUIRED: + raise RuntimeError("TLS certificate verification is unexpectedly disabled.") + if not context.check_hostname: + raise RuntimeError("TLS hostname verification is unexpectedly disabled.") + + +def _inject_truststore() -> None: + """Route Python SSL contexts through the operating-system trust API.""" + import truststore + + truststore.inject_into_ssl() + + +def _select_ca_bundle() -> Path: + """Choose an explicit CA bundle for verified installer and runtime fallback.""" + for variable in ( + _project_ca_bundle_environment_variable(), + "LABCONSTRICTOR_CA_BUNDLE", + "SSL_CERT_FILE", + "REQUESTS_CA_BUNDLE", + "CURL_CA_BUNDLE", + ): + candidate = os.environ.get(variable, "").strip() + if candidate: + path = Path(candidate).expanduser() + if path.is_file(): + return path.resolve() + + import certifi + + return Path(certifi.where()).resolve() + + +def _install_bundle_fallback(bundle: Path) -> None: + """Use a verified PEM bundle without enumerating the Windows cert store.""" + original_context_type = ssl.SSLContext + + def create_context( + purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH, + *, + cafile: str | os.PathLike[str] | None = None, + capath: str | os.PathLike[str] | None = None, + cadata: str | bytes | None = None, + ) -> ssl.SSLContext: + if purpose == ssl.Purpose.SERVER_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_CLIENT) + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + elif purpose == ssl.Purpose.CLIENT_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_SERVER) + else: + raise ValueError(purpose) + + if cafile or capath or cadata: + context.load_verify_locations( + cafile=os.fspath(cafile) if cafile else None, + capath=os.fspath(capath) if capath else None, + cadata=cadata, + ) + else: + context.load_verify_locations(cafile=str(bundle)) + + keylogfile = os.environ.get("SSLKEYLOGFILE") + if keylogfile and hasattr(context, "keylog_filename"): + context.keylog_filename = keylogfile + return context + + ssl.create_default_context = create_context # type: ignore[assignment] + ssl._create_default_https_context = create_context # type: ignore[attr-defined] + os.environ["SSL_CERT_FILE"] = str(bundle) + os.environ.setdefault("REQUESTS_CA_BUNDLE", str(bundle)) + os.environ.setdefault("CURL_CA_BUNDLE", str(bundle)) + + +def configure_tls() -> tuple[str, list[str]]: + """Prepare TLS before Jupyter/Tornado imports and return mode plus notes.""" + notes: list[str] = [] + + try: + if "truststore" not in getattr(ssl.SSLContext, "__module__", ""): + _inject_truststore() + _probe_ssl() + return "native truststore", notes + except Exception as exc: + notes.append(f"Native truststore activation failed: {exc}") + + try: + bundle = _select_ca_bundle() + _install_bundle_fallback(bundle) + _probe_ssl() + notes.append(f"Using verified CA bundle fallback: {bundle}") + return "verified CA bundle fallback", notes + except Exception as exc: + notes.append(f"CA bundle fallback failed: {exc}") + raise RuntimeError("Unable to create a verified TLS context. " + " | ".join(notes)) from exc + + +def _diagnostics(tls_mode: str, notes: list[str]) -> dict[str, object]: + return { + "status": "ok", + "application": PROJECT_DISPLAY_NAME, + "tls_mode": tls_mode, + "notes": notes, + "ca_bundle_override_variable": _project_ca_bundle_environment_variable(), + "python": sys.version.split()[0], + "python_executable": sys.executable, + "openssl": ssl.OPENSSL_VERSION, + "platform": platform.platform(), + "jupyterlab": _package_version("jupyterlab"), + "jupyter_server": _package_version("jupyter-server"), + "tornado": _package_version("tornado"), + "truststore": _package_version("truststore"), + "pip_system_certs": _package_version("pip-system-certs"), + "certifi": _package_version("certifi"), + "prefix": str(PREFIX), + "log": str(LOG_PATH), + } + + +def _show_error_dialog(message: str) -> None: + if os.name != "nt": + return + try: + import tkinter as tk + from tkinter import messagebox + + root = tk.Tk() + root.withdraw() + messagebox.showerror(f"{PROJECT_DISPLAY_NAME} could not start", message) + root.destroy() + except Exception: + pass + + +def run_jupyter(notebook: Path) -> int: + if not notebook.is_file(): + raise FileNotFoundError(f"Welcome notebook not found: {notebook}") + + # Import only after configure_tls() has completed. Tornado creates SSL + # contexts during import on some versions. + from jupyterlab.labapp import main + + home = Path.home().resolve() + try: + notebook.resolve().relative_to(home) + root_dir = home + except ValueError: + # All-users installations can live outside the home directory. + root_dir = PREFIX.resolve() + + sys.argv = [ + "jupyter-lab", + str(notebook.resolve()), + "--ServerApp.ip=127.0.0.1", + f"--ServerApp.root_dir={root_dir}", + "--ServerApp.shutdown_no_activity_timeout=30", + "--FileContentsManager.always_delete_dir=True", + ] + result = main() + return int(result or 0) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=f"Launch {PROJECT_DISPLAY_NAME} in its packaged JupyterLab environment safely." + ) + parser.add_argument("notebook", nargs="?", type=Path, default=DEFAULT_NOTEBOOK) + parser.add_argument( + "--self-test", + action="store_true", + help="Validate TLS and Jupyter imports without starting the server.", + ) + parser.add_argument( + "--print-ca-bundle", + action="store_true", + help="Print the selected verified CA bundle path and exit.", + ) + args = parser.parse_args(argv) + + try: + if args.print_ca_bundle: + print(_select_ca_bundle(), flush=True) + return 0 + + _write_log("Starting application launcher") + tls_mode, notes = configure_tls() + _write_log(f"TLS mode: {tls_mode}") + for note in notes: + # Recovery details remain available in launcher_debug.log and + # self-test JSON without alarming users during a normal launch. + _write_log(note, console=False) + + import jupyterlab.labapp # noqa: F401 + import tornado.netutil # noqa: F401 + + diagnostics = _diagnostics(tls_mode, notes) + if args.self_test: + print(json.dumps(diagnostics, indent=2), flush=True) + _write_log("Launcher self-test completed successfully") + return 0 + + _write_log(f"Opening notebook: {args.notebook}") + return run_jupyter(args.notebook) + except KeyboardInterrupt: + _write_log("Launcher interrupted by user") + return 130 + except Exception as exc: + details = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + _write_log(details.rstrip()) + friendly = ( + f"{PROJECT_DISPLAY_NAME} could not start, but no certificate-store changes are required.\n\n" + f"A diagnostic log was written to:\n{LOG_PATH}\n\n" + f"Technical message: {exc}" + ) + print("\n" + friendly, file=sys.stderr, flush=True) + _show_error_dialog(friendly) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.template_sync/resources/v0_1_22_to_v0_1_23/.tools/python/check_placeholders.py b/.template_sync/resources/v0_1_22_to_v0_1_23/.tools/python/check_placeholders.py new file mode 100644 index 0000000..b06559f --- /dev/null +++ b/.template_sync/resources/v0_1_22_to_v0_1_23/.tools/python/check_placeholders.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Stop a release whose installer would ship a template placeholder (CellMigrationLab/LabConstrictor#40). + +The repository initialisation (the LabConstrictor web form) replaces the template's placeholders with the app's names. A placeholder +it misses survives into the installer: `import PYTHON_PROJ_NAME` in post_install.sh / .bat made every installer of an app with Python +code in src/ fail at its last step. This script runs in the release workflow after the versioned files are updated and before anything +is committed or built, and fails with the file, the line and the fix when an initialisation placeholder is left in a file the +installer ships (app/**, construct.yaml, setup.py, environment.yaml), or when the repository is the raw, uninitialised template. + +Placeholders that are filled in later on purpose are not checked: BASE_PATH_KEYWORD (at install time), PYTHON_VERSION and +JUPYTERLAB_VERSION (by the requirements workflow). + +Usage: python .tools/python/check_placeholders.py [--repository-root PATH] +""" +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_23.md" + +# The placeholders the initialisation replaces (keys of conversion_table in LabConstrictor_streamlit's placeholders.py, +# plus the launcher icon paths it fills in itself). VERSION_NUMBER is also rewritten by bump_version.py, which runs before this check. +INIT_PLACEHOLDERS = ( + "LOWER_PROJ_NAME", + "PYTHON_PROJ_NAME", + "UNDERSCORED_PROJECT_NAME", + "PROJECT_NAME", + "VERSION_NUMBER", + "WELCOME_IMAGE", + "HEADER_IMAGE", + "ICON_IMAGE", + "GITHUB_OWNER", + "GITHUB_REPO_NAME", + "HIDE_CODE_DISABLED", + "ICON_IMAGE_PATH", + "ICON_ICO_IMAGE_PATH", + "ICON_ICNS_IMAGE_PATH", +) +SHIPPED_FILES = ("construct.yaml", "setup.py", "environment.yaml") +SHIPPED_FOLDERS = ("app",) +WELCOME_NOTEBOOK = "app/menuinst/Welcome.ipynb" +WELCOME_TEMPLATE = ".tools/templates/Welcome_template.ipynb" + + +def placeholder_pattern(name: str) -> re.Pattern[str]: + """A placeholder on its own or followed by '_' (PYTHON_PROJ_NAME_lc_tools), never inside a longer name (UNDERSCORED_PROJECT_NAME).""" + return re.compile(r"(? list[Path]: + files = [root / name for name in SHIPPED_FILES if (root / name).is_file()] + for folder in SHIPPED_FOLDERS: + if (root / folder).is_dir(): + files.extend(sorted(p for p in (root / folder).rglob("*") if p.is_file())) + return files + + +def leftover_placeholders(root: Path) -> list[str]: + problems = [] + for path in shipped_files(root): + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue # images, icons and other binary files + rel = path.relative_to(root).as_posix() + # The Welcome notebook is rebuilt from its template at every release: the fix belongs in the template. + where = f" (fix it in {WELCOME_TEMPLATE}, which this notebook is made from)" if rel == WELCOME_NOTEBOOK else "" + for number, line in enumerate(text.splitlines(), start=1): + for name, pattern in PATTERNS.items(): + if pattern.search(line): + problems.append(f"{rel}:{number}: the template placeholder {name} was never replaced{where}: {line.strip()[:160]}") + return problems + + +def check(root: Path) -> list[str]: + construct = root / "construct.yaml" + if construct.is_file() and re.search(r"^name:\s*UNDERSCORED_PROJECT_NAME\s*$", construct.read_text(encoding="utf-8"), re.MULTILINE): + return ["construct.yaml: this is the raw LabConstrictor template; initialise the repository with the LabConstrictor form before releasing it"] + return leftover_placeholders(root) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Fail when a template placeholder is left in a file the installer ships.") + parser.add_argument("--repository-root", type=Path, default=Path.cwd()) + args = parser.parse_args(argv) + problems = check(args.repository_root.resolve()) + if not problems: + print("No template placeholder is left in the files the installer ships.") + return 0 + print("The installer would be broken: these files still hold template placeholders.", file=sys.stderr) + for problem in problems: + print(f" {problem}", file=sys.stderr) + print( + "Replace each placeholder with your app's value (PYTHON_PROJ_NAME: the Python package of the app, usually its folder in src/; " + "PROJECT_NAME: the app name), " + f"commit, and publish the release again. See {DOCS_URL}", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_23_to_v0_1_24/.tools/python/release_platforms.py b/.template_sync/resources/v0_1_23_to_v0_1_24/.tools/python/release_platforms.py new file mode 100644 index 0000000..4083e6b --- /dev/null +++ b/.template_sync/resources/v0_1_23_to_v0_1_24/.tools/python/release_platforms.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Which installers a release builds: the systems of `distribution.platforms` in labconstrictor-app.yaml (CellMigrationLab/LabConstrictor#42). + +The release workflow builds one installer per system. An app that cannot run on a system (TensorFlow 2.17+ has no wheels for Intel Macs, for +example) leaves that system out of `distribution.platforms`, and then: + * the release workflow does not build it (this script writes the build matrix of release_constructor.yml); + * the download page (.tools/docs/download_executable.md, written by bump_version.py) has no button for it. +Without labconstrictor-app.yaml, or without `distribution.platforms` in it, every system below is built, as before template 0.1.24. + +Usage: python .tools/python/release_platforms.py [--repository-root PATH] [--github-output FILE] +""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any, NamedTuple + +import yaml + +MANIFEST = "labconstrictor-app.yaml" +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_24.md" + + +class Build(NamedTuple): + platform: str # the name in distribution.platforms + os_name: str # matrix.os_name of release_constructor.yml (names the build job, its log and dist/ folder) + runner: str # the GitHub runner that builds it + files: tuple[str, ...] # how its installers end: - + label: str # for people: the download page and the messages + + +BUILDS = ( + Build("linux-x86_64", "linux", "ubuntu-latest", ("-Linux-x86_64.sh",), "Linux"), + Build("macos-arm64", "macos-arm64", "macos-15", ("-MacOSX-arm64.pkg", "-MacOSX-arm64.sh"), "Macs with Apple silicon (M1, M2, ...)"), + Build("macos-x86_64", "macos-intel", "macos-15-intel", ("-MacOSX-x86_64.pkg", "-MacOSX-x86_64.sh"), "Macs with an Intel processor"), + Build("windows-x86_64", "windows", "windows-latest", ("-Windows-x86_64.exe",), "Windows"), +) + + +def listed_platforms(root: Path) -> list[str] | None: + """`distribution.platforms` of the app manifest; None when there is no manifest or the key is left out (every system).""" + path = root / MANIFEST + if not path.is_file(): + return None + try: + data: Any = yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as exc: + raise ValueError(f"{MANIFEST} is not valid YAML: {exc}") from exc + distribution = data.get("distribution") if isinstance(data, dict) else None + platforms = distribution.get("platforms") if isinstance(distribution, dict) else None + if platforms is None: + return None + if not isinstance(platforms, list) or not all(isinstance(item, str) for item in platforms): + raise ValueError(f"distribution.platforms in {MANIFEST} must be a list of system names, such as [windows-x86_64, macos-arm64]") + return platforms + + +def builds(root: Path) -> list[Build]: + """The builds of a release, in the order of BUILDS. Raises ValueError when the manifest lists no system this template builds.""" + listed = listed_platforms(root) + if listed is None: + return list(BUILDS) + chosen = [build for build in BUILDS if build.platform in listed] + if not chosen: + known = ", ".join(build.platform for build in BUILDS) + raise ValueError( + f"distribution.platforms in {MANIFEST} lists {', '.join(listed) or 'nothing'}, and the release builds installers only for {known}. " + "Add at least one of them, or remove distribution.installer if the app has no installer." + ) + return chosen + + +def skipped_builds(root: Path) -> list[Build]: + """The systems the release does not build (none without distribution.platforms).""" + chosen = builds(root) + return [build for build in BUILDS if build not in chosen] + + +def matrix(chosen: list[Build]) -> dict[str, list[dict[str, str]]]: + return {"include": [{"os_name": build.os_name, "runner": build.runner} for build in chosen]} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Print the build matrix of the release: the systems of distribution.platforms in labconstrictor-app.yaml.") + parser.add_argument("--repository-root", type=Path, default=Path.cwd()) + parser.add_argument("--github-output", type=Path, help="append matrix= to this file (the GITHUB_OUTPUT of a workflow step)") + args = parser.parse_args(argv) + root = args.repository_root.resolve() + try: + chosen = builds(root) + listed = listed_platforms(root) + except ValueError as exc: + print(f"{exc} See {DOCS_URL}", file=sys.stderr) + return 1 + if listed is None: + print(f"Building every installer: {MANIFEST} does not list distribution.platforms.") + else: + print(f"Building the installers of distribution.platforms in {MANIFEST}: {', '.join(build.platform for build in chosen)}.") + for build in BUILDS: + if build not in chosen: + print(f" Not built: {build.platform} ({build.label}).") + for name in listed: + if name not in {build.platform for build in BUILDS}: + print(f" Not built: {name} (the release has no runner for it).") + value = json.dumps(matrix(chosen), separators=(",", ":")) + print(f"matrix={value}") + if args.github_output: + with args.github_output.open("a", encoding="utf-8") as handle: + handle.write(f"matrix={value}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_24_to_v0_1_25/.github/workflows/publish_pypi.yml b/.template_sync/resources/v0_1_24_to_v0_1_25/.github/workflows/publish_pypi.yml new file mode 100644 index 0000000..cfd03da --- /dev/null +++ b/.template_sync/resources/v0_1_24_to_v0_1_25/.github/workflows/publish_pypi.yml @@ -0,0 +1,79 @@ +name: Publish the Python package to PyPI + +# Publishes the app's own Python code (the package in src/) on PyPI at each release, with the version of the release: the same +# moment and the same version as the installers (release_constructor.yml). +# +# OFF BY DEFAULT: both jobs are skipped unless the repository variable PYPI_PUBLISH is +# true -> publish on PyPI (pypi.org) +# testpypi -> publish on TestPyPI (test.pypi.org), a trial +# No secret or token: PyPI trusted publishing. One-time setup (a pending trusted publisher on pypi.org for this workflow file and the +# environment "pypi", then the variable): .tools/docs/external_code_upload.md. To turn it off, delete the variable. + +on: + release: + types: + - published + +permissions: + contents: read + +jobs: + build: + name: Build the package of src/ + if: vars.PYPI_PUBLISH == 'true' || vars.PYPI_PUBLISH == 'testpypi' + runs-on: ubuntu-latest + outputs: + url: ${{ steps.build.outputs.url }} + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Install requirements + run: pip install -r .tools/requirements.txt build==1.3.0 + + # The tag (v1.2.3 or 1.2.3) without the v. The checkout is the tagged commit, before the "Update version" commit of + # release_constructor.yml: pypi_package.py writes this version into setup.py itself (not committed). + - name: Build and check the package (nothing is uploaded yet) + id: build + env: + TAG: ${{ github.event.release.tag_name }} + PYPI_PUBLISH: ${{ vars.PYPI_PUBLISH }} + run: python .tools/python/pypi_package.py --version "${TAG#v}" --index "$PYPI_PUBLISH" --outdir dist --github-output "$GITHUB_OUTPUT" + + - name: Store the distributions + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: python-package-distributions + path: dist/ + if-no-files-found: error + + publish: + name: Upload to ${{ vars.PYPI_PUBLISH == 'testpypi' && 'TestPyPI' || 'PyPI' }} + needs: build + if: vars.PYPI_PUBLISH == 'true' || vars.PYPI_PUBLISH == 'testpypi' + runs-on: ubuntu-latest + # The environment named in the trusted publisher on pypi.org (and test.pypi.org). GitHub creates it on the first run; protection + # rules added to it (Settings > Environments > pypi), such as required reviewers, then apply to every upload. + environment: + name: pypi + url: ${{ needs.build.outputs.url }} + permissions: + id-token: write # trusted publishing: PyPI accepts a short-lived token that GitHub signs for this workflow and environment + steps: + - name: Download the distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: python-package-distributions + path: dist/ + + - name: Upload + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + repository-url: ${{ vars.PYPI_PUBLISH == 'testpypi' && 'https://test.pypi.org/legacy/' || 'https://upload.pypi.org/legacy/' }} diff --git a/.template_sync/resources/v0_1_24_to_v0_1_25/.tools/python/pypi_package.py b/.template_sync/resources/v0_1_24_to_v0_1_25/.tools/python/pypi_package.py new file mode 100644 index 0000000..d7783b7 --- /dev/null +++ b/.template_sync/resources/v0_1_24_to_v0_1_25/.tools/python/pypi_package.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Build the app's Python package (the code in src/) for PyPI, as .github/workflows/publish_pypi.yml does at each release. + +The workflow runs only when the repository variable PYPI_PUBLISH is "true" (PyPI) or "testpypi" (TestPyPI, a trial). This script: + +1. stops before building, with the reason, when the release cannot be published: no package in src/, a version that is not X.Y.Z, + a version that is already on the index, another workflow of the repository that also publishes to PyPI, or a setup.py that + still has a template placeholder; +2. writes the release version into setup.py of the checkout, without committing it: the release tag points to the commit before + the "Update version" commit of the release workflow, so the committed version cannot be trusted. The name is the one in + setup.py; `distribution.pip` of labconstrictor-app.yaml, when there is one, must be the same name; +3. builds the source distribution and the wheel (`python -m build`: the wheel is built from the source distribution, so a file + missing from it shows), and checks their name, version and dependencies. + +It never uploads: the next job of the workflow does, with PyPI trusted publishing (no token). + +Usage: + python .tools/python/pypi_package.py --version 1.2.3 [--index pypi|testpypi] [--outdir dist] [--github-output FILE] +""" +from __future__ import annotations + +import argparse +import email.parser +import re +import subprocess +import sys +import tarfile +import tomllib +import urllib.error +import urllib.request +import zipfile +from email.message import Message +from pathlib import Path +from typing import Any, Callable + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = "publish_pypi.yml" +DOCS = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/external_code_upload.md#4-publish-the-code-on-pypi-optional" +# --index: the value of PYPI_PUBLISH ("true" is PyPI) -> (label, address) +INDEXES = {"pypi": ("PyPI", "https://pypi.org"), "true": ("PyPI", "https://pypi.org"), "testpypi": ("TestPyPI", "https://test.pypi.org")} +VERSION_RE = re.compile(r"\d+\.\d+\.\d+") +# Text in a workflow that uploads to PyPI (the action of the template, or twine). +PUBLISH_MARKERS = ("pypa/gh-action-pypi-publish", "twine upload") +PLACEHOLDERS = ("PYTHON_PROJ_NAME", "VERSION_NUMBER", "PYTHON_VERSION") + + +class PackageError(Exception): + """A reason not to publish, written to the log of the workflow.""" + + +def normalise(name: str) -> str: + """The name as PyPI compares names (PEP 503): my_App.tools and my-app-tools are the same project.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def packages(root: Path) -> list[str]: + """The packages of src/: its folders with an __init__.py.""" + src = root / "src" + if not src.is_dir(): + return [] + return sorted(path.parent.name for path in src.glob("*/__init__.py")) + + +def other_publishers(root: Path) -> list[str]: + """The workflows of the repository, other than the template's, that upload to PyPI.""" + found = [] + folder = root / ".github" / "workflows" + for path in sorted(folder.glob("*.y*ml")) if folder.is_dir() else []: + if path.name == WORKFLOW: + continue + text = path.read_text(encoding="utf-8", errors="replace") + if any(marker in text for marker in PUBLISH_MARKERS): + found.append(path.relative_to(root).as_posix()) + return found + + +def manifest_pip_name(root: Path) -> str | None: + """`distribution.pip` of labconstrictor-app.yaml: the name of the package on PyPI, when the app gives one.""" + import yaml + + path = root / "labconstrictor-app.yaml" + if not path.is_file(): + return None + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as exc: + raise PackageError(f"labconstrictor-app.yaml is not valid YAML ({exc}); run the 'Check app manifest' workflow to see where") from exc + distribution = data.get("distribution") if isinstance(data, dict) else None + name = distribution.get("pip") if isinstance(distribution, dict) else None + return name.strip() if isinstance(name, str) and name.strip() else None + + +def _value_re(key: str) -> re.Pattern[str]: + return re.compile(rf"^(?P[ \t]*{key}\s*=\s*)(?P[\"'])(?P[^\"'\n]*)(?P=quote)", re.MULTILINE) + + +def setup_value(text: str, key: str) -> str | None: + """The first `key="value"` of setup.py (name, version), or None when it is not written there as a string.""" + match = _value_re(key).search(text) + return match.group("value") if match else None + + +def set_setup_value(text: str, key: str, value: str) -> str: + return _value_re(key).sub(lambda m: f"{m.group('head')}{m.group('quote')}{value}{m.group('quote')}", text, count=1) + + +def pyproject_project(root: Path) -> dict[str, Any] | None: + """The [project] table of pyproject.toml, when the package is described there (it then wins over setup.py).""" + path = root / "pyproject.toml" + if not path.is_file(): + return None + try: + project = tomllib.loads(path.read_text(encoding="utf-8")).get("project") + except tomllib.TOMLDecodeError as exc: + raise PackageError(f"pyproject.toml is not valid TOML: {exc}") from exc + return project if isinstance(project, dict) else None + + +def version_on_index(index: str, name: str, version: str, opener: Callable[..., Any] = urllib.request.urlopen) -> bool | None: + """True when the index already has this version of the project, False when not, None when the index could not be asked.""" + url = f"{INDEXES[index][1]}/pypi/{normalise(name)}/{version}/json" + try: + with opener(url, timeout=30) as response: + return bool(response.status == 200) + except urllib.error.HTTPError as exc: + return False if exc.code == 404 else None + except (urllib.error.URLError, OSError): + return None + + +def prepare(root: Path, version: str, index: str, check_index: bool = True) -> str: + """Check that the release can be published and write its version (and name) into setup.py; returns the name on the index.""" + if not VERSION_RE.fullmatch(version): + raise PackageError(f"The release version {version!r} is not X.Y.Z (the tag must be 1.2.3 or v1.2.3, as for the installers).") + found = packages(root) + if not found: + raise PackageError( + "There is no Python package in src/ (a folder with an __init__.py, for example src/my_app/__init__.py), so there is nothing to " + f"publish. Add your code to src/ (see .tools/docs/external_code_upload.md), or delete the repository variable PYPI_PUBLISH. {DOCS}" + ) + others = other_publishers(root) + if others: + raise PackageError( + f"{', '.join(others)} also publishes to PyPI: with PYPI_PUBLISH set, the release would be uploaded twice. Keep one: delete the " + f"repository variable PYPI_PUBLISH (your workflow keeps publishing), or delete your workflow (this one publishes at each release). {DOCS}" + ) + + pip_name = manifest_pip_name(root) + project = pyproject_project(root) + setup_path = root / "setup.py" + if project is not None and "name" in project: + # pyproject.toml describes the package: its name and version are used as they are, and must match. + name = str(project["name"]) + if pip_name and normalise(pip_name) != normalise(name): + raise PackageError(f"distribution.pip of labconstrictor-app.yaml is {pip_name}, but pyproject.toml names the package {name}: make them the same.") + if "version" in project.get("dynamic", []): + return name + if project.get("version") != version: + raise PackageError( + f"pyproject.toml gives the version {project.get('version')}, not the release version {version}: set `version = \"{version}\"` in " + "pyproject.toml, commit, and publish the release again." + ) + return name + if not setup_path.is_file(): + raise PackageError("There is no setup.py (nor a [project] table in pyproject.toml) to build the package from: restore the template's setup.py.") + + text = setup_path.read_bytes().decode("utf-8") # the line endings are kept when the version is written + left = [placeholder for placeholder in PLACEHOLDERS if placeholder in text and placeholder != "VERSION_NUMBER"] + if left: + raise PackageError( + f"setup.py still has the template placeholder {', '.join(left)}: PYTHON_PROJ_NAME is the name of the package (for example my_app), " + "PYTHON_VERSION the oldest Python series it runs on (for example 3.12). Replace it, commit, and publish the release again." + ) + setup_name = setup_value(text, "name") + if pip_name and setup_name and normalise(pip_name) != normalise(setup_name): + raise PackageError( + f"distribution.pip of labconstrictor-app.yaml is {pip_name}, but setup.py names the package {setup_name}: make them the same " + "(distribution.pip is the name the App Centre tells people to pip install; the package of src/ is published under setup.py's name)." + ) + package_name = setup_name or pip_name + if not package_name: + raise PackageError("setup.py has no name=\"...\" for the package: give it the name it should have on PyPI (and in distribution.pip).") + if check_index: + label = INDEXES[index][0] + exists = version_on_index(index, package_name, version) + if exists: + raise PackageError( + f"{label} already has {package_name} {version}, and a version can be uploaded only once (even after it was deleted). " + f"Publish a new release with a higher version (the installers are built for it too). " + f"{INDEXES[index][1]}/project/{normalise(package_name)}/{version}/" + ) + if exists is None: + print(f"WARNING: {label} could not be asked whether {package_name} {version} already exists; the upload fails if it does.") + + updated = set_setup_value(text, "version", version) + if updated != text: + # newline="" keeps the line endings of the file + with setup_path.open("w", encoding="utf-8", newline="") as handle: + handle.write(updated) + return package_name + + +def left_out_requirements(root: Path) -> list[str]: + """Lines of requirements.txt that the template's setup.py does not turn into dependencies (options, paths, URLs).""" + setup_text = (root / "setup.py").read_text(encoding="utf-8") if (root / "setup.py").is_file() else "" + path = root / "requirements.txt" + if "read_requirements()" not in setup_text or not path.is_file(): + return [] + try: + from packaging.requirements import InvalidRequirement, Requirement + except ImportError: + return [] + left = [] + for line in (raw.split("#", 1)[0].strip() for raw in path.read_text(encoding="utf-8").splitlines()): + if not line: + continue + try: + if Requirement(line).url is None: + continue + except InvalidRequirement: + pass + left.append(line) + return left + + +def build(root: Path, outdir: Path, isolation: bool = True) -> None: + """`python -m build`: the source distribution, then the wheel built from it.""" + command = [sys.executable, "-m", "build", "--outdir", str(outdir), *([] if isolation else ["--no-isolation"]), str(root)] + print("Running:", " ".join(command), flush=True) + result = subprocess.run(command) + if result.returncode: + raise PackageError("The package could not be built: see the output of `python -m build` above.") + + +def _headers(data: bytes) -> Message: + return email.parser.BytesParser().parsebytes(data, headersonly=True) + + +def read_metadata(outdir: Path) -> tuple[Message, Message, list[Path]]: + """The metadata of the wheel and of the source distribution in outdir, and the two files.""" + wheels = sorted(outdir.glob("*.whl")) + sdists = sorted(outdir.glob("*.tar.gz")) + if len(wheels) != 1 or len(sdists) != 1: + raise PackageError(f"Expected one wheel and one source distribution in {outdir}, found: {', '.join(p.name for p in sorted(outdir.iterdir())) or 'nothing'}") + with zipfile.ZipFile(wheels[0]) as archive: + member = next((n for n in archive.namelist() if n.count("/") == 1 and n.endswith(".dist-info/METADATA")), None) + if member is None: + raise PackageError(f"{wheels[0].name} has no METADATA") + wheel = _headers(archive.read(member)) + with tarfile.open(sdists[0]) as archive: + info = next((m for m in archive.getmembers() if m.name.count("/") == 1 and m.name.endswith("/PKG-INFO")), None) + handle = archive.extractfile(info) if info is not None else None + if handle is None: + raise PackageError(f"{sdists[0].name} has no PKG-INFO") + sdist = _headers(handle.read()) + return wheel, sdist, [sdists[0], wheels[0]] + + +def check(outdir: Path, name: str, version: str) -> list[str]: + """Check the built files; returns their names.""" + wheel, sdist, files = read_metadata(outdir) + for label, metadata in (("wheel", wheel), ("source distribution", sdist)): + if normalise(str(metadata.get("Name", ""))) != normalise(name): + raise PackageError(f"The {label} is named {metadata.get('Name')}, not {name}: setup.py or pyproject.toml set another name.") + if metadata.get("Version") != version: + raise PackageError(f"The {label} has the version {metadata.get('Version')}, not the release version {version}: setup.py or pyproject.toml set it.") + requirements = wheel.get_all("Requires-Dist") or [] + urls = [requirement for requirement in requirements if " @ " in requirement] + if urls: + raise PackageError( + f"PyPI refuses a package whose dependency is a URL: {'; '.join(urls)}. Publish that dependency on PyPI first and name it with a version, " + "or keep the URL in requirements.txt only (the installer still installs it)." + ) + if sdist.get_all("Requires-Dist") is not None and sorted(sdist.get_all("Requires-Dist") or []) != sorted(requirements): + raise PackageError( + "The wheel built from the source distribution has other dependencies than the source distribution: a file setup.py reads is not in " + "the source distribution (requirements.txt needs `include requirements.txt` in MANIFEST.in)." + ) + return [path.name for path in files] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Build and check the app's Python package (src/) for PyPI. Nothing is uploaded.") + parser.add_argument("--version", required=True, help="The release version, X.Y.Z (the tag without the v)") + parser.add_argument("--index", default="pypi", choices=sorted(INDEXES), help="pypi (or true, the value of PYPI_PUBLISH) or testpypi") + parser.add_argument("--outdir", default="dist", help="Where to write the two files (default: dist)") + parser.add_argument("--repository-root", default=str(ROOT)) + parser.add_argument("--github-output", help="Append name=, version= and url= to this file (GitHub Actions $GITHUB_OUTPUT)") + parser.add_argument("--no-isolation", action="store_true", help="Build with the setuptools already installed (no download)") + parser.add_argument("--offline", action="store_true", help="Do not ask the index whether the version exists") + args = parser.parse_args(argv) + + root = Path(args.repository_root).resolve() + outdir = Path(args.outdir) + if not outdir.is_absolute(): + outdir = root / outdir + label, address = INDEXES[args.index] + try: + name = prepare(root, args.version, args.index, check_index=not args.offline) + for line in left_out_requirements(root): + print(f"WARNING: the line `{line}` of requirements.txt is not a dependency the package can declare on {label} (an option, a path or a URL): left out.") + if outdir.exists() and any(outdir.iterdir()): + raise PackageError(f"{outdir} is not empty: remove it first, so that only this release is uploaded.") + build(root, outdir, isolation=not args.no_isolation) + files = check(outdir, name, args.version) + except PackageError as exc: + print(f"::error title=The package cannot be published::{exc}", file=sys.stderr) + print(f"ERROR: {exc}", file=sys.stderr) + return 1 + + url = f"{address}/project/{normalise(name)}/{args.version}/" + print(f"Built {name} {args.version} for {label}: {', '.join(files)}. The next job uploads it: {url}") + if args.github_output: + with open(args.github_output, "a", encoding="utf-8") as handle: + handle.write(f"name={name}\nversion={args.version}\nurl={url}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.template_sync/resources/v0_1_24_to_v0_1_25/MANIFEST.in b/.template_sync/resources/v0_1_24_to_v0_1_25/MANIFEST.in new file mode 100644 index 0000000..757a970 --- /dev/null +++ b/.template_sync/resources/v0_1_24_to_v0_1_25/MANIFEST.in @@ -0,0 +1,3 @@ +# The source distribution of the app's Python package (setup.py, src/, README.md, LICENSE) also carries requirements.txt: +# setup.py reads the dependencies from it when pip builds the package from the source distribution. +include requirements.txt diff --git a/.template_sync/resources/v0_1_24_to_v0_1_25/setup.py b/.template_sync/resources/v0_1_24_to_v0_1_25/setup.py new file mode 100644 index 0000000..ac5f8f4 --- /dev/null +++ b/.template_sync/resources/v0_1_24_to_v0_1_25/setup.py @@ -0,0 +1,57 @@ +"""The Python package of the app: the code in src/ (see .tools/docs/external_code_upload.md). + +The installer installs it into the app. With the repository variable PYPI_PUBLISH, .github/workflows/publish_pypi.yml also +publishes it on PyPI at every release, with the version of the release. The package needs what requirements.txt lists, and +its description on PyPI is README.md. Both files are read when the package is built; they may be missing (the installer). +""" +import os +import re +from pathlib import Path + +from setuptools import find_packages, setup + +HERE = Path(__file__).resolve().parent +# A requirement: a project, optional extras, optional version specifiers, an optional environment marker. +REQUIREMENT_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\s*(\[[A-Za-z0-9._,\s-]*\])?\s*([<>=!~]=?\s*[^\s,;]+(\s*,\s*[<>=!~]=?\s*[^\s,;]+)*)?\s*(;.+)?") + + +def is_requirement(line): + """True for a requirement setuptools accepts; options (-r, --index-url), paths and URLs are not requirements.""" + try: + from packaging.requirements import InvalidRequirement, Requirement + except ImportError: + return REQUIREMENT_RE.fullmatch(line) is not None + try: + return Requirement(line).url is None + except InvalidRequirement: + return False + + +def read_requirements(): + """The requirements in requirements.txt, one per line (comments and anything else left out); none without the file.""" + path = HERE / "requirements.txt" + if not path.is_file(): + return [] + lines = (line.split("#", 1)[0].strip() for line in path.read_text(encoding="utf-8").splitlines()) + return [line for line in lines if line and is_requirement(line)] + + +def read_readme(): + path = HERE / "README.md" + return path.read_text(encoding="utf-8") if path.is_file() else "" + + +# The repository on GitHub, when the package is built by a workflow (GitHub sets GITHUB_REPOSITORY). +REPOSITORY = os.environ.get("GITHUB_REPOSITORY") + +setup( + name="PYTHON_PROJ_NAME", + version="VERSION_NUMBER", + long_description=read_readme(), + long_description_content_type="text/markdown", + project_urls={"Source": f"https://github.com/{REPOSITORY}"} if REPOSITORY else {}, + package_dir={"": "src"}, + packages=find_packages(where="src"), + python_requires=">=PYTHON_VERSION", + install_requires=read_requirements(), +) diff --git a/.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/external_code_upload_pypi.md b/.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/external_code_upload_pypi.md new file mode 100644 index 0000000..15022aa --- /dev/null +++ b/.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/external_code_upload_pypi.md @@ -0,0 +1,52 @@ +## 4. Publish the code on PyPI (optional) + +The installer always puts your package into the app. You can also publish it on [PyPI](https://pypi.org), so that anyone can install it with `pip install`, in Google Colab or in their own Python. Each release then does both, with the same version: the GitHub Actions workflow `.github/workflows/publish_pypi.yml` builds the package and uploads it when you publish a release, next to the installers. + +It is **off until you turn it on**, and GitHub stores no password or token for it: PyPI trusts this repository's workflow directly ([trusted publishing](https://docs.pypi.org/trusted-publishers/)). + +**What is published** + +| | | +|---|---| +| Name | The `name=` of `setup.py`: the name of the package, given when the repository was initialised (unless you changed it). If `labconstrictor-app.yaml` has `distribution.pip`, it must be the same name. | +| Version | The release tag without the `v`: release `v1.2.0` publishes 1.2.0. | +| Code | Every package in `src/` (a folder with an `__init__.py`). | +| Dependencies | Each line of `requirements.txt`, as it is written (exact versions included). Options (`-r`, `--extra-index-url`), paths and URLs are left out, with a warning in the log: PyPI refuses dependencies given as URLs. | +| Description | `README.md` of the repository, shown on the PyPI page. | +| License | The `LICENSE` file. | + +### One-time setup + +1. **Check that the name is free.** Open `https://pypi.org/project//`. A "404 Not Found" page means nobody uses it. If it is taken, change `name=` in `setup.py` (and `distribution.pip`) and commit. +2. **Register this workflow on PyPI.** Log in to [pypi.org](https://pypi.org) (create an account if you have none; PyPI asks for two-factor authentication). Open your account menu > **Your projects** > **Publishing** ([pypi.org/manage/account/publishing](https://pypi.org/manage/account/publishing/)). Under **Add a new pending publisher**, choose the **GitHub** tab. The form has five fields; fill them in exactly: + - **PyPI Project Name:** the name of the package. + - **Owner:** the GitHub user or organisation that owns the repository (`CellMigrationLab` in `github.com/CellMigrationLab/MyApp`). + - **Repository name:** the repository (`MyApp`). + - **Workflow name:** `publish_pypi.yml` + - **Environment name:** `pypi` + + Click **Add**. The publisher appears under **Pending publishers** below the form. It does not reserve the name: the project is created by your first release. If the project already exists on PyPI and you own it, add the publisher in the project instead: **Your projects** > the project > **Manage** > **Publishing**. +3. **Turn it on in GitHub.** In the repository, open **Settings** > **Secrets and variables** > **Actions**, then the **Variables** tab (not **Secrets**: a secret cannot turn a workflow on). Click **New repository variable**, type `PYPI_PUBLISH` as the name and `true` as the value, and click **Add variable**. +4. **Publish a release** as usual ([Create executable installers](executable_creation.md)). In the **Actions** tab, the workflow **Publish the Python package to PyPI** runs next to **Build Release Installers**. When both jobs are green, the package is at `https://pypi.org/project//`. The upload job shows the link too. + +### Try it on TestPyPI first (optional) + +[TestPyPI](https://test.pypi.org) is a separate copy of PyPI for trials, with its own account. Add the same pending publisher at [test.pypi.org/manage/account/publishing](https://test.pypi.org/manage/account/publishing/), give the variable `PYPI_PUBLISH` the value `testpypi`, and publish a release. Install the result with: + +```bash +pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ +``` + +Then change the variable to `true`: the next release goes to PyPI. + +### Turn it off + +Delete the variable `PYPI_PUBLISH` (**Settings** > **Secrets and variables** > **Actions** > **Variables**). The workflow stays in the repository and is skipped at each release (a grey icon in the **Actions** tab, not a failure). What was published stays on PyPI. + +### Good to know + +- **A version can be uploaded only once**, even after it was deleted from PyPI. The workflow checks this before it builds anything and stops with a clear message; to publish a fix, make a new release with a higher version. +- **The release writes its version into `setup.py`** (the "Update version" commit of the release workflow), so the file and PyPI agree. +- **To approve each upload by hand**, open **Settings** > **Environments** > **pypi** (GitHub creates it at the first run) and add **Required reviewers**. +- **A repository that already publishes to PyPI with a workflow of its own** does not get `publish_pypi.yml` from the template update, so nothing is uploaded twice. See [the design note of template 0.1.25](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_25.md). +- If the workflow fails, see [Troubleshooting](troubleshooting.md#publishing-to-pypi-fails). diff --git a/.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/troubleshooting_pypi.md b/.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/troubleshooting_pypi.md new file mode 100644 index 0000000..a05685f --- /dev/null +++ b/.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/troubleshooting_pypi.md @@ -0,0 +1,18 @@ +## Publishing to PyPI fails + +The workflow **Publish the Python package to PyPI** (`publish_pypi.yml`) runs at a release only when the repository variable `PYPI_PUBLISH` is `true` or `testpypi` (see [Upload external code](external_code_upload.md#4-publish-the-code-on-pypi-optional)). Its first job checks and builds the package; its second job uploads it. The installers do not depend on it: a failure here leaves the release and its installers as they are. + +| What you see | What to do | +|---|---| +| Both jobs are grey (skipped) | The variable is missing or has another value. It must be a **variable** (Settings > Secrets and variables > Actions > **Variables**), not a secret, named `PYPI_PUBLISH`, with the value `true` or `testpypi` exactly. | +| `invalid-publisher: valid token, but no corresponding publisher` | The trusted publisher on pypi.org (or test.pypi.org for `testpypi`) does not match this workflow. Check the five fields: owner, repository, workflow `publish_pypi.yml`, environment `pypi`, and the project name. Then re-run the failed job (Actions > the run > **Re-run failed jobs**). | +| `... isn't allowed to upload to project ...` (403) | The name belongs to another PyPI project that this repository is not a publisher of. If it is yours, add the publisher in that project's **Publishing** page; if not, choose another `name=` in `setup.py` (and `distribution.pip`). | +| `PyPI already has ` (or `File already exists`) | That version was uploaded before; a version can be uploaded only once, even after it was deleted. Publish a new release with a higher version. | +| `There is no Python package in src/` | Add your code as a folder with an `__init__.py` in `src/` (see [Upload external code](external_code_upload.md)), or delete the variable `PYPI_PUBLISH`. | +| `... also publishes to PyPI` | Another workflow of the repository uploads to PyPI too. Keep one: delete the variable `PYPI_PUBLISH`, or delete the other workflow. | +| `distribution.pip of labconstrictor-app.yaml is ..., but setup.py names the package ...` | Make the two names the same. | +| `PyPI refuses a package whose dependency is a URL` | `setup.py` lists a dependency as `name @ git+https://...`. Publish that dependency on PyPI and name it with a version, or move the URL to `requirements.txt` (the installer still installs it; the PyPI package leaves it out). | +| `setup.py still has the template placeholder ...` | Replace the placeholder in `setup.py` (the log says which), commit, and publish a new release. | +| The upload job waits | The `pypi` environment has required reviewers (Settings > Environments > pypi): one of them approves the upload in the run. | + +After a fix, re-run the failed jobs of the run if nothing in the repository changed (a publisher fixed on pypi.org); otherwise publish a new release. See [the design note of template 0.1.25](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_25.md). 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_9_to_v0_1_10/.tools/docs/troubleshooting.md b/.template_sync/resources/v0_1_9_to_v0_1_10/.tools/docs/troubleshooting.md new file mode 100644 index 0000000..c8e40a8 --- /dev/null +++ b/.template_sync/resources/v0_1_9_to_v0_1_10/.tools/docs/troubleshooting.md @@ -0,0 +1,58 @@ +# Troubleshooting + +## App still appears in the Windows Installed apps list after uninstalling + +On Windows, it may happen that, after uninstalling the app from `Settings > Apps > Installed apps` as explained in the [uninstalling guide](./download_executable.md), the app still appears in the list and does not allow you to uninstall it again, showing a message like: + +![Uninstall error message](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/troubleshooting/Not_Uninstall.png) + +The solution is to go to the Control Panel and uninstall it from there. To do this: + +1. Open the Control Panel. You can search for it in the Windows search bar. +2. Go to `Programs > Programs and Features`. +3. Find the LabConstrictor-based app in the list, right-click on it, and select `Uninstall`. +4. A message may appear saying something like: "An error occurred while trying to uninstall xxx. It might have already been uninstalled." Click `Yes` to confirm. + +This should remove the app even if the previous error message appears. + +## Synchronisation is failing on GitHub Actions + +It may happen that your `Sync with Template Repository` workflow fails with an error like: + +```text +Error: GitHub Actions is not permitted to create or approve pull requests. +``` + +This means that your repository or organization does not allow GitHub Actions to create and approve pull requests. To fix this, change the workflow permissions in the repository or organization settings: + +> Go to Settings > Actions > General > Workflow permissions and check **Allow GitHub Actions to create and approve pull requests**. + +## JupyterLab does not start because Windows reports an ASN.1 certificate error + +LabConstrictor-based installers include a TLS-resilient launcher. It attempts +native operating-system certificate verification before JupyterLab imports +Tornado and provides a verified CA-bundle fallback when a malformed Windows +certificate-store entry cannot be parsed. SSL and hostname verification are +never disabled. + +The constructor environment intentionally does not include +`pip-system-certs`. Its automatic Python startup hook can fail before the +application launcher has an opportunity to select the verified fallback. +Post-install pip commands instead use an explicit CA bundle while preserving +certificate verification. + +Diagnostic information is written to `launcher_debug.log` and +`menuinst_debug.log` in the installation directory. Maintainers can run the +same preflight used by the installer with: + +```text +\python.exe \PROJECT_NAME\launch_jupyter.py --self-test +``` + +The self-test reports the project-specific CA override variable. It is derived +from the application name by replacing punctuation and spaces with underscores +and converting it to uppercase, for example `MY_PROJECT_CA_BUNDLE`. All +LabConstrictor-based applications also accept the shared +`LABCONSTRICTOR_CA_BUNDLE` variable. Set either variable to an organization PEM +bundle before installation or launch when a private certificate authority is +required. diff --git a/.template_sync/resources/v0_1_9_to_v0_1_10/app/bash_bat_scripts/post_install.bat b/.template_sync/resources/v0_1_9_to_v0_1_10/app/bash_bat_scripts/post_install.bat new file mode 100644 index 0000000..37793df --- /dev/null +++ b/.template_sync/resources/v0_1_9_to_v0_1_10/app/bash_bat_scripts/post_install.bat @@ -0,0 +1,191 @@ +@ECHO OFF +SETLOCAL EnableExtensions + +SET "LOG_FILE=%PREFIX%\menuinst_debug.log" +SET "PYTHON_EXE=%PREFIX%\python.exe" +SET "PROJECT_ROOT=%PREFIX%\PROJECT_NAME" +SET "BASE_REQUIREMENTS=%PROJECT_ROOT%\requirements.txt" +SET "GPU_REQUIREMENTS=%PROJECT_ROOT%\requirements_gpu.txt" +SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%" +SET "NVIDIA_SMI=" +SET "CA_BUNDLE=" +SET "FAILURE_MESSAGE=" +SET "CERTIFI_PATH_FILE=%TEMP%\labconstrictor_certifi_%RANDOM%_%RANDOM%.txt" + +> "%LOG_FILE%" echo Running post_install + +IF NOT EXIST "%PYTHON_EXE%" ( + SET "FAILURE_MESSAGE=Bundled Python executable was not found at %PYTHON_EXE%." + GOTO :fail +) +IF NOT EXIST "%PROJECT_ROOT%\launch_jupyter.py" ( + SET "FAILURE_MESSAGE=TLS-resilient launcher was not found at %PROJECT_ROOT%\launch_jupyter.py." + GOTO :fail +) +IF NOT EXIST "%BASE_REQUIREMENTS%" ( + SET "FAILURE_MESSAGE=Base requirements file was not found at %BASE_REQUIREMENTS%." + GOTO :fail +) + +REM pip 24.2+ uses the operating-system trust store by default. Some Windows +REM certificate stores contain malformed entries that OpenSSL cannot parse. +REM Keep verification enabled while opting out of system trust for installer +REM pip operations and using an explicit verified CA bundle. +SET "PIP_USE_DEPRECATED=legacy-certs" + +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --print-ca-bundle > "%CERTIFI_PATH_FILE%" 2>> "%LOG_FILE%" +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Unable to locate a verified CA bundle." + GOTO :fail +) +SET /P "CA_BUNDLE="<"%CERTIFI_PATH_FILE%" +DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 + +IF NOT DEFINED CA_BUNDLE ( + SET "FAILURE_MESSAGE=No verified CA bundle could be selected." + GOTO :fail +) +IF NOT EXIST "%CA_BUNDLE%" ( + SET "FAILURE_MESSAGE=Selected CA bundle does not exist: %CA_BUNDLE%" + GOTO :fail +) + +SET "PIP_CERT=%CA_BUNDLE%" +SET "REQUESTS_CA_BUNDLE=%CA_BUNDLE%" +SET "CURL_CA_BUNDLE=%CA_BUNDLE%" +echo Using verified CA bundle for installer network operations: "%CA_BUNDLE%" >> "%LOG_FILE%" + +IF EXIST "%GPU_REQUIREMENTS%" ( + CALL :detect_nvidia_smi + IF DEFINED NVIDIA_SMI ( + echo NVIDIA GPU utility detected, installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%LOG_FILE%" + SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%" + ) ELSE ( + echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" + ) +) ELSE ( + echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" +) + +echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application requirements installation failed." + GOTO :fail +) + +IF EXIST "%PROJECT_ROOT%\requirements-windows.txt" ( + echo Installing Windows-specific requirements. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install -r "%PROJECT_ROOT%\requirements-windows.txt" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Windows-specific requirements installation failed." + GOTO :fail + ) +) + +REM External Python code is optional in LabConstrictor projects. If setup.py is +REM bundled, install it without a temporary build environment and verify that +REM the generated import package is usable. Otherwise continue without it. +IF EXIST "%PROJECT_ROOT%\setup.py" ( + echo Found setup.py, installing PROJECT_NAME package locally without build isolation. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install --no-deps --no-build-isolation "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=PROJECT_NAME package installation failed." + GOTO :fail + ) + + "%PYTHON_EXE%" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Installed PROJECT_NAME package could not be imported as PYTHON_PROJ_NAME." + GOTO :fail + ) +) ELSE ( + echo No setup.py detected; this project does not bundle an optional Python package. >> "%LOG_FILE%" +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\include_path.py" --path "%PREFIX%" --files "%PROJECT_ROOT%\notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher path preparation failed." + GOTO :fail +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\hide_code_cells.py" "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Notebook metadata preparation failed." + GOTO :fail +) + +REM Keep conda verification enabled, but avoid the Windows trust store that +REM failed during installation. Conda accepts a CA bundle path for ssl_verify. +echo Configuring conda to use verified CA bundle: "%CA_BUNDLE%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m conda config --system --set ssl_verify "%CA_BUNDLE%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: Could not configure conda with the selected CA bundle. The application launcher still has its own verified fallback. >> "%LOG_FILE%" +) + +REM Validate TLS and Jupyter imports before creating shortcuts or registering +REM the application. +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --self-test >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher preflight failed. See menuinst_debug.log and launcher_debug.log." + GOTO :fail +) +echo Launcher preflight completed successfully. >> "%LOG_FILE%" + +"%PYTHON_EXE%" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Python installation diagnostics failed." + GOTO :fail +) + +"%PYTHON_EXE%" -c "from menuinst.api import install; import os; print(install(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application shortcut creation failed." + GOTO :fail +) + +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" +SET "UNINSTALL_EXE=%PREFIX%\Uninstall-UNDERSCORED_PROJECT_NAME.exe" +SET "DISPLAY_ICON=%PROJECT_ROOT%\logo.ico" +SET "DISPLAY_VERSION=VERSION_NUMBER" +SET "PUBLISHER=GITHUB_OWNER" +echo Registering PROJECT_NAME in Windows Apps list >> "%LOG_FILE%" +reg add "%ARP_KEY%" /v DisplayName /d "PROJECT_NAME" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayVersion /d "%DISPLAY_VERSION%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v Publisher /d "%PUBLISHER%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v InstallLocation /d "%PREFIX%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayIcon /d "%DISPLAY_ICON%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v UninstallString /d "\"%UNINSTALL_EXE%\"" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v QuietUninstallString /d "\"%UNINSTALL_EXE%\" /S" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoModify /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoRepair /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 + +echo Post-install completed successfully. >> "%LOG_FILE%" +echo Post-install completed successfully. +ENDLOCAL +EXIT /B 0 + +:fail +IF EXIST "%CERTIFI_PATH_FILE%" DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 +IF NOT DEFINED FAILURE_MESSAGE SET "FAILURE_MESSAGE=Post-install failed for an unknown reason." +echo ERROR: %FAILURE_MESSAGE% >> "%LOG_FILE%" +echo ERROR: %FAILURE_MESSAGE% +echo See "%LOG_FILE%" for details. +ENDLOCAL +EXIT /B 1 + +:detect_nvidia_smi +FOR %%P IN ( + "%ProgramFiles%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%ProgramW6432%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%SystemRoot%\System32\nvidia-smi.exe" + "%SystemRoot%\Sysnative\nvidia-smi.exe" +) DO ( + IF NOT DEFINED NVIDIA_SMI IF EXIST "%%~P" SET "NVIDIA_SMI=%%~P" +) +IF DEFINED NVIDIA_SMI GOTO :EOF + +FOR /F "delims=" %%I IN ('where.exe nvidia-smi.exe 2^>NUL') DO ( + IF NOT DEFINED NVIDIA_SMI SET "NVIDIA_SMI=%%~fI" +) +GOTO :EOF diff --git a/.template_sync/resources/v0_1_9_to_v0_1_10/app/bash_bat_scripts/post_install.sh b/.template_sync/resources/v0_1_9_to_v0_1_10/app/bash_bat_scripts/post_install.sh new file mode 100644 index 0000000..348eee1 --- /dev/null +++ b/.template_sync/resources/v0_1_9_to_v0_1_10/app/bash_bat_scripts/post_install.sh @@ -0,0 +1,96 @@ +#!/bin/bash +set -euo pipefail + +LOG_FILE="$PREFIX/menuinst_debug.log" +PYTHON_EXE="$PREFIX/bin/python" +PROJECT_ROOT="$PREFIX/PROJECT_NAME" +BASE_REQUIREMENTS="$PROJECT_ROOT/requirements.txt" +GPU_REQUIREMENTS="$PROJECT_ROOT/requirements_gpu.txt" +SELECTED_REQUIREMENTS="$BASE_REQUIREMENTS" + +echo "Running post_install" > "$LOG_FILE" + +fail() { + echo "ERROR: $1" | tee -a "$LOG_FILE" >&2 + exit 1 +} + +[ -x "$PYTHON_EXE" ] || fail "Bundled Python executable was not found at $PYTHON_EXE." +[ -f "$PROJECT_ROOT/launch_jupyter.py" ] || fail "TLS-resilient launcher was not found at $PROJECT_ROOT/launch_jupyter.py." +[ -f "$BASE_REQUIREMENTS" ] || fail "Base requirements file was not found at $BASE_REQUIREMENTS." + +# pip 24.2+ uses system certificates by default. Opt out for installer pip +# operations and use an explicit verified CA bundle instead. +export PIP_USE_DEPRECATED=legacy-certs +CA_BUNDLE="$("$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --print-ca-bundle 2>> "$LOG_FILE")" +[ -s "$CA_BUNDLE" ] || fail "No valid verified CA bundle could be selected: $CA_BUNDLE" + +export PIP_CERT="$CA_BUNDLE" +export REQUESTS_CA_BUNDLE="$CA_BUNDLE" +export CURL_CA_BUNDLE="$CA_BUNDLE" +echo "Using verified CA bundle for installer network operations: $CA_BUNDLE" >> "$LOG_FILE" + +if [ -f "$GPU_REQUIREMENTS" ]; then + if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "macOS detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + elif command -v nvidia-smi >/dev/null 2>&1; then + echo "NVIDIA GPU detected, installing GPU requirements from $GPU_REQUIREMENTS" >> "$LOG_FILE" + SELECTED_REQUIREMENTS="$GPU_REQUIREMENTS" + else + echo "NVIDIA GPU not detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + fi +else + echo "GPU requirements file not found, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" +fi + +echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE" +"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1 + +if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "Detected macOS platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-macos.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-macos.txt" >> "$LOG_FILE" 2>&1 + fi +elif [[ "${OSTYPE:-}" == "linux-gnu"* ]]; then + echo "Detected Linux platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-linux.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$PROJECT_ROOT/requirements-linux.txt" >> "$LOG_FILE" 2>&1 + fi +else + echo "Unknown platform: ${OSTYPE:-unset}" >> "$LOG_FILE" +fi + +# External Python code is optional. Verify the generated package only when the +# constructor bundled setup.py and src/. +if [ -f "$PROJECT_ROOT/setup.py" ]; then + echo "Found setup.py, installing PROJECT_NAME package locally without build isolation" >> "$LOG_FILE" + "$PYTHON_EXE" -m pip install --no-deps --no-build-isolation "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + "$PYTHON_EXE" -c "import PYTHON_PROJ_NAME; print('PROJECT_NAME import successful:', PYTHON_PROJ_NAME.__file__)" >> "$LOG_FILE" 2>&1 +else + echo "No setup.py detected; this project does not bundle an optional Python package." >> "$LOG_FILE" +fi + +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PROJECT_ROOT/notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/pre_uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/hide_code_cells.py" "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + +# Keep conda verification enabled while avoiding the system certificate store +# that failed. Conda accepts a CA bundle path for ssl_verify. +if ! "$PYTHON_EXE" -m conda config --system --set ssl_verify "$CA_BUNDLE" >> "$LOG_FILE" 2>&1; then + echo "WARNING: Could not configure conda with the selected CA bundle. The launcher still has its own verified fallback." >> "$LOG_FILE" +fi + +# Do not create the application shortcut unless launcher preflight succeeds. +"$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --self-test >> "$LOG_FILE" 2>&1 +echo "Launcher preflight completed successfully." >> "$LOG_FILE" + +"$PYTHON_EXE" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" -c "from menuinst.api import install; import os; print(install(os.path.join('$PREFIX', 'PROJECT_NAME', 'notebook_launcher.json')))" >> "$LOG_FILE" 2>&1 + +echo "Post-install completed successfully." >> "$LOG_FILE" + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi diff --git a/.template_sync/resources/v0_1_9_to_v0_1_10/app/menuinst/notebook_launcher.json b/.template_sync/resources/v0_1_9_to_v0_1_10/app/menuinst/notebook_launcher.json new file mode 100644 index 0000000..bcb2c44 --- /dev/null +++ b/.template_sync/resources/v0_1_9_to_v0_1_10/app/menuinst/notebook_launcher.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://schemas.conda.org/menuinst/menuinst-1-1-3.schema.json", + "menu_name": "PROJECT_NAME", + "menu_items": [ + { + "name": "PROJECT_NAME", + "description": "Launch PROJECT_NAME in its packaged JupyterLab environment.", + "activate": true, + "terminal": true, + "working_dir": "{{ HOME }}", + "command": [ + "{{ PYTHON }}", + "{{ PREFIX }}/PROJECT_NAME/launch_jupyter.py", + "{{ PREFIX }}/PROJECT_NAME/notebooks/Welcome.ipynb" + ], + "platforms": { + "win": { + "icon": "ICON_ICO_IMAGE_PATH" + }, + "linux": { + "icon": "ICON_IMAGE_PATH" + }, + "osx": { + "icon": "ICON_ICNS_IMAGE_PATH" + } + } + } + ] +} diff --git a/.template_sync/resources/v0_1_9_to_v0_1_10/app/python_scripts/launch_jupyter.py b/.template_sync/resources/v0_1_9_to_v0_1_10/app/python_scripts/launch_jupyter.py new file mode 100644 index 0000000..0f91726 --- /dev/null +++ b/.template_sync/resources/v0_1_9_to_v0_1_10/app/python_scripts/launch_jupyter.py @@ -0,0 +1,286 @@ +"""TLS-resilient JupyterLab launcher for PROJECT_NAME. + +Certificate handling is configured before JupyterLab imports Tornado. On +Windows this prevents one malformed certificate-store entry from terminating +the application. Certificate and hostname verification remain enabled in every +supported mode. +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import re +import ssl +import sys +import traceback +from datetime import datetime, timezone +from importlib import metadata +from pathlib import Path + +PROJECT_DISPLAY_NAME = "PROJECT_NAME" +SCRIPT_DIR = Path(__file__).resolve().parent +_INSTALLED_LAYOUT = (SCRIPT_DIR / "notebooks").is_dir() +if _INSTALLED_LAYOUT: + APP_ROOT = SCRIPT_DIR + PREFIX = APP_ROOT.parent +else: + # Repository layout: app/python_scripts/launch_jupyter.py + repository_root = SCRIPT_DIR.parents[1] + APP_ROOT = repository_root if (repository_root / "notebooks").is_dir() else SCRIPT_DIR + PREFIX = APP_ROOT +DEFAULT_NOTEBOOK = APP_ROOT / "notebooks" / "Welcome.ipynb" +LOG_PATH = PREFIX / "launcher_debug.log" + + +def _write_log(message: str, *, console: bool = True) -> None: + timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") + line = f"[{timestamp}] {message}" + if console: + print(message, flush=True) + try: + with LOG_PATH.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except OSError: + # Logging must never prevent the application from launching. + pass + + +def _package_version(name: str) -> str: + try: + return metadata.version(name) + except metadata.PackageNotFoundError: + return "not installed" + + +def _project_ca_bundle_environment_variable() -> str: + normalized = re.sub(r"[^A-Za-z0-9]+", "_", PROJECT_DISPLAY_NAME).strip("_").upper() + return f"{normalized or 'LABCONSTRICTOR_APP'}_CA_BUNDLE" + + +def _probe_ssl() -> None: + """Create a verified client context without making a network request.""" + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) + if context.verify_mode != ssl.CERT_REQUIRED: + raise RuntimeError("TLS certificate verification is unexpectedly disabled.") + if not context.check_hostname: + raise RuntimeError("TLS hostname verification is unexpectedly disabled.") + + +def _inject_truststore() -> None: + """Route Python SSL contexts through the operating-system trust API.""" + import truststore + + truststore.inject_into_ssl() + + +def _select_ca_bundle() -> Path: + """Choose an explicit CA bundle for verified installer and runtime fallback.""" + for variable in ( + _project_ca_bundle_environment_variable(), + "LABCONSTRICTOR_CA_BUNDLE", + "SSL_CERT_FILE", + "REQUESTS_CA_BUNDLE", + "CURL_CA_BUNDLE", + ): + candidate = os.environ.get(variable, "").strip() + if candidate: + path = Path(candidate).expanduser() + if path.is_file(): + return path.resolve() + + import certifi + + return Path(certifi.where()).resolve() + + +def _install_bundle_fallback(bundle: Path) -> None: + """Use a verified PEM bundle without enumerating the Windows cert store.""" + original_context_type = ssl.SSLContext + + def create_context( + purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH, + *, + cafile: str | os.PathLike[str] | None = None, + capath: str | os.PathLike[str] | None = None, + cadata: str | bytes | None = None, + ) -> ssl.SSLContext: + if purpose == ssl.Purpose.SERVER_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_CLIENT) + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + elif purpose == ssl.Purpose.CLIENT_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_SERVER) + else: + raise ValueError(purpose) + + if cafile or capath or cadata: + context.load_verify_locations( + cafile=os.fspath(cafile) if cafile else None, + capath=os.fspath(capath) if capath else None, + cadata=cadata, + ) + else: + context.load_verify_locations(cafile=str(bundle)) + + keylogfile = os.environ.get("SSLKEYLOGFILE") + if keylogfile and hasattr(context, "keylog_filename"): + context.keylog_filename = keylogfile + return context + + ssl.create_default_context = create_context # type: ignore[assignment] + ssl._create_default_https_context = create_context # type: ignore[attr-defined] + os.environ["SSL_CERT_FILE"] = str(bundle) + os.environ.setdefault("REQUESTS_CA_BUNDLE", str(bundle)) + os.environ.setdefault("CURL_CA_BUNDLE", str(bundle)) + + +def configure_tls() -> tuple[str, list[str]]: + """Prepare TLS before Jupyter/Tornado imports and return mode plus notes.""" + notes: list[str] = [] + + try: + if "truststore" not in getattr(ssl.SSLContext, "__module__", ""): + _inject_truststore() + _probe_ssl() + return "native truststore", notes + except Exception as exc: + notes.append(f"Native truststore activation failed: {exc}") + + try: + bundle = _select_ca_bundle() + _install_bundle_fallback(bundle) + _probe_ssl() + notes.append(f"Using verified CA bundle fallback: {bundle}") + return "verified CA bundle fallback", notes + except Exception as exc: + notes.append(f"CA bundle fallback failed: {exc}") + raise RuntimeError("Unable to create a verified TLS context. " + " | ".join(notes)) from exc + + +def _diagnostics(tls_mode: str, notes: list[str]) -> dict[str, object]: + return { + "status": "ok", + "application": PROJECT_DISPLAY_NAME, + "tls_mode": tls_mode, + "notes": notes, + "ca_bundle_override_variable": _project_ca_bundle_environment_variable(), + "python": sys.version.split()[0], + "python_executable": sys.executable, + "openssl": ssl.OPENSSL_VERSION, + "platform": platform.platform(), + "jupyterlab": _package_version("jupyterlab"), + "jupyter_server": _package_version("jupyter-server"), + "tornado": _package_version("tornado"), + "truststore": _package_version("truststore"), + "pip_system_certs": _package_version("pip-system-certs"), + "certifi": _package_version("certifi"), + "prefix": str(PREFIX), + "log": str(LOG_PATH), + } + + +def _show_error_dialog(message: str) -> None: + if os.name != "nt": + return + try: + import tkinter as tk + from tkinter import messagebox + + root = tk.Tk() + root.withdraw() + messagebox.showerror(f"{PROJECT_DISPLAY_NAME} could not start", message) + root.destroy() + except Exception: + pass + + +def run_jupyter(notebook: Path) -> int: + if not notebook.is_file(): + raise FileNotFoundError(f"Welcome notebook not found: {notebook}") + + # Import only after configure_tls() has completed. Tornado creates SSL + # contexts during import on some versions. + from jupyterlab.labapp import main + + home = Path.home().resolve() + try: + notebook.resolve().relative_to(home) + root_dir = home + except ValueError: + # All-users installations can live outside the home directory. + root_dir = PREFIX.resolve() + + sys.argv = [ + "jupyter-lab", + str(notebook.resolve()), + "--ServerApp.ip=127.0.0.1", + f"--ServerApp.root_dir={root_dir}", + "--ServerApp.shutdown_no_activity_timeout=30", + "--FileContentsManager.always_delete_dir=True", + ] + result = main() + return int(result or 0) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=f"Launch {PROJECT_DISPLAY_NAME} in its packaged JupyterLab environment safely." + ) + parser.add_argument("notebook", nargs="?", type=Path, default=DEFAULT_NOTEBOOK) + parser.add_argument( + "--self-test", + action="store_true", + help="Validate TLS and Jupyter imports without starting the server.", + ) + parser.add_argument( + "--print-ca-bundle", + action="store_true", + help="Print the selected verified CA bundle path and exit.", + ) + args = parser.parse_args(argv) + + try: + if args.print_ca_bundle: + print(_select_ca_bundle(), flush=True) + return 0 + + _write_log("Starting application launcher") + tls_mode, notes = configure_tls() + _write_log(f"TLS mode: {tls_mode}") + for note in notes: + # Recovery details remain available in launcher_debug.log and + # self-test JSON without alarming users during a normal launch. + _write_log(note, console=False) + + import jupyterlab.labapp # noqa: F401 + import tornado.netutil # noqa: F401 + + diagnostics = _diagnostics(tls_mode, notes) + if args.self_test: + print(json.dumps(diagnostics, indent=2), flush=True) + _write_log("Launcher self-test completed successfully") + return 0 + + _write_log(f"Opening notebook: {args.notebook}") + return run_jupyter(args.notebook) + except KeyboardInterrupt: + _write_log("Launcher interrupted by user") + return 130 + except Exception as exc: + details = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + _write_log(details.rstrip()) + friendly = ( + f"{PROJECT_DISPLAY_NAME} could not start, but no certificate-store changes are required.\n\n" + f"A diagnostic log was written to:\n{LOG_PATH}\n\n" + f"Technical message: {exc}" + ) + print("\n" + friendly, file=sys.stderr, flush=True) + _show_error_dialog(friendly) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.template_sync/sync.py b/.template_sync/sync.py new file mode 100644 index 0000000..f752545 --- /dev/null +++ b/.template_sync/sync.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import argparse +import importlib.util +from pathlib import Path +from typing import Any + + +def parse_manifest(manifest_path): + # This function parsers the manifest file withouth the need from external dependencies + template_version = None + migrations = [] + current_migration = None + in_migrations = False + + # Read the manifest file line by line and parse it manually + for raw_line in manifest_path.read_text(encoding="utf-8").splitlines(): + line = raw_line.rstrip() + stripped = line.strip() + + if not stripped or stripped.startswith("#"): + continue + + if not in_migrations: + if stripped.startswith("template_version:"): + template_version = stripped.split(":", 1)[1].strip() + continue + if stripped == "migrations:": + in_migrations = True + continue + raise ValueError(f"Unsupported manifest line: {line}") + + if stripped.startswith("- "): + current_migration = {} + migrations.append(current_migration) + key, value = stripped[2:].split(":", 1) + current_migration[key.strip()] = value.strip() + continue + + if current_migration is None or ":" not in stripped: + raise ValueError(f"Unsupported migration line: {line}") + + key, value = stripped.split(":", 1) + current_migration[key.strip()] = value.strip() + + if not template_version: + raise ValueError("Manifest is missing template_version") + + for migration in migrations: + missing_keys = {"from", "to", "script"} - migration.keys() + if missing_keys: + missing = ", ".join(sorted(missing_keys)) + raise ValueError(f"Migration entry is missing keys: {missing}") + + return { + "template_version": template_version, + "migrations": migrations, + } + + +def parse_version(version: str) -> tuple[int, ...]: + try: + return tuple(int(part) for part in version.split(".")) + except ValueError as exc: + raise ValueError(f"Invalid version string: {version}") from exc + + +def resolve_migration_chain( + migrations: list[dict[str, str]], from_version: str, to_version: str +) -> list[dict[str, str]]: + if parse_version(from_version) > parse_version(to_version): + raise ValueError( + f"Downgrades are not supported: {from_version} -> {to_version}" + ) + + if from_version == to_version: + return [] + + migration_map = {migration["from"]: migration for migration in migrations} + resolved: list[dict[str, str]] = [] + current_version = from_version + + while current_version != to_version: + migration = migration_map.get(current_version) + if migration is None: + raise ValueError( + "No migration path found from " + f"{from_version} to {to_version}. Missing step starting at " + f"{current_version}." + ) + + next_version = migration["to"] + if parse_version(next_version) <= parse_version(current_version): + raise ValueError( + "Migration versions must move forward strictly: " + f"{current_version} -> {next_version}" + ) + + resolved.append(migration) + current_version = next_version + + return resolved + + +def load_migration(script_path: Path): + module_name = f"template_sync_{script_path.stem}" + spec = importlib.util.spec_from_file_location(module_name, script_path) + if spec is None or spec.loader is None: + raise RuntimeError(f"Unable to load migration script: {script_path}") + + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + migrate = getattr(module, "migrate", None) + if not callable(migrate): + raise RuntimeError( + f"Migration script does not define callable migrate(): {script_path}" + ) + + return migrate + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Run template synchronization migrations." + ) + parser.add_argument("--from-version", required=True) + parser.add_argument("--to-version", required=True) + parser.add_argument( + "--repository-root", + default=".", + help="Path to the repository root that should be updated.", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Only print the migration plan.", + ) + args = parser.parse_args() + + repo_root = Path(args.repository_root).resolve() + manifest_path = repo_root / ".template_sync" / "manifest.yaml" + manifest = parse_manifest(manifest_path) + + target_version = manifest["template_version"] + if target_version != args.to_version: + raise ValueError( + f"Target version {args.to_version} does not match manifest version " + f"{target_version}" + ) + + migration_chain = resolve_migration_chain( + manifest["migrations"], args.from_version, args.to_version + ) + + if not migration_chain: + print("No migrations required.") + return 0 + + print( + "Applying template sync migrations:", + " -> ".join( + [args.from_version] + [migration["to"] for migration in migration_chain] + ), + ) + + for migration in migration_chain: + script_path = repo_root / ".template_sync" / migration["script"] + print( + f"Running migration {migration['from']} -> {migration['to']} " + f"using {migration['script']}" + ) + if args.dry_run: + continue + + migrate = load_migration(script_path) + migrate( + repo_root=repo_root, + context={ + "from_version": migration["from"], + "to_version": migration["to"], + "manifest": manifest, + }, + ) + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.tools/bash/build_installer_with_constructor.sh b/.tools/bash/build_installer_with_constructor.sh new file mode 100644 index 0000000..b326475 --- /dev/null +++ b/.tools/bash/build_installer_with_constructor.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Build the platform-specific installer using the prepared constructor env. +set -euo pipefail + +if ! command -v conda >/dev/null 2>&1; then + if [ -n "${CONDA:-}" ] && [ -f "${CONDA}/etc/profile.d/conda.sh" ]; then + # shellcheck disable=SC1090 + source "${CONDA}/etc/profile.d/conda.sh" + elif [ -n "${MAMBA_ROOT_PREFIX:-}" ] && [ -f "${MAMBA_ROOT_PREFIX}/etc/profile.d/micromamba.sh" ]; then + # shellcheck disable=SC1090 + source "${MAMBA_ROOT_PREFIX}/etc/profile.d/micromamba.sh" + else + echo "conda command is not available in PATH and CONDA is unset." >&2 + exit 1 + fi +fi + +mkdir -p "${OUTPUT_DIR:?}" +conda run -n "${CONSTRUCTOR_ENV:?}" constructor . --output-dir "${OUTPUT_DIR}" diff --git a/.tools/bash/create_constructor_environment.sh b/.tools/bash/create_constructor_environment.sh new file mode 100644 index 0000000..1e8ed9e --- /dev/null +++ b/.tools/bash/create_constructor_environment.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Create the conda environment used for constructor builds. +set -euo pipefail + +if ! command -v conda >/dev/null 2>&1; then + if [ -n "${CONDA:-}" ] && [ -f "${CONDA}/etc/profile.d/conda.sh" ]; then + # shellcheck disable=SC1090 + source "${CONDA}/etc/profile.d/conda.sh" + elif [ -n "${MAMBA_ROOT_PREFIX:-}" ] && [ -f "${MAMBA_ROOT_PREFIX}/etc/profile.d/micromamba.sh" ]; then + # shellcheck disable=SC1090 + source "${MAMBA_ROOT_PREFIX}/etc/profile.d/micromamba.sh" + else + echo "conda command is not available in PATH and CONDA is unset." >&2 + exit 1 + fi +fi + +# conda-standalone (the installer's _conda.exe) older than 26.9.3 writes package +# records without paths_data when constructor disables conda's safety checks. +# conda 26.9 and later in the installed app then cannot find the Windows +# launcher stub, and `conda init --reverse` in the uninstaller asks for admin +# rights (conda/conda#16856, fixed in conda 26.9.3). +conda create -y -n "${CONSTRUCTOR_ENV:?}" -c conda-forge -c defaults python=3.11 constructor "conda-standalone>=26.9.3" diff --git a/.tools/bash/run_with_context.sh b/.tools/bash/run_with_context.sh new file mode 100644 index 0000000..ad67d15 --- /dev/null +++ b/.tools/bash/run_with_context.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Helper to run a command, capture its output, and build a context-rich log. +set -euo pipefail + +if [ "$#" -lt 4 ]; then + echo "Usage: run_with_context.sh " >&2 + exit 2 +fi + +LOG_PATH="$1" +shift +STEP_LABEL="$1" +shift +SCRIPT_PATH="$1" +shift + +WORKFLOW_PATH="${WORKFLOW_PATH:-.github/workflows/update_on_notebook_change.yml}" +INSTRUCTIONS=$'You are explaining a GitHub Actions error to a non-programmer maintaining a LabConstrictor-based repository.\nAlways start with a short summary of what failed and in which workflow step.\nWhen the log points to dependency or requirements issues, remind them that each notebook can ship a requirements.yaml, LabConstrictor merges those into a single requirements.txt/environment.yaml, and a shared Python version plus common package list is required so the generated installer works for every notebook.\nIf the problem clearly is not about dependencies, explicitly say so and direct them to open/consult an issue at https://github.com/CellMigrationLab/LabConstrictor/issues.\nStructure your explanation as:\n1. One or two sentences describing what went wrong and where.\n2. The most likely cause in simple language (include the requirements context above when relevant).\n3. Clear next steps to fix or verify (no code unless essential).\n\nThis file contains: (a) the error log, (b) the workflow YAML, (c) the Python script.\n' + +TMP_FILE="$(mktemp)" + +set +e +"$@" 2>&1 | tee "$TMP_FILE" +STATUS=${PIPESTATUS[0]} +set -e + +if [ "$STATUS" -ne 0 ]; then + mkdir -p "$(dirname "$LOG_PATH")" + { + printf '%s\n' "$INSTRUCTIONS" + printf 'There has been an error while running %s, this is the error message:\n' "$STEP_LABEL" + cat "$TMP_FILE" + printf '\nThis is the GitHub action workflow:\n' + cat "$WORKFLOW_PATH" + printf '\nThis is the %s script:\n' "$STEP_LABEL" + cat "$SCRIPT_PATH" + } > "$LOG_PATH" +else + : # No log file on success +fi + +rm -f "$TMP_FILE" +exit "$STATUS" diff --git a/.tools/bash/test_conda_environment.sh b/.tools/bash/test_conda_environment.sh new file mode 100644 index 0000000..4742aca --- /dev/null +++ b/.tools/bash/test_conda_environment.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# Test script to validate conda environment creation and pip requirements installation +# This script creates a test conda environment from environment.yaml and installs pip requirements + +set -e # Exit on any error +set -u # Exit on undefined variables + +is_truthy() { + case "${1:-}" in + 1|true|TRUE|True|yes|YES|Yes|on|ON|On) + return 0 + ;; + *) + return 1 + ;; + esac +} + +if is_truthy "${SKIP_CONDA_ENV_TEST:-}"; then + echo "SKIP_CONDA_ENV_TEST is enabled; skipping conda environment validation." + exit 0 +fi + +echo "==========================================" +echo "Testing Conda Environment Creation" +echo "==========================================" + +# Define test environment name +TEST_ENV_NAME="potential-potato-test-env" + +# Clean up any existing test environment +echo "Cleaning up any existing test environment..." +mamba env remove -n "$TEST_ENV_NAME" -y 2>/dev/null || true + +# Create conda environment from environment.yaml +echo "" +echo "Creating conda environment from environment.yaml..." +if [ ! -f "environment.yaml" ]; then + echo "ERROR: environment.yaml not found!" + exit 1 +fi + +mamba env create -n "$TEST_ENV_NAME" -f environment.yaml -y + +# Activate the environment +echo "" +echo "Activating test environment..." +# Note: In CI, conda/mamba environments need to be activated via conda run +# or by sourcing the activation script + +# Test pip installation of requirements.txt, or of its lock file (requirements.lock.txt, written by +# .tools/python/lock_requirements.py) when there is one: the installer installs the lock file, so that is what is tested. +if [ ! -f "requirements.txt" ]; then + echo "ERROR: requirements.txt not found!" + mamba env remove -n "$TEST_ENV_NAME" -y + exit 1 +fi +REQUIREMENTS_FILE="requirements.txt" +if [ -f "requirements.lock.txt" ]; then + REQUIREMENTS_FILE="requirements.lock.txt" +fi +echo "" +echo "Installing requirements from $REQUIREMENTS_FILE..." + +# Check if the requirements file is not empty +if [ ! -s "$REQUIREMENTS_FILE" ]; then + echo "WARNING: $REQUIREMENTS_FILE is empty, skipping pip install" +else + echo "Installing packages with pip..." + mamba run -n "$TEST_ENV_NAME" pip install --prefer-binary -r "$REQUIREMENTS_FILE" +fi + +# Report dependency conflicts between the pip packages and the conda packages of the environment. Only a warning: a conflict +# among the conda packages themselves must not block the notebooks. +echo "" +echo "Checking the installed packages for conflicts (pip check)..." +if ! mamba run -n "$TEST_ENV_NAME" pip check; then + echo "::warning::pip check found dependency conflicts in the test environment (see the step log); the installer may behave differently than expected." +fi + +# Verify installation by checking Python and key packages +echo "" +echo "Verifying installation..." +echo "Python version:" +mamba run -n "$TEST_ENV_NAME" python --version + +echo "" +echo "Installed pip packages (sample):" +mamba run -n "$TEST_ENV_NAME" pip list | head -n 20 + +# Clean up test environment +echo "" +echo "Cleaning up test environment..." +mamba env remove -n "$TEST_ENV_NAME" -y + +echo "" +echo "==========================================" +echo "โœ“ Conda environment test completed successfully!" +echo "==========================================" diff --git a/.tools/docs/README.md b/.tools/docs/README.md new file mode 100644 index 0000000..a21f622 --- /dev/null +++ b/.tools/docs/README.md @@ -0,0 +1,58 @@ +# LabConstrictor +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.20758747.svg)](https://doi.org/10.5281/zenodo.20758747) + +![LabConstrictor Comic](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/comic.png) + +**LabConstrictor turns your Jupyter notebooks into desktop apps that anyone can install.** Your users download an installer, double-click, and work. They need no Python, no pip and no terminal. + +This repository is a GitHub template. You bring the notebooks; it builds the installers for Windows, macOS and Linux, and gives the app a Welcome page that lists your notebooks. + +**Website, guides and ready-made apps: ** + +## Who is it for? + +- **Researchers** who want colleagues to run an analysis without setting up Python. +- **Developers** who ship interactive notebooks to people who do not code. +- **Teachers** who want a workshop to start with a double-click. + +Looking for an app to use, not to build? Go to the [App Centre](https://cellmigrationlab.github.io/LabConstrictor-Site/apps/). + +## What your users get + +![An installed LabConstrictor app: installer, Welcome notebook and a notebook with hidden code](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Summary.gif) + +- An installer for their system: `.exe` (Windows), `.pkg` (macOS) or `.sh` (Linux). +- A Welcome notebook that opens in the browser and lists the app's notebooks. +- Notebooks with the code hidden, so they look like an app. The code can be shown again. +- A notice when a newer version of the app is available. + +## Quick start + +You need a GitHub account and the notebooks you want to share. Read [Before getting started](./before_getting_started.md) first, then: + +1. [Create a new repository from this template](./create_repository.md) +2. [Enable automatic template updates](./template_synchronization.md) +3. [Initialise your repository](./initialise_repository.md) with the web form +4. [Upload external code](./external_code_upload.md) (optional) +5. [Upload your notebooks](./notebook_upload.md) +6. [Create the installers](./executable_creation.md) + +The same guides, with pictures and a search box, are on the [website](https://cellmigrationlab.github.io/LabConstrictor-Site/build/). + +## Go further + +- [List your app in the App Centre](./app_manifest.md) +- [Offer your app's functions in napari, Fiji and QuPath](./tools_bridge.md) (experimental) +- [Write notebooks that run in both Colab and JupyterLab](./notebook_portability.md) +- [See what others have built](./use_cases.md) +- [All guides](./README.md) + +## Contributing and questions + +Bug fixes and improvements are welcome: read the [contributing guidelines](.github/CONTRIBUTING.md). Using LabConstrictor, or stuck? [Open an issue](https://github.com/CellMigrationLab/LabConstrictor/issues). + +## Citation + +If you use LabConstrictor in your research, please cite the project to support its development: + +Ivรกn Hidalgo-Cenalmor, Marcela Xiomara Rivera Pineda, Bruno M. Saraiva, Ricardo Henriques, and Guillaume Jacquemet. **Packaging Jupyter notebooks as installable desktop apps using LabConstrictor. arXiv preprint 2026** DOI: https://doi.org/10.48550/arXiv.2603.10704 diff --git a/.tools/docs/accept_pull_request.md b/.tools/docs/accept_pull_request.md new file mode 100644 index 0000000..c0fd3dd --- /dev/null +++ b/.tools/docs/accept_pull_request.md @@ -0,0 +1,35 @@ +# Accept a pull request + +Follow these steps or watch the GIF at the end to learn how to accept a Pull Request (PR) on GitHub. LabConstrictor template updates are delivered this way after you complete the [automatic synchronization setup](template_synchronization.md). + +## 1. Go to the Pull Requests tab + +Go to the **Pull Requests** tab in your GitHub repository to see a list of all Pull Requests. You can refer to the screenshot below. + +![Pull Request Tab](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/PR_tab.png) + +## 2. Select the Pull Request to review + +The most recent Pull Request is usually at the top. Click its title to open and review it. + +## 3. Merge the Pull Request + +Click the green **Merge pull request** button, then click **Confirm merge** to complete the process. + +## 4. Delete the branch (optional) + +Once you have merged, you can delete the related branch by clicking the **Delete branch** button. + +![Accept a Pull Request GIF](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Accept_PR.gif) + + +--- + +
+ +[โ† Previous](initialise_repository.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](notebook_requirements.md) + + +
diff --git a/.tools/docs/app_manifest.md b/.tools/docs/app_manifest.md new file mode 100644 index 0000000..c5b787b --- /dev/null +++ b/.tools/docs/app_manifest.md @@ -0,0 +1,202 @@ +# Describe your app: the `labconstrictor-app.yaml` file + +`labconstrictor-app.yaml` is a small text file in the root of your repository. It says what your app is, in your own words. You write it once and keep it up to date yourself. + +Three things read it: + +- **The [App Centre](https://cellmigrationlab.github.io/LabConstrictor-Site/apps/)** builds your app's card and page from it. +- **Your release workflow** reads `platforms` to decide which installers to build. +- **Your installer** passes `hosts` and `host_requirements` to napari, Fiji and QuPath, so they know whether to list your app. + +Version numbers and download links are not in the file. They always come from your latest GitHub release. + +## Step 1: get the file + +The [repository initialiser](initialise_repository.md) asks for a one-sentence summary, the kind of app and the software it also works in. It adds the file to the initialisation pull request. Read it there and edit it if you like. + +If you skipped that section, or your repository is older than the file, create `labconstrictor-app.yaml` in the root of your repository and paste the minimal example below. The [Submit page](https://cellmigrationlab.github.io/LabConstrictor-Site/submit/) also has a form that writes the file for you and checks it as you type. + +## Step 2: start with the minimal file + +These five fields are required. This file is complete and valid: + +```yaml +schema: 1 +name: My App +summary: Counts nuclei in 2D fluorescence images and saves a table. +kind: analysis +distribution: + installer: true +``` + +## Step 3: add what helps people choose your app + +A fuller example. Everything after `distribution` is optional. + +```yaml +# yaml-language-server: $schema=https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json +schema: 1 +name: My App +summary: Counts nuclei in 2D fluorescence images and saves a table. +description: |- + A few paragraphs of plain text. + + Separate paragraphs with a blank line. +kind: analysis +hosts: [notebook, napari, qupath] +host_requirements: + napari: + min_version: 0.1.0-alpha.5 + why: Older plugins do not show the outlines + required: false +distribution: + installer: true + platforms: [windows-x86_64, macos-arm64, linux-x86_64] + colab: + - label: Notebook + url: https://colab.research.google.com/github/you/my-app/blob/main/notebooks/App/App.ipynb + pip: my-app +status: Available +license: MIT +authors: + - name: Ada Lovelace + orcid: 0000-0002-1825-0097 +doi: 10.1371/journal.pbio.3002740 +inputs: + - 2D TIFF images, one channel per file +outputs: + - Label masks and a CSV table +limitations: + - Not tested on 3D data +quickstart: + - Open the app and run the Welcome notebook. +categories: [nuclei, counting] +homepage: https://github.com/you/my-app +docs_url: https://github.com/you/my-app#readme +icon: app/logo/logo.png +screenshots: + - path: docs/screenshot.png + caption: The result table next to the segmented image +``` + +The first line lets editors with YAML support (for example VS Code) check the file as you type. Everything is plain text: no HTML and no Markdown. + +## The fields + +| Field | Required | What it does | Example | +|---|---|---|---| +| `schema` | Yes | The format version. Always `1`. | `1` | +| `name` | Yes | The name people know the app by (2 to 60 characters). | `My App` | +| `summary` | Yes | One sentence for the app card (20 to 200 characters). | `Counts nuclei in 2D images.` | +| `kind` | Yes | What the app is for. One of `analysis`, `segmentation`, `simulation`, `game`, `training`, `utility`. It drives the filter in the App Centre. | `analysis` | +| `distribution` | Yes | How people get the app. At least one of `installer`, `colab`, `pip`. See below. | `installer: true` | +| `hosts` | No | Where the app's tools run: `notebook`, `napari`, `fiji`, `qupath`. See below. | `[notebook, napari]` | +| `host_requirements` | No | The oldest napari, Fiji or QuPath plugin your tools need. See below. | | +| `description` | No | A few paragraphs for the app page (up to 2000 characters). | | +| `status` | No | `Experimental`, `Available` or `Deprecated`. | `Available` | +| `license` | No | The licence, as an SPDX name. | `MIT` | +| `authors` | No | A list of people: `name`, and optionally `orcid`. | `- name: Ada Lovelace` | +| `doi` | No | The DOI of the paper to cite, not of a software archive. The app page shows it as the citation. | `10.1371/journal.pbio.3002740` | +| `inputs`, `outputs`, `limitations` | No | Short lists for the app page: one to six lines of 5 to 200 characters each. | `- 2D TIFF images` | +| `quickstart` | No | Up to six short steps for a first run. | `- Open the app.` | +| `categories` | No | Up to six words a scientist would search for. | `[nuclei, counting]` | +| `homepage`, `docs_url` | No | Web addresses. They must start with `https://`. | | +| `icon` | No | A square PNG in your repository. SVG is not accepted. | `app/logo/logo.png` | +| `screenshots` | No | One to six pictures in your repository (PNG, JPG or GIF), each with a `path` and a `caption`. The caption is also the text for screen readers. | | + +The App Centre asks for a few optional fields: `status`, `quickstart`, `screenshots`, a licence, and `inputs` and `outputs` for analysis, segmentation and simulation apps. Without them your app is still listed; its page says "Not stated" or leaves that part out. + +### `distribution`: how people get the app + +| Key | What it does | +|---|---| +| `installer: true` | Your latest GitHub release carries the installers LabConstrictor builds. | +| `platforms` | The systems you support. Needs `installer: true`. Only these installers are built and offered. | +| `colab` | A list of Google Colab notebooks, each with a `label` and a `url` on `colab.research.google.com`. Only the notebooks you list are shown. | +| `pip` | The name of your package on PyPI. | + +`platforms` also decides which installers your releases build (template 0.1.24 or later). Leave a system out when your app cannot run there. Without `platforms`, every installer is built: `windows-x86_64`, `linux-x86_64`, `macos-arm64` (Apple silicon) and `macos-x86_64` (Intel Macs). `windows-arm64` and `linux-arm64` are accepted, but no installer is built for them. + +### `hosts`: where your tools are offered + +This field matters only if your app [exposes tools](tools_bridge.md). napari, Fiji and QuPath list your app only if you name them here. Write the hosts you have tested the app in. + +- `hosts: [notebook]` means no plugin lists the app. Its tools still work in the notebook and on the command line. +- Without a `hosts` line, every plugin lists the app. Say what you mean instead. +- Names are lower case. The check refuses a misspelt, repeated or capitalised name. + +## 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 + +The **Check App Centre manifest** workflow runs when you change the file and when you publish a release: + +- If the file is missing, it shows a warning and passes. +- If the file is invalid, it fails and says what to fix. This never stops your installers from being built. +- It rejects fields it does not know (this catches typos, so the schema is not loosened); the template keeps its copy of the schema in step with the App Centre, see [Keep your app up to date](keep_app_up_to_date.md). +- It also checks that the icon and screenshots you name exist in the repository. + +## Check it yourself + +To get an answer before you push, you have two more ways: + +1. **On your computer.** From the root of your repository: + + ```bash + pip install pyyaml jsonschema + python .tools/python/check_app_manifest.py + ``` + +2. **In your browser.** Paste your values into the form on the [Submit page](https://cellmigrationlab.github.io/LabConstrictor-Site/submit/). It checks them against the same schema. + +If your app exposes tools, also run `labconstrictor-tools check --module _lc_tools --app-manifest labconstrictor-app.yaml`. It prints the `hosts` and `host_requirements` it read, which is what the installer will register. + +The rules themselves are in the [schema](https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json). Your repository has a copy in `.tools/schema/`, and the check uses that copy. + +## Common mistakes + +| What the check says, or what you see | Fix | +|---|---| +| A field "is not allowed" or is "unexpected" | The name is misspelt, or it is at the wrong level. For example `platforms` belongs under `distribution`. | +| `summary` is too short or too long | Write one sentence of 20 to 200 characters. | +| `platforms` without `installer` | Add `installer: true`. `platforms` only applies to installers. | +| The icon or a screenshot is "not found" | The path starts at the root of your repository, with no leading `/`. The file must be committed. | +| A Colab link is refused | The address must start with `https://colab.research.google.com/`. | +| `min_version: 0.2` is refused | YAML reads `0.2` as a number. Put it in quotes: `"0.2"`. | +| Your app is missing from napari, Fiji or QuPath | The host is not in `hosts`, or the app was installed before you added it. Publish a release and install it again. | +| The check passes but nothing changes in the App Centre | The App Centre reads the file from your default branch and updates once a day. | +| Text shows `**stars**` or tags | The fields are plain text. Remove Markdown and HTML. | + +## Get listed + +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. You do this once: later releases appear by themselves. + +The technical rules for `hosts` and `host_requirements` are in the [LabConstrictor-Tools manifest reference](https://cellmigrationlab.github.io/LabConstrictor-Tools/MANIFEST/). + +--- + +
+ +[โ† Previous](initialise_repository.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](external_code_upload.md) + + +
diff --git a/.tools/docs/before_getting_started.md b/.tools/docs/before_getting_started.md new file mode 100644 index 0000000..d47cd7a --- /dev/null +++ b/.tools/docs/before_getting_started.md @@ -0,0 +1,52 @@ +# Before getting started with LabConstrictor + +Welcome to LabConstrictor! This guide will walk you through the basics and show you what you need to get started. + +## ๐ŸŽฏ LabConstrictor in a Nutshell + +LabConstrictor is a template repository that lets you turn Jupyter notebooks into desktop apps. It handles the setup for you via automated GitHub Actions. Here are its main features: + +### โš™๏ธ Easy Configuration + +LabConstrictor has a web form that makes it easy to set up your repository, add your branding, and upload or update your notebooks and their dependencies. + +### ๐Ÿ–ฅ๏ธ Cross-Platform Installers + +Automatic workflows create installers for Windows (.exe), macOS (.pkg), and Linux (.sh). This makes it simple for users on any platform to install and run your notebooks. The installers are created using [Conda Constructor](https://github.com/conda/constructor). + +### ๐Ÿ“ฆ Environment Management + +LabConstrictor uses `requirements.yaml` files to manage dependencies. Automatic workflows ensure your notebooks run consistently across different systems. LabConstrictor also includes helper notebooks for generating and validating requirement files. + +### ๐Ÿ“ˆ Version Control + +LabConstrictor includes helper cells that track notebook versions and notify users when updates are available. This way, everyone can use the latest features and fixes. + +### โœจ User-Friendly Experience + +The installers take care of the setup, so users can open your notebooks with a desktop app. The app shows a Welcome Dashboard where users can check versions and pick notebooks. Notebooks have hidden code and a play button to run cells, giving a clean, app-like feel. Your repository can be private or public, giving you full control over who can access and use your notebooks. + +### ๐Ÿ“ฑ Offline Usage + +If your notebooks donโ€™t need internet access, users can run the desktop apps offline after they install them. + +## โœ… LabConstrictor Requirements + +To get started with LabConstrictor, you only need the following: + +- **๐Ÿ™ GitHub Account:** Youโ€™ll need a GitHub account to make a new repository from the LabConstrictor template. +- **๐Ÿ“’ Jupyter Notebooks:** Have your Jupyter notebooks ready to package into desktop apps. +- **๐Ÿ Python Environment:** Youโ€™ll need a Python environment (local or online) where your notebooks run without errors. This is needed to create and check requirement files. Alternatively, you can create the requirement files yourself, but this may be prone to errors. +- **(Optional) ๐Ÿ–ผ๏ธ Images, logo and icons:** for branding your executable installer. We recommend following the [images guidelines](./installer_images.md) for further information and guidance. + + +--- + +
+ +โ† Previous            +[๐Ÿ  Home](README.md)            +[Next โ†’](create_repository.md) + + +
diff --git a/.tools/docs/code_hiding.md b/.tools/docs/code_hiding.md new file mode 100644 index 0000000..31f013c --- /dev/null +++ b/.tools/docs/code_hiding.md @@ -0,0 +1,33 @@ +# Hide code cells in notebooks + +LabConstrictor gives the option to hide code cells in Jupyter notebooks, making them cleaner and avoiding overwhelming users with too much code. + +## How is this for? + +This feature is only useful if your notebooks don't require any code modifications by the user. For example, if your notebook is purely for data visualisation and analysis, or if interaction with the user is done through widgets, hiding code cells can enhance the user experience. If your notebook requires users to modify code cells, it's best to keep them visible. + +## How is this different from collapsing cells? + +JupyterLab already provides a way of collapsing the cell by clicking the blue bar on the left side of the cell. However, this method uncollapses the cell when the user clicks anywhere inside the cell, which can be inconvenient for users to chose the cell they want to run. + +This feature avoids that problem by providing a dedicated button to show or hide all code cells in the notebook and allowing the user to freely click the code cell. Additionally, when hiding code cells using this feature, a play button appears next to each code cell, allowing users to run code cells more intuitively. + +## How does the play button work? + +Depending on the versions of JupyterLab and ipywidgets you use, when code cells are hidden, a play button might show up next to each code cell: + +![Play Button vs Missing](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Notebook_Cell_Button.png) + +Clicking this button runs the corresponding code cell without revealing the code. Whether or not the play button appears, you can always run a code cell by selecting it and clicking the play button in the top toolbar: + +![Toolbar Play Button](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Notebook_Play_Button.png) + +## How to hide or show code cells? + +Depending on your initialisation your code cells will be hidden by default or shown by default. In either case, the visibility of code cells can be toggled using the `Show/Hide Code` button in the top toolbar: + +![Show Hide Code Button](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Notebook_ShowHide_Button.png) + +## Where is this controlled? + +Hiding code cells is done by a small script, [`hide_code_cells.py`](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/templates/hide_code_cells.py). In your own repository it is `app/python_scripts/hide_code_cells.py`, and it runs when you upload or change a notebook. To switch the feature on or off, set `HIDE_CODE_DISABLED` in that file (`False` hides the code cells), or initialise your repository again with the [repository initialiser](https://labconstrictor-form.streamlit.app/) and choose the other option. diff --git a/.tools/docs/create_repository.md b/.tools/docs/create_repository.md new file mode 100644 index 0000000..0d30864 --- /dev/null +++ b/.tools/docs/create_repository.md @@ -0,0 +1,45 @@ +# Create your repository + +To start, open the [LabConstrictor template on GitHub](https://github.com/CellMigrationLab/LabConstrictor) and click the `Use this template` button at the top of the page. This will let you create a new repository using the LabConstrictor template. + + +1. Click the green **Use this template** button at the top right of the main repository page. +2. Select **Create a new repository**. + +![Use template screenshot](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Use_Template.png) + +3. Next, youโ€™ll need to fill in some details: + +* **Include all branches:** +Please, let the default `Off` option. + +* **Owner:** +Pick either your personal account or your research groupโ€™s organization. + +* **Repository Name:** +Pick a short, memorable name (for example, `MyLabTools`). +> **Note:** This name will be used as the default name for your application installer. + +* **Description** *(Optional)*: +Write a brief description of what your notebooks do (for example, "Automated cell migration analysis"). + +* **Visibility:** + * **Public:** Select this if you want to share your installer right away. + * **Private:** Select this if youโ€™re still working on the tools or want to keep the code within your lab. A private repository cannot be listed in the App Centre: make it public before you submit your app. + +4. Click **Create repository**. ๐ŸŽ‰ Thatโ€™s it! Your repository is now set up and ready to go. + +## Template updates (optional, later) + +We recommend setting up automatic template updates after your first release. Without the update token, the weekly **Sync with Template Repository** run stops with the error "Synchronization setup required" as soon as a newer template version exists, and your repository receives no update pull request. See [Keep your app up to date](keep_app_up_to_date.md). + +--- + +
+ +[โ† Previous](before_getting_started.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](initialise_repository.md) + + +
diff --git a/.tools/docs/download_executable.md b/.tools/docs/download_executable.md new file mode 100644 index 0000000..d724417 --- /dev/null +++ b/.tools/docs/download_executable.md @@ -0,0 +1,18 @@ +### Sorry, but no executable files are available yet + +In order to create the executables, please remember to upload notebooks and create a release: + + - First: [**Upload Your Notebooks**](notebook_upload.md) + - Then: [**Create Executable Installers**](executable_creation.md) + +Once you've done that, the executables will appear here for download. Or you will be able to find them in the "Releases" section of your repository. + +--- + +
+ +[โ† Previous](executable_creation.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](notebook_usage.md) + +
\ No newline at end of file diff --git a/.tools/docs/executable_creation.md b/.tools/docs/executable_creation.md new file mode 100644 index 0000000..e104c40 --- /dev/null +++ b/.tools/docs/executable_creation.md @@ -0,0 +1,41 @@ +# Create installer files + +After uploading your notebooks to the repository, follow these steps to create executable files for sharing. + +## โš ๏ธ Please check before proceeding: + +Open the Actions tab in your repository and check that no workflows are running. If one is in progress, wait until it finishes. Starting a release while other jobs are running may cause build conflicts. + +## 1. Draft a new release + +1. Go to your repository's main page. +2. Click on Releases (usually on the right sidebar). +3. Click `Create a new release` and provide the following information: + - **Tag**: Click `Create a new tag` and enter a version number, for example, `0.0.1`. + > **IMPORTANT**: Make sure that it follows a semantic versioning format (MAJOR.MINOR.PATCH) e.g. `1.0.0`, `1.2.3`, `2.1.0`. A `v` in front (`v1.0.0`) also works: the installers are named with the version without it. + - **Release title**: Enter a title for your release, such as `Initial release`. + - **Description** (optional): Enter a description for your release, for example, `This is the initial release of my project.` + +## 2. Publish the release + +Once you have entered all the required information, click `Publish release`. This action will start the automated workflow to create installer executable files for your notebooks. To monitor the process, see [How to check the automatic workflow status](workflow_status.md). + +When the automated workflow completes, open your repository's **Releases** page, open the release you published and download the installers from its **Assets** list. + +## 3. After the release + +- Try your installer yourself: [Install an app](install.md), then [Use notebooks after installation](notebook_usage.md). +- List your app in the App Centre: [Describe your app for the App Centre](app_manifest.md). +- Receive future template improvements as pull requests: [Keep your app up to date](keep_app_up_to_date.md). + + +--- + +
+ +[โ† Previous](notebook_upload.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](installer_images.md) + + +
diff --git a/.tools/docs/external_code_upload.md b/.tools/docs/external_code_upload.md new file mode 100644 index 0000000..4c5fc89 --- /dev/null +++ b/.tools/docs/external_code_upload.md @@ -0,0 +1,125 @@ +# Upload external code + +If you want to use your own Python modules or scripts in Jupyter notebooks, follow these steps to upload them easily. + +## 1. Prepare your external code + +Organize your external code and follow Python packaging best practices. Set up the right folder structure, add an `__init__.py` file, and list any required dependencies. + +**Suggested Directory Structure:** + +```text +src/ +|-- fast4dreg/ +| |-- __init__.py +| |-- my_script.py +| |-- subpackage/ +| |-- __init__.py +``` + +### What goes in `__init__.py`? + +Think of `__init__.py` as the file that tells Python โ€œthis folder is a packageโ€. + + If you leave it empty, that is perfectly fineโ€”the package will still import correctly. When you want to make notebooks feel friendlier, you can re-export helper functions so users can discover them more easily: + +```python +# src/fast4dreg/__init__.py +from .my_script import run_analysis, load_config + +__all__ = ["run_analysis", "load_config"] +``` + +Each folder that you plan to import (for example, `src/subpackage/`) should also have its own `__init__.py`. Keep it empty unless you want to expose selected helpers from that subpackage. + +If you need further readings on `__init__.py`, check out this quick [Geeks for Geeks tutorial](https://www.geeksforgeeks.org/python/what-is-__init__-py-file-in-python/) or the [Real Python guide](https://realpython.com/python-init-py/). +## 2. Upload your external code to the repository + +Go to the src folder in your repository and upload your files or folders there. + +![Upload external code GIF](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Upload_src.gif) + +## 3. How to import into your notebook + +Once uploaded, your external code will be available to your notebooks as a package. To use it, import it as shown in the examples below: + +**Import the whole package:** +```python +import fast4dreg +``` + +If your folder under `src/` is called `celltools`, then `import celltools` will work because `src/celltools/__init__.py` exists. + +**Import function:** +```python +from fast4dreg import my_script +``` + +**Import submodule:** +```python +from fast4dreg.subpackage import submodule1 +``` + +## 4. Publish the code on PyPI (optional) + +The installer always puts your package into the app. You can also publish it on [PyPI](https://pypi.org), so that anyone can install it with `pip install`, in Google Colab or in their own Python. Each release then does both, with the same version: the GitHub Actions workflow `.github/workflows/publish_pypi.yml` builds the package and uploads it when you publish a release, next to the installers. + +It is **off until you turn it on**, and GitHub stores no password or token for it: PyPI trusts this repository's workflow directly ([trusted publishing](https://docs.pypi.org/trusted-publishers/)). + +**What is published** + +| | | +|---|---| +| Name | The `name=` of `setup.py`: the name of the package, given when the repository was initialised (unless you changed it). If `labconstrictor-app.yaml` has `distribution.pip`, it must be the same name. | +| Version | The release tag without the `v`: release `v1.2.0` publishes 1.2.0. | +| Code | Every package in `src/` (a folder with an `__init__.py`). | +| Dependencies | Each line of `requirements.txt`, as it is written (exact versions included). Options (`-r`, `--extra-index-url`), paths and URLs are left out, with a warning in the log: PyPI refuses dependencies given as URLs. | +| Description | `README.md` of the repository, shown on the PyPI page. | +| License | The `LICENSE` file. | + +### One-time setup + +1. **Check that the name is free.** Open `https://pypi.org/project//`. A "404 Not Found" page means nobody uses it. If it is taken, change `name=` in `setup.py` (and `distribution.pip`) and commit. +2. **Register this workflow on PyPI.** Log in to [pypi.org](https://pypi.org) (create an account if you have none; PyPI asks for two-factor authentication). Open your account menu > **Your projects** > **Publishing** ([pypi.org/manage/account/publishing](https://pypi.org/manage/account/publishing/)). Under **Add a new pending publisher**, choose the **GitHub** tab. The form has five fields; fill them in exactly: + - **PyPI Project Name:** the name of the package. + - **Owner:** the GitHub user or organisation that owns the repository (`CellMigrationLab` in `github.com/CellMigrationLab/MyApp`). + - **Repository name:** the repository (`MyApp`). + - **Workflow name:** `publish_pypi.yml` + - **Environment name:** `pypi` + + Click **Add**. The publisher appears under **Pending publishers** below the form. It does not reserve the name: the project is created by your first release. If the project already exists on PyPI and you own it, add the publisher in the project instead: **Your projects** > the project > **Manage** > **Publishing**. +3. **Turn it on in GitHub.** In the repository, open **Settings** > **Secrets and variables** > **Actions**, then the **Variables** tab (not **Secrets**: a secret cannot turn a workflow on). Click **New repository variable**, type `PYPI_PUBLISH` as the name and `true` as the value, and click **Add variable**. +4. **Publish a release** as usual ([Create executable installers](executable_creation.md)). In the **Actions** tab, the workflow **Publish the Python package to PyPI** runs next to **Build Release Installers**. When both jobs are green, the package is at `https://pypi.org/project//`. The upload job shows the link too. + +### Try it on TestPyPI first (optional) + +[TestPyPI](https://test.pypi.org) is a separate copy of PyPI for trials, with its own account. Add the same pending publisher at [test.pypi.org/manage/account/publishing](https://test.pypi.org/manage/account/publishing/), give the variable `PYPI_PUBLISH` the value `testpypi`, and publish a release. Install the result with: + +```bash +pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ +``` + +Then change the variable to `true`: the next release goes to PyPI. + +### Turn it off + +Delete the variable `PYPI_PUBLISH` (**Settings** > **Secrets and variables** > **Actions** > **Variables**). The workflow stays in the repository and is skipped at each release (a grey icon in the **Actions** tab, not a failure). What was published stays on PyPI. + +### Good to know + +- **A version can be uploaded only once**, even after it was deleted from PyPI. The workflow checks this before it builds anything and stops with a clear message; to publish a fix, make a new release with a higher version. +- **The release writes its version into `setup.py`** (the "Update version" commit of the release workflow), so the file and PyPI agree. +- **To approve each upload by hand**, open **Settings** > **Environments** > **pypi** (GitHub creates it at the first run) and add **Required reviewers**. +- **A repository that already publishes to PyPI with a workflow of its own** does not get `publish_pypi.yml` from the template update, so nothing is uploaded twice. See [the design note of template 0.1.25](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_25.md). +- If the workflow fails, see [Troubleshooting](troubleshooting.md#publishing-to-pypi-fails). + +--- + +
+ +[โ† Previous](app_manifest.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](keep_app_up_to_date.md) + + +
diff --git a/.tools/docs/initialise_repository.md b/.tools/docs/initialise_repository.md new file mode 100644 index 0000000..0b31be3 --- /dev/null +++ b/.tools/docs/initialise_repository.md @@ -0,0 +1,22 @@ +# Initialise your repository + +Now that your repository is set up, you can start to customise it. To get started, you will need: + +- A name for your project/application (e.g., `CellAnalyzer`). +- An initial version number (e.g., `0.0.1`). +- A one-sentence summary of what your app does, its kind, and the software it also works in. They go into the description file for the [App Centre](app_manifest.md). +- (Optionally) Images for App installer customisation. See [Installer Images Customisation](installer_images.md) for more details on the images you can provide. + +Once you have everything ready, go to [https://labconstrictor-form.streamlit.app/](https://labconstrictor-form.streamlit.app/). If you see a `Zzzz` message for inactivity, click `Yes, get this app back up!`. Next, select `Start initialisation` in the **Initialise GitHub repository** section. Follow the instructions on the website. After you submit the form, a Pull Request with suggested changes will be created in your repository. To learn how to accept these suggestions, see [How to accept a Pull Request](accept_pull_request.md). After you accept the suggestions, the main README will move to [.tools/docs](.). But don't be afraid, the new README will have a link pointing the instructions for future reference, so you wonโ€™t lose access to them. + + +--- + +
+ +[โ† Previous](create_repository.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](accept_pull_request.md) + + +
diff --git a/.tools/docs/install.md b/.tools/docs/install.md new file mode 100644 index 0000000..b23b6ef --- /dev/null +++ b/.tools/docs/install.md @@ -0,0 +1,45 @@ +# Install an app + +Installing takes about 6-8 minutes and you only do it once. You need an internet connection while installing: the installer downloads the app's Python packages. Download the installer for your system from the app's page in the [App Centre](https://cellmigrationlab.github.io/LabConstrictor-Site/apps/) (or from the app's GitHub release) and follow the steps for your system. + +> **Check where it comes from.** The installers are not code-signed yet, so your system will warn you. Download only from the app's own GitHub release (the address starts with `https://github.com/` followed by the app's owner and repository, as shown on the app's page), and run it only if you trust that owner. A listing in the App Centre checks that the files come from the app's repository; it is not a security audit. + +> A command prompt window opens during installation on Windows; this is normal, do not close it. + +## Before you install + +- **Install path.** The install path must contain no space: the installer refuses a path with a space. Use a path such as `C:\LabConstrictor\` on Windows or `~/labconstrictor/` on macOS and Linux. + +## Install on Windows + +1. Download the `.exe` file and double-click it. +2. If Windows shows "Windows protected your PC", click "More info" and then "Run anyway". The installers are not code-signed yet. + + ![Windows protected your PC: click More info, then Run anyway](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Windows_Protected_your_PC.png) + +3. Follow the on-screen prompts. Launch the app from the Start Menu or your desktop. + +## Install on a Mac + +1. Choose your file: open the Apple menu, then About This Mac. If the Chip or Processor says Intel, download the Intel installer; if it says M1, M2 or similar, download the Apple Silicon one. +2. Double-click the `.pkg` file. If macOS refuses to open it, go to System Settings, Privacy & Security, scroll down to the message about the package and click "Open Anyway" (it appears only after you tried to open the file once). If you do not see it, try opening the file again, then check this page again. +3. Follow the prompts (we recommend "Install only for me"). Launch the app from your Applications folder. + +## Install on Linux + +1. Download the `.sh` file. +2. Open a terminal in the download folder and run `bash` followed by the name of the file you downloaded, for example: `bash MyApp-0.1.0-Linux-x86_64.sh` +3. Follow the prompts, then launch the app from your applications menu. + +## Update an installed app + +- **macOS and Windows.** On macOS and Windows, update an app by uninstalling the old version first and then installing the new one: the installer does not install over an existing install. On macOS, if you already ran the new installer over the old version and it stopped or reported a failure at the end, move only the old app shortcut (for example `~/Applications/MyApp.app`) to the Bin, keep the app's folder in your home folder, and run the installer again ([known issue](https://github.com/CellMigrationLab/LabConstrictor/issues/34)). +- **Linux.** On Linux, running the installer with `-u` updates in place only if the previous install finished; otherwise delete `/pkgs` or uninstall the app and install it again. + +## Where the app is listed + +If the app ships tools for Napari, Fiji or QuPath, the installer registers them with LabConstrictor Tools and passes the `hosts:` line of the app's `labconstrictor-app.yaml` (the installer bundles that file). A host lists the app only if the line names it: with `hosts: [notebook, napari]` the app is listed in Napari, and not in Fiji or QuPath. Without the file, or without a `hosts:` line, the app is registered without hosts, every host lists it, and `menuinst_debug.log` in the install folder says so (`'' declares no hosts, so it is listed in every host; ...`). + +## Next + +Open the app and start working: [Use notebooks after installation](notebook_usage.md). If something goes wrong, see [Troubleshooting an installed app](troubleshooting_installed_app.md). diff --git a/.tools/docs/installer_images.md b/.tools/docs/installer_images.md new file mode 100644 index 0000000..1c3a589 --- /dev/null +++ b/.tools/docs/installer_images.md @@ -0,0 +1,45 @@ +# Customise the installer images + +The generated installer and desktop app can be customised with you own images. This will help to give your app a more professional look and feel. This customisation is optional and can be done when initialising your repository or at any time later. + +You can provide the following images for customisation: + +| Image Type | Recommended Size | Format | Description | +|------------|------------------|--------|-------------| +| Logo | 256x256 pixels | PNG | This image will be used in the executable installer and on the created desktop app. | +| Banner | 164x314 pixels | PNG | This vertical image will be used as a banner in the installer. | +| Header | 150x57 pixels | PNG | This image will be used as the header in the installer. | + +When preparing your images, please ensure they meet the recommended size and format for optimal display. Here are some examples of custom images used in an installer: + +## Logo: +![LabConstrictor Logo](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/LabConstrictor_Logo.png) + +## Banner: +![LabConstrictor Banner](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/LabConstrictor_Banner.png) + +## Header: +![LabConstrictor Header](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/LabConstrictor_Header.png) + +## Default Installer + +In case you do not provide any images during the initialisation of your repository, default placeholder images will be used: + +![Default Installer Images](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Customisation_Default.png) + +## Customised Installer + +When you provide your own images, the installer will reflect your custom branding: + +![Customised Installer Images](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Customisation_Custom.png) + +--- + +
+ +[โ† Previous](executable_creation.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](app_manifest.md) + + +
diff --git a/.tools/docs/keep_app_up_to_date.md b/.tools/docs/keep_app_up_to_date.md new file mode 100644 index 0000000..5831bee --- /dev/null +++ b/.tools/docs/keep_app_up_to_date.md @@ -0,0 +1,32 @@ +# Keep your app up to date + +The LabConstrictor template keeps improving. Your repository can receive those improvements, including updates to its GitHub Actions workflows, as a pull request that you review and merge. This is optional and can wait until after your first release. + +## How it works + +The **Sync with Template Repository** workflow runs every Monday at 09:00 UTC, and you can also start it yourself from the **Actions** tab. When the template has a newer version than your repository, the workflow applies the changes needed to move your repository to that version and opens a pull request titled "Sync template to version" followed by the new version number. You then merge it as described in [Accept a pull request](accept_pull_request.md). When your repository is already on the latest template version, the run ends without opening a pull request. + +Template-managed files, such as the copy of the App Centre manifest schema used by the **Check App Centre manifest** workflow, are refreshed by the same pull request. If that check rejects a field the App Centre accepts, your copy of the schema is older than the App Centre: merge the latest sync pull request. + +## What you lose without the setup + +Opening that pull request needs a token that you create and save in your repository as the secret `LABCONSTRICTOR_SYNC_TOKEN`. Without it, the workflow stops with the error "Synchronization setup required" as soon as a newer template version exists. No update pull request is created, so your repository stays on the template version it has. + +## Set it up + +Follow [Enable automatic LabConstrictor template updates](template_synchronization.md): create the token, save it as the secret, and renew it when it expires ([Renewing an expired token](template_synchronization.md#renewing-an-expired-token)). + +## If it does not work + +See [Synchronisation is failing on GitHub Actions](troubleshooting.md#synchronisation-is-failing-on-github-actions), and [Check the status of GitHub workflows](workflow_status.md) for how to read a failed run. + +--- + +
+ +[โ† Previous](external_code_upload.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](template_synchronization.md) + + +
diff --git a/.tools/docs/migration_0_1_16.md b/.tools/docs/migration_0_1_16.md new file mode 100644 index 0000000..1bebb03 --- /dev/null +++ b/.tools/docs/migration_0_1_16.md @@ -0,0 +1,65 @@ +# Template 0.1.16: how the Tools bridge hooks reach an existing app + +Design note for the 0.1.16 migration (`.template_sync/migrations/v0_1_15_to_v0_1_16.py`). Short version: the hooks reach an **existing app** through the normal template synchronization pull request, and reach **people who already installed it** only when they install a newer installer of the app. Nothing in the template can change an installed copy by itself. + +## 1. What "update" means in this template (checked in the code) + +There are two different things called "the app": + +| | Where it lives | How it changes | +|---|---|---| +| The **app repository** (created from the template) | GitHub | The weekly workflow `sync_template.yml` ("Sync with Template Repository") compares `.template_sync/manifest.yaml` (`template_version`) of the repository with the template's `main`, copies the template's `.template_sync` folder, runs the chain of migrations with `.template_sync/sync.py`, and opens a pull request ("Sync template to version X"). It needs the secret `LABCONSTRICTOR_SYNC_TOKEN`; without it the workflow stops with an error and the repository stays on its version. The owner reviews and merges. | +| The **installed app** | The user's computer (a conda prefix made by the `constructor` installer) | Never by the template. `post_install` runs once while an installer runs. Nothing runs on update: there is no self-update step, no version check in the scripts, and the notebook update check (`notebook_latest_versions.yaml`) only tells people that a notebook has a newer version. | + +So the real path of a template change to a user is: template `main` (version bump) -> sync pull request in the app repository (migration edits the scripts) -> owner merges -> owner publishes a **release** of the app (`release_constructor.yml` builds the installers from the repository) -> the user downloads and runs the new installer. + +What the installer does with the scripts (from `construct.yaml` and the `constructor` sources): + +* `post_install.sh/.bat` are run by the installer at the end of every install (`pkgs/post_install.*`). **How a user gets the new installer onto an existing install differs by system** (observed in the first run of the LabConstrictor-Tools workflow `smoke_migration.yml`, run 38298832113, with NucleiSky): + * Linux: `bash installer.sh -u -p ` updates the existing prefix in place and runs `post_install` again (works). + * macOS: the same `-u` stops in `post_install` because menuinst refuses an existing shortcut ("App already exists at ~/Applications/.app"). This is how the template behaves today, independent of the hooks. Run the app's `uninstall.sh` first, then the new installer. + * Windows: the silent installer exits with code 2 when the folder already holds an install. Uninstall first (Settings > Apps), then install the new version. + So "update" on macOS and Windows means uninstall and install again; user data outside the install folder is not touched (the scripts only remove the install folder). +* `pre_uninstall.bat` is copied by the Windows installer to `\pre_uninstall.bat` and run by the uninstaller (constructor's `pre_uninstall` exists on Windows only). +* `pre_uninstall.sh` and `uninstall.sh` are plain `extra_files` copied to the prefix on Linux and macOS (constructor has no uninstall hook there). `post_install` fills the `BASE_PATH` token with the real prefix. + +## 2. What the migration changes + +In the **app repository**, in this order (each file independently): + +| File | Change | +|---|---| +| `app/bash_bat_scripts/post_install.sh` | the hook block (detect `_lc_tools`, `pip install` of Tools, `labconstrictor_tools register`) is inserted before the `include_path.py` line | +| `app/bash_bat_scripts/post_install.bat` | the same block for Windows; `SETLOCAL EnableExtensions` becomes `SETLOCAL EnableExtensions DisableDelayedExpansion` | +| `app/bash_bat_scripts/pre_uninstall.sh` / `.bat` | the `unregister` call (with a warning if a registry entry stays) is inserted before the `menuinst ... remove` line | +| `app/bash_bat_scripts/uninstall.sh` | only if it is exactly the 0.1.15 text: a failed `pre_uninstall` and a failed `rm -rf` are reported (exit 1 if the folder cannot be removed) | +| `.tools/docs/tools_bridge.md`, `.tools/docs/README.md` | the guide and its index entry | +| `.tools/schema/labconstrictor-app.schema.json`, `.tools/python/check_app_manifest.py`, `.tools/docs/app_manifest.md`, `.github/workflows/check_app_manifest.yml` | the App Centre manifest check, refreshed as template-managed files (byte copies, as in 0.1.15). The 0.1.15 schema copy was stale and rejected `inputs`, `outputs`, `limitations`, `status` and `distribution.platforms`; the copy is now the Site schema. The app's own `labconstrictor-app.yaml` is never touched | + +`construct.yaml` needs no change: `pre_uninstall.sh`, `uninstall.sh` and the post/pre scripts are already listed, and `bump_constructor.py` adds every file under `src/` (including `src/_lc_tools/`) at release time. The tool module itself (`src/_lc_tools/`) belongs to the app author and is not created by the migration. + +Rules: + +* **Idempotent.** A script that already mentions `labconstrictor_tools` is left unchanged; a second run changes nothing (tested). Apps that carried the hooks before (the `bridge-test` apps) are therefore not given the block twice (only their Tools source is pinned, see the next point). +* **Already-present hooks are pinned.** Apps whose hooks came from the `bridge-test` branch (NucleiSky pull request 32, VLab4Mic) have the Tools source `https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/heads/main.zip`. For such a script the migration does not insert the block again; it rewrites exactly that source to the form the template scripts use (a `LC_TOOLS_PIN` line, in `post_install.sh` before the `LC_TOOLS_MODULE=` line and in `post_install.bat` before the `LC_TOOLS_SPEC` line, and the `.../archive/refs/tags/.zip` URL; the tag is read from the template scripts) and logs `[migration 0.1.16] ...post_install.sh: updated: unpinned Tools source ... rewritten to the pinned tag ...`. Only that exact text is rewritten (the `${LC_TOOLS_SPEC:-}` default in the `.sh`, the `IF NOT DEFINED LC_TOOLS_SPEC SET` line in the `.bat`, exactly one occurrence of the URL). Anything else (a fork URL, another branch, another variable, two occurrences) is left unchanged and printed as `SKIPPED the pin`, with the manual step: replace `refs/heads/main.zip` by `refs/tags/.zip`. A second run changes nothing. Tested with the real lines of VLab4Mic and NucleiSky pull request 32 (`tests/fixtures/bridge_test_hooks/`). +* **Package name.** The package that carries `_lc_tools` is found, in order, from the single `src/_lc_tools`, the single package in `src/`, the name in `setup.py`, and finally the `[project]` name of `pyproject.toml` (hyphens become underscores; accepted only if `src//` exists). The last step is for apps such as NucleiSky: several packages in `src/` and a `setup.py` shim without a name. If none decides, the `post_install` hooks are not added (a message says so) and the rest is migrated. +* **Surgical.** The block is inserted before a known line, so the app's own edits stay. If the script is missing, was rewritten, or lacks the variables the block uses (`PYTHON_EXE`, `PROJECT_ROOT`, `LOG_FILE`, `BASE_PATH`), that file is **skipped with a message** (`SKIPPED: ...`) and the rest still runs. The migration never raises for such a file, so the sync pull request is still created. +* **No tools, no effect.** For an app without a `_lc_tools` module the hooks are inert: `post_install` finds no module and skips the step; `pre_uninstall` stays silent unless a registry entry exists. The migration says so in its log. +* **Never deletes.** It writes only the files in the table (no `.orig`, nothing removed); notebooks, `src/`, requirements, `construct.yaml` and `labconstrictor-app.yaml` are not touched. Line endings of each file are kept. +* **Logs.** Every step prints one line prefixed `[migration 0.1.16]` in the "Run template migrations" step of the workflow. +* **Version.** `template_version` goes to 0.1.16 (the template's rule: bump when users must act; a sync pull request is only opened when the version is higher). +* **Pinned to a tag.** The inserted block installs Tools from `.../archive/refs/tags/v0.2.0-rc.1.zip` (one variable, `LC_TOOLS_PIN`, at the start of the block in `post_install.sh` and `post_install.bat`), not from the moving `refs/heads/main.zip`; `LC_TOOLS_SPEC` still overrides it exactly as before. Amending the 0.1.16 migration for this was safe: when it was done no app repository had synced to 0.1.16 (NucleiSky, CellTracksColab and GuessTheCondition were at 0.1.15 with an open sync pull request to 0.1.15 and no 0.1.16 branch; VLab4Mic has no `.template_sync`). Moving the pin later is a one-string change, see `tools_bridge.md`. + +## 3. What cannot be migrated (honest answer) + +* **A copy that is already installed cannot be changed by a template version.** Its `post_install` already ran; the Linux/macOS `pre_uninstall.sh`/`uninstall.sh` and the Windows `pre_uninstall.bat` in the prefix are old files. They change only when a newer installer is run over the prefix (`-u` on Linux) or after an uninstall and a fresh install (macOS, Windows). There is no mechanism in the template, and none is added here, that edits files inside someone's prefix: it would need code that runs on the user's computer without the user installing anything. +* **An app only gets tools if a release contains `src/_lc_tools/`.** The tool module is a file of the installer (`extra_files`); an installed app whose installer did not ship it has nothing to register, whatever the scripts say. So "apps pick up the hooks when they update" means: the app owner merges the sync pull request **and publishes a new release**, and users install it. +* **Old installs keep uninstalling the old way.** Uninstalling an app installed from an old installer does not unregister anything (it never registered). That is harmless. The reverse case is the risk: an app registered by a new installer and then removed by deleting its folder by hand leaves an entry in `~/.labconstrictor/apps` (see `labconstrictor-tools doctor`). +* **Repositories that did not receive the sync** (no `LABCONSTRICTOR_SYNC_TOKEN`, workflow disabled, sync pull request not merged) stay on their version and do not get the hooks; they can copy the files by hand from `.tools/docs/tools_bridge.md`. +* **Customised scripts** are skipped (see above): those apps need the block added by hand. +* **Windows `.bat`.** The migration and the generated `.bat` text are tested in the template tests on the files only. Running them on Windows is verified only by the smoke workflow in LabConstrictor-Tools, not here. + +## 4. Test plan + +* Template tests (`tests/test_template_sync_0_1_16.py`): old scripts of 0.1.15 become byte-identical to the 0.1.16 template scripts rendered for the app; second run changes nothing; hooks already present are untouched except for the pin (real bridge-test texts of VLab4Mic and NucleiSky pull request 32, LF and CRLF, second run, customised sources skipped); the package name from `pyproject.toml` (NucleiSky-like tree); the docs index entry placement; CRLF/LF preserved; customised and missing files skipped without failing; user files untouched; the `sync.py` entry point; the migrated bash scripts run against a stub Python (register, failed registration, no tools module, uninstall unregisters and removes only the prefix, failed unregister only warns). +* LabConstrictor-Tools workflow `smoke_migration.yml`: an app at an old template version is built and installed, migrated by this branch with `sync.py`, a new installer is built and the install is updated to it (in place on Linux, uninstall then install on macOS and Windows), `labconstrictor-tools list` and `doctor` are checked, then the app is uninstalled, on Linux, macOS and Windows. diff --git a/.tools/docs/migration_0_1_17.md b/.tools/docs/migration_0_1_17.md new file mode 100644 index 0000000..1c43f69 --- /dev/null +++ b/.tools/docs/migration_0_1_17.md @@ -0,0 +1,38 @@ +# Template 0.1.17: install Tools before the package import check + +Design note for the 0.1.17 migration (`.template_sync/migrations/v0_1_16_to_v0_1_17.py`). It changes only the installer scripts `app/bash_bat_scripts/post_install.sh` and `post_install.bat` of an app repository. How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md) (a new installer is needed; nothing edits an existing install). + +## 1. The problem + +Template 0.1.16 ran `import ` (the check that the installed app package works) **before** the block that installs `labconstrictor-tools` and registers the app. An app package that imports `labconstrictor_tools` at module level therefore failed with `ModuleNotFoundError` and the installer aborted (Linux/macOS `exit 1`; Windows `ERROR: Installed ... package could not be imported`, exit code 2). Seen in a clean-sandbox test of the Playground 0.0.2 release; Playground fixed its own package with lazy imports. An app whose only importer is `_lc_tools` (NucleiSky) was never affected, because that module is not imported by the check. + +## 2. The change + +New order in `post_install` (both systems): + +1. install the app package (`pip install --no-deps --no-build-isolation`), +2. if the package ships `_lc_tools`: install `labconstrictor-tools` (the pinned tag, or `LC_TOOLS_SPEC`), +3. `import ` check (unchanged), +4. register the app with `labconstrictor_tools register` (unchanged, as before after the check). + +A failed Tools install is a `WARNING` in `menuinst_debug.log`, the registration is skipped, and the installation goes on. If the package itself needs Tools at import time, the import check then fails, which is the correct outcome. Apps without a `_lc_tools` module do not install Tools at all, as before. + +* `post_install.sh`: the pin (`LC_TOOLS_PIN`), `LC_TOOLS_MODULE` and the `pip install` move into a block between the package install and the import check, which sets `LC_TOOLS_READY=1` on success; the registration block keeps its place and registers only when `LC_TOOLS_READY` is 1. +* `post_install.bat`: the pin, `LC_TOOLS_SPEC` and the `pip install` (still through Python, so `cmd.exe` never re-parses the value) move into a subroutine `:install_lc_tools` at the end of the file, called with `CALL` before the import check. A subroutine is used because `%VAR%` inside a parenthesised block is expanded when the block is read, so a variable set in that block could not be used in it. The registration block keeps its place and registers only when `LC_TOOLS_READY` is 1. The file keeps CRLF line endings. + +## 3. What the migration does + +Surgical and idempotent, like the 0.1.16 migration. For each of the two scripts it recognises the 0.1.16 hook (the template text, an unpinned hand-integrated hook, or a hook with another Tools source) and only + +* inserts the Tools install block before the import check line, +* moves the lines that define the pin / module / spec out of the registration block into that block (a one-line comment stays behind), +* replaces the single `pip install` line of the registration block by the `LC_TOOLS_READY` check. + +The Tools source of the app (default URL or its own `LC_TOOLS_SPEC` default) is copied, not replaced. Not touched: any other line, the app's own customisations, files without the hook (the 0.1.16 migration adds the hook first when the chain runs both), scripts that do not match the known shape (printed as `SKIPPED` with the manual step), and line endings. A script that already contains `LC_TOOLS_READY` is left unchanged, so a second run changes nothing. Nothing is deleted. + +If the package name cannot be told, the scripts are still migrated from the names found in the hook itself (the tools module name is read from the existing hook), so no package detection is needed. + +## 4. What is not verified here + +* The Windows script is not run by the template tests (no `cmd.exe`); the end-to-end check is the smoke workflow of LabConstrictor-Tools (`smoke_migration.yml`) on a Windows runner. +* Installed copies are not changed: a new installer must be built and run. diff --git a/.tools/docs/migration_0_1_18.md b/.tools/docs/migration_0_1_18.md new file mode 100644 index 0000000..c67185d --- /dev/null +++ b/.tools/docs/migration_0_1_18.md @@ -0,0 +1,79 @@ +# Template 0.1.18: new Tools pin, pinned GitHub Actions, install rules + +Design note for the 0.1.18 migration (`.template_sync/migrations/v0_1_17_to_v0_1_18.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. What changes + +| Part | Change | +|---|---| +| Tools pin | `LC_TOOLS_PIN` in `app/bash_bat_scripts/post_install.sh` and `post_install.bat` moves from `v0.2.0-rc.1` to `v0.3.0-alpha.1`. | +| GitHub Actions | Every third-party `uses:` in the workflows is pinned by the commit SHA of the tag it named (the tag stays as a trailing comment). No version is upgraded. | +| Install guide | `.tools/docs/install.md` states three install rules (section 4). | +| Tools guide | `.tools/docs/tools_bridge.md` names the new pinned tag. | +| App hosts | The installer bundles the app's `labconstrictor-app.yaml` and `post_install` passes it to `labconstrictor-tools register --app-manifest`, so the `hosts:` line of the app decides which hosts list it (section 7). | +| Template CI | Only in the template repository itself: the workflow `.github/workflows/tests.yml` runs the template's tests, `black`, `ruff` and `mypy`. It does not run in apps (it checks `github.repository`) and is not delivered by the migration. | + +The pinned tag `v0.3.0-alpha.1` of LabConstrictor-Tools must exist before an installer built from this template is used: the installer downloads the archive of that tag. + +## 2. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. Each file gets one line in the output: `updated`, `unchanged` or `SKIPPED` with the reason. + +* **Pin.** In each of the two scripts the line `LC_TOOLS_PIN="v0.2.0-rc.1"` (`SET "LC_TOOLS_PIN=v0.2.0-rc.1"` in the `.bat`) is changed to the new tag **only if it still holds exactly the old template value**. An app with its own pin, an unpinned hook (the source is `refs/heads/main.zip` or its own `LC_TOOLS_SPEC`) or no hook stays as it is and a note says so. Only the value inside the quotes changes. +* **Workflows.** Five files: `check_app_manifest.yml`, `release_constructor.yml`, `sync_template.yml`, `update_on_notebook_change.yml`, `update_on_src_change.yaml`. A file is replaced by the pinned template file **only if it is still identical to the previous template version** (line endings are ignored when comparing). A file that is already the pinned template file is unchanged. A file that the app customised (or pinned in part) is skipped, and the message lists the third-party actions that are still pinned by tag only, so the maintainer can pin them by hand with the table in section 3. A workflow that is not in the repository is not created. +* **Install guide.** If `.tools/docs/install.md` exists, the sections "Before you install" and "Update an installed app" are inserted before `## Install on Windows` and before `## Next` (each only if its heading is missing); if an anchor line is missing the step is skipped with a message. +* **Tools guide.** `.tools/docs/tools_bridge.md` is rewritten only if it is still the 0.1.17 text. +* **App hosts.** See section 7. + +Changing files under `.github/workflows/` needs the synchronization token to have the `workflows=write` permission, as for every earlier workflow change ([template_synchronization.md](template_synchronization.md)). + +## 3. Pinned actions + +| Action | Tag | Commit SHA | +|---|---|---| +| actions/checkout | v4 | `11d5960a326750d5838078e36cf38b85af677262` | +| actions/setup-python | v4 | `7f4fc3e22c37d6ff65e88745f38bd3157c663f7c` | +| actions/upload-artifact | v7 | `cf430e030ddbb5b0abf93d22962f4752f3646cd9` | +| tj-actions/changed-files | v44 | `2d756ea4c53f7f6b397767d8723b3a10a9f35bf2` | +| conda-incubator/setup-miniconda | v3 | `fc2d68f6413eb2d87b895e92f8584b5b94a10167` | +| stefanzweifel/git-auto-commit-action | v5 | `b863ae1933cb653a53c021fe36dbb774e1fb9403` | +| softprops/action-gh-release | v2 | `3bb12739c298aeb8a4eeaf626c5b8d85266b0e65` | +| peter-evans/create-pull-request | v6 | `c5a7806660adbe173f04e3e038b0ccdcd758773c` | + +Mutable tags can be moved to other code (the March 2025 `tj-actions/changed-files` incident), and these workflows hold write tokens. The SHAs are the ones apps already carry after their own pinning pull requests (for example NucleiSky pull request 37). To move to a newer version, change the SHA and the tag comment together, in the live workflow and in the copy under `.template_sync/resources/` of the latest migration. + +## 4. The three install rules + +Stated in `.tools/docs/install.md` with this wording (a test checks that every doc that states them uses the same sentences): + +* The install path must contain no space: the installer refuses a path with a space. Use a path such as `C:\LabConstrictor\` on Windows or `~/labconstrictor/` on macOS and Linux. +* On macOS and Windows, update an app by uninstalling the old version first and then installing the new one: the installer does not install over an existing install. +* On Linux, running the installer with `-u` updates in place only if the previous install finished; otherwise delete `/pkgs` or uninstall the app and install it again. + +## 5. Template tests in CI + +`.github/workflows/tests.yml` runs on every pull request and on every push to `main`, with read-only permissions: all `tests/test_*.py`, then `black --check`, `ruff check` and `mypy` on `.template_sync`, `.tools/python` and `tests`. The linters are configured in `pyproject.toml` to the state of the code at 0.1.18 (no behaviour change was made to satisfy them); tighten the configuration when code is cleaned up. + +## 6. What is not verified here + +* Installed copies are not changed: a new installer must be built and run. +* The Windows script is not run by the template tests; the end-to-end check is `smoke_migration.yml` of LabConstrictor-Tools on a Windows runner. + +## 7. App hosts: the installer passes the `hosts:` line to Tools + +Problem found by the Tools readiness check: Tools lists an app in a host (Napari, Fiji, QuPath) only for the hosts its registry entry names, but the installer never told Tools. `labconstrictor-app.yaml` was not in the installer and `post_install` called `register` without `--app-manifest`, so every registered app had no `hosts` and every host listed it. + +What the template does now: + +* **Bundle.** `bump_constructor.py` adds `labconstrictor-app.yaml: /labconstrictor-app.yaml` to `extra_files` in `construct.yaml` when the file exists in the repository (a mapping to a missing file would fail the installer build, so it is not added otherwise; an existing mapping whose file is gone is reported, not removed). +* **Register.** In `post_install.sh` / `.bat` the Tools hook passes `--app-manifest /labconstrictor-app.yaml` to `register`. If the file is not in the installation, the app is registered without hosts and `menuinst_debug.log` says so with the sentence Tools uses: `'' declares no hosts, so it is listed in every host; register it with --app-manifest (or --hosts) to choose`. A manifest that is there but has no `hosts:` line is read by Tools, which registers the app without hosts and prints the same sentence (it reaches the same log); the hook does not parse the file itself. There is no silent fallback; a manifest with an invalid `hosts:` line makes `register` refuse (Tools exit code 2), which the hook logs as `WARNING: tool registration failed`. + +What the migration does in an app repository (same rules as above: surgical, idempotent, never deletes, never raises, line endings kept): + +* `construct.yaml`: adds the `extra_files` entry **only if** the repository has a `labconstrictor-app.yaml` and the entry is not there yet, with the project folder read from the `Welcome.ipynb` entry. No manifest: `SKIPPED` with the instruction (add the file, then the entry). An `extra_files` that is not a block list, or no readable project folder: `SKIPPED`. +* `post_install.sh` / `.bat`: inserts the manifest lookup and the log lines in the Tools hook and adds the argument to the app's own `register` line (the app's own arguments stay). A hook that already has `--app-manifest` or `--hosts` is unchanged. A hook of another shape (no `lc_note` before the register line in the `.sh`; a register line that is not `IF NOT ERRORLEVEL 1 ... >> LOG 2>&1` in the `.bat`) is `SKIPPED` and nothing is written. +* `bump_constructor.py` of an app is not touched: the entry the migration writes into `construct.yaml` survives it. An app that adds its manifest later adds the mapping by hand (or takes the new `bump_constructor.py` of the template). + +Adopting it, per app: have a `labconstrictor-app.yaml` with a `hosts:` line at the repository root, take this template version (the synchronization pull request), build and release a new installer. Installed copies do not change: reinstall. + +The template CI runs the live `post_install` in a fake prefix on Linux, macOS and Windows (`tests/smoke/post_install_hosts.py`) with the real `labconstrictor-tools` and checks that the registry entry's `hosts` equals the `hosts:` line of each real manifest in `tests/fixtures/manifests`. The job installs Tools through `post_install` from the pinned tag `v0.3.0-alpha.1` (`LC_TOOLS_PIN`), so it also tests that URL: if the tag does not install, the job fails. diff --git a/.tools/docs/migration_0_1_19.md b/.tools/docs/migration_0_1_19.md new file mode 100644 index 0000000..6d11645 --- /dev/null +++ b/.tools/docs/migration_0_1_19.md @@ -0,0 +1,29 @@ +# Template 0.1.19: src_change.yaml in every installer, Python series in setup.py + +Design note for the 0.1.19 migration (`.template_sync/migrations/v0_1_18_to_v0_1_19.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. What changes + +| Part | Problem | Change | +|---|---|---| +| `.tools/python/bump_constructor.py` | `ensure_extra_files` removed the `.tools/meta/src_change.yaml` mapping from `extra_files` and then re-added it only if it was not in `existing_sources`, a list made before the removal. An app whose `construct.yaml` had the mapping lost it at the next release, and got it back at the one after: every other installer had no `src_change.yaml`, so the Welcome notebook of that release could not offer source-code updates. Found in CellTracksColab 1.1.4. | The mapping is always re-added after the removal. | +| `.tools/python/merge_requirements.py` | It wrote the exact Python release of the installer into `setup.py` (`python_requires=">=3.12.13"`). A source install (`pip install -e .`) then failed on any earlier patch release of the same series, for example the Python 3.12.3 of Ubuntu 24.04: `current Python version (3.12.3) does not satisfy Python>=3.12.13`. | It writes the series (`python_requires=">=3.12"`). `environment.yaml` keeps the exact pin used by the installer. | +| `setup.py` of an app | Holds the exact release written by the old script. | Changed to the series by the migration (only that exact shape). | + +The installers are not affected by the `setup.py` change: they bundle their own Python, which already satisfied the old requirement. + +## 2. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. Each file gets one line in the output: `updated`, `unchanged` or `SKIPPED` with the reason. + +* **`bump_constructor.py` and `merge_requirements.py`.** The known 0.1.18 block is replaced by the 0.1.19 block. A file that already has the 0.1.19 block is `unchanged` (CellTracksColab took both fixes before this version, in its pull requests 66 and 67). A file where the 0.1.18 block is not found once (customised) is `SKIPPED`; apply the change of section 1 by hand. +* **`setup.py`.** A `python_requires=">=X.Y.Z"` (single or double quotes) becomes `">=X.Y"`. The template placeholder `">=PYTHON_VERSION"`, a series that is already there, or any other specifier (for example `~=3.12.1`) is `unchanged`. Two or more `python_requires` lines: `SKIPPED`. +* A file that is not in the repository is not created. + +## 3. Adopting it + +Take this template version (the synchronization pull request), then build and release a new installer: the release workflow runs the new `bump_constructor.py`, which puts `src_change.yaml` back into `construct.yaml` and into the installer. Installed copies do not change: reinstall. + +## 4. What is not verified here + +* The installer build itself is not run by the template tests. The tests run the new `bump_constructor.py` three times on a small app (`src_change.yaml` stays mapped every time; the 0.1.18 script drops and restores it) and `merge_requirements.py` on a small app (it writes `>=3.12` and keeps `python=3.12.13` in `environment.yaml`). diff --git a/.tools/docs/migration_0_1_20.md b/.tools/docs/migration_0_1_20.md new file mode 100644 index 0000000..3560756 --- /dev/null +++ b/.tools/docs/migration_0_1_20.md @@ -0,0 +1,49 @@ +# Template 0.1.20: lock files, no lost workflow pushes, a launcher that starts fresh + +Design note for the 0.1.20 migration (`.template_sync/migrations/v0_1_19_to_v0_1_20.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. What changes + +| Part | Problem | Change | +|---|---|---| +| `update_on_notebook_change.yml`, `update_on_src_change.yaml` | One push that changes both `src/` and `notebooks/` starts both workflows. They shared one concurrency group, so they ran one after the other, but each checks out the commit that triggered it: the second one committed on top of an old `main` and its push was rejected (`non-fast-forward`). Seen in CellMigrationLab/LabChronicle runs 41727822989 (notebook workflow) and 41800906840 (src workflow). The notebook workflow then ran "Revert user commit that broke requirements" (its condition was any failure), created a revert of the user's merge commit, and was stopped only because that push was rejected too. | The commit step commits, and when the push is rejected it rebases onto the latest branch (`git rebase --autostash`) and pushes again (5 attempts). The revert runs only when the conda test failed, on top of the latest branch, with `-m 1` only for a merge commit. Each workflow has its own concurrency group (a group keeps only one waiting run, so a third push cancelled the waiting run of the other workflow). The checkout stays on the triggering commit, because `update_changelog.py` and `update_version_last_commit.py` compare it with its parent. `stefanzweifel/git-auto-commit-action` is no longer used. | +| Requirements (`requirements*.txt`) | The installer ran `pip install -r requirements.txt`: the notebooks' packages are pinned, the packages they depend on are not, so two installations of one release could get different versions. | `.tools/python/lock_requirements.py` (run by the notebook workflow after the merge) writes `requirements*.lock.txt` next to each requirements file with `uv pip compile --universal`: every package with its exact version, for Windows, macOS and Linux. `post_install.sh` / `.bat` install the lock file when the installer bundles one (`bump_constructor.py` bundles it), and the conda test of the workflow installs it too, then runs `pip check` (a warning only). | +| `launch_jupyter.py` | When JupyterLab stopped, the terminal window closed at once (macOS, Linux) or stayed open with a prompt (Windows). Every app shares `~/.jupyter/lab/workspaces` and opens JupyterLab in the home folder, so a new session restored the notebooks of other apps (a NucleiSky notebook in a LabChronicle session). | The launcher asks to press Enter when JupyterLab stops (also after an error; not for `--self-test`, `--print-ca-bundle` or `--no-wait`). JupyterLab gets a new, empty workspace folder at every launch, removed when it stops: only the Welcome notebook opens. Settings and themes are kept (they are not in the workspaces). | +| `notebook_launcher.json` | On Windows, menuinst runs the shortcut with `cmd /K`, which keeps the window open after the command. | The Windows command ends with `& exit`, so the window closes after Enter. | +| `notebook_usage.md` | Said to stop JupyterLab with `Ctrl+C`. | Names **File > Shut Down** first, and the Enter prompt. | + +### How a lock file is made + +* One lock file per requirements file: `requirements.lock.txt`, `requirements_gpu.lock.txt`, `requirements-windows.lock.txt`, ... A package that only one platform needs carries an environment marker (`colorama==0.4.6 ; sys_platform == 'win32'`). +* `--python-version` is the Python of `environment.yaml`. uv reads it as the lowest Python, so a few packages can appear twice with a `python_full_version` marker; pip installs the line that matches the installer's Python. +* The conda packages of `environment.yaml` (`jupyterlab`, `pip`, `setuptools`, `certifi`, ...) are installed by the installer itself: they are not written to the lock file (their dependencies are), and a conda pin such as `jupyterlab=4.4.0` constrains the resolution. +* The per-OS files are resolved with `requirements.lock.txt` as constraints, so a package both files need gets one version. The GPU file is resolved on its own (its PyTorch comes from the CUDA index, whose `--extra-index-url` line is copied to the lock file). +* Versions only, no hashes. +* The header holds a fingerprint of the inputs (the requirement lines, the Python and JupyterLab versions, the lock format). The file is written again only when one of them changes, so a release without new requirements installs the same versions as the previous one. To move every package to its newest version, delete the lock files and run **Updates on notebook change** by hand. +* If a file cannot be locked (no solution, uv missing), the step prints a GitHub warning, removes the out-of-date lock file and goes on: the installer installs the plain requirements file. `bump_constructor.py` removes the mapping of a lock file that is gone, so the installer build does not fail on it. + +## 2. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. Each file gets one line in the output: `updated`, `unchanged` or `SKIPPED` with the reason. + +* **The two workflows, `test_conda_environment.sh`, `launch_jupyter.py`.** Replaced by the 0.1.20 file only when the app's file is still the 0.1.19 template file (rendered with the app's name; line endings ignored). A customised file is `SKIPPED`: apply the change of section 1 by hand. +* **`lock_requirements.py`.** Created (it is new). An app that has its own file keeps it (`SKIPPED`). +* **`.tools/requirements.txt`.** `uv==0.13.3` is added, unless the file already names `uv`. +* **`post_install.sh` / `.bat`.** The known install lines are replaced by the lines that pick the lock file. If one of them is not found exactly once, the file is `SKIPPED`. +* **`bump_constructor.py`.** `ensure_lock_files_in_extra_files` is inserted before `def ensure_extra_files(` and called after `ensure_requirements_in_extra_files(data)`. Both lines must be found once (LabChronicle's own script qualifies). +* **`notebook_launcher.json`.** The Windows command is added (the shared command plus `"&", "exit"`) when the file has the template shape and formatting; a file with its own Windows command is `SKIPPED`. +* **`notebook_usage.md`.** The sentence on stopping JupyterLab is replaced when it is the 0.1.19 text. +* A file that is not in the repository is not created (except `lock_requirements.py`, when `.tools/python` exists). + +## 3. Adopting it + +1. Merge the synchronization pull request. +2. Run **Actions > Updates on notebook change > Run workflow** once: it writes the lock files (the next push of a `requirements.yaml` would too). Check that the run is green and committed `requirements*.lock.txt`. +3. Build and release a new installer: it bundles the lock files and the new launcher. Installed copies do not change: reinstall. + +## 4. Limitations and what is not verified here + +* **macOS terminal.** After Enter, Terminal.app closes the window only if its profile says so (*Settings > Profiles > Shell > When the shell exits*); otherwise it shows `[Process completed]`. Not tested on a Mac yet. +* **Windows and `Ctrl+C`.** Stopping JupyterLab with `Ctrl+C` makes `cmd` ask `Terminate batch job (Y/N)?` after Enter: `N` closes the window, `Y` leaves it open. **File > Shut Down** avoids the question. +* **The lock covers pip only.** Constructor already fixes the conda packages when the installer is built. +* **Tested here:** the commit and revert steps of the workflows run with bash and git against a local origin that moved during the run (a rebased push, a conflict that pushes nothing, the revert of a merge and of a plain commit); `lock_requirements.py` with a fake uv (fingerprint, constraints, index lines, failures); `bump_constructor.py`; the launcher's workspace folder and Enter prompt; the migration on a 0.1.19 app and on customised files. `uv pip compile --universal` itself was tried by hand on LabChronicle's requirements (CPU, GPU with the CUDA index, Windows file). Not tested: a real GitHub Actions run, an installer build, and a launch on Windows, macOS and Linux. diff --git a/.tools/docs/migration_0_1_21.md b/.tools/docs/migration_0_1_21.md new file mode 100644 index 0000000..f6e6f01 --- /dev/null +++ b/.tools/docs/migration_0_1_21.md @@ -0,0 +1,36 @@ +# Template 0.1.21: no administrator prompt when uninstalling on Windows + +Design note for the 0.1.21 migration (`.template_sync/migrations/v0_1_20_to_v0_1_21.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. The problem + +On Windows, uninstalling any app made with template 0.1.20 or earlier shows a User Account Control prompt for `python.exe` from an unknown publisher. The command line is `"\python.exe" -m conda.core.initialize "\tmp\tmpโ€ฆ.json"`. Whether the user answers **Yes** or **No**, the step fails and a "Failed to clean AutoRun" error with Abort, Retry and Ignore follows; **Retry** shows the prompt again. With **Ignore** the app is removed and nothing outside the app folder is changed. **Abort**, the default button, stops the uninstall halfway and leaves the app folder on disk. Found in round alpha.4 (LabConstrictor-Tools issue 141, row WIN-15) with Playground, GuessTheCondition, NucleiSky and VLab4Mic. + +Why it happens: + +1. Constructor's NSIS installer installs the packages with its bundled `_conda.exe` (conda-standalone) and sets `CONDA_SAFETY_CHECKS=disabled`. Before conda 26.9.3, disabled safety checks skip the step that fills `paths_data` in each package record (`conda-meta/*.json`): every package without prefix placeholders gets `"paths": []`, `conda-launchers` included. Our installers were built with conda-standalone 26.5.2. +2. The app environment includes `conda` (26.9.3 in the alpha.4 installers). Since 26.9.0, conda finds the Windows launcher stub (`share/conda-launchers/cli-64.exe`) through the `paths_data` of `conda-launchers`. With an empty list it raises `FileNotFoundError`, although the file is on disk. +3. Because the environment has `conda`, the uninstaller runs `condabin\conda.bat init cmd.exe --reverse --user`, even with `initialize_conda: false`. `conda init` treats any `OSError` as a permission problem (`needs sudo โ€ฆ\Scripts\conda.exe`) and reruns itself as administrator. As administrator the file is still not found, so the prompt never helps. + +Upstream: [conda/conda#16856](https://github.com/conda/conda/issues/16856), fixed by [conda/conda#16855](https://github.com/conda/conda/pull/16855) in conda 26.9.3. Miniforge hit the same bug ([conda-forge/miniforge#913](https://github.com/conda-forge/miniforge/issues/913)); the fix there is to build with conda-standalone 26.9.3 or later. + +## 2. What changes + +| Part | Change | +|---|---| +| `.tools/bash/create_constructor_environment.sh` | The constructor environment is created with `"conda-standalone>=26.9.3"`. Constructor itself only requires `conda-standalone >=24.11.0`, so without the pin the solver may pick an older one. The installer's `_conda.exe` then writes complete `paths_data`, and `conda init --reverse` finds the launcher. | + +## 3. What the migration does + +* The known 0.1.20 `conda create` line is replaced by the pinned line and a comment. The line endings of the file are kept. +* A file that already has the 0.1.21 line is `unchanged`. A file that names `conda-standalone` in another way, or where the 0.1.20 line is not found once (customised), is `SKIPPED`: add `"conda-standalone>=26.9.3"` to its `conda create` by hand. +* A file that is not in the repository is not created. + +## 4. Adopting it + +Take this template version (the synchronization pull request), then build and release a new installer. Installed copies do not change: an app installed with an older installer keeps the prompt when it is uninstalled. Answering **No** and then **Ignore** is safe; see [Troubleshooting an installed app](troubleshooting_installed_app.md). + +## 5. What is not verified here + +* The installer build and uninstall are not run by the template tests. They check the migration on the 0.1.20 script, with LF and CRLF line endings, for an app that already has the pin and for a customised file, and that the migrated script is valid shell. +* That a build with conda-standalone 26.9.3 or later writes complete `paths_data` comes from the upstream fix and the Miniforge report. It has not yet been checked on a LabConstrictor installer: after the next Windows build, `conda-meta\conda-launchers-*.json` should list six paths, and the uninstall should show no prompt. diff --git a/.tools/docs/migration_0_1_22.md b/.tools/docs/migration_0_1_22.md new file mode 100644 index 0000000..94643fb --- /dev/null +++ b/.tools/docs/migration_0_1_22.md @@ -0,0 +1,68 @@ +# Template 0.1.22: TensorFlow apps install on Windows computers with an NVIDIA GPU + +Design note for the 0.1.22 migration (`.template_sync/migrations/v0_1_21_to_v0_1_22.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. The problems + +### 1.1 Windows + NVIDIA GPU: the installation of a TensorFlow app fails + +`post_install.bat` installs `requirements_gpu.txt` (its lock file) when it finds `nvidia-smi`. `merge_requirements.py` wrote that file by rewriting `tensorflow` to `tensorflow[and-cuda]` for every system. + +* TensorFlow's `and-cuda` extra lists `nvidia-*` packages with **no platform marker**. +* Some of them exist only as Linux wheels: `nvidia-nccl-cu12` has never had a Windows or macOS wheel, and the newest `nvidia-cublas-cu12` (12.9.3.13) is Linux-only. +* `lock_requirements.py` locks with `uv pip compile --universal`, which pins them for every system. +* On Windows, `pip install -r requirements_gpu.lock.txt` then stops with `No matching distribution found for nvidia-...`, and the installer ends with "Application requirements installation failed". + +TensorFlow has had no native Windows GPU build since 2.10, so `[and-cuda]` never helped on Windows anyway. macOS was not affected: `post_install.sh` always installs the CPU file there. + +Found while planning a StarDist 2D (TensorFlow 2.20) app. Reproduced with uv 0.13 for `x86_64-pc-windows-msvc`: + +| Lock file | Result | +|---|---| +| 0.1.21 GPU lock | `No solution found` | +| 0.1.22 GPU lock | installs (106 packages, no `nvidia-*`) | + +On Linux the 0.1.22 lock still installs `tensorflow` with the CUDA packages (119 packages). + +### 1.2 The version cell always says "not listed" on Colab + +The snippet in [notebook_upload.md](notebook_upload.md) did `config.get(notebook_name, "")` on `notebooks/notebook_latest_versions.yaml`. `sync_notebook_versions.py` writes that file grouped by folder (`"": {"": ""}`), so the lookup always returned `""`. + +## 2. What changes + +| Part | Change | +|---|---| +| `.tools/python/merge_requirements.py` | In the GPU file, each `tensorflow` line becomes two lines: `tensorflow[and-cuda]==X ; sys_platform == "linux"` and `tensorflow==X ; sys_platform != "linux"`. A line's own marker is kept and combined with `and`. uv then marks every `nvidia-*` package `sys_platform == 'linux'`. | +| `.tools/docs/notebook_upload.md` | The version cell looks the notebook up inside its folder group. | +| `.tools/docs/notebook_requirements.md` | One paragraph on what the GPU file does for TensorFlow. | + +## 3. What the migration does + +* **merge_requirements.py:** + * The new function is inserted before the known 0.1.21 `build_gpu_lines`. + * The tensorflow branch of `build_gpu_lines` is replaced. + * The module docstring sentence is updated when it is still the 0.1.21 text. + * The two code changes are made together or not at all. + * A file that already has `tensorflow_gpu_lines` is `unchanged`. + * A customised file is `SKIPPED`; apply section 2 by hand. +* **notebook_upload.md:** the one known lookup line is replaced; a customised file is `SKIPPED`. +* **Missing files** are not created. Line endings are kept. +* **Notebooks are not edited.** A notebook that already contains the old snippet keeps it. Replace the line `latest_version = config.get(notebook_name, "")` in its version cell with the two lines from [notebook_upload.md](notebook_upload.md). + +## 4. Adopting it + +1. Take this template version (the synchronization pull request). +2. Regenerate the GPU lock: push a notebook change, or run **Actions > Updates on notebook change > Run workflow**. +3. Build and release a new installer. + +An installer made with an older template still fails on Windows computers with an NVIDIA GPU. A workaround for those users: rename or hide `nvidia-smi.exe` during the installation, so that the CPU file is used. + +## 5. What is not verified here + +* The template tests check: + * the new GPU lines; + * the migration on the 0.1.21 files (LF and CRLF); + * idempotence; + * customised files; + * the chain from older versions. +* The lock results above come from uv's resolver for each platform (`uv pip install --dry-run --python-platform ...`), not from an installer run on a Windows computer with an NVIDIA GPU. diff --git a/.tools/docs/migration_0_1_23.md b/.tools/docs/migration_0_1_23.md new file mode 100644 index 0000000..fdf2c7e --- /dev/null +++ b/.tools/docs/migration_0_1_23.md @@ -0,0 +1,46 @@ +# Template 0.1.23: no template placeholder in the installer + +Design note for the 0.1.23 migration (`.template_sync/migrations/v0_1_22_to_v0_1_23.py`), issue [#40](https://github.com/CellMigrationLab/LabConstrictor/issues/40). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. The problem + +The template's files hold placeholders (`PROJECT_NAME`, `PYTHON_PROJ_NAME`, ...) that the repository initialisation, the [LabConstrictor form](https://labconstrictor-form.streamlit.app) (`CellMigrationLab/LabConstrictor_streamlit`), replaces with the app's names. It replaces each placeholder only in the files it lists for it, and three files were missing from those lists: + +| File | Placeholder left | Effect | +|---|---|---| +| `app/bash_bat_scripts/post_install.sh` and `.bat` | `PYTHON_PROJ_NAME` (since template 0.1.16) | An app with Python code in `src/` cannot be installed: the last step runs `import PYTHON_PROJ_NAME` and fails with `No module named 'PYTHON_PROJ_NAME'`. Found with StarDist2D 1.0.0. | +| `app/python_scripts/launch_jupyter.py` | `PROJECT_NAME` | The launcher's error messages say "PROJECT_NAME could not start". | +| `.tools/templates/Welcome_template.ipynb` | `PROJECT_NAME` | The Welcome notebook says "Welcome to PROJECT_NAME!" (LabConstrictor Playground). | + +Apps that reached 0.1.16 through the migrations are not affected by the first row: the 0.1.16 migration wrote the package name. Nothing caught it, because the workflows never install the installers they build. + +## 2. What changes + +| Part | Change | +|---|---| +| The form (`LabConstrictor_streamlit`) | The three files are added to its placeholder lists (`placeholders.py`), and the form refuses to open its pull request when a placeholder is left in a file the installer ships. Its tests initialise a clone of the template's `main` (in its CI, also every week), so a placeholder added to the template later is caught too. | +| `.tools/python/check_placeholders.py` (new) | Fails when an initialisation placeholder is left in a file the installer ships (`app/**`, `construct.yaml`, `setup.py`, `environment.yaml`), and names the file, the line and the fix. It also refuses the raw, uninitialised template. Placeholders filled in later on purpose are not checked: `BASE_PATH_KEYWORD` (at install), `PYTHON_VERSION` and `JUPYTERLAB_VERSION` (by the requirements workflow). | +| `.github/workflows/release_constructor.yml` | Runs the check in both jobs, right after `bump_Welcome_notebook.py`: before the version commit and before any installer is built. | + +The check fails the release rather than fixing the files itself: the maintainer sees what was wrong, fixes the repository once, and publishes the release again. + +## 3. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. + +* **Placeholders.** In `post_install.sh`, `post_install.bat`, `launch_jupyter.py` and `Welcome_template.ipynb`, a placeholder that is still there is replaced: `PYTHON_PROJ_NAME` with the app's Python package, `PROJECT_NAME` with the app name. A file without placeholders is `unchanged`. + * The package is found as in the 0.1.16 migration: the single `_lc_tools` module in `src/`, else the single package in `src/`, else the name in `setup.py`, else the `[project]` name of `pyproject.toml`. When none is found, the file is `SKIPPED`: replace the placeholder by hand. + * The app name is the `menu_name` of `app/menuinst/notebook_launcher.json`, which the form wrote, else `PROJECT_DISPLAY_NAME` in `launch_jupyter.py`. +* **The check.** `.tools/python/check_placeholders.py` is created. A repository with its own file of that name keeps it (`SKIPPED`). +* **The workflow.** The check is added after the `bump_Welcome_notebook.py` command in each job of `release_constructor.yml`. A workflow without that command (customised) is `SKIPPED`: add the five lines by hand (see the template's file). +* An uninitialised repository (`construct.yaml` still names `UNDERSCORED_PROJECT_NAME`) is not touched. + +## 4. Adopting it + +Take this template version (the synchronization pull request) and release a new installer. If the release stops at "check_placeholders.py", its log lists each file and line: replace the placeholder there, commit, and publish the release again. Installed copies do not change: reinstall. + +## 5. What is checked here, and what is not + +* Tests (`tests/test_template_sync_0_1_23.py`): the check on clean and broken apps; the migration on a broken 0.1.22 app (then the check passes and a second run changes nothing), on a healthy app, with CRLF, an unknown package, a customised workflow and the raw template; the sync chain from 0.1.22; the live workflow equals the 0.1.22 workflow migrated. +* The check was run after the release scripts (`bump_version.py`, `bump_constructor.py`, `bump_Welcome_notebook.py`) on copies of NucleiSky, LabConstrictor Playground, Guess the Condition, LabConstrictor_Demo, LabChronicle, CellTracksColab, StarDist2D, CellPatcher and VLab4Mic. It passes for all of them except the Playground, whose Welcome notebook really says "Welcome to PROJECT_NAME!": the migration repairs it. +* The installers themselves are not built or installed by these tests. diff --git a/.tools/docs/migration_0_1_24.md b/.tools/docs/migration_0_1_24.md new file mode 100644 index 0000000..0bd70d7 --- /dev/null +++ b/.tools/docs/migration_0_1_24.md @@ -0,0 +1,43 @@ +# Template 0.1.24: download links for "v" tags, installers only for the supported systems, the app's own Jupyter kernel + +Design note for the 0.1.24 migration (`.template_sync/migrations/v0_1_23_to_v0_1_24.py`), issues [#41](https://github.com/CellMigrationLab/LabConstrictor/issues/41), [#42](https://github.com/CellMigrationLab/LabConstrictor/issues/42) and [#43](https://github.com/CellMigrationLab/LabConstrictor/issues/43). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. The problems + +| Issue | What happened | Seen in | +|---|---|---| +| #41 | A release tagged `v1.0.0` wrote download links to `/releases/download/1.0.0/...`. The release workflow strips the `v` for the version, and `bump_version.py` used that version for the folder of the link too. The real folder is the tag, `v1.0.0`, so every button of the download page returned 404. | StarDist2D 1.0.0 | +| #42 | Every release built the four installers (Windows, Linux, Macs with Apple silicon and with Intel), also for a system the app cannot run on. TensorFlow 2.17 and later has no wheels for Intel Macs, so that installer failed at its last step. The release page and the download page still offered it. | StarDist2D 1.0.0 | +| #43 | Jupyter looks for kernels in the user's folder before the app's own folder. On a computer where someone once ran `python -m ipykernel install --user`, the user's "python3" kernel won, the notebook ran in that other Python, and its first import of the app failed with `No module named ''`. For the app's prefix, a constructor base environment, jupyter_core (5.x) does not prefer the environment by itself. | StarDist2D 1.0.0 on Linux | + +## 2. What changes + +| Part | Change | +|---|---| +| `.github/workflows/release_constructor.yml` | Both "Determine release version" steps also export the tag as typed, `RELEASE_TAG`. A new `platforms` job runs `release_platforms.py`, and the build job takes its matrix from it (`fromJSON(needs.platforms.outputs.matrix)`). | +| `.tools/python/release_platforms.py` (new) | Reads `distribution.platforms` of `labconstrictor-app.yaml` and writes the build matrix: only the systems listed, all four without the key (or without the file), as before. It fails, with the reason, when the file is not valid YAML, when `platforms` is not a list, or when it lists none of the four (`windows-arm64` and `linux-arm64` have no build). | +| `.tools/python/bump_version.py` | The download links point to the tag (`--tag`, default `$RELEASE_TAG`, else the version); the installer names keep the bare version. It refuses a tag that is neither the version nor `v` + the version. A system that is not built gets a note on the download page instead of its button. A later release also finds links written for a `v` tag. | +| `app/python_scripts/launch_jupyter.py` | `run_jupyter()` sets `JUPYTER_PREFER_ENV_PATH=1` before JupyterLab is imported: the app's own kernel (and configuration) comes before the user's. It is set, not defaulted, so a user's `JUPYTER_PREFER_ENV_PATH=0` cannot bring the problem back. JupyterLab settings and themes are not affected: they are not on these paths. | + +`bump_version.py` reads the tag from the environment, so it and the workflow do not depend on each other: an app whose `bump_version.py` is customised and was left unchanged keeps working, with the old links. + +## 3. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. + +* **`release_platforms.py`** is created. A repository with its own file of that name keeps it (`SKIPPED`). +* **`bump_version.py`:** seven known blocks are changed (the import of `os`, `replace_version_placeholder` and two new functions, the download-page function, the `--tag` option and its check, the call). When one of them is not found exactly once, the file is customised and is left as it is (`SKIPPED`); apply the change by hand from the template's file. A change elsewhere in the file (CellPatcher refuses pre-release versions in `main()`) does not stop it. +* **`release_constructor.yml`**, two independent parts: + * the `RELEASE_TAG` line before each `RAW="${RAW#v}"` line; + * the `platforms` job and the matrix, only when the build job's matrix is exactly the template's four builds. A matrix changed by hand (the LabConstrictor Playground removed the Intel Mac build) is left as it is (`SKIPPED`). To move to `distribution.platforms`, list the systems in `labconstrictor-app.yaml` and copy the `platforms` job and the `matrix:` line from the template's workflow. +* **`launch_jupyter.py`:** the variable goes before the comment and the import of `jupyterlab.labapp` in `run_jupyter()`; without them, `SKIPPED`. + +## 4. Adopting it + +Take this template version (the synchronization pull request). If your app cannot run on a system, leave that system out of `distribution.platforms` in `labconstrictor-app.yaml` (see [App Centre manifest](app_manifest.md)); the App Centre already uses the same list. Then release a new installer: users get the kernel fix by installing it. A release whose `platforms` job fails is described in [Troubleshooting](troubleshooting.md). + +## 5. What is checked here, and what is not + +* Tests (`tests/test_template_sync_0_1_24.py`): the download links for `v1.2.3` and `1.2.3` tags, the tag check, the notes for systems that are not built; the matrix with and without `distribution.platforms` and the failures; the launcher sets the variable before it imports JupyterLab, also over a user's `0`; the migration on 0.1.23 files (the result is the live template file, a second run changes nothing), with CRLF, a customised `bump_version.py` (also CellPatcher's), a customised matrix and missing files; the sync chain from 0.1.23. +* jupyter_core's own handling of `JUPYTER_PREFER_ENV_PATH` was checked by hand by the issue's author on the StarDist2D Linux install, not by these tests. +* A release with the new workflow has not run yet: the `platforms` job and `fromJSON` matrix are checked only by reading them. diff --git a/.tools/docs/migration_0_1_25.md b/.tools/docs/migration_0_1_25.md new file mode 100644 index 0000000..1759245 --- /dev/null +++ b/.tools/docs/migration_0_1_25.md @@ -0,0 +1,60 @@ +# Template 0.1.25: publish the app's Python code on PyPI at each release (opt-in) + +Design note for the 0.1.25 migration (`.template_sync/migrations/v0_1_24_to_v0_1_25.py`). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md); this one changes no installed app: it only adds a release step that a developer turns on. + +## 1. The problem + +An app's own Python code (`src/`) was installed into the app and could be imported by its notebooks, but nothing in the template published it on PyPI: only NucleiSky did, with a workflow of its own. The package itself was not ready for PyPI either: + +| Part | What was wrong | +|---|---| +| `setup.py` | `install_requires=[]`: the dependencies lived in `requirements.txt` (and its lock file) only. No description (README). | +| `bump_version.py` | It never wrote the release version into `setup.py`, which kept the version of the initialisation (`0.0.1`). | +| The release | The tag points to the commit *before* the "Update version" commit of the release workflow, so a job that builds from the tag cannot trust the committed version. | + +## 2. Design (chosen 2026-11-12) + +| Question | Choice | Why | +|---|---|---| +| On or off | A new workflow in every app, **off by default**: both jobs have `if: vars.PYPI_PUBLISH == 'true' \|\| vars.PYPI_PUBLISH == 'testpypi'`. | An app that does not use it sees skipped jobs, never a failure. A repository *variable* is the switch because a secret cannot be read in a job's `if:`. | +| When | A published GitHub release, the moment the installers are built. | One version for the installers and for PyPI. | +| Version | The tag without the `v`, as `release_constructor.yml` does. `pypi_package.py` writes it into `setup.py` of the checkout (not committed). | The tagged commit has the previous version. | +| Authentication | PyPI trusted publishing (OIDC): `permissions: id-token: write`, GitHub environment `pypi`, `pypa/gh-action-pypi-publish` pinned by SHA. No secret, no API-token fallback. | Recommended by PyPI. A project-scoped token needs the project to exist already; a pending publisher creates it at the first release. | +| Trial | `PYPI_PUBLISH=testpypi` uploads to TestPyPI (same environment name, a publisher registered on test.pypi.org). | A dry run that does not use the PyPI name. | +| Name | `name=` of `setup.py`. `distribution.pip` of `labconstrictor-app.yaml` is **not** the switch; when present, it must be the same name (PEP 503 normalised), otherwise the build stops. | The App Centre tells people to `pip install` the `distribution.pip` name. Renaming silently could publish the wrong code under it: VLab4Mic's `src/` holds only `vlab4mic_lc_tools` (`setup.py` name `vlab4mic-lc-tools`), while a `distribution.pip: vlab4mic` would name VLab4Mic itself, which is published from another repository. | +| Dependencies | `setup.py` reads `requirements.txt` when the package is built: one requirement per line, as written (exact pins included). Options, paths and URLs are left out (`pypi_package.py` warns about each). | One list for the installer and PyPI. The installer builds the package with `pip install --no-deps --no-build-isolation`, and `requirements.txt` is next to `setup.py` there: a line setuptools would refuse is dropped, so it can never break an installation. `MANIFEST.in` puts `requirements.txt` in the source distribution, so a wheel built from it has the same dependencies. | +| Description | `README.md` (Markdown), and the repository as the `Source` link (from `GITHUB_REPOSITORY`, set by GitHub Actions). | Both files may be missing (the installer): the package still builds. | + +Two jobs, as PyPI recommends: `build` (no special permission) runs `.tools/python/pypi_package.py` and stores `dist/` as an artifact; `publish` (only `id-token: write`, environment `pypi`) downloads it and uploads it. + +`pypi_package.py` stops **before building**, with a GitHub error annotation, when: + +* there is no package in `src/` (a folder with an `__init__.py`); +* the version is not X.Y.Z; +* the index already has that version (`/pypi///json` answers 200); when the index cannot be asked, it only warns (the upload then fails if the version exists); +* another workflow of the repository uploads to PyPI (`pypa/gh-action-pypi-publish` or `twine upload`): the release would be uploaded twice; +* `distribution.pip` and `setup.py` name different packages; +* `setup.py` still has `PYTHON_PROJ_NAME` or `PYTHON_VERSION`; +* `pyproject.toml` describes the package (a `[project]` table) with another version than the release (its version is not rewritten). + +After `python -m build` (the wheel is built from the source distribution), it checks the name and version of both files, refuses a dependency given as a URL (PyPI refuses it on upload), and checks that the wheel has the dependencies of the source distribution. + +## 3. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. + +* **`.tools/python/pypi_package.py`** is created; a repository with its own file of that name keeps it (`SKIPPED`). +* **`.github/workflows/publish_pypi.yml`** is created, off. It is **not** created when another workflow of the repository already uploads to PyPI (NucleiSky's `publish_to_pypi.yml`, which publishes when `project.version` of `pyproject.toml` changes on `main`): the log says so, and that nothing is needed to keep publishing that way. To move to the template's workflow, delete yours, copy `publish_pypi.yml` from the template, and register it on pypi.org (a project you own: **Manage** > **Publishing**). +* **`setup.py`** is replaced by the 0.1.25 template's, with the app's name, version and Python series, only when it is exactly the template's earlier file with those three values filled in (CellTracksColab, LabChronicle, LabConstrictor_Demo, Stardist2D). A `setup.py` changed by hand (the Playground and GuessTheCondition list their dependencies, CellPatcher has a URL dependency, VLab4Mic names one package, NucleiSky is a shim for `pyproject.toml`) is left as it is (`SKIPPED`); if such an app turns PyPI publishing on, its `setup.py` is built as it is, and `pypi_package.py` reports what PyPI would refuse. +* **`MANIFEST.in`** is created only next to the 0.1.25 `setup.py`. An app's own `MANIFEST.in` is kept; without the line `include requirements.txt`, the log asks to add it. +* **`bump_version.py`:** three known blocks (the `setup.py` path and pattern, the new `bump_setup_py()`, its call in `main()`). Customised, `SKIPPED`: the release then leaves `setup.py`'s version alone (`publish_pypi.yml` still publishes the release version). + +## 4. Adopting it + +Take this template version (the synchronization pull request). Nothing is published until the one-time setup in [Upload external code](external_code_upload.md#4-publish-the-code-on-pypi-optional): a pending trusted publisher on pypi.org (owner, repository, workflow `publish_pypi.yml`, environment `pypi`), then the repository variable `PYPI_PUBLISH=true`. To turn it off, delete the variable. Failures are described in [Troubleshooting](troubleshooting.md#publishing-to-pypi-fails). + +## 5. What is checked here, and what is not + +* Tests (`tests/test_template_sync_0_1_25.py`): the workflow is off without the variable, uses trusted publishing, no secret, actions pinned by SHA; `setup.py` keeps the placeholders the form, `bump_constructor.py`, `merge_requirements.py` and `check_placeholders.py` rely on; what `setup.py` passes to setuptools with and without `requirements.txt` and `README.md` (the installer), also without `packaging`; every stop of `pypi_package.py`; **the source distribution and the wheel of an initialised copy are built** (without network) and their metadata checked; `bump_version.py` writes the release version into `setup.py` and keeps CRLF; the migration on 0.1.24 files (a second run changes nothing), with CRLF, the uninitialised template, customised files, NucleiSky's own workflow and missing folders; the sync chain from 0.1.24. +* The migration was also run on copies of real apps (NucleiSky, the Playground, Stardist2D, CellPatcher, VLab4Mic, CellTracksColab, LabChronicle, LabConstrictor_Demo, GuessTheCondition), with the whole chain from their template versions (0.1.19 to 0.1.22), then a second time (no change), and the package of each app that got the workflow was built with `pypi_package.py` (no upload). CellTracksColab, LabChronicle, LabConstrictor_Demo and Stardist2D got the new `setup.py`; the others kept theirs. Every build passed except CellPatcher's, which stops as intended: its `setup.py` needs two packages from GitHub URLs, which PyPI refuses. +* **Nothing was uploaded** to PyPI or TestPyPI: the `publish` job (trusted publishing, `pypa/gh-action-pypi-publish`) and the `if:` on `vars` are checked only by reading them. The first real check is a release of an app with `PYPI_PUBLISH=testpypi`. diff --git a/.tools/docs/migration_0_1_26.md b/.tools/docs/migration_0_1_26.md new file mode 100644 index 0000000..4562277 --- /dev/null +++ b/.tools/docs/migration_0_1_26.md @@ -0,0 +1,33 @@ +# Template 0.1.26: the app's own documentation explains PyPI publishing + +Design note for the 0.1.26 migration (`.template_sync/migrations/v0_1_25_to_v0_1_26.py`). It changes documentation only. + +## 1. The problem + +Template 0.1.25 ([migration_0_1_25.md](migration_0_1_25.md)) added opt-in PyPI publishing to every app: `publish_pypi.yml` and `pypi_package.py`. Its migration did not touch the app's documentation, so an app's own `.tools/docs/external_code_upload.md` still ended at "3. How to import into your notebook", and its `troubleshooting.md` had no PyPI entry. The one-time setup (a pending publisher on pypi.org, the repository variable `PYPI_PUBLISH`) was described only in the template's documentation. The Playground's synchronisation pull request to 0.1.25 showed it. + +## 2. What the migration does + +Each step is independent, idempotent, never deletes and never raises for a customised file, and keeps the line endings of each file. Both texts are the template's, byte for byte, frozen in `.template_sync/resources/v0_1_25_to_v0_1_26/.tools/docs/`. + +* **`.tools/docs/external_code_upload.md`** gets the section **4. Publish the code on PyPI (optional)**. A page that already has the section is unchanged. A page with a section 4 of its own is left as it is (`SKIPPED`). +* **`.tools/docs/troubleshooting.md`** gets the entry **Publishing to PyPI fails**, unless it already has it. The apps' troubleshooting pages differ from the template's (they have entries of their own), so the end of the content is the only place that fits all of them. +* **Where the text goes:** at the end of the page's content, just before the Previous / Home / Next links (a `---` line, then `
` ... `
`). The links stay the last thing on the page: if text followed them, the migration moves them to the bottom. A page without these links gets the text at its end. +* A missing page is not created. + +The template's own `troubleshooting.md` had its links in the middle of the page: the entries of 0.1.23, 0.1.24 and 0.1.25 were added after them. In 0.1.26 they are at the bottom, and a test checks that every documentation page of the template ends with its links. The apps' troubleshooting pages were not affected: no migration added those entries to them. + +Why not more: + +* **The pages are not replaced.** The apps' copies differ from the template's (the title "Adding External Code", other Previous / Next links, entries of their own), so only the new section is added. +* **The docs index (`.tools/docs/README.md`) is not changed.** Its entry for the page differs from app to app (`#### 3. [*(Optional)* **Upload external code**](./external_code_upload.md)`, `- [Upload external code (optional)](external_code_upload.md)`, ...) and still leads to the page. + +## 3. The texts work in an app + +* **No placeholder.** The form does not fill in an app's documentation, so the "Name" row of the section no longer shows `PYTHON_PROJ_NAME`: it says the name is the `name=` of `setup.py`. +* **Links.** The relative links lead to pages every app has (`external_code_upload.md`, `troubleshooting.md`, `executable_creation.md`). The design note of 0.1.25, which apps do not have, is linked by its address on GitHub, in the template's pages too. + +## 4. What is checked here, and what is not + +* Tests (`tests/test_template_sync_0_1_26.py`): the frozen texts turn the template's pages of 0.1.24 into the live pages (the troubleshooting page with its links in the middle, which end at the bottom); every documentation page of the template ends with its links; the texts have no placeholder and no link to a page apps lack; an app's page (another title, other links, CRLF) gets the section before its links and keeps CRLF; a troubleshooting page with links, with text after its links, without links; a page with its own section 4, pages that already explain it, missing and unreadable pages; a second run changes nothing; the sync chain from 0.1.25. +* The migration was also run on copies of real apps (see the pull request). diff --git a/.tools/docs/migration_0_1_27.md b/.tools/docs/migration_0_1_27.md new file mode 100644 index 0000000..06e8bcd --- /dev/null +++ b/.tools/docs/migration_0_1_27.md @@ -0,0 +1,24 @@ +# Template 0.1.27: an app can say which plugin version its tools need + +Design note for the 0.1.27 migration (`.template_sync/migrations/v0_1_26_to_v0_1_27.py`). Proposal and plan: [LabConstrictor-Tools #155](https://github.com/CellMigrationLab/LabConstrictor-Tools/issues/155). + +## 1. The problem + +Hosts already require a minimum LabConstrictor-Tools inside an app. The other direction was missing: an app could not say that its tools need, for example, LabConstrictor-QuPath 0.1.0-alpha.6 (Replace keeps your own annotations) or LabConstrictor-Fiji 0.1.0-alpha.6 (progress of long trainings in the Log window). People with an older plugin got the old behaviour without being told to update. StarDist2D 1.2 needs both. + +## 2. What changes + +* **Schema** (`.tools/schema/labconstrictor-app.schema.json`, the App Centre's copy): an optional field `host_requirements`, one entry per plugin (`napari`, `fiji`, `qupath`), each with `min_version` and/or `features`, and optionally `why` and `required`. The installer already passes `labconstrictor-app.yaml` to `labconstrictor-tools register --app-manifest`; Tools with feature `host_requirements_v1` copies the field into the registry entry, and plugins that implement the rule warn when theirs is older. +* **Documentation** (`.tools/docs/app_manifest.md`): the section "Plugin versions your tools need (optional)". + +## 3. What the migration does + +Each step is independent, idempotent, never deletes and never raises for a customised file. + +* The schema copy is replaced by the template's (the template owns it, and a test keeps it equal to the App Centre's). Without this, an app that adds the field fails its manifest check, because the schema rejects unknown fields. A repository without a schema copy is left alone. +* The section goes before "## The automatic check" of `app_manifest.md`; on a page without that heading, before its Previous / Home / Next links, or at its end. A page that has the section is unchanged; line endings are kept. +* `labconstrictor-app.yaml` is not touched: the field is optional and each app decides whether it needs it. + +## 4. Tests + +`tests/test_template_sync_0_1_27.py`: the frozen resources equal the template's files; the schema accepts a valid declaration and refuses the notebook, an empty entry, a version like `latest` and an unknown key; a 0.1.26 app reaches the template's files and a second run changes nothing; CRLF, a page without the heading, a page without links, missing and unreadable files; the sync chain from 0.1.26. diff --git a/.tools/docs/migration_0_1_28.md b/.tools/docs/migration_0_1_28.md new file mode 100644 index 0000000..a24ec7a --- /dev/null +++ b/.tools/docs/migration_0_1_28.md @@ -0,0 +1,19 @@ +# Template 0.1.28: installers use LabConstrictor-Tools v0.3.0-alpha.2 + +Design note for the 0.1.28 migration (`.template_sync/migrations/v0_1_27_to_v0_1_28.py`). Context: [LabConstrictor-Tools #155](https://github.com/CellMigrationLab/LabConstrictor-Tools/issues/155). + +## Why + +Template 0.1.27 let an app declare `host_requirements` in `labconstrictor-app.yaml` (the oldest napari, Fiji or QuPath plugin it needs). The installer passes that file to `labconstrictor-tools register --app-manifest`, but only Tools v0.3.0-alpha.2 or later copies the block into the registry entry, where the plugins read it. Older Tools ignore it. So the installers must install v0.3.0-alpha.2. + +## What the migration does + +* `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 is left as it is, with a note. Line endings are kept. +* `.tools/docs/tools_bridge.md`: the tag `v0.3.0-alpha.1` is replaced by `v0.3.0-alpha.2`. +* Missing files are not created; nothing is deleted; a second run changes nothing. + +The new pin reaches users with the app's next release. The tag `v0.3.0-alpha.2` must exist before such an installer is used (the template CI installs from it). + +## Tests + +`tests/test_template_sync_0_1_28.py`: the template pins the new tag once per script and names it in the guide; a 0.1.27 app reaches the template files and a second run changes nothing; an own pin, a script without the hook and missing files are left alone; the sync chain from 0.1.27. The frozen resources of 0.1.17 and 0.1.18 are compared with the live files through `tests/_v0_1_28.py`, which moves the pin back. diff --git a/.tools/docs/migration_0_1_31.md b/.tools/docs/migration_0_1_31.md new file mode 100644 index 0000000..8a43816 --- /dev/null +++ b/.tools/docs/migration_0_1_31.md @@ -0,0 +1,54 @@ +# Template 0.1.31: no silent change of a notebook's package versions, no lost work when a notebook is updated + +Design note for the 0.1.31 migration (`.template_sync/migrations/v0_1_30_to_v0_1_31.py`), issues [#48](https://github.com/CellMigrationLab/LabConstrictor/issues/48) and [#49](https://github.com/CellMigrationLab/LabConstrictor/issues/49). How a change reaches an installed copy is described in [migration_0_1_16.md](migration_0_1_16.md): a new installer is needed, nothing edits an existing install. + +## 1. The problems + +**#48, the requirements merge changed versions without a word.** `merge_requirements.py` (run by **Updates on notebook change**) merged the `requirements.yaml` of every notebook and, for a package required by several notebooks, kept the highest version: the policy of issue #4 ("if two versions are in conflict in principle take the newest one"). For scientific workflows a successful install does not mean the same results, so a notebook validated with `numpy==1.26.4` silently ran with `numpy==2.0.0`. Running it showed more than the code review that found it (all exited with 0): + +| Notebook A | Notebook B | Merged until 0.1.30 | +|---|---|---| +| `numpy==1.26.4` | `numpy==2.0.0` | `numpy==2.0.0`, in either file order | +| `numpy<2.0` | | `numpy==2.0`: every requirement was written as `==`, here the one excluded version | +| `numpy<2` | `numpy>=2.1` | `numpy==2.1` | +| `numpy==1.26.4 ; sys_platform == "win32"` | `numpy==2.0.0 ; sys_platform != "win32"` | only the second line: no numpy on Windows | + +NucleiSky's notebooks pin `cellpose`, `ipywidgets`, `scikit-image`, `tifffile`, `torch` and `zarr` to different versions, and LabChronicle's pin `tqdm` to two versions: they relied on this. The old merge also treated `scikit-image` and `scikit_image` as two packages (pip then refuses the file), and wrote `ipywidgets==>=7.0.0` when no notebook gave a Python version. + +**#49, the notebook update could overwrite the user's work.** The **Update** button of the Welcome notebook downloaded the new notebook and wrote it over the user's copy, with their code changes, parameters and saved outputs, with no question and no copy. A failed write could leave a broken notebook, and a private repository without a token crashed the button. + +## 2. What changes + +| Part | Change | +|---|---| +| `.tools/python/merge_requirements.py` | Requirements are kept as written and combined per package (`numpy>=1.24,<2`); names are compared as pip compares them. Different exact pins, a pin outside another notebook's range, or ranges no version meets stop the merge, before any file is written, with every notebook and requirement (sorted, so the file order cannot hide one). `requirements_overrides.yaml` can decide explicitly, with a required reason; each decision is written at the top of the generated files. Requirements with different markers stay separate lines. A notebook's OS-specific requirements are checked against the common ones. `--check` only looks for conflicts. | +| `.tools/requirements.txt` | `packaging==25.0` (versions and specifiers as pip reads them). | +| `requirements_overrides.yaml` (new, only where needed) | See section 3. | +| `.github/workflows/update_on_notebook_change.yml` | A push of `requirements_overrides.yaml` runs the workflow and the merge. | +| `.github/workflows/release_constructor.yml` | The bump-version job runs `merge_requirements.py --check` after `check_placeholders.py`: a release stops while a conflict is unresolved (a failed merge leaves the previous `requirements.txt` in place, which would otherwise be released). | +| `.tools/templates/Welcome_template.ipynb` | **Update** asks first, says where the copy goes and to close the notebook's tab; then downloads, checks that the download is a notebook, copies the current file to `.backup-.ipynb` (never overwriting an earlier backup), writes the new notebook to a temporary file and moves it into place, and only then records the new version. Cancel or any failure changes nothing. The app-version check that decides whether a notebook can be updated is unchanged. | + +Why not detect local changes: JupyterLab saves outputs into the notebook (and autosaves), so a used notebook always differs from the installed one; a check would ask every time anyway. Asking every time and always keeping a copy is simpler and loses nothing. + +Why a range check of our own: a lock failure is only a warning (the installer then installs the plain `requirements.txt`), so an impossible range would reach the users. `satisfiable()` tries every version a requirement names and versions just above it; a range only a closer version could meet is reported as a conflict (stop and decide), never guessed. + +## 3. What the migration does + +Every step is independent, idempotent, never deletes, never raises for a customised file (the sync pull request is still created) and keeps the line endings of each file. + +* **`merge_requirements.py`** is replaced by the 0.1.31 file when it is still the 0.1.30 template file; a customised one is left as it is (`SKIPPED`). +* **`.tools/requirements.txt`** gets `packaging==25.0` unless it installs packaging already. +* **`requirements_overrides.yaml`** is created only when the notebooks' `dependencies` already pin a package to different versions. Each entry keeps the version the merge chose until now (the newest pin), so the app installs what it installed before, and its reason says so and lists the pins: check each one and replace the reason with yours. An existing file is left as it is. +* **`update_on_notebook_change.yml`:** three known lines (push paths, changed files, the merge condition); a customised workflow is `SKIPPED` (run the workflow by hand after changing the overrides). +* **`release_constructor.yml`:** the check goes after the first `check_placeholders.py` command (the bump-version job), only when the repository's `merge_requirements.py` knows `--check`. +* **`Welcome_template.ipynb`:** the update handler of the notebook table is replaced (compared line by line, trailing spaces ignored) and the backup function added; a customised table cell is `SKIPPED`. The Welcome notebook of the next release is made from it. + +## 4. Adopting it + +Take this template version (the synchronization pull request). If it created `requirements_overrides.yaml`, check each decision with the notebooks that pin another version; change the notebooks or the decision as needed. Then release a new installer: users get the safe update with it. + +## 5. What is checked here, and what is not + +* Tests (`tests/test_template_sync_0_1_31.py`): the merge on the cases of #48 (both file orders, ranges, markers, names, OS-specific lists, overrides with and without a reason, `--check` writes nothing); the backup function (first install, backup, two updates in the same second, a download that is not a notebook); the migration on 0.1.30 files and on customised ones, the seeded overrides of a NucleiSky-like app and the merge accepting them, CRLF, a second run; the sync chain from 0.1.30. +* The migration and the merge were run on copies of the real apps. +* The confirmation dialog and the buttons of the Welcome notebook are not run by these tests: they need a person in an installed app. diff --git a/.tools/docs/notebook_portability.md b/.tools/docs/notebook_portability.md new file mode 100644 index 0000000..012a0b3 --- /dev/null +++ b/.tools/docs/notebook_portability.md @@ -0,0 +1,140 @@ +# Write notebooks that run in both Google Colab and JupyterLab + +LabConstrictor ships notebooks as desktop apps built on JupyterLab. At the same time, many collaborators and reviewers prefer Google Colab for quick, cloud-based runs. Writing your notebook to work in both environments makes it easier for users to: + +- **Choose their preferred platform** (Colab in the browser, JupyterLab locally or inside LabConstrictor). +- **Collaborate and review quickly** without forcing everyone to install dependencies. +- **Reproduce results** across cloud and local setups, reducing โ€œworks on my machineโ€ issues. +- **Avoid hidden environment assumptions** that only exist in one runtime. + +Below are practical patterns to keep notebooks portable and readable across both runtimes. + +## 1. Keep explanatory text visible when code is hidden + +LabConstrictor apps often hide code cells to present an app-like UI (see [Hide code cells in notebooks](code_hiding.md)). + +If you place `# @title` **at the top of the cell** in Colab, it would give a header to the code cell on Google Colab while remaining visible in local JupyterLab sessions. Follow the example below to keep your notebook clear and user-friendly in both environments: + +```python +# @title Data input + +# Rest of the cell... +``` + +> **Note:** If you need an explanation longer than a line, please use a **Markdown cell** with the explanation. This way, the text is visible everywhere, regardless of code visibility. + +## 2. Guard Colab-only setup code + +Colab-specific setup (mounting Google Drive, installing GPU-only deps, `!pip` installs) should run **only** on Colab. To avoid failures when running locally, wrap it like this: + +```python +import sys + +if 'google.colab' in sys.modules: + print("๐Ÿš€ Detected Google Colab. Starting installation...") + + !pip install -q "cellpose[all]" tifffile + !pip install -q instanseg-torch + + from google.colab import userdata + from google.colab import drive + + drive.mount('/content/gdrive') + + print("โœ… Colab setup done") +else: + # Fallback for local environments + print("โš ๏ธ Not running in Colab. Please ensure dependencies are installed and data paths are set.") +``` + +## 3. Prefer cross-platform paths and storage + +- Use `pathlib.Path` and **relative paths** when possible. +- Avoid hard-coding Colab paths like `/content` or `/content/gdrive` outside guarded blocks. +- For data files, include a **config cell** where users can set a local path or select a file. + +## 4. Avoid Colab-only UI helpers + +Avoid using Colab forms (see [Google's guide to Colab forms](https://colab.research.google.com/notebooks/forms.ipynb)) as they wonโ€™t work in JupyterLab. Instead, we recommend using ipywidgets or simple input prompts that work in both environments. This ensures your notebook remains interactive and user-friendly regardless of where itโ€™s run. + +For example, you could turn this Colab form: + +```python +model_name = "Model A" # @param ["Model A", "Model B", "Model C"] +print(f"You selected: {model_name}") +``` + +![Colab form example](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/colab_vs_local/colab.png) + +Into, for example an ipywidgets dropdown that works in both environments: + +**Option A** - with an observable function: + +```python +import ipywidgets as widgets +from IPython.display import display + +model_dropdown = widgets.Dropdown( + options=["Model A", "Model B", "Model C"], + description="Select a model:", + style={'description_width': 'initial'} +) +output = widgets.HTML() + +def on_model_change(change): + if change['type'] == 'change' and change['name'] == 'value': + output.value = f"You selected: {change['new']}" +model_dropdown.observe(on_model_change) + +display(model_dropdown, output) +``` + +![ipywidgets dropdown example](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/colab_vs_local/local_option1.png) + +**Option B** - With a button to confirm the selection: + +```python +import ipywidgets as widgets +from IPython.display import display + +model_dropdown = widgets.Dropdown( + options=["Model A", "Model B", "Model C"], + description="Select a model:", + style={'description_width': 'initial'} +) +confirm_button = widgets.Button(description="Confirm Selection") +output = widgets.HTML() + +def on_confirm_button_click(b): + output.value = f"You selected: {model_dropdown.value}" +confirm_button.on_click(on_confirm_button_click) + +display(model_dropdown, confirm_button, output) +``` + +![ipywidgets dropdown with button example](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/colab_vs_local/local_option2.png) + +As you can see the ipywidgets options require a bit more code, but they work in both environments and are much more versatile in functionality and visualization. + +## 5. Clearly label runtime-specific instructions + +To reduce confusion and keep the flow smooth in both environments, add small callouts in Markdown to guide the user, for example: + +> **Colab users:** Run the `Colab setup` cell first to mount Google Drive. +> +> **JupyterLab users:** Skip the `Colab setup` cell and configure the local data path instead. + +## 6. Test in both environments before release + +Testing both environments before making it public ensures a smooth experience for all users: + +1. Run the notebook end-to-end in **JupyterLab** (or local Jupyter) to validate the LabConstrictor experience. +2. Run the same notebook in **Google Colab** to confirm cloud compatibility. + +--- + +
+ +[๐Ÿ  Home](README.md) + +
diff --git a/.tools/docs/notebook_requirements.md b/.tools/docs/notebook_requirements.md new file mode 100644 index 0000000..ac4a480 --- /dev/null +++ b/.tools/docs/notebook_requirements.md @@ -0,0 +1,112 @@ +# Generate the requirements of your notebook + +You can get your Jupyter notebookโ€™s requirements automatically with Option 1 or manually with Option 2. + +* **Option 1 (Automated):** Recommended if you need to generate requirements from scratch. +* **Option 2 (Manual):** Recommended if you already have a versioned `requirements.txt` file, as it will be faster. + +--- + +## Option 1: Automated Extraction of Requirements + +### 1. Open the Requirements Generator Notebook + +**โš ๏ธ IMPORTANT:** You will need to choose the option based on the environment you used to run the target notebook whose requirements you want to extract. + + * Did you ran your notebook locally on your machine (with Conda/VirtualEnv)? โžก๏ธ Locally + * Did you ran your notebook on Google Colab? โžก๏ธ Online + +In both cases the Python environment that you use for the notebook, needs to run without errors. Knowing this please choose the option that best suits your case: + +* **Locally:** Go to the [Requirements_Generator.ipynb](../notebooks/Requirements_Generator.ipynb) notebook, download it (clicking on the button indicated on the screenshot below โฌ‡๏ธ) and open it in your local Python environment (conda or virtualenv). + > **Note**: When using it locally, the Python environment where you open the requirements generator notebook needs to be exactly the one you use to run the target notebook whose requirements you want to extract. For example, if you have multiple conda environments, you need to make sure that you use the same conda environment that you use to run the target notebook. + +![Download Notebook](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Download_Notebook.png) + +* **Google Colab:** Open the notebook directly in Google Colab by opening the [Requirements Generator in Colab](https://colab.research.google.com/github/CellMigrationLab/LabConstrictor/blob/main/.tools/notebooks/Requirements_Generator.ipynb). + +### 2. Run the Requirements Generator + +Follow the instructions provided inside the notebook to generate the `requirements.yaml` file. You will be prompted to provide the path to the notebook file you wish to analyse. + +--- + +## Option 2: Manual Extraction of Requirements + +### 1. Create a `requirements.yaml` File + +You will need to create a `requirements.yaml` file similar to the [example requirements.yaml file](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/templates/requirements.yaml). This file must contain the following three fields: + +* **`dependencies`:** A list of all packages used in the notebook along with their versions. The list needs to be indexed with a hyphen (`-`) followed by a space before each package. +* **`python_version`:** The version of Python used in the notebook (e.g., `3.11.1`). +* **`description`:** A short description of the notebook and its purpose. + +**Example File Content:** + +```yaml +dependencies: + - pandas==2.2.2 + - ipython==7.34.0 + - tqdm==4.67.1 +description: This notebook is for analyzing cell migration data... +python_version: 3.11.1 + +``` + +### 2. Open the Requirements Validator Notebook + +We recommend using **Google Colab** for this step, as you do not need a specific Python environment to run the validator. + +* **Google Colab (Recommended):** Open the notebook directly by opening the [Requirements Validator in Colab](https://colab.research.google.com/github/CellMigrationLab/LabConstrictor/blob/main/.tools/notebooks/Requirements_Validator.ipynb). +* **Locally:** Download the [Requirements_Validator.ipynb](https://raw.githubusercontent.com/CellMigrationLab/LabConstrictor/main/.tools/notebooks/Requirements_Validator.ipynb) and open it in any Python environment that has `ipywidgets` installed. + +### 3. Run the Requirements Validator + +Follow the instructions provided inside the notebook to validate your file. You will need to provide the path to your newly created `requirements.yaml` file when prompted. + +--- + +## What happens next: the lock file + +When you push a notebook with its `requirements.yaml`, the workflow **Updates on notebook change** merges the requirements of every notebook into `requirements.txt` (plus `requirements_gpu.txt` and, if a notebook needs them, `requirements-windows.txt`, `requirements-linux.txt` or `requirements-macos.txt`). + +The installer uses `requirements_gpu.txt` when it finds an NVIDIA GPU on Windows or Linux. In that file `tensorflow` becomes `tensorflow[and-cuda]` on Linux only: TensorFlow has had no Windows GPU build since version 2.10, and its CUDA packages exist only for Linux, so Windows keeps plain `tensorflow` (CPU). + +### When notebooks ask for different versions of a package + +The merge never changes a notebook's requirement silently. Requirements are kept as written (`numpy>=1.24` stays `numpy>=1.24`), and the requirements of several notebooks are combined (`numpy>=1.24,<2`). The workflow stops, and no requirements file is written, when: + +* two notebooks pin a package to different versions (`numpy==1.26.4` and `numpy==2.0.0`); +* a pin does not meet another notebook's requirement (`numpy==2.0.0` and `numpy<2`); +* no version meets all the requirements (`numpy<2` and `numpy>=2.1`). + +The log of the **Run merge script** step names the package, every notebook and its requirement. Then either: + +* **make the notebooks agree:** change their `requirements.yaml` to a version that works for every notebook; or +* **decide explicitly** in `requirements_overrides.yaml`, at the top of the repository, which requirement every notebook gets, and why: + +```yaml +overrides: + numpy: + use: "==2.0.0" + reason: "Notebook A was re-run with numpy 2.0.0 and gives the same results; notebook B needs 2.0." +``` + +The decision and its reason are written at the top of the generated requirements files. Pushing `requirements_overrides.yaml` runs the workflow again. A release also stops while a conflict is not resolved. Requirements with different platform markers (`; sys_platform == "win32"`) are kept as separate lines, and `NumPy`, `numpy` and `num_py` count as the same package, as for pip. + +It then writes a **lock file** next to each of them (`requirements.lock.txt`, ...). A lock file lists every package the installer installs, including the packages your packages depend on, each with its exact version, for Windows, macOS and Linux. The installer installs the lock file, so every installation of a release gets the same versions. + +* A lock file changes only when its requirements file, the Python version or the JupyterLab version changes. Pushing a notebook without new requirements does not move any version. +* To move every package to its newest version, delete the `requirements*.lock.txt` files and run **Updates on notebook change** by hand (**Actions > Updates on notebook change > Run workflow**). +* If the requirements cannot be locked, the workflow shows a warning and the installer installs the plain `requirements.txt` instead. + +--- + +
+ +[โ† Previous](accept_pull_request.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](notebook_upload.md) + + +
diff --git a/.tools/docs/notebook_upload.md b/.tools/docs/notebook_upload.md new file mode 100644 index 0000000..1341f14 --- /dev/null +++ b/.tools/docs/notebook_upload.md @@ -0,0 +1,178 @@ +# Add or update a notebook + +If you want to add or update a notebook in your project repository, just follow these steps to upload it smoothly. + +## 1. Prepare your notebook + +To ensure your notebook works with the versioning tracking provided by the LabConstrictor application, please follow these three steps to prepare your notebook: + +1. First, create a cell at the top of your notebook (see our [JupyterLab guide](https://github.com/CellMigrationLab/docs-hub/blob/main/docs/JupyterLab/JupyterLab_Guide.md) if you need help with that). +2. Then, copy and paste the code below into that cell. +3. Finally, update the `current_version` variable with the version of your notebook (for example, "0.0.2") and the `notebook_name` variable with the name of your notebook file (without the .ipynb extension). + +> IMPORTANT NOTE: Each time you change the notebook's logic, update the version number on `current_version` variable so users can see there is a new version. + +``` +# @markdown Run this cell to check this notebook's version. + +current_version = "0.0.1" +notebook_name = "Notebook_template" # Replace with the actual notebook name + +# First of all check if ipywidgets is installed, if not through an informative error +try: + import ipywidgets as widgets +except ImportError: + raise ImportError("ipywidgets is not installed. Please install it using 'pip install ipywidgets' or 'conda install -c conda-forge ipywidgets'.") + +from IPython.display import display + +try: + from google.colab import output + output.enable_custom_widget_manager() + + try: + import yaml + except ImportError: + raise ImportError("pyyaml is not installed. Please install it using 'pip install pyyaml' or 'conda install -c conda-forge pyyaml'.") + + import requests + import base64 + + # Create widgets + github_repo = widgets.Text( + value="", + description="*GitHub Repository URL:", + placeholder="e.g https://github.com/username/repository", + layout=widgets.Layout(width="70%"), + style={'description_width': '150px'}, + ) + + github_token = widgets.Password( + value="", + description="*Personal Access Token:", + placeholder="[Disabled] e.g. ghp_XXXXXXXXXXXXXXXXXXXX", + disabled=True, + layout=widgets.Layout(width="70%"), + style={'description_width': '150px'}, + ) + + test_button = widgets.Button( + description="Test Connection", + button_style='success', + ) + + output_area = widgets.HTML() + + # By default the repository is considered public + if "repository_is_private" not in globals(): + repository_is_private = False + elif repository_is_private: + github_token.disabled = False + github_token.placeholder = "e.g. ghp_XXXXXXXXXXXXXXXXXXXX" + + def on_test_button_clicked(b): + global repository_is_private + + # Check that the GitHub repository URL is provided + if not github_repo.value: + output_area.value = "โš ๏ธ Please provide a GitHub repository URL." + return + + # Get the owner and repo name from the URL + repo_url = github_repo.value.rstrip('/') + github_owner, github_repo_name = repo_url.split('/')[-2:] + + # Online version checking file path + version_file_path = "notebooks/notebook_latest_versions.yaml" + version_url = f"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/{version_file_path}" + + # Do an initial request to check if the repository is public + if not repository_is_private: + version_response = requests.get(version_url) + if version_response.status_code == 404: + repository_is_private = True + github_token.disabled = False + github_token.placeholder = "e.g. ghp_XXXXXXXXXXXXXXXXXXXX" + output_area.value = f"โš ๏ธ We have detected that the repository might be private. Please provide a Personal Access Token and click 'Test Connection' again." + return + else: + headers = {"Accept": "application/vnd.github.v3+json"} + if not github_token.value: + output_area.value = "โš ๏ธ Personal Access Token is required for private repositories." + return + headers["Authorization"] = f"token {github_token.value}" + + version_response = requests.get(version_url, headers=headers) + + # Check the response status + if version_response.status_code == 200: + content = version_response.json()['content'] + decoded_content = base64.b64decode(content).decode('utf-8') + config = yaml.safe_load(decoded_content) + # notebook_latest_versions.yaml groups the notebooks by folder: {"": {"": ""}} + latest_version = next((str(group[notebook_name]) for group in (config or {}).values() + if isinstance(group, dict) and notebook_name in group), "") + + output_area.value = (f"Notebook version: `{current_version}`
" + f"Latest version available: `{latest_version}`
") + + if latest_version == "": + output_area.value += "โš ๏ธ This notebook is not listed in the version file.
" + elif current_version == latest_version: + output_area.value += "โœ… This notebook is up-to-date.
" + else: + output_area.value += f"โš ๏ธ A new version of this notebook is available." + else: + output_area.value += "โš ๏ธ Could not retrieve the version file.
" + + test_button.on_click(on_test_button_clicked) + # Widget layout + widget_box = widgets.VBox([github_repo, github_token, test_button, output_area]) + display(widget_box) +except ImportError: + display(widgets.HTML('To check the notebook version, please go to the Welcome notebook.')) +``` + +## 2. Generate the requirements file + +Follow the steps in the [Obtain requirements of the notebook](notebook_requirements.md) guide to create the `requirements.yaml` file for your notebook. + +## 3. Upload to the repository + +1. Open the [LabConstrictor website](https://labconstrictor-form.streamlit.app/). If you see a `Zzzz` message for inactivity, click `Yes, get this app back up!`. +2. Select **Upload/Update notebook**. +3. Upload your notebook file (`.ipynb`) and the `requirements.yaml` file you created. +4. Click **โž• Validate & Add Submission**. If the notebook and its requirements pass the checks, the notebook appears in the **๐Ÿ“ƒ Submission list**. You can repeat steps 3 and 4 to add more notebooks to the list before uploading. +5. In the **โฌ†๏ธ Upload it to GitHub** section, enter your repository URL and your personal access token. + * *(Don't have a token? See [How to create a personal access token](personal_access_token.md))* +6. Click **๐Ÿš€ Create pull request**. + + +## 4. Merge and Verify + +If you need help merging the pull request, see the [Accept a Pull Request](accept_pull_request.md) guide for instructions. An automatic workflow will check your notebook and its dependencies. +* **Check Status:** See [How to check workflow status](workflow_status.md). +* Failure Protocol: If the merged requirements cannot be installed, the system automatically undoes the merge. Check the logs, fix the problem in your local notebook or requirements, and upload again. +* If notebooks ask for different versions of the same package, the workflow stops before anything is installed and the requirements files are not changed. See [When notebooks ask for different versions of a package](notebook_requirements.md#when-notebooks-ask-for-different-versions-of-a-package). + +--- + +## How to update an existing notebook + +Updating a notebook works the same way as adding a new one: + +1. Bump the version: In the top cell of your notebook, increase the `current_version` (for example, from '1.0.0' to '1.0.1'). +2. Regenerate requirements: Run the bottom cell to make sure `requirements.yaml` matches the new version number. +3. Upload: Use the [LabConstrictor App](https://labconstrictor-form.streamlit.app/) to upload your file. + * *Ensure the filename matches the existing one in the repository exactly.* + +--- + +
+ +[โ† Previous](notebook_requirements.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](executable_creation.md) + + +
diff --git a/.tools/docs/notebook_usage.md b/.tools/docs/notebook_usage.md new file mode 100644 index 0000000..2f86a28 --- /dev/null +++ b/.tools/docs/notebook_usage.md @@ -0,0 +1,44 @@ +# Use notebooks after installation + +After you install the desktop application, this guide will show you how to use the Jupyter notebooks that come with it. + +## 1. Launching the Application + +To open the application, go to the Start Menu on Windows or Linux, or the Applications folder on macOS. Search for the application name and click its icon to start it. + +## 2. Welcome Notebook + +When you start the application, a terminal will pop up. + +> Don't be scared by the terminal, it is normal: it keeps your Jupyter Lab session running. **Do not close the terminal** until you have finished working with your notebooks. When you have, stop the Jupyter Lab session with **File > Shut Down** in Jupyter Lab (or click on the terminal window and press `Ctrl+C`). The terminal then asks you to press `Enter`, and closes. + +After some seconds, Jupyter Lab will open in your default web browser. The welcome notebook will appear automatically: + +![Welcome Notebook](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Welcome_Notebook.png) + +### Updating a notebook + +When a newer version of a notebook is published, the Welcome notebook shows **Update** next to it. Updating replaces your copy of the notebook, so before anything changes it asks you to confirm, and it keeps your current copy, with your changes and outputs, as `.backup-.ipynb` in the same folder. Close the notebook's tab before updating: otherwise JupyterLab can save the old copy over the new one. If the download fails, your notebook is not changed. + +## 3. How to Run Notebooks? + +You might be used to work with notebooks on JupyterLab (in case you need some guidance on JupyterLab check [this guide](https://github.com/CellMigrationLab/docs-hub/blob/main/docs/JupyterLab/JupyterLab_Guide.md)). Still, LabConstrictor uses some features that can slightly change how you interact with notebooks. Please check [this guide](code_hiding.md) to understand how to run notebooks packaged with LabConstrictor. + +## 4. Accessing your Notebooks + +Once you run the welcome notebook, a dashboard will show a list of available notebooks. It looks similar to the screenshot in the [Welcome Notebook](#2-welcome-notebook) step. + +In the last column of the dashboard, you'll see a button called `Open the notebook`. Click it to open that notebook in a new tab and run it just like you did with the welcome notebook. + + +--- + + +
+ +[โ† Previous](download_executable.md)            +[๐Ÿ  Home](README.md)            +Next โ†’ + + +
diff --git a/.tools/docs/personal_access_token.md b/.tools/docs/personal_access_token.md new file mode 100644 index 0000000..b0632c7 --- /dev/null +++ b/.tools/docs/personal_access_token.md @@ -0,0 +1,39 @@ +# Generate a GitHub personal access token + +> Looking for the token used by the automatic template update workflow? Follow the dedicated [automatic template synchronization guide](template_synchronization.md). It uses a repository-scoped fine-grained token with a different purpose and secret name. + +If you want to work with GitHub repositories from your notebook, like cloning, editing, or pushing files, youโ€™ll need a GitHub Personal Access Token (PAT). This token lets you authenticate your API calls and gives you the right permissions. The GIF below shows the steps to create a token. + +![Gif of generating a GitHub token](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/GitHub_Access_Token.gif) + +> The LabConstrictor repository form accepts only a classic token, which starts with `ghp_`. A fine-grained token (it starts with `github_pat_`) is rejected. + +To see the full steps, follow the instructions below. + +## Create the token + +1. Go to https://github.com/ and sign in. +2. Click your profile icon (top right) โž” **Settings** +3. In the left sidebar, select **Developer settings** โž” **Personal access tokens** โž” **Tokens (classic)** +4. On the top right side (at the same level as `Personal access tokens (classic)`), click on **Generate new token** โž” **Generate new token (classic)** +5. Give your token a descriptive **Name** (e.g., `Notebook RW Token`) and set an **Expiration** if desired +6. Under **Scopes**, tick **repo** + - *(Optional: To only work with public repositories, select **public_repo** instead of **repo**)* +7. Click **Generate token** at the bottom +8. **Copy** your new token right away. You wonโ€™t be able to see it again later! +9. Paste the token into your notebookโ€™s `GitHub-token` field, so API calls authenticate as the chosen owner. + +A classic token with the **repo** scope can read and write your repositories, so keep it private. + + +--- + + +
+ +[โ† Previous](troubleshooting.md)            +[๐Ÿ  Home](README.md)            +Next โ†’ + + +
diff --git a/.tools/docs/template_synchronization.md b/.tools/docs/template_synchronization.md new file mode 100644 index 0000000..1c512ea --- /dev/null +++ b/.tools/docs/template_synchronization.md @@ -0,0 +1,82 @@ +# Enable automatic LabConstrictor template updates + +LabConstrictor periodically checks the main template for improvements. When an update is available, the **Sync with Template Repository** workflow prepares the changes in a pull request so you can review and merge them safely. + +You will need to do a one-time GitHub setup to create a token that allows LabConstrictor to update your repository. This token described below is limited to the repository you select. LabConstrictor does not need access to your other repositories. + +## What do I need to do? + +Follow the same instructions that are given in the following video and instructions below. + +## Step 1: Create the synchronization token + +![GIF showing the token creation](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Synchronisation_Token_Creation.gif) + +Follow steps on the GIF or click on [this link](https://github.com/settings/personal-access-tokens/new?name=LabConstrictor+Sync&description=Allows+LabConstrictor+to+prepare+template+update+pull+requests.&expires_in=365&contents=write&pull_requests=write&workflows=write) and follow the steps below: + +1. Under **Resource owner**, select the owner of your LabConstrictor repository. +2. Under **Repository access**, select **Only select repositories**. +3. Select your LabConstrictor repository. +4. Choose an expiration period that suits you. The prefilled suggestion is 365 days. +5. Confirm these repository permissions: + - **Contents:** Read and write + - **Pull requests:** Read and write + - **Workflows:** Read and write +6. Select **Generate token**. +7. Copy the generated token. + +> GitHub shows the complete token only once. Keep the page open until you have saved it in Step 2. + +## Step 2: Save the token as a repository secret + +![GIF showing the secret creation](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Synchronisation_Secret_Creation.gif) + +1. Open your LabConstrictor repository. +2. Select **Settings**. +3. In the left sidebar, select **Secrets and variables**, then **Actions**. +4. Select **New repository secret**. +5. Enter this exact name: + + ```text + LABCONSTRICTOR_SYNC_TOKEN + ``` + +6. Paste the token into the **Secret** field. +7. Select **Add secret**. + +> GitHub encrypts repository secrets. The token will not be displayed in the repository or in normal workflow logs. + +## Step 3 (situational): One-time step for repositories created before template version 0.1.12 + +An older synchronization workflow does not yet reference `LABCONSTRICTOR_SYNC_TOKEN`. If you already saw an error saying that a GitHub App cannot create or update a workflow without `workflows` permission, make this small edit once: + +1. Open [`.github/workflows/sync_template.yml`](../../.github/workflows/sync_template.yml) in your repository. +2. Select the pencil icon to edit the file. +3. Copy and paste all the lines from the [LabConstrictor original workflow](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.github/workflows/sync_template.yml). + +4. Select **Commit changes** and commit directly to the default branch. +5. Run **Sync with Template Repository** again. + +The migration will then install the complete updated workflow automatically. This manual edit is only needed once for repositories whose existing workflow predates token integration. + +## Renewing an expired token + +When the token expires: + +1. Create a replacement token using Step 1. +2. Open **Settings โ†’ Secrets and variables โ†’ Actions**. +3. Select `LABCONSTRICTOR_SYNC_TOKEN`. +4. Select **Update secret** and paste the replacement token. +5. Run synchronization again. + +You do not need to edit the workflow again. + +--- + +
+ +[โ† Create repository](create_repository.md)            +[๐Ÿ  Documentation home](README.md)            +[Initialise repository โ†’](initialise_repository.md) + +
diff --git a/.tools/docs/tools_bridge.md b/.tools/docs/tools_bridge.md new file mode 100644 index 0000000..c557edb --- /dev/null +++ b/.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/troubleshooting.md b/.tools/docs/troubleshooting.md new file mode 100644 index 0000000..1c66d13 --- /dev/null +++ b/.tools/docs/troubleshooting.md @@ -0,0 +1,75 @@ +# Troubleshooting repository setup + +Problems with your repository on GitHub. For problems with an installed app on your computer, see [Troubleshooting an installed app](troubleshooting_installed_app.md). + +## Synchronisation is failing on GitHub Actions + +The **Sync with Template Repository** workflow needs the encrypted repository secret `LABCONSTRICTOR_SYNC_TOKEN` because template migrations can update files in `.github/workflows/`. Follow the [automatic template synchronization guide](template_synchronization.md) for the complete beginner-friendly setup. + +### The synchronization token is missing + +Create the token and save it under **Settings โ†’ Secrets and variables โ†’ Actions** with this exact name: + +```text +LABCONSTRICTOR_SYNC_TOKEN +``` + +### GitHub refuses to update a workflow file + +If the error says GitHub is refusing to create or update a workflow without `workflows` permission, ensure the token has all of these repository permissions: + +- **Contents:** Read and write +- **Pull requests:** Read and write +- **Workflows:** Read and write + +Repositories created before template version `0.1.12` also need the one-time workflow edit described in the synchronization guide so the existing workflow starts using the secret. + +### Bad credentials or authentication failed + +The token may have expired or been revoked. Create a replacement token and update the existing `LABCONSTRICTOR_SYNC_TOKEN` secret. + +## The release stops at "check_placeholders.py" + +The release workflow checks, before it builds the installers, that no template placeholder (`PROJECT_NAME`, `PYTHON_PROJ_NAME`, `UNDERSCORED_PROJECT_NAME`, ...) is left in a file the installer ships. An installer built with one would fail on the users' computers (for example `No module named 'PYTHON_PROJ_NAME'` at the end of the installation). + +The log of the failed step lists each file and line. Replace the placeholder there with your app's value: `PYTHON_PROJ_NAME` is the Python package of the app (usually its folder in `src/`), `PROJECT_NAME` the app name. For `app/menuinst/Welcome.ipynb`, edit `.tools/templates/Welcome_template.ipynb` instead: the Welcome notebook is made from it at every release. Commit, then publish the release again. See [migration_0_1_23.md](migration_0_1_23.md). + +## The release stops at "Installers to build" + +The `platforms` job of the release workflow reads `distribution.platforms` in `labconstrictor-app.yaml` to decide which installers to build. It stops when the file is not valid YAML, when `platforms` is not a list, or when it lists none of the systems the release builds installers for: `windows-x86_64`, `linux-x86_64`, `macos-arm64` and `macos-x86_64`. The log of the step says which. Fix `labconstrictor-app.yaml` (see [App Centre manifest](app_manifest.md)), commit, then publish the release again. See [migration_0_1_24.md](migration_0_1_24.md). + +## "The notebooks ask for incompatible package versions" + +The **Run merge script** step of **Updates on notebook change**, or the `merge_requirements.py --check` command of a release, stops when notebooks pin a package to different versions, or ask for versions that no single version meets. Its log lists the package, each notebook and its requirement. Make the notebooks agree, or decide in `requirements_overrides.yaml` which requirement every notebook gets and why, then push it: the workflow runs again. See [When notebooks ask for different versions of a package](notebook_requirements.md#when-notebooks-ask-for-different-versions-of-a-package) and [migration_0_1_31.md](migration_0_1_31.md). + +If the template synchronization to 0.1.31 created `requirements_overrides.yaml`, its entries keep the versions your app installed until now (the newest of the pins). Check each one with every notebook that uses the package, and replace its reason with yours. + +## Publishing to PyPI fails + +The workflow **Publish the Python package to PyPI** (`publish_pypi.yml`) runs at a release only when the repository variable `PYPI_PUBLISH` is `true` or `testpypi` (see [Upload external code](external_code_upload.md#4-publish-the-code-on-pypi-optional)). Its first job checks and builds the package; its second job uploads it. The installers do not depend on it: a failure here leaves the release and its installers as they are. + +| What you see | What to do | +|---|---| +| Both jobs are grey (skipped) | The variable is missing or has another value. It must be a **variable** (Settings > Secrets and variables > Actions > **Variables**), not a secret, named `PYPI_PUBLISH`, with the value `true` or `testpypi` exactly. | +| `invalid-publisher: valid token, but no corresponding publisher` | The trusted publisher on pypi.org (or test.pypi.org for `testpypi`) does not match this workflow. Check the five fields: owner, repository, workflow `publish_pypi.yml`, environment `pypi`, and the project name. Then re-run the failed job (Actions > the run > **Re-run failed jobs**). | +| `... isn't allowed to upload to project ...` (403) | The name belongs to another PyPI project that this repository is not a publisher of. If it is yours, add the publisher in that project's **Publishing** page; if not, choose another `name=` in `setup.py` (and `distribution.pip`). | +| `PyPI already has ` (or `File already exists`) | That version was uploaded before; a version can be uploaded only once, even after it was deleted. Publish a new release with a higher version. | +| `There is no Python package in src/` | Add your code as a folder with an `__init__.py` in `src/` (see [Upload external code](external_code_upload.md)), or delete the variable `PYPI_PUBLISH`. | +| `... also publishes to PyPI` | Another workflow of the repository uploads to PyPI too. Keep one: delete the variable `PYPI_PUBLISH`, or delete the other workflow. | +| `distribution.pip of labconstrictor-app.yaml is ..., but setup.py names the package ...` | Make the two names the same. | +| `PyPI refuses a package whose dependency is a URL` | `setup.py` lists a dependency as `name @ git+https://...`. Publish that dependency on PyPI and name it with a version, or move the URL to `requirements.txt` (the installer still installs it; the PyPI package leaves it out). | +| `setup.py still has the template placeholder ...` | Replace the placeholder in `setup.py` (the log says which), commit, and publish a new release. | +| The upload job waits | The `pypi` environment has required reviewers (Settings > Environments > pypi): one of them approves the upload in the run. | + +After a fix, re-run the failed jobs of the run if nothing in the repository changed (a publisher fixed on pypi.org); otherwise publish a new release. See [the design note of template 0.1.25](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_25.md). + +--- + +
+ +[โ† Previous](workflow_status.md)            +[๐Ÿ  Home](README.md)            +[Next โ†’](personal_access_token.md) + + +
diff --git a/.tools/docs/troubleshooting_installed_app.md b/.tools/docs/troubleshooting_installed_app.md new file mode 100644 index 0000000..d186437 --- /dev/null +++ b/.tools/docs/troubleshooting_installed_app.md @@ -0,0 +1,68 @@ +# Troubleshooting an installed app + +Problems with an app on your computer, after you installed it. For problems with your repository on GitHub, see [Troubleshooting repository setup](troubleshooting.md). + +## App still appears in the Windows Installed apps list after uninstalling + +On Windows, it may happen that, after uninstalling the app from `Settings > Apps > Installed apps` as explained in the [uninstalling guide](./download_executable.md), the app still appears in the list and does not allow you to uninstall it again, showing a message like: + +![Uninstall error message](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/troubleshooting/Not_Uninstall.png) + +The solution is to go to the Control Panel and uninstall it from there. To do this: + +1. Open the Control Panel. You can search for it in the Windows search bar. +2. Go to `Programs > Programs and Features`. +3. Find the LabConstrictor-based app in the list, right-click on it, and select `Uninstall`. +4. A message may appear saying something like: "An error occurred while trying to uninstall xxx. It might have already been uninstalled." Click `Yes` to confirm. + +This should remove the app even if the previous error message appears. + +## Windows asks for administrator rights for python.exe while uninstalling + +Uninstalling an app made with template 0.1.20 or earlier may show a User Account Control prompt: "Do you want to allow this app from an unknown publisher to make changes to your device? python.exe", with the program location `"\python.exe" -m conda.core.initialize ...`. + +The prompt is not needed. Click **No**. The uninstaller then shows a "Failed to clean AutoRun" error with Abort, Retry and Ignore: click **Ignore**. The uninstall finishes normally and nothing outside the app folder is changed. Clicking **Yes** does not help: the same step fails again and shows the same error, and **Retry** asks a second time. + +Do not click **Abort**, even though it is the default button: it stops the uninstall halfway and leaves the app folder on disk. If that happened, run `Uninstall-.exe` in the app folder again. + +The cause is a conda bug in the tool that built the installer (conda/conda#16856). Installers built with template 0.1.21 or later do not have it; see [migration_0_1_21.md](migration_0_1_21.md). + +## The notebook fails with "No module named ..." although the installation finished + +If someone once ran `python -m ipykernel install --user` on the computer (common with Anaconda or pip setups), Jupyter has a personal "python3" kernel in the user's folder (`~/.local/share/jupyter/kernels/python3` on Linux, `~/Library/Jupyter/kernels/python3` on macOS, `%APPDATA%\jupyter\kernels\python3` on Windows). Apps made with template 0.1.23 or earlier then run their notebooks in that other Python, and the first cell that imports the app fails with `ModuleNotFoundError: No module named ''`. + +Install a release made with template 0.1.24 or later: its launcher always uses the app's own kernel. Until then, removing that personal kernel folder also works, but it affects the other Jupyter installations that use it. See [migration_0_1_24.md](migration_0_1_24.md). + +## My changes to a notebook are gone after an update + +Since template 0.1.31, the **Update** button of the Welcome notebook keeps your copy before it replaces a notebook: look for `.backup-.ipynb` in the same folder, and open it in JupyterLab. Apps made with template 0.1.30 or earlier replace the notebook without a copy. + +## JupyterLab does not start because Windows reports an ASN.1 certificate error + +LabConstrictor-based installers include a TLS-resilient launcher. It attempts +native operating-system certificate verification before JupyterLab imports +Tornado and provides a verified CA-bundle fallback when a malformed Windows +certificate-store entry cannot be parsed. SSL and hostname verification are +never disabled. + +The constructor environment intentionally does not include +`pip-system-certs`. Its automatic Python startup hook can fail before the +application launcher has an opportunity to select the verified fallback. +Post-install pip commands instead use an explicit CA bundle while preserving +certificate verification. + +Diagnostic information is written to `launcher_debug.log` and +`menuinst_debug.log` in the installation directory. Maintainers can run the +same preflight used by the installer with: + +```text +\python.exe \PROJECT_NAME\launch_jupyter.py --self-test +``` + +The self-test reports the project-specific CA override variable. It is derived +from the application name by replacing punctuation and spaces with underscores +and converting it to uppercase, for example `MY_PROJECT_CA_BUNDLE`. All +LabConstrictor-based applications also accept the shared +`LABCONSTRICTOR_CA_BUNDLE` variable. Set either variable to an organization PEM +bundle before installation or launch when a private certificate authority is +required. diff --git a/.tools/docs/use_cases.md b/.tools/docs/use_cases.md new file mode 100644 index 0000000..9d3e328 --- /dev/null +++ b/.tools/docs/use_cases.md @@ -0,0 +1,20 @@ +# LabConstrictor use cases + +Here are some tools that have already been created using LabConstrictor: + - [VLab4Mic](#vlab4mic) + +## VLab4Mic + +

+ 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/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:** + +Determining whether a microscopy experiment can resolve a specific feature of a protein assembly remains difficult because researchers must balance imaging modality, labelling strategy, and probe choice. We present VLab4Mic, a simulation platform that predicts structural resolvability before experiments. Starting from atomic models from the PDB or AlphaFold predictions, VLab4Mic places antibodies, nanobodies, chemical linkers, or fluorescent proteins on epitopes, applies stochastic labelling and steric constraints, and generates virtual samples for widefield, confocal, AiryScan, Stimulated Emission Depletion (STED), and Single-Molecule Localisation Microscopy (SMLM). Comparisons with nuclear pore complex data show realistic agreement across modalities. Case studies show that HIV capsid appearance depends strongly on orientation, and that STED and SMLM distinguish domed from flat clathrin lattices, whereas confocal and AiryScan struggle. VLab4Mic thereby helps researchers predict which biological questions are experimentally tractable with a given imaging configuration before spending time finetuning imaging parameters at the microscope. + +A Bluesky post about VLab4Mic: [VLab4Mic on Bluesky](https://bsky.app/profile/henriqueslab.bsky.social/post/3mnw2p2j5pk24). diff --git a/.tools/docs/workflow_status.md b/.tools/docs/workflow_status.md new file mode 100644 index 0000000..785917f --- /dev/null +++ b/.tools/docs/workflow_status.md @@ -0,0 +1,45 @@ +# Check the status of GitHub workflows + +When you upload a notebook or make a release, GitHub Actions starts a workflow to check your code and build the installers. The template synchronization workflow additionally requires the one-time [`LABCONSTRICTOR_SYNC_TOKEN` setup](template_synchronization.md). + +## 1. Monitor the Progress + +1. Go to the **Actions** tab in your GitHub repository. +2. Youโ€™ll see a list of recent workflows. Find the one that matches your latest commit or release. +3. Check the status icon next to the workflow name: + +![GitHub Actions Status Icons](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/actions_status_icons.png) + +## 2. How to Debug a Failure + +If the workflow fails, donโ€™t worry. The system creates an error log thatโ€™s ready for you to use. + +1. **Download the Log:** + * Click on the failed workflow run. + * Scroll down to the bottom of the page to the **Artifacts** section. + * Download the log file listed there (it is a plain `.log` text file, nothing to unzip). + +2. **Copy & Paste into AI:** + * Open the log file in any text editor. + * **This file is already formatted as a prompt.** It includes all the context and error details you need. + * Just **copy all the text** and paste it into your preferred AI tool (like ChatGPT, Gemini, or Claude). The AI will explain the error and show you how to fix your notebook or `requirements.yaml`. + +--- + +### ๐Ÿ’ก Best Practice for Large Updates + +If youโ€™re planning a big update, like changing several notebooks or adding complex dependencies, donโ€™t push straight to the main branch. + +Instead, **create a new branch**, make your changes there, and check that the workflows pass (โœ…) before merging into the main branch. This helps keep your live app working. + +--- + +
+ +โ† Previous            +[๐Ÿ  Home](README.md)            +[Next โ†’](troubleshooting.md) + + +
+ diff --git a/.tools/meta/src_change.yaml b/.tools/meta/src_change.yaml new file mode 100644 index 0000000..9579048 --- /dev/null +++ b/.tools/meta/src_change.yaml @@ -0,0 +1 @@ +src_last_modified: "2026-11-07_08:21:40" diff --git a/.tools/notebooks/Requirements_Generator.ipynb b/.tools/notebooks/Requirements_Generator.ipynb new file mode 100644 index 0000000..0626fef --- /dev/null +++ b/.tools/notebooks/Requirements_Generator.ipynb @@ -0,0 +1,1353 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "aad8538a", + "metadata": { + "id": "aad8538a" + }, + "source": [ + "# Generate your requirements file\n", + "\n", + "This notebook exports the current environment's package requirements to a `requirements` file. This file is really important as you will need it to upload it together with the notebook into your repository. Please, run the code cell bellow and follow the steps.\n", + "\n", + "> **IMPORANT**: Make sure that you are running this notebook in the same environment you used to run the notebook you are uploading." + ] + }, + { + "cell_type": "markdown", + "id": "bde8848f", + "metadata": {}, + "source": [ + "# Step 0: Import main functionalities" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf3d64d2", + "metadata": { + "cellView": "form", + "collapsed": false, + "id": "bf3d64d2", + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @markdown Run this cell to import main functionalities\n", + "\n", + "# First of all check if ipywidgets is installed, if not through an informative error\n", + "try:\n", + " import ipywidgets as widgets\n", + "except ImportError:\n", + " raise ImportError(\"ipywidgets is not installed. Please install it using 'pip install ipywidgets' or 'conda install -c conda-forge ipywidgets'.\")\n", + "\n", + "# For the requirements extraction we will need nbformat and pyyaml installed, also check for them\n", + "try:\n", + " import nbformat\n", + "except ImportError:\n", + " raise ImportError(\"nbformat is not installed. Please install it using 'pip install nbformat' or 'conda install -c conda-forge nbformat'.\")\n", + "\n", + "try:\n", + " import yaml\n", + "except ImportError:\n", + " raise ImportError(\"pyyaml is not installed. Please install it using 'pip install pyyaml' or 'conda install -c conda-forge pyyaml'.\")\n", + "\n", + "from IPython.display import display\n", + "from pathlib import Path\n", + "import importlib.metadata\n", + "import subprocess\n", + "import contextlib\n", + "import importlib\n", + "import platform\n", + "import nbformat\n", + "import yaml\n", + "import re\n", + "import sys\n", + "import os\n", + "import io\n", + "import html\n", + "import shutil\n", + "import tempfile\n", + "import uuid\n", + "\n", + "import_regex = r'^[ \\t]*import .*'\n", + "from_regex = r'^[ \\t]*from .* import .*'\n", + "\n", + "LOCAL_SCAN_EXTENSIONS = {'.py'}\n", + "LOCAL_SCAN_LIMIT = 200 # fail-safe limit to avoid scanning huge trees\n", + "LOCAL_SCAN_PREVIEW = 8\n", + "GITHUB_CLONE_ROOT = Path(tempfile.gettempdir()) / \"requirements_helper_repos\"\n", + "\n", + "\n", + "def extract_code_import_lines(code):\n", + " list_import_lines = []\n", + "\n", + " # We are going line by line analyzing them\n", + " lines = code.split('\\n')\n", + " for line in lines:\n", + " if re.match(import_regex, line) or re.match(from_regex, line):\n", + " list_import_lines.append(line.strip())\n", + " return list_import_lines\n", + "\n", + "def extract_imported_packages(code):\n", + " list_import_packages = []\n", + " lines = code.split('\\n')\n", + " for line in lines:\n", + " line = line.strip()\n", + "\n", + " # Handle \"import X\" or \"import X, Y\" or \"import X as Y\"\n", + " if re.match(import_regex, line):\n", + " # Extract package name after 'import'\n", + " match = re.search(r'import\\s+(.+)', line)\n", + " if match:\n", + " packages = match.group(1).split(',') # Handle multiple imports\n", + " for pkg in packages:\n", + " pkg = pkg.split(' as ')[0].strip() # Remove \"as alias\"\n", + " pkg = pkg.split('.')[0] # Get root package only\n", + " if pkg:\n", + " list_import_packages.append(pkg)\n", + "\n", + " # Handle \"from X import Y\"\n", + " elif re.match(from_regex, line):\n", + " # Extract module name after 'from'\n", + " match = re.search(r'from\\s+([^\\s]+)\\s+import', line)\n", + " if match:\n", + " module = match.group(1).split('.')[0] # Get root package\n", + " if module and module != '.': # Skip relative imports\n", + " list_import_packages.append(module)\n", + "\n", + " return list_import_packages\n", + "\n", + "def extract_pip_install(code):\n", + " list_pip_install_lines = []\n", + " lines = code.split('\\n')\n", + "\n", + " for line in lines:\n", + " line = line.strip()\n", + "\n", + " # Skip empty lines and comments\n", + " if not line or line.startswith('#'):\n", + " continue\n", + "\n", + " # Check if line starts with ! or %\n", + " if line.startswith('!') or line.startswith('%'):\n", + " # Remove the leading ! or %\n", + " clean_command = line[1:].strip()\n", + "\n", + " # Verify it contains 'install' keyword\n", + " if 'install' in clean_command:\n", + " # Remove trailing comments if present\n", + " if '#' in clean_command:\n", + " clean_command = clean_command.split('#')[0].strip()\n", + "\n", + " list_pip_install_lines.append(clean_command)\n", + "\n", + " return list_pip_install_lines\n", + "\n", + "def is_builtin_or_stdlib(package_name):\n", + " \"\"\"Check if a package is a built-in or standard library module.\"\"\"\n", + " if package_name in sys.builtin_module_names:\n", + " return True\n", + "\n", + " if hasattr(sys, 'stdlib_module_names') and package_name in sys.stdlib_module_names:\n", + " return True\n", + "\n", + " # Fallback: common stdlib modules for older Python versions\n", + " stdlib_modules = {\n", + " 're', 'sys', 'os', 'platform', 'pathlib', 'json', 'math', 'random',\n", + " 'datetime', 'time', 'collections', 'itertools', 'functools', 'operator',\n", + " 'pickle', 'csv', 'sqlite3', 'threading', 'subprocess', 'shutil', 'glob',\n", + " 'io', 'codecs', 'logging', 'argparse', 'configparser', 'tempfile',\n", + " 'urllib', 'http', 'email', 'base64', 'hashlib', 'hmac', 'secrets',\n", + " 'struct', 'textwrap', 'string', 'warnings', 'contextlib', 'abc',\n", + " 'importlib', 'inspect', 'traceback', 'unittest', 'doctest', 'pdb',\n", + " 'profile', 'pstats', 'timeit', 'statistics', 'asyncio', 'concurrent',\n", + " 'socket', 'ssl', 'select', 'selectors', 'queue', 'multiprocessing',\n", + " 'copy', 'types', 'enum', 'dataclasses', 'typing', 'weakref',\n", + " 'array', 'heapq', 'bisect', 'graphlib', 'decimal', 'fractions',\n", + " 'numbers', 'cmath', 'zlib', 'gzip', 'bz2', 'lzma', 'tar', 'zipfile',\n", + " 'netrc', 'xdrlib', 'plistlib', 'html', 'xml',\n", + " 'webbrowser', 'cgi', 'wsgiref', 'uuid', 'socketserver', 'xmlrpc',\n", + " }\n", + "\n", + " return package_name in stdlib_modules\n", + "\n", + "\n", + "def is_environment_specific(package_name):\n", + " \"\"\"Check if a package is environment-specific and shouldn't be in requirements.\"\"\"\n", + " environment_specific = {\n", + " 'google',\n", + " 'google.colab',\n", + " 'colab',\n", + " 'IPython',\n", + " 'ipykernel',\n", + " 'jupyter',\n", + " 'jupyterlab',\n", + " }\n", + " return package_name in environment_specific\n", + "\n", + "\n", + "def package_exists_on_pypi(package_name):\n", + " \"\"\"Check if a package exists on PyPI using the PyPI JSON API.\"\"\"\n", + " try:\n", + " import requests\n", + " response = requests.get(f\"https://pypi.org/pypi/{package_name}/json\", timeout=2)\n", + " return response.status_code == 200\n", + " except:\n", + " return True\n", + "\n", + "\n", + "def get_package_version(package_name):\n", + " try:\n", + " module = importlib.import_module(package_name)\n", + " return module.__version__\n", + " except AttributeError:\n", + " try:\n", + " return importlib.metadata.version(package_name)\n", + " except:\n", + " return \"\"\n", + " except:\n", + " return \"\"\n", + "\n", + "\n", + "def get_package_name_for_pip(import_name):\n", + " \"\"\"\n", + " Convert import name to pip package name.\n", + " E.g., 'docx' -> 'python-docx', 'cv2' -> 'opencv-python'\n", + " \"\"\"\n", + " known_mappings = {\n", + " 'docx': 'python-docx',\n", + " 'cv2': 'opencv-python',\n", + " 'skimage': 'scikit-image',\n", + " 'PIL': 'Pillow',\n", + " 'yaml': 'pyyaml',\n", + " 'sklearn': 'scikit-learn',\n", + " 'bs4': 'beautifulsoup4',\n", + " 'dotenv': 'python-dotenv',\n", + " 'fpdf': 'fpdf2',\n", + " }\n", + "\n", + " if import_name in known_mappings:\n", + " return known_mappings[import_name]\n", + "\n", + " # Try to find via installed distributions\n", + " try:\n", + " for dist in importlib.metadata.distributions():\n", + " try:\n", + " top_level = dist.read_text('top_level.txt')\n", + " if top_level and import_name in top_level.split('\\n'):\n", + " return dist.name\n", + " except:\n", + " pass\n", + " except:\n", + " pass\n", + "\n", + " # Fallback: assume import name is correct\n", + " return import_name\n", + "\n", + "\n", + "def load_pip_freeze_requirements():\n", + " mapping = {}\n", + " try:\n", + " result = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'], text=True)\n", + " except Exception:\n", + " return mapping\n", + "\n", + " for raw_line in result.splitlines():\n", + " line = raw_line.strip()\n", + " if not line or line.startswith('#'):\n", + " continue\n", + "\n", + " requirement = line\n", + " key = None\n", + "\n", + " if line.startswith('-e '):\n", + " entry = line[3:].strip()\n", + " if '#egg=' in entry:\n", + " key = entry.split('#egg=', 1)[1]\n", + " elif ' @ ' in entry:\n", + " key = entry.split(' @ ', 1)[0]\n", + " requirement = entry\n", + "\n", + " elif ' @ ' in line:\n", + " key = line.split(' @ ', 1)[0]\n", + "\n", + " elif '==' in line:\n", + " key = line.split('==', 1)[0]\n", + "\n", + " elif '#egg=' in line:\n", + " key = line.split('#egg=', 1)[1]\n", + "\n", + " else:\n", + " key = line\n", + "\n", + " if key:\n", + " mapping[key.strip().lower()] = requirement\n", + "\n", + " return mapping\n", + "\n", + "\n", + "def requirement_from_pip_freeze(import_name, pip_freeze_requirements):\n", + " lower_name = import_name.lower()\n", + " if lower_name in pip_freeze_requirements:\n", + " return pip_freeze_requirements[lower_name]\n", + "\n", + " pip_name = get_package_name_for_pip(import_name)\n", + " if pip_name and pip_name.lower() in pip_freeze_requirements:\n", + " return pip_freeze_requirements[pip_name.lower()]\n", + "\n", + " return None\n", + "\n", + "def sanitize_path_input(raw):\n", + " \"\"\"\n", + " Turn a user-pasted path into a safe Path without using `os`.\n", + " - Strips ASCII + smart quotes and surrounding punctuation\n", + " - Expands ~ to the user home directory\n", + " - Replaces common Windows placeholders (%USERPROFILE%, %HOMEPATH%) with the home dir\n", + " - Normalises mixed slashes\n", + " \"\"\"\n", + " s = str(raw or \"\").strip()\n", + " if not s:\n", + " return Path(\"\")\n", + "\n", + " # Remove all kinds of quotes people paste (ASCII and curly/smart quotes)\n", + " s = re.sub(r'[\\\"\\'\\u201c\\u201d\\u2018\\u2019]', \"\", s)\n", + "\n", + " # Trim accidental leading/trailing punctuation or commas\n", + " s = s.strip(\" \\t\\n\\r,;<>\")\n", + "\n", + " # Expand ~ at the start to the user's home dir\n", + " home = Path.home().as_posix()\n", + " if s == \"~\":\n", + " s = home\n", + " elif s.startswith(\"~/\") or s.startswith(\"~\\\\\"):\n", + " s = home + s[1:]\n", + "\n", + " # Common Windows env placeholders -> expand to home (no os.environ access here)\n", + " # This covers the most common pasted forms like %USERPROFILE%\\Documents\n", + " s = s.replace(\"%USERPROFILE%\", home)\n", + " s = s.replace(\"%HOMEPATH%\", home)\n", + "\n", + " # Replace repeated backslash-quote artefacts that sometimes appear from copy/paste\n", + " s = s.replace('\\\\\"', '').replace(\"\\\\'\", \"\")\n", + "\n", + " # Normalise forward/back slashes to the OS-agnostic form; Path() will handle exact OS semantics\n", + " s = s.replace(\"/\", str(Path.home()).startswith(\"\\\\\") and \"\\\\\" or \"/\") if False else s # noop kept explicit: Path handles slashes\n", + "\n", + " # Final strip (in case replacements introduced new edge whitespace/punctuation)\n", + " s = s.strip(\" \\t\\n\\r,;<>\")\n", + "\n", + " return Path(s)\n", + "\n", + "\n", + "def parse_local_path_entries(multiline_text):\n", + " \"\"\"\n", + " Convert newline-separated user input into Path objects that exist on disk.\n", + " Returns a tuple (paths, errors).\n", + " \"\"\"\n", + " if not multiline_text:\n", + " return [], []\n", + "\n", + " parsed_paths = []\n", + " errors = []\n", + " seen = set()\n", + "\n", + " for raw_line in multiline_text.splitlines():\n", + " trimmed = raw_line.strip()\n", + " if not trimmed:\n", + " continue\n", + "\n", + " candidate = sanitize_path_input(trimmed).expanduser()\n", + " if not str(candidate):\n", + " continue\n", + "\n", + " if not candidate.exists():\n", + " errors.append(f\"{trimmed} (path not found)\")\n", + " continue\n", + "\n", + " try:\n", + " resolved = candidate.resolve()\n", + " except Exception:\n", + " resolved = candidate\n", + "\n", + " key = str(resolved)\n", + " if key in seen:\n", + " continue\n", + " seen.add(key)\n", + " parsed_paths.append(resolved)\n", + "\n", + " return parsed_paths, errors\n", + "\n", + "\n", + "def expand_local_entries(entries, limit=LOCAL_SCAN_LIMIT):\n", + " \"\"\"\n", + " Expand a list of file/folder entries into individual files we can scan.\n", + " Returns (files, warnings). Only .py files are considered.\n", + " \"\"\"\n", + " expanded_files = []\n", + " warnings = []\n", + " seen = set()\n", + "\n", + " def register_file(file_path):\n", + " try:\n", + " resolved = file_path.resolve()\n", + " except Exception:\n", + " resolved = file_path\n", + "\n", + " key = str(resolved)\n", + " if key in seen:\n", + " return True\n", + "\n", + " if limit and len(expanded_files) >= limit:\n", + " return False\n", + "\n", + " seen.add(key)\n", + " expanded_files.append(resolved)\n", + " return True\n", + "\n", + " for entry in entries:\n", + " try:\n", + " if entry.is_file():\n", + " if entry.suffix.lower() in LOCAL_SCAN_EXTENSIONS:\n", + " if not register_file(entry):\n", + " warnings.append(\n", + " f\"Reached the scan limit ({limit} files). Remaining files were skipped.\"\n", + " )\n", + " break\n", + " else:\n", + " warnings.append(f\"{entry} (unsupported file type)\")\n", + " elif entry.is_dir():\n", + " found_any = False\n", + " for suffix in LOCAL_SCAN_EXTENSIONS:\n", + " for candidate in sorted(entry.rglob(f\"*{suffix}\")):\n", + " found_any = True\n", + " if not register_file(candidate):\n", + " warnings.append(\n", + " f\"Reached the scan limit ({limit} files). Remaining files were skipped.\"\n", + " )\n", + " return expanded_files, warnings\n", + " if not found_any:\n", + " warnings.append(f\"{entry} (no .py files found)\")\n", + " else:\n", + " warnings.append(f\"{entry} (not a file or folder)\")\n", + " except Exception as exc:\n", + " warnings.append(f\"{entry}: {exc}\")\n", + "\n", + " return expanded_files, warnings\n", + "\n", + "\n", + "\n", + "def _create_clone_destination():\n", + " GITHUB_CLONE_ROOT.mkdir(parents=True, exist_ok=True)\n", + " return GITHUB_CLONE_ROOT / f\"repo_{uuid.uuid4().hex}\"\n", + "\n", + "def clone_github_repository(repo_url, branch=None):\n", + " if shutil.which('git') is None:\n", + " raise RuntimeError(\"Git is not available in this environment. Please install Git to add helper repositories.\")\n", + " destination = _create_clone_destination()\n", + " cmd = ['git', 'clone', '--depth', '1']\n", + " if branch:\n", + " cmd += ['--branch', branch]\n", + " cmd += [repo_url, str(destination)]\n", + " try:\n", + " subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True)\n", + " except subprocess.CalledProcessError as exc:\n", + " raise RuntimeError(\"Git clone failed: \" + exc.output.strip()) from exc\n", + " except FileNotFoundError:\n", + " raise RuntimeError(\"Git is not installed or not on PATH. Please install Git to add helper repositories.\")\n", + " return destination\n", + "\n", + "def fetch_github_helper_path(repo_url, repo_subpath=\"\", branch=\"\"):\n", + " repo_url = (repo_url or '').strip()\n", + " if not repo_url:\n", + " raise ValueError(\"Please provide a GitHub repository URL.\")\n", + " repo_subpath = (repo_subpath or '').strip().strip('\\\\/')\n", + " branch = (branch or '').strip()\n", + "\n", + " cloned_repo = clone_github_repository(repo_url, branch or None)\n", + " helper_root = cloned_repo / repo_subpath if repo_subpath else cloned_repo\n", + "\n", + " if not helper_root.exists():\n", + " raise FileNotFoundError(\n", + " f\"Path '{repo_subpath or '.'}' was not found inside the repository {repo_url}.\"\n", + " )\n", + "\n", + " return helper_root\n", + "\n", + "def resolve_ipywidgets_version(py_version):\n", + " try:\n", + " py_major, py_minor = map(int, py_version.split(\".\")[:2])\n", + " \n", + " if py_major >= 3 and py_minor >= 9:\n", + " return \"8.1.7\" # Latest stable for modern Python + JupyterLab 4\n", + " elif py_major >= 3 and py_minor >= 7:\n", + " return \"8.1.6\" # Good for Python 3.7+\n", + " else:\n", + " return \"7.7.2\" # Fallback for older environments\n", + " except Exception:\n", + " return \">=7.0.0\" # Safe fallback\n", + "\n", + "def is_colab():\n", + " return \"COLAB_RELEASE_TAG\" in os.environ or \"COLAB_GPU\" in os.environ\n", + "\n", + "\n", + "def render_section(content_container, *objs):\n", + " \"\"\"Render downstream UI inside a single widget container (or fallback to display).\"\"\"\n", + " if content_container is not None:\n", + " content_container.children = tuple(objs)\n", + " else:\n", + " display(*objs)\n", + "\n", + "display(widgets.HTML(\"โœ… Core functionalities loaded! Start with Step 1.\"))" + ] + }, + { + "cell_type": "markdown", + "id": "c788a83f", + "metadata": {}, + "source": [ + "# Step 1: Select the notebook you want to extract requirements from" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "be3f07e9", + "metadata": {}, + "outputs": [], + "source": [ + "# @markdown Run this cell to choose notebook\n", + "\n", + "colab_flag = is_colab()\n", + "\n", + "mount_title = widgets.HTML(\n", + " \"

1.- Click the button to mount your Google Drive

\"\n", + ")\n", + "mount_btn = widgets.Button(\n", + " description=\"Mount Google Drive\",\n", + " button_style=\"info\",\n", + " layout=widgets.Layout(width=\"100%\")\n", + ")\n", + "mount_status = widgets.HTML(\"\")\n", + "\n", + "colab_find_notebook = widgets.HTML(\n", + " \"

2.- Find your notebook

\"\n", + " \"
    \"\n", + " \"
  1. On the left sidebar, click on the folder icon to open the file explorer.
  2. \"\n", + " \"
  3. You should see a `drive` folder, otherwise go back to Step 1.
  4. \"\n", + " \"
  5. Go to drive > MyDrive. There you will find your Google Drive files.
  6. \"\n", + " \"
  7. Locate the notebook you want to extract requirements from. Notebook are stored by default in Colab Notebooks folder.
  8. \"\n", + " \"
\"\n", + "\n", + " \"

What if I cannot find my notebook?

\"\n", + " \"It might happen that your notebook is not stored in Google Drive. Do you have it stored locally on your computer?\"\n", + " \"
    \"\n", + " \"
  • If yes, drag and drop it in Colab's file explorer for a single use or upload it to Google Drive for persistent storage.
  • \"\n", + " \"
  • If not, you can download it from wherever you have it stored (e.g., GitHub, email, etc.) and then upload it to Google Drive or directly to Colab.
  • \"\n", + " \"
\"\n", + " \"In case the notebook is in another Colab session you can always download it following these steps:\"\n", + " \"
    \"\n", + " \"
  1. Open the Colab session where your notebook is.
  2. \"\n", + " \"
  3. On top, go to File > Download > Download .ipynb.
  4. \"\n", + " \"
\"\n", + ")\n", + "colab_path_title = widgets.HTML(\n", + " \"

3.- Provide a notebook path

\"\n", + " \"Right-click on the notebook on Colab's file explorer and select 'Copy path'.
\"\n", + " \"Then paste the full path below and click 'Use this notebook'.\"\n", + ")\n", + "\n", + "local_find_notebook = widgets.HTML(\n", + " \"

1.- Locate your local notebook

\"\n", + " \"Please make sure you know the full path to your local notebook file (with .ipynb extension).\"\n", + ")\n", + "\n", + "local_path_title = widgets.HTML(\n", + " \"

2.- Provide a notebook path

\"\n", + " \"Please paste the full path to your local notebook below and click 'Use this notebook'.\"\n", + ")\n", + "path_widget = widgets.Text(\n", + " placeholder=\"/content/drive/MyDrive/your_notebook.ipynb\" if colab_flag else \"path/to/your_notebook.ipynb\",\n", + " description=\"Notebook path:\",\n", + " layout=widgets.Layout(width=\"99%\"),\n", + " style={'description_width': 'initial'}\n", + ")\n", + "path_status = widgets.HTML(\"\")\n", + "\n", + "use_btn = widgets.Button(\n", + " description=\"Use this notebook\",\n", + " button_style=\"success\",\n", + " layout=widgets.Layout(width=\"99%\")\n", + ")\n", + "\n", + "nb_path = None\n", + "\n", + "def on_mount(_):\n", + " try:\n", + " from google.colab import drive\n", + " with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):\n", + " drive.mount(\"/content/drive\", force_remount=True)\n", + " mount_status.value = \"โœ… Drive mounted. Update the path if needed, then click 'Use this notebook'.\"\n", + " except Exception as e:\n", + " mount_status.value = f\"โŒ Drive mount failed: {str(e)}\"\n", + "\n", + "def on_use(_):\n", + " global nb_path\n", + " nb_path = sanitize_path_input(path_widget.value).expanduser()\n", + "\n", + " # Allow folder input: if it's a directory, try to find .ipynb inside it\n", + " if nb_path.exists() and nb_path.is_dir():\n", + " nbs = sorted(nb_path.glob(\"*.ipynb\"))\n", + " if len(nbs) == 1:\n", + " nb_path = nbs[0]\n", + " elif len(nbs) > 1:\n", + " path_status.value = \"โŒ Multiple notebooks found in that folder. Please paste the full .ipynb path.\"\n", + " return\n", + " else:\n", + " path_status.value = \"โŒ No .ipynb files found in that folder. Please paste a full .ipynb path.\"\n", + " return\n", + "\n", + " if not nb_path.exists() or nb_path.suffix != \".ipynb\":\n", + " if colab_flag:\n", + " path_status.value = (\n", + " \"โŒ Invalid path. Please paste a valid .ipynb path and try again, e.g., \"\n", + " \"/content/drive/MyDrive/Colab Notebooks/your_notebook.ipynb\"\n", + " )\n", + " else:\n", + " path_status.value = (\n", + " \"โŒ Invalid path. Please paste an absolute path to a valid local .ipynb path and try again. For example: \"\n", + " \"
    \"\n", + " r\"
  • C:\\Users\\YourName\\Notebooks\\your_notebook.ipynb (Windows)
  • \"\n", + " \"
  • /home/yourname/notebooks/your_notebook.ipynb (Linux/Mac)
  • \"\n", + " \"
\"\n", + " )\n", + " return\n", + "\n", + " path_status.value = f\"โœ… You have chosen: {nb_path}\"\n", + " path_status.value += \"
If the notebook is correct, please go to Step 2.\"\n", + "\n", + "if 'import_regex' not in globals():\n", + " display(widgets.HTML(\"โŒ Main functionalities not loaded. Please go to Step 0 to import them.\"))\n", + "else:\n", + " if colab_flag:\n", + " mount_btn.on_click(on_mount)\n", + " use_btn.on_click(on_use)\n", + "\n", + " if colab_flag:\n", + " layout_children = [\n", + " mount_title,\n", + " mount_btn,\n", + " mount_status,\n", + " colab_find_notebook,\n", + " colab_path_title,\n", + " ]\n", + " else:\n", + " layout_children = [\n", + " local_find_notebook,\n", + " local_path_title,\n", + " ]\n", + "\n", + " layout_children.extend([path_widget, use_btn, path_status])\n", + " container = widgets.VBox(layout_children, layout=widgets.Layout(width=\"100%\"))\n", + " display(container)" + ] + }, + { + "cell_type": "markdown", + "id": "30933a7d", + "metadata": {}, + "source": [ + "# Step 2: Choose whether to include additional helper files (local or GitHub) for the requirements extraction\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "82540b12", + "metadata": {}, + "outputs": [], + "source": [ + "# @markdown Run this cell to choose whether to include additional local files for the requirements extraction\n", + "if 'import_regex' not in globals():\n", + " display(widgets.HTML(\"❌ Main functionalities not loaded. Please go to Step 0 to import them.\"))\n", + "elif 'nb_path' not in globals() or nb_path is None:\n", + " display(widgets.HTML(\"❌ No notebook selected. Please go to Step 1 and select a notebook to extract requirements.\"))\n", + "else:\n", + " instructions = widgets.HTML(\n", + " f\"

๐Ÿ’ป Include helper modules stored locally

\"\n", + " \"

If your notebook imports functions or classes from local .py files, list those paths below (one per line) so we can scan them for dependencies.

\"\n", + " \"
    \"\n", + " \"
  • Paths can be absolute or relative to the current working directory.
  • \"\n", + " \"
  • Only files ending in .py are processed. Notebook files and other extensions are ignored.
  • \"\n", + " \"
  • Folders are scanned recursively for .py files.
  • \"\n", + " f\"
  • To keep things fast we scan up to {LOCAL_SCAN_LIMIT} files.
  • \"\n", + " \"
  • Leave the field empty or click skip if there are no helper modules.
  • \"\n", + " \"
\"\n", + " )\n", + " paths_input = widgets.Textarea(\n", + " placeholder=\"e.g.\\nsrc/helpers.py\\ncustom_layers/\\n../shared/utils/data_loader.py\",\n", + " description='Local files/folders:',\n", + " layout=widgets.Layout(width='99%', height='140px'),\n", + " style={'description_width': 'initial'}\n", + " )\n", + " scan_btn = widgets.Button(\n", + " description='Scan paths and continue',\n", + " button_style='info',\n", + " layout=widgets.Layout(width='50%')\n", + " )\n", + " skip_btn = widgets.Button(\n", + " description='Skip (no extra files)',\n", + " layout=widgets.Layout(width='50%')\n", + " )\n", + " status = widgets.HTML()\n", + "\n", + " github_instructions = widgets.HTML(\n", + " \"

๐ŸŒ Include helper modules from GitHub repositories

\"\n", + " \"

If the helper .py files live in another repository, provide its URL along with the folder (or file) path inside it.

\"\n", + " \"
    \"\n", + " \"
  • Repositories are downloaded to a temporary folder for this session.
  • \"\n", + " \"
  • Only .py files in the paths you specify are scanned.
  • \"\n", + " \"
  • Optionally set a branch name if you do not want the default branch.
  • \"\n", + " \"
  • You can add as many repositories as needed.
  • \"\n", + " \"
\"\n", + " )\n", + " repo_url_input = widgets.Text(\n", + " placeholder=\"https://github.com/owner/repo.git\",\n", + " description='Repository URL:',\n", + " layout=widgets.Layout(width='99%'),\n", + " style={'description_width': 'initial'}\n", + " )\n", + " repo_branch_input = widgets.Text(\n", + " placeholder=\"main (optional)\",\n", + " description='Branch (optional):',\n", + " layout=widgets.Layout(width='99%'),\n", + " style={'description_width': 'initial'}\n", + " )\n", + " repo_subpath_input = widgets.Text(\n", + " placeholder=\"path/in/repo (leave blank for entire repo)\",\n", + " description='Helper path:',\n", + " layout=widgets.Layout(width='99%'),\n", + " style={'description_width': 'initial'}\n", + " )\n", + " add_repo_btn = widgets.Button(\n", + " description='Add GitHub helper files',\n", + " button_style='info',\n", + " layout=widgets.Layout(width='50%')\n", + " )\n", + " clear_repo_btn = widgets.Button(\n", + " description='Clear GitHub helpers',\n", + " layout=widgets.Layout(width='50%')\n", + " )\n", + " github_status = widgets.HTML()\n", + " github_summary = widgets.HTML(\"No GitHub helper folders added yet.\")\n", + "\n", + " entries = []\n", + " local_entries = []\n", + " github_entries = []\n", + " github_records = []\n", + "\n", + " def update_entries():\n", + " global entries\n", + " combined = []\n", + " seen = set()\n", + " for collection in (local_entries, github_entries):\n", + " for path in collection:\n", + " key = str(path)\n", + " if key in seen:\n", + " continue\n", + " seen.add(key)\n", + " combined.append(path)\n", + " entries = combined\n", + "\n", + " def render_github_summary():\n", + " if not github_records:\n", + " return \"No GitHub helper folders added yet.\"\n", + " value = \"
    \"\n", + " for record in github_records:\n", + " repo = html.escape(record['repo'])\n", + " branch = html.escape(record['branch']) if record['branch'] else \"\"\n", + " subpath = html.escape(record['subpath'])\n", + " local_path = html.escape(record['local'])\n", + " branch_suffix = f\" โžก๏ธ branch: {branch}\" if branch else \"\"\n", + " value += f\"
  • {repo}{branch_suffix} โžก๏ธ {subpath}
  • \"\n", + " value += \"
\"\n", + " return value\n", + "\n", + " update_entries()\n", + "\n", + " def handle_scan(_):\n", + " parsed, errors = parse_local_path_entries(paths_input.value)\n", + " local_entries.clear()\n", + " local_entries.extend(parsed)\n", + " update_entries()\n", + " if errors:\n", + " message = \"โŒ We could not find these paths:
    \"\n", + " for err in errors:\n", + " message += f\"
  • {html.escape(err)}
  • \"\n", + " message += \"
\"\n", + " status.value = message\n", + " return\n", + " if local_entries:\n", + " status.value = \"โœ… Your additional modules were successfully included and will be processed!\"\n", + " status.value += \"
โœ… Now, check if you want to include more helper files and if not, please go to the Step 3 to continue.\"\n", + " else:\n", + " status.value = \"โš ๏ธ No valid paths were provided. Only the notebook will be analyzed for requirements.\"\n", + " status.value += \"
โœ… Now, check if you want to include more helper files and if not, please go to the Step 3 to continue.\"\n", + "\n", + " def handle_skip(_):\n", + " local_entries.clear()\n", + " update_entries()\n", + " status.value = \"โš ๏ธ The scan was skipped. Only the notebook and any GitHub helpers you add will be analyzed.\"\n", + " status.value += \"
โœ… Now, check if you want to include more helper files and if not, please go to the Step 3 to continue.\"\n", + "\n", + " def handle_add_repo(_):\n", + " repo_url = repo_url_input.value.strip()\n", + " branch = repo_branch_input.value.strip()\n", + " subpath = repo_subpath_input.value.strip()\n", + " if not repo_url:\n", + " github_status.value = \"โŒ Please provide a valid GitHub repository URL.\"\n", + " return\n", + " try:\n", + " helper_path = fetch_github_helper_path(repo_url, subpath, branch)\n", + " except Exception as exc:\n", + " github_status.value = \"โŒ Unable to add GitHub helper files: \" + html.escape(str(exc))\n", + " return\n", + " helper_key = str(helper_path)\n", + " if any(str(path) == helper_key for path in github_entries):\n", + " github_status.value = \"โš ๏ธ That repository path has already been added.\"\n", + " return\n", + " github_entries.append(helper_path)\n", + " github_records.append({\n", + " 'repo': repo_url,\n", + " 'branch': branch,\n", + " 'subpath': subpath or '.',\n", + " 'local': helper_key,\n", + " })\n", + " update_entries()\n", + " github_summary.value = render_github_summary()\n", + " github_status.value = \"โœ… GitHub helper files added. They will be processed with your notebook.\"\n", + " github_status.value += \"
โœ… Now, check if you want to include more helper files and if not, please go to the Step 3 to continue.\"\n", + "\n", + " def handle_clear_repos(_):\n", + " if not github_entries:\n", + " github_status.value = \"โš ๏ธ There are no GitHub helper entries to clear.\"\n", + " return\n", + " github_entries.clear()\n", + " github_records.clear()\n", + " update_entries()\n", + " github_summary.value = render_github_summary()\n", + " github_status.value = \"โš ๏ธ GitHub helper selections cleared. Only the notebook and local paths will be analyzed.\"\n", + "\n", + " scan_btn.on_click(handle_scan)\n", + " skip_btn.on_click(handle_skip)\n", + " add_repo_btn.on_click(handle_add_repo)\n", + " clear_repo_btn.on_click(handle_clear_repos)\n", + "\n", + " buttons_box = widgets.HBox(\n", + " [scan_btn, skip_btn],\n", + " layout=widgets.Layout(width='99%', justify_content='space-between')\n", + " )\n", + "\n", + " repo_buttons_box = widgets.HBox(\n", + " [add_repo_btn, clear_repo_btn],\n", + " layout=widgets.Layout(width='99%', justify_content='space-between')\n", + " )\n", + "\n", + " repo_inputs_box = widgets.VBox(\n", + " [repo_url_input, repo_branch_input, repo_subpath_input],\n", + " layout=widgets.Layout(width='99%')\n", + " )\n", + "\n", + " github_summary.value = render_github_summary()\n", + "\n", + " display(\n", + " widgets.HTML(\"

๐Ÿ“ฅ Include helper modules:

\"),\n", + " github_instructions,\n", + " repo_inputs_box,\n", + " repo_buttons_box,\n", + " github_status,\n", + " github_summary,\n", + " instructions,\n", + " paths_input,\n", + " buttons_box,\n", + " status,\n", + " )\n" + ] + }, + { + "cell_type": "markdown", + "id": "0543ae9f", + "metadata": {}, + "source": [ + "# Step 3: Check if provided files contain any Pypi installations" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5ab5c20", + "metadata": {}, + "outputs": [], + "source": [ + "# @markdown Run this cell to check if provided files contain any Pypi installations\n", + "def check_pip_install(notebook_path, additional_entries):\n", + " try:\n", + " colab_nb = nbformat.read(notebook_path, as_version=4)\n", + " except Exception as exc:\n", + " raise RuntimeError(\"Unable to read the selected notebook: \" + str(exc))\n", + "\n", + " try:\n", + " local_dependency_files, local_scan_warnings = expand_local_entries(\n", + " additional_entries,\n", + " limit=LOCAL_SCAN_LIMIT,\n", + " )\n", + " except Exception as exc:\n", + " raise RuntimeError(\"Failed to scan the provided paths: \" + str(exc))\n", + "\n", + " pip_install_lines = []\n", + "\n", + " for cell in colab_nb.cells:\n", + " if cell.cell_type == \"code\":\n", + " pip_install_lines.extend(extract_pip_install(cell.source))\n", + "\n", + " for local_file in local_dependency_files:\n", + " suffix = local_file.suffix.lower()\n", + " try:\n", + " if suffix == \".py\":\n", + " try:\n", + " code_blob = local_file.read_text(encoding=\"utf-8\")\n", + " except UnicodeDecodeError:\n", + " code_blob = local_file.read_text(encoding=\"utf-8\", errors=\"ignore\")\n", + " pip_install_lines.extend(extract_pip_install(code_blob))\n", + " else:\n", + " continue\n", + " except Exception as exc:\n", + " local_scan_warnings.append(f\"{local_file}: {exc}\")\n", + "\n", + " # Remove duplicates while preserving order\n", + " pip_install_lines = list(dict.fromkeys(pip_install_lines))\n", + "\n", + " display(widgets.HTML(f\"

Detected pip install commands

\"))\n", + "\n", + " if pip_install_lines:\n", + " from IPython import get_ipython\n", + " get_ipython().set_next_input(\"print('hello')\", replace=False)\n", + " explanation_html = widgets.HTML(\n", + " \"

The following pip install commands were detected in the notebook or the scanned helper .py files.

\"\n", + " \"Please ensure these packages are installed in order to be detected and included in the generated requirements.yaml file.
\"\n", + " \"If you want to install them now, we have facilitated you a code cell bellow this one with the code to install them, so please:\"\n", + " \"
    \"\n", + " \"
  1. Run the code cell below.
  2. \"\n", + " \"
  3. Wait for the installation to complete.
  4. \"\n", + " \"
  5. Delete the code cell and go to Step 4.
  6. \"\n", + " \"
\"\n", + " \"If you have already installed them, please delete the code cell bellow with the installation commands and continue to Step 4.\"\n", + " )\n", + " pip_installed_textarea = widgets.Textarea(\n", + " value=\"\\n\".join([f\"!{line}\" for line in pip_install_lines]),\n", + " description='Detected pip installs:',\n", + " layout=widgets.Layout(width='99%', height='100px'),\n", + " style={'description_width': 'initial'}\n", + " )\n", + "\n", + " installing_text = \"\\n\".join([f\"!{line}\" for line in pip_install_lines])\n", + " installing_text += \"\\nprint('โœ… Installation complete! Please, delete this code cell and go to Step 4.')\"\n", + " get_ipython().set_next_input(installing_text, replace=False)\n", + "\n", + " display(explanation_html, pip_installed_textarea)\n", + " else:\n", + " display(widgets.HTML(\"No pip install commands detected in the notebook or the scanned helper .py files.
โœ… Please continue to Step 4.\"))\n", + "\n", + "if 'import_regex' not in globals():\n", + " display(widgets.HTML(\"โŒ Main functionalities not loaded. Please go to Step 0 to import them.\"))\n", + "elif 'nb_path' not in globals() or nb_path is None:\n", + " display(widgets.HTML(\"โŒ No notebook selected. Please go to Step 1 and select a notebook to extract requirements.\"))\n", + "elif 'entries' not in globals() or entries is None:\n", + " display(widgets.HTML(\"โŒ No information about additional helper files (local or GitHub). Please go to Step 2 and choose whether to include additional helper files for the requirements extraction.\"))\n", + "else:\n", + " check_pip_install(nb_path, entries)" + ] + }, + { + "cell_type": "markdown", + "id": "1fce76ac", + "metadata": {}, + "source": [ + "# Step 4: Extract dependencies and generate the requirements file" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1bbb5bef", + "metadata": {}, + "outputs": [], + "source": [ + "# @markdown Run this cell to extract depenencies and generate the requirements file\n", + "def process_notebook(additional_entries, content_container, notebook_path, pip_freeze_requirements):\n", + " loading = widgets.HTML(\"Scanning notebook and selected files...\")\n", + " render_section(content_container, loading)\n", + "\n", + " try:\n", + " local_dependency_files, local_scan_warnings = expand_local_entries(\n", + " additional_entries,\n", + " limit=LOCAL_SCAN_LIMIT,\n", + " )\n", + " except Exception as exc:\n", + " render_section(\n", + " content_container,\n", + " widgets.HTML(\n", + " \"โŒ Failed to scan the provided paths: \"\n", + " + html.escape(str(exc))\n", + " )\n", + " )\n", + " return\n", + "\n", + " try:\n", + " colab_nb = nbformat.read(notebook_path, as_version=4)\n", + " except Exception as exc:\n", + " render_section(\n", + " content_container,\n", + " widgets.HTML(\n", + " \"โŒ Unable to read the selected notebook: \"\n", + " + html.escape(str(exc))\n", + " )\n", + " )\n", + " return\n", + "\n", + " # Gather imports\n", + " all_imports = []\n", + "\n", + " for cell in colab_nb.cells:\n", + " if cell.cell_type == \"code\":\n", + " all_imports.extend(extract_imported_packages(cell.source))\n", + " for local_file in local_dependency_files:\n", + " suffix = local_file.suffix.lower()\n", + " try:\n", + " if suffix == \".py\":\n", + " try:\n", + " code_blob = local_file.read_text(encoding=\"utf-8\")\n", + " except UnicodeDecodeError:\n", + " code_blob = local_file.read_text(encoding=\"utf-8\", errors=\"ignore\")\n", + " all_imports.extend(extract_imported_packages(code_blob))\n", + " else:\n", + " continue\n", + " except Exception as exc:\n", + " local_scan_warnings.append(f\"{local_file}: {exc}\")\n", + "\n", + " # Remove duplicates while preserving order\n", + " all_imports = list(dict.fromkeys(all_imports))\n", + "\n", + " # Process packages to get versions\n", + " versioned_packages = []\n", + " not_found_packages = []\n", + " filtered_packages = []\n", + "\n", + " for pkg in all_imports:\n", + " normalized_pkg = pkg.strip()\n", + "\n", + " if is_builtin_or_stdlib(normalized_pkg):\n", + " continue\n", + "\n", + " if is_environment_specific(normalized_pkg):\n", + " filtered_packages.append(f\"{normalized_pkg} (environment-specific)\")\n", + " continue\n", + "\n", + " freeze_requirement = requirement_from_pip_freeze(\n", + " normalized_pkg, pip_freeze_requirements\n", + " )\n", + " pip_name = get_package_name_for_pip(normalized_pkg)\n", + "\n", + " if freeze_requirement:\n", + " versioned_packages.append(freeze_requirement)\n", + " continue\n", + "\n", + " try:\n", + " version = get_package_version(normalized_pkg)\n", + " except Exception:\n", + " version = \"\"\n", + "\n", + " if not version and pip_name and pip_name != normalized_pkg:\n", + " version = get_package_version(pip_name)\n", + "\n", + " if pip_name and not package_exists_on_pypi(pip_name):\n", + " filtered_packages.append(f\"{pip_name} (not on PyPI)\")\n", + " continue\n", + "\n", + " resolved_name = pip_name or normalized_pkg\n", + "\n", + " if version:\n", + " versioned_packages.append(f\"{resolved_name}=={version}\")\n", + " else:\n", + " not_found_packages.append(resolved_name)\n", + "\n", + " # Get the current Python version\n", + " python_version = platform.python_version()\n", + "\n", + " def build_local_files_html():\n", + " if not local_dependency_files:\n", + " return \"\"\n", + " preview_paths = local_dependency_files[:LOCAL_SCAN_PREVIEW]\n", + " value = \"Local files scanned:
    \"\n", + " for path in preview_paths:\n", + " value += f\"
  • {html.escape(str(path))}
  • \"\n", + " remaining = len(local_dependency_files) - len(preview_paths)\n", + " if remaining > 0:\n", + " value += f\"
  • ... and {remaining} more
  • \"\n", + " value += \"
\"\n", + " return value\n", + "\n", + " def build_local_warnings_html():\n", + " if not local_scan_warnings:\n", + " return \"\"\n", + " value = \"Local scan notes:
    \"\n", + " for note in local_scan_warnings:\n", + " value += f\"
  • {html.escape(str(note))}
  • \"\n", + " value += \"
\"\n", + " return value\n", + "\n", + " local_files_html_value = build_local_files_html()\n", + " local_warnings_html_value = build_local_warnings_html()\n", + "\n", + " def show_requirements_dialog():\n", + " \"\"\"Display the version info and generate requirements dialog.\"\"\"\n", + " version_info = widgets.HTML(\n", + " \"

โœ… Requirements correctly extracted!

\"\n", + " \"

These are the packages that were detected from the notebook and any optional helper .py files you provided.

\"\n", + " )\n", + "\n", + " if local_files_html_value:\n", + " version_info.value += local_files_html_value\n", + "\n", + " version_info.value += \"

โœ… Found packages with versions:

\"\n", + " version_info.value += \"

These packages were found on your environment with version information and will be included in the generated requirements file.

\"\n", + " version_info.value += \"
    \"\n", + " for vp in versioned_packages:\n", + " version_info.value += f\"
  • {html.escape(vp)}
  • \"\n", + " version_info.value += \"
\"\n", + "\n", + " if filtered_packages:\n", + " version_info.value += \"

โš ๏ธ Filtered packages (excluded from requirements):

\"\n", + " version_info.value += \"

You should not worry too much about these packages. These are packages that were detected but will not be included in the generated requirements file because they are either environment-specific (e.g., IPython, jupyterlab, etc.) or not available on PyPI.

\"\n", + " version_info.value += \"
    \"\n", + " for fp in filtered_packages:\n", + " version_info.value += f\"
  • {html.escape(fp)}
  • \"\n", + " version_info.value += \"
\"\n", + "\n", + " if not_found_packages:\n", + " version_info.value += \"

โŒ Packages not found on your environment or without version info:

\"\n", + " version_info.value += \"

Careful: These packages were detected but could not be found in your environment or do not have version information available.
Please, be sure that you are in the correct environment where you run the notebook or that the packages are installed.
In case they are not installed remember to install them with pip install <package_name> or conda install <package_name>.

\"\n", + " version_info.value += \"
    \"\n", + " for np in not_found_packages:\n", + " version_info.value += f\"
  • {html.escape(np)}
  • \"\n", + " version_info.value += \"
\"\n", + "\n", + " if local_warnings_html_value:\n", + " version_info.value += local_warnings_html_value\n", + "\n", + " version_info.value += f\"

Detected Python version:

{html.escape(python_version)}
\"\n", + "\n", + " # Ask for a notebook description + generate requirements.yaml\n", + " version_info.value += \"

Provide a description for your notebook:

\"\n", + " version_info.value += \"

This description will be included in the generated requirements file and can be helpful for documentation purposes or to give context about the notebook's purpose and functionality.

\"\n", + " version_info.value += \"

After writing the description, click Validate & preview requirements file to inspect the YAML before using Generate & save requirements file to write it.

\"\n", + " default_notebook_description = f\"This notebook '{notebook_path.name}' is for ...\"\n", + "\n", + " description = widgets.Textarea(\n", + " value=default_notebook_description,\n", + " placeholder='Type something',\n", + " description='Description:',\n", + " disabled=False,\n", + " layout=widgets.Layout(width='99%', height='80px')\n", + " )\n", + "\n", + " preview_button = widgets.Button(\n", + " description='Validate & preview requirements file',\n", + " disabled=False,\n", + " button_style='info',\n", + " tooltip='Build a preview of the requirements.yaml file',\n", + " icon='search',\n", + " layout=widgets.Layout(width='99%')\n", + " )\n", + " generate_button = widgets.Button(\n", + " description='Generate & save requirements file',\n", + " disabled=True,\n", + " button_style='success',\n", + " tooltip='Preview your requirements before generating the file',\n", + " icon='check',\n", + " layout=widgets.Layout(width='99%')\n", + " )\n", + " preview_output = widgets.HTML()\n", + " final_output = widgets.HTML()\n", + "\n", + " last_preview = {\n", + " 'payload': None,\n", + " 'description': None,\n", + " 'yaml': None,\n", + " 'warning': \"\",\n", + " }\n", + "\n", + " def build_requirements_payload(description_text):\n", + " prepared_packages = list(versioned_packages)\n", + " added_ipywidgets = False\n", + " ipywidgets_warning = \"\"\n", + " ipywidget_version = resolve_ipywidgets_version(python_version)\n", + " ipywidget_requirement = f\"ipywidgets=={ipywidget_version}\"\n", + " for idx_pkg, pkg in enumerate(prepared_packages):\n", + " if pkg.startswith(\"ipywidgets\"):\n", + " prepared_packages[idx_pkg] = ipywidget_requirement\n", + " added_ipywidgets = True\n", + " break\n", + "\n", + " if not added_ipywidgets:\n", + " prepared_packages.append(ipywidget_requirement)\n", + " else:\n", + " ipywidgets_warning = f\"โš ๏ธ Warning! The ipywidgets version has been overridden to {ipywidget_version}.
\"\n", + "\n", + " payload = {\n", + " 'description': description_text,\n", + " 'python_version': python_version,\n", + " 'dependencies': prepared_packages,\n", + " 'windows_dependencies': [],\n", + " 'linux_dependencies': [],\n", + " 'macos_dependencies': [],\n", + " }\n", + " return payload, ipywidgets_warning\n", + "\n", + " def on_preview_clicked(_):\n", + " preview_output.value = \"\"\n", + " final_output.value = \"\"\n", + " desc_text = description.value.strip()\n", + " if not desc_text:\n", + " preview_output.value = \"โŒ Please provide a valid description before previewing.\"\n", + " generate_button.disabled = True\n", + " generate_button.tooltip = 'Preview your requirements before generating the file'\n", + " return\n", + " try:\n", + " payload, warning = build_requirements_payload(desc_text)\n", + " except Exception as exc:\n", + " preview_output.value = \"โŒ Failed to build the requirements preview: \" + html.escape(str(exc))\n", + " generate_button.disabled = True\n", + " generate_button.tooltip = 'Preview your requirements before generating the file'\n", + " return\n", + "\n", + " preview_yaml = yaml.dump(payload, default_flow_style=False, sort_keys=False)\n", + " preview_html = \"\"\n", + " if warning:\n", + " preview_html += warning\n", + " # Look if the python version is bellow 3.11\n", + " if tuple([int(e) for e in python_version.split('.')]) < (3, 11):\n", + " preview_html += \"โš ๏ธ Warning! The Python version is below 3.11. The play button feature may not be supported (check here to know more about the play button).
\"\n", + " preview_html += f\"Preview of {nb_path.stem}_requirements.yaml (nothing has been saved yet):\"\n", + " preview_html += \"
\"\n",
+    "            preview_html += html.escape(preview_yaml)\n",
+    "            preview_html += \"
\"\n", + " preview_output.value = preview_html\n", + "\n", + " last_preview['payload'] = payload\n", + " last_preview['description'] = desc_text\n", + " last_preview['yaml'] = preview_yaml\n", + " last_preview['warning'] = warning\n", + " generate_button.disabled = False\n", + " generate_button.tooltip = 'Generate requirements.yaml using the preview above'\n", + "\n", + " def on_generate_clicked(_):\n", + " final_output.value = \"\"\n", + " if not last_preview['payload']:\n", + " final_output.value = \"โŒ Please preview your requirements file before generating.\"\n", + " generate_button.disabled = True\n", + " generate_button.tooltip = 'Preview your requirements before generating the file'\n", + " return\n", + " current_description = description.value.strip()\n", + " if current_description != (last_preview['description'] or ''):\n", + " final_output.value = \"โŒ The description has changed. Please preview again before generating the file.\"\n", + " generate_button.disabled = True\n", + " generate_button.tooltip = 'Preview your requirements before generating the file'\n", + " return\n", + "\n", + " requirements_path = Path(f'{nb_path.stem}_requirements.yaml')\n", + " try:\n", + " with open(requirements_path, 'w') as file:\n", + " yaml.dump(last_preview['payload'], file, default_flow_style=False)\n", + " except Exception as exc:\n", + " final_output.value = \"โŒ Failed to save the requirements file: \" + html.escape(str(exc))\n", + " return\n", + "\n", + " success_message = f\"โœ… Congrats! Your {requirements_path.name} file has been generated successfully!
\"\n", + " if last_preview['warning']:\n", + " success_message = last_preview['warning'] + success_message\n", + " if is_colab():\n", + " from google.colab import files\n", + " files.download(requirements_path)\n", + " success_message += f'Your {requirements_path.name} file will be automatically downloaded. Additionally, you could find it in {requirements_path.resolve()}
'\n", + " else:\n", + " success_message += f'You can find your {requirements_path.name} file in {requirements_path.resolve()}.
'\n", + " success_message += \"Please validate its content, edit if necessary (missed packages or edge cases) and in case you edited validate it using the Requirements Validator notebook.\"\n", + " final_output.value = success_message\n", + "\n", + " preview_button.on_click(on_preview_clicked)\n", + " generate_button.on_click(on_generate_clicked)\n", + "\n", + " render_section(content_container, \n", + " version_info, description, preview_button, preview_output, generate_button, final_output)\n", + "\n", + " show_requirements_dialog()\n", + "\n", + "if 'import_regex' not in globals():\n", + " display(widgets.HTML(\"โŒ Main functionalities not loaded. Please go to Step 0 to import them.\"))\n", + "elif 'nb_path' not in globals() or nb_path is None:\n", + " display(widgets.HTML(\"โŒ No notebook selected. Please go to Step 1 and select a notebook to extract requirements.\"))\n", + "elif 'entries' not in globals() or entries is None:\n", + " display(widgets.HTML(\"โŒ No information about additional helper files (local or GitHub). Please go to Step 2 and choose whether to include additional helper files for the requirements extraction.\"))\n", + "else:\n", + " content_container = widgets.VBox(layout=widgets.Layout(width=\"100%\"))\n", + "\n", + " # Load pip-freeze mapping (do it here so it reflects the runtime env at click-time)\n", + " pip_freeze_requirements = load_pip_freeze_requirements()\n", + "\n", + " try:\n", + " process_notebook(entries, content_container, nb_path, pip_freeze_requirements)\n", + " except Exception as exc:\n", + " content_container.children = (\n", + " widgets.HTML(\n", + " \"โŒ Failed to extract requirements: \"\n", + " + str(exc)\n", + " ),\n", + " )\n", + "\n", + " container = widgets.VBox([content_container], layout=widgets.Layout(width=\"100%\"))\n", + " display(container)" + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "labchronicle", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.tools/notebooks/Requirements_Validator.ipynb b/.tools/notebooks/Requirements_Validator.ipynb new file mode 100644 index 0000000..10a613e --- /dev/null +++ b/.tools/notebooks/Requirements_Validator.ipynb @@ -0,0 +1,122 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cb54a2c7", + "metadata": {}, + "source": [ + "# Validate your requirements.yaml file\n", + "\n", + "You might have created your `requirements.yaml` file manually or using the requirements generator notebook and you have modified it. Use this notebook to validate that the file is correctly formatted. You can use this notebook to validate your `requirements.yaml` file before uploading it to your repository.\n", + "\n", + "> **NOTE**: You do not need to run this notebook in the same environment as the one used to run the notebook you are uploading." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4bd33249", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# @markdown Validate your requirements.yaml file\n", + "\n", + "import yaml\n", + "from pathlib import Path\n", + "import ipywidgets as widgets\n", + "from IPython.display import display\n", + "\n", + "required_keys = {\"dependencies\", \"python_version\", \"description\"}\n", + "alt_python_key = \"python\"\n", + "\n", + "def validate_requirements(path: Path):\n", + " if not path.exists():\n", + " return False, [f\"File not found: {path}\"]\n", + " try:\n", + " with path.open(\"r\", encoding=\"utf-8\") as f:\n", + " data = yaml.safe_load(f)\n", + " except Exception as exc:\n", + " return False, [f\"YAML read error: {exc}\"]\n", + " if not isinstance(data, dict):\n", + " return False, [\"YAML root must be a mapping (key/value pairs).\"]\n", + "\n", + " keys = set(data.keys())\n", + " missing = required_keys - keys\n", + " messages = []\n", + " python_key = \"python_version\"\n", + " if \"python_version\" not in data and alt_python_key in data:\n", + " python_key = alt_python_key\n", + " missing -= {\"python_version\"}\n", + " if missing:\n", + " messages.append(\"Missing required keys: \" + \", \".join(sorted(missing)))\n", + "\n", + " deps = data.get(\"dependencies\")\n", + " if deps is None:\n", + " messages.append(\"Key 'dependencies' is required.\")\n", + " elif not isinstance(deps, list):\n", + " messages.append(\"'dependencies' must be a YAML list (lines prefixed with '- ').\")\n", + " else:\n", + " for d in deps:\n", + " if not isinstance(d, str):\n", + " messages.append(f\"{d} (is not a string)\")\n", + " elif not d.strip():\n", + " messages.append(f\"{d} (is an empty string)\")\n", + " elif ' - ' in d:\n", + " messages.append(f\"{d} (contains ' - ': possible indentation error in YAML)\")\n", + "\n", + " if python_key not in data:\n", + " messages.append(\"'python_version' is required.\")\n", + " elif not isinstance(data.get(python_key), str) or not data.get(python_key).strip():\n", + " messages.append(f\"'{python_key}' must be a non-empty string (for example: 3.10.13).\")\n", + "\n", + " if \"description\" not in data or not isinstance(data.get(\"description\"), str) or not data.get(\"description\").strip():\n", + " messages.append(\"'description' must be a non-empty string.\")\n", + "\n", + " return len(messages) == 0, messages\n", + "\n", + "path_input = widgets.Text(\n", + " value=\"requirements.yaml\",\n", + " description=\"Path:\",\n", + " layout=widgets.Layout(width=\"99%\"),\n", + " style={\"description_width\": \"initial\"},\n", + ")\n", + "validate_btn = widgets.Button(\n", + " description=\"Validate requirements.yaml\",\n", + " button_style=\"success\",\n", + " layout=widgets.Layout(width=\"99%\"),\n", + ")\n", + "output_html = widgets.HTML()\n", + "\n", + "def on_validate(_):\n", + " path = Path(path_input.value).expanduser().resolve()\n", + " ok, messages = validate_requirements(path)\n", + " if ok:\n", + " output_html.value = f\"โœ… Validation passed for {path.name}.\"\n", + " else:\n", + " output_html.value = f\"โš ๏ธ Issues found in the given {path.name}:
    \"\n", + " for msg in messages:\n", + " output_html.value += f\"
  • โŒ {msg}
  • \"\n", + " output_html.value += \"
\"\n", + "\n", + "validate_btn.on_click(on_validate)\n", + "display(path_input, validate_btn, output_html)\n" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.tools/python/bump_Welcome_notebook.py b/.tools/python/bump_Welcome_notebook.py new file mode 100644 index 0000000..8b42866 --- /dev/null +++ b/.tools/python/bump_Welcome_notebook.py @@ -0,0 +1,80 @@ +from pathlib import Path +import yaml +import json +import sys + + +def build_notebook_list(notebooks_root: Path): + items = [] + for ipynb in notebooks_root.rglob("*.ipynb"): + # Path relative to notebooks folder + rel = ipynb.relative_to(notebooks_root) + name = ipynb.stem + + # Path to the notebook's requirements.yaml + requirements_path = ipynb.with_name("requirements.yaml") + description = "-" + if requirements_path.exists(): + # Read the requirements.yaml to get the description + with requirements_path.open(encoding="utf-8") as f: + reqs = yaml.safe_load(f) + if isinstance(reqs, dict) and "description" in reqs: + description = reqs["description"] + + path = "notebooks/" + str(rel).replace('\\', '/') + + items.append({ + "name": name, + "description": description, + "path": path, + }) + # Sort for deterministic order + items.sort(key=lambda x: x["path"]) + return items + + +def populate_template(template_path: Path, output_path: Path, owner: str, repo: str, notebooks_root: Path): + data = json.loads(template_path.read_text(encoding="utf-8")) + + # Generate notebooks list + notebooks_list = build_notebook_list(notebooks_root) + + # Replace in cells: GITHUB_OWNER, GITHUB_REPO_NAME, and DICT_OF_NOTEBOOKS + for cell in data.get("cells", []): + if cell.get("cell_type") == "code": + # Replace owner/repo placeholders + new_source = [] + for line in cell.get("source", []): + line = line.replace("GITHUB_OWNER", owner) + line = line.replace("GITHUB_REPO_NAME", repo) + # Replace notebooks = DICT_OF_NOTEBOOKS with concrete list + if "notebooks = DICT_OF_NOTEBOOKS" in line: + line = "notebooks = " + json.dumps(notebooks_list, ensure_ascii=False) + new_source.append(line) + cell["source"] = new_source + + output_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") + + +def main(): + # Args: owner repo [template_path] [output_path] + if len(sys.argv) < 3: + print("Usage: populate_Welcome_notebook.py [template] [output]", file=sys.stderr) + sys.exit(1) + + owner = sys.argv[1] + repo = sys.argv[2] + + template_path = Path(".tools/templates/Welcome_template.ipynb") + output_path = Path("app/menuinst/Welcome.ipynb") + notebooks_root = Path("notebooks").resolve() + + output_path.parent.mkdir(parents=True, exist_ok=True) + + populate_template(template_path, output_path, owner, repo, notebooks_root) + print(f"Populated Welcome notebook written to: {output_path}") + + +if __name__ == "__main__": + main() + diff --git a/.tools/python/bump_constructor.py b/.tools/python/bump_constructor.py new file mode 100644 index 0000000..1a35a15 --- /dev/null +++ b/.tools/python/bump_constructor.py @@ -0,0 +1,340 @@ +import sys +from pathlib import Path +import yaml +import re + +DEBUG_PREFIX = "[bump_constructor]" + + +def debug(message: str) -> None: + print(f"{DEBUG_PREFIX} {message}") + + +def load_construct(path: Path) -> dict: + return yaml.safe_load(path.read_text(encoding="utf-8")) + +def save_construct_surgical(path: Path, data: dict, original_text: str) -> str: + """Update only extra_files section while preserving the rest of the file structure.""" + # Convert updated extra_files back to YAML string + extra_files = data.get("extra_files", []) + extra_files_yaml = "extra_files:\n" + for item in extra_files: + if isinstance(item, dict): + for src, dst in item.items(): + extra_files_yaml += f"- {src}: {dst}\n" + else: + extra_files_yaml += f"- {item}\n" + + # Find and replace the extra_files section in the original text + pattern = r"extra_files:\n((?:- .+\n)*)" + if re.search(pattern, original_text): + updated = re.sub(pattern, extra_files_yaml, original_text) + path.write_text(updated, encoding="utf-8") + else: + # Fallback: if no extra_files found, use standard dump + path.write_text(yaml.dump(data, sort_keys=False, allow_unicode=True), encoding="utf-8") + + +def extract_project_folder(extra_files: list) -> str: + """Extract the project folder name from existing mappings (e.g., from Welcome.ipynb dest).""" + for item in extra_files: + if isinstance(item, dict): + for src, dst in item.items(): + if "Welcome.ipynb" in src or "Welcome.ipynb" in dst: + # Extract first folder from destination path + parts = dst.split("/") + if parts: + return parts[0] + # Fallback + return "Fast4DRegPy" + +def ensure_requirements_in_extra_files(construct_data: dict): + extra_files = construct_data.get("extra_files") + if extra_files is None: + extra_files = [] + construct_data["extra_files"] = extra_files + + # Check if requirements.txt is included, if not, add it + requirements_included = any( + isinstance(item, dict) and "requirements.txt" in item for item in extra_files + ) + if not requirements_included: + extra_files.append({"requirements.txt": "Fast4DRegPy/requirements.txt"}) + debug("Added mapping for requirements.txt") + else: + debug("requirements.txt mapping already present") + + gpu_requirements_included = any( + isinstance(item, dict) and "requirements_gpu.txt" in item for item in extra_files + ) + if not gpu_requirements_included and Path("requirements_gpu.txt").exists(): + extra_files.append({"requirements_gpu.txt": "Fast4DRegPy/requirements_gpu.txt"}) + debug("Added mapping for requirements_gpu.txt") + elif Path("requirements_gpu.txt").exists(): + debug("requirements_gpu.txt mapping already present") + else: + debug("requirements_gpu.txt not found, skipping GPU requirements mapping") + + # Check if requirements-linux.txt exists and is included, if not, add it + if Path("requirements-linux.txt").exists(): + linux_included = any( + isinstance(item, dict) and "requirements-linux.txt" in item for item in extra_files + ) + if not linux_included: + extra_files.append({"requirements-linux.txt": "Fast4DRegPy/requirements-linux.txt"}) + debug("Added mapping for requirements-linux.txt") + else: + debug("requirements-linux.txt mapping already present") + else: + debug("requirements-linux.txt not found, skipping Linux requirements mapping") + # Check if requirements-windows.txt exists and is included, if not, add it + if Path("requirements-windows.txt").exists(): + windows_included = any( + isinstance(item, dict) and "requirements-windows.txt" in item for item in extra_files + ) + if not windows_included: + extra_files.append({"requirements-windows.txt": "Fast4DRegPy/requirements-windows.txt"}) + debug("Added mapping for requirements-windows.txt") + else: + debug("requirements-windows.txt mapping already present") + else: + debug("requirements-windows.txt not found, skipping Windows requirements mapping") + + # Check if requirements-macos.txt exists and is included, if not, add it + if Path("requirements-macos.txt").exists(): + macos_included = any( + isinstance(item, dict) and "requirements-macos.txt" in item for item in extra_files + ) + if not macos_included: + extra_files.append({"requirements-macos.txt": "Fast4DRegPy/requirements-macos.txt"}) + debug("Added mapping for requirements-macos.txt") + else: + debug("requirements-macos.txt mapping already present") + else: + debug("requirements-macos.txt not found, skipping macOS requirements mapping") + + # Update the construct data with the modified extra_files + construct_data["extra_files"] = extra_files + + +APP_MANIFEST = "labconstrictor-app.yaml" + + +def ensure_app_manifest_in_extra_files(construct_data: dict, manifest_path: Path = Path(APP_MANIFEST)) -> bool: + """Bundle labconstrictor-app.yaml in the installer, so post_install can pass its hosts: line to Tools (--app-manifest). + + The mapping is added only when the file exists (it is optional, and a mapping to a missing file would fail the installer build). + Returns True when the mapping was added. A mapping whose file is gone is reported, never removed. + """ + extra_files = construct_data.setdefault("extra_files", []) + mapped = any(isinstance(item, dict) and APP_MANIFEST in item for item in extra_files) + if manifest_path.exists() and not mapped: + extra_files.append({APP_MANIFEST: f"{extract_project_folder(extra_files)}/{APP_MANIFEST}"}) + debug(f"Added mapping for {APP_MANIFEST} (its hosts: line goes to Tools at install time)") + return True + if mapped and not manifest_path.exists(): + debug(f"WARNING: extra_files maps {APP_MANIFEST} but the file does not exist: the installer build will fail until it is added or the mapping is removed") + elif not mapped: + debug(f"{APP_MANIFEST} not found: the app will be registered without hosts (listed in every host)") + return False + +LOCK_FILES = ( + "requirements.lock.txt", + "requirements_gpu.lock.txt", + "requirements-linux.lock.txt", + "requirements-windows.lock.txt", + "requirements-macos.lock.txt", +) + + +def ensure_lock_files_in_extra_files(construct_data: dict) -> None: + """Bundle the lock files (requirements*.lock.txt, written by lock_requirements.py) next to their requirements files. + + post_install installs a lock file instead of its requirements file when the installer bundles one. A mapping whose lock file is gone + (the requirements could not be locked) is removed, because constructor fails on a missing file. + """ + extra_files = construct_data.setdefault("extra_files", []) + project_folder = extract_project_folder(extra_files) + for lock_file in LOCK_FILES: + mapped = [item for item in extra_files if isinstance(item, dict) and lock_file in item] + if Path(lock_file).exists(): + if not mapped: + extra_files.append({lock_file: f"{project_folder}/{lock_file}"}) + debug(f"Added mapping for {lock_file}") + else: + debug(f"{lock_file} mapping already present") + elif mapped: + for item in mapped: + extra_files.remove(item) + debug(f"Removed the mapping of {lock_file}: the file does not exist (the installer installs the requirements file instead)") + + +def ensure_extra_files(construct_data: dict, notebooks_root: Path, src_root: Path) -> int: + extra_files = construct_data.get("extra_files") + if extra_files is None: + extra_files = [] + construct_data["extra_files"] = extra_files + + # Extract the project folder name from existing mappings + project_folder = extract_project_folder(extra_files) + debug(f"Using project folder: {project_folder}") + + # Normalize existing entries into a dict for quick lookup + existing_sources = set() + existing_dests = set() + normalized_items = [] + + for item in extra_files: + # Items can be either dicts (k: v) or strings with mapping? Assume dicts per example + if isinstance(item, dict): + for src, dst in item.items(): + existing_sources.add(str(src)) + existing_dests.add(str(dst)) + normalized_items.append({str(src): str(dst)}) + else: + # If strings are present, keep them + normalized_items.append(item) + + ntbk_added = 0 + repo_root = Path(".").resolve() + + # For safety, remove any existing notebooks/*.ipynb entries to avoid duplicates, we will re-add them with correct paths + normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src).startswith("notebooks/") and src.endswith(".ipynb") for src in item.keys()))] + + # Include all notebooks under notebooks/ directory + for ipynb in notebooks_root.rglob("*.ipynb"): + rel = ipynb.relative_to(repo_root).as_posix() + if not rel.startswith("notebooks/"): + continue + src = rel + dst = f"{project_folder}/{rel}" + + # if src in existing_sources or dst in existing_dests: + # continue + + normalized_items.append({src: dst}) + ntbk_added += 1 + debug(f"Included notebook: {src} -> {dst}") + + # First get the name of the package from setup.py + setup_path = repo_root / "setup.py" + project_name = "Fast4DRegPy" + if setup_path.exists(): + setup_text = setup_path.read_text(encoding="utf-8") + name_match = re.search(r'name\s*=\s*["\']([^"\']+)["\']', setup_text) + if name_match: + project_name = name_match.group(1) + debug(f"Detected setup.py package name: {project_name}") + else: + debug("setup.py not found at repository root") + + # For safety, remove any existing src/ entries to avoid duplicates, we will re-add them with correct paths + normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src).startswith("src/") for src in item.keys()))] + + # Include all the Python scripts under src/ directory + src_added = 0 + only_init_files = True + included_src_flag = False + for py_file in src_root.rglob("*.py"): + rel = py_file.relative_to(repo_root).as_posix() + + # Avoid any python files that are not in the src/ directory + if not rel.startswith("src/"): + continue + + # Control if we only have __init__.py files + if not py_file.name == "__init__.py": + only_init_files = False + + src = rel + dst = f"{project_folder}/{rel}" + + # if src in existing_sources or dst in existing_dests: + # continue + + normalized_items.append({src: dst}) + included_src_flag = True + src_added += 1 + debug(f"Included source file: {src} -> {dst}") + + if only_init_files: + debug("Only __init__.py files found under src/, skipping setup.py and src change marker packaging") + included_src_flag = False + + # For safety also remove setup.py and src_change.yaml if they exist in the extra_files to avoid duplicates, we will re-add them with correct paths if src/ is included + normalized_items = [item for item in normalized_items if not (isinstance(item, dict) and any(str(src) in ["setup.py", ".tools/meta/src_change.yaml"] for src in item.keys()))] + + if included_src_flag: + # Also include the setup.py file at the root if not already included + setup_src = "setup.py" + setup_dst = f"{project_folder}/setup.py" + + normalized_items.append({setup_src: setup_dst}) + src_added += 1 + debug(f"Included setup.py: {setup_src} -> {setup_dst}") + + # Include the external code change tracking file if it exists + src_change_file = ".tools/meta/src_change.yaml" + if Path(src_change_file).exists(): + # The mapping was removed from normalized_items above, so always re-add it here; + # checking existing_sources would drop it on every other release. + src_change_dst = f"{project_folder}/src_change.yaml" + normalized_items.append({src_change_file: src_change_dst}) + src_added += 1 + debug(f"Included src change marker: {src_change_file} -> {src_change_dst}") + else: + debug("src change marker not found, skipping") + else: + # If the user has removed the src/directory, remove the generated setup.py and src_change.yaml + debug("No non-__init__.py files found under src/, skipping setup.py and src change marker packaging") + setup_dst = Path(project_folder) / "setup.py" + if setup_dst.exists(): + setup_dst.unlink() + src_change_dst = Path(project_folder) / "src_change.yaml" + if src_change_dst.exists(): + src_change_dst.unlink() + + # Optionally sort entries (dicts by their single key) for determinism + def sort_key(item): + if isinstance(item, dict): + # single-key dict + k = next(iter(item.keys())) + return (0, k) + return (1, str(item)) + + normalized_items.sort(key=sort_key) + construct_data["extra_files"] = normalized_items + debug(f"Final extra_files entries: {len(normalized_items)}") + for item in normalized_items: + debug(f"extra_files entry: {item}") + + return ntbk_added, src_added + + +def main(): + construct_path = Path("construct.yaml") if len(sys.argv) < 2 else Path(sys.argv[1]) + notebooks_root = Path("notebooks").resolve() + src_root = Path("src").resolve() + + if not construct_path.exists(): + print(f"construct.yaml not found at: {construct_path}", file=sys.stderr) + sys.exit(1) + + # Read original text to preserve formatting + original_text = construct_path.read_text(encoding="utf-8") + + data = load_construct(construct_path) + # Check if the requirements files are included in extra_files, if not, add them + ensure_requirements_in_extra_files(data) + ensure_lock_files_in_extra_files(data) + ensure_app_manifest_in_extra_files(data) + + # Update extra_files with notebooks and src files + ntbk_added, src_added = ensure_extra_files(data, notebooks_root, src_root) + + # Write using surgical update to preserve platform-specific scripts + save_construct_surgical(construct_path, data, original_text) + print(f"Added {ntbk_added} notebook(s) and {src_added} source file(s) to extra_files.") + +if __name__ == "__main__": + main() diff --git a/.tools/python/bump_notebook_README.py b/.tools/python/bump_notebook_README.py new file mode 100644 index 0000000..0a16e18 --- /dev/null +++ b/.tools/python/bump_notebook_README.py @@ -0,0 +1,55 @@ +from collections import defaultdict +from pathlib import Path +import sys + +NOTEBOOK_DIR = Path("notebooks").resolve() +README_PATH = NOTEBOOK_DIR / "README.md" + + +def discover_notebooks(directory: Path) -> list[Path]: + return sorted( + (path.relative_to(directory) for path in directory.rglob("*.ipynb")), + key=lambda p: p.as_posix(), + ) + + +def build_readme_content(notebooks: list[Path]) -> str: + lines = ["# Notebooks", ""] + if not notebooks: + lines.append("No notebooks found in this folder.") + lines.append("") + return "\n".join(lines) + + lines.append("Indexed list of folders and notebooks:") + lines.append("") + + grouped: dict[Path, list[Path]] = defaultdict(list) + for notebook in notebooks: + grouped[notebook.parent].append(notebook) + + for folder, files in grouped.items(): + files.sort(key=lambda p: p.name.lower()) + + for folder in sorted(grouped.keys(), key=lambda p: p.as_posix()): + folder_label = "." if folder == Path(".") else folder.as_posix() + lines.append(f"- [{folder_label}]({folder_label.replace(' ', '%20')}):") + for notebook in grouped[folder]: + lines.append(f" - [{notebook.name}]({notebook.as_posix().replace(' ', '%20')})") + lines.append("") + + return "\n".join(lines).rstrip() + "\n" + + +def main(): + if not NOTEBOOK_DIR.exists(): + print("notebooks directory not found.", file=sys.stderr) + sys.exit(1) + + notebooks = discover_notebooks(NOTEBOOK_DIR) + content = build_readme_content(notebooks) + README_PATH.write_text(content, encoding="utf-8") + print(f"Wrote {README_PATH} with {len(notebooks)} notebook(s).") + + +if __name__ == "__main__": + main() diff --git a/.tools/python/bump_version.py b/.tools/python/bump_version.py new file mode 100644 index 0000000..e8e5f10 --- /dev/null +++ b/.tools/python/bump_version.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +import argparse +import os +import pathlib +import re +import shutil +import sys +import textwrap + +ROOT = pathlib.Path(__file__).resolve().parents[2] +CONSTRUCT = ROOT / "construct.yaml" + +# Match version line with optional quotes and optional trailing comment +VERSION_LINE_RE = re.compile( + r'^(version:\s*)(?P["\']?)(?P\d+\.\d+\.\d+)(?P=quote)(?P\s*(?:#.*)?)$', + re.MULTILINE, +) +CONCLUSION_LINE_RE = re.compile( + r'^(conclusion_text:\s*)(?:(?P["\'])(?P.*?)(?P=quote)|(?P.*?))(?P\s*(?:#.*)?)$', + re.MULTILINE, +) +PKG_VERSION_RE = re.compile(r'^(\s*SET\s+"PKG_VERSION=)(\d+\.\d+\.\d+)("\s*)$', re.MULTILINE) +POST_INSTALL = ROOT / "app" / "bash_bat_scripts" / "post_install.bat" +# version="1.2.3" in setup.py: the version of the app's Python package (src/) +SETUP = ROOT / "setup.py" +SETUP_VERSION_RE = re.compile(r"^(?P[ \t]*version\s*=\s*)(?P[\"'])\d+\.\d+\.\d+(?P=quote)", re.MULTILINE) + +# The folder of a release in a download link: /releases/download// (the tag is 1.2.3 or v1.2.3). +DOWNLOAD_PATH_RE = re.compile(r"/releases/download/v?\d+\.\d+\.\d+/") +# A button of the download page: +DOWNLOAD_BUTTON_RE = re.compile(r'\s*]*>\s*') +NOT_BUILT_NOTE = "> No installer is built for {label}: this app does not support it." + + +def replace_version_placeholder(text: str, new_version: str, tag: str | None = None) -> str: + """Render the release version in download documentation. + + Handles both pristine templates containing ``VERSION_NUMBER`` and + initialized repositories where that placeholder was already rendered to an + older explicit version such as ``0.0.0``. The links point to the release + tag as it was typed (``v1.2.3`` or ``1.2.3``); the installer names carry + the version without ``v`` (CellMigrationLab/LabConstrictor#41). + """ + explicit_versions = set( + re.findall(r"/releases/download/v?(\d+\.\d+\.\d+)/", text) + ) + + text = text.replace("VERSION_NUMBER", new_version) + for previous_version in explicit_versions: + text = text.replace(previous_version, new_version) + return DOWNLOAD_PATH_RE.sub(f"/releases/download/{tag or new_version}/", text) + + +def drop_unbuilt_buttons(text: str, not_built: list[tuple[tuple[str, ...], str]]) -> str: + """Replace the download button of each system the release does not build with a note (CellMigrationLab/LabConstrictor#42). + + ``not_built`` holds (installer name endings, label) pairs, from release_platforms.py. The "or" between + two buttons goes when one of them became a note. + """ + if not not_built: + return text + + def _button(match: re.Match) -> str: + link = match.group(0).split('"', 2)[1] + for endings, label in not_built: + if link.endswith(endings): + return NOT_BUILT_NOTE.format(label=label) + return match.group(0) + + lines = DOWNLOAD_BUTTON_RE.sub(_button, text).split("\n") + note_start = NOT_BUILT_NOTE.split("{", 1)[0] + kept = [] + for index, line in enumerate(lines): + if line.strip() == "or": + before = next((other for other in reversed(lines[:index]) if other.strip()), "") + after = next((other for other in lines[index + 1 :] if other.strip()), "") + if before.startswith(note_start) or after.startswith(note_start): + continue + kept.append(line) + return "\n".join(kept) + + +def not_built_systems() -> list[tuple[tuple[str, ...], str]]: + """(installer name endings, label) of each system left out of distribution.platforms in labconstrictor-app.yaml.""" + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + import release_platforms + + return [(build.files, build.label) for build in release_platforms.skipped_builds(ROOT)] + +def replace_version_in_file(file_path: pathlib.Path, old_version: str, new_version: str) -> bool: + """Replace all occurrences of old_version with new_version in a file. + + Works for markdown and Python files. Handles various version formats: + - Bare versions: 1.2.3 + - With 'v' prefix: v1.2.3 + - In quotes: "1.2.3" or '1.2.3' + - In version strings: version 1.2.3, __version__ = "1.2.3" + + Args: + file_path: Path to the file to update + old_version: Current version string (X.Y.Z format) + new_version: New version string (X.Y.Z format) + + Returns: + True if any replacements were made, False otherwise + """ + if not file_path.exists(): + return False + + text = file_path.read_text(encoding="utf-8") + original_text = text + + # Escape dots for regex + old_escaped = re.escape(old_version) + + # Pattern matches version with optional surrounding characters but preserves them + # Matches: v1.2.3, "1.2.3", '1.2.3', (1.2.3), [1.2.3], bare 1.2.3 + # Does NOT match partial versions like 1.2.34 or 11.2.3 + pattern = re.compile( + r'(?<=["\'\[(\s>v]|^)' + # Lookbehind: quote, bracket, paren, space, >, v, or start + old_escaped + + r'(?=["\'\])\s<,;]|$)' # Lookahead: quote, bracket, paren, space, <, comma, semicolon, or end + ) + + # Also match v-prefixed versions explicitly + v_pattern = re.compile(r'(v)' + old_escaped + r'(?=["\'\])\s<,;!]|$)') + + # Replace v-prefixed versions + text = v_pattern.sub(r'\g<1>' + new_version, text) + + # Replace other versions + text = pattern.sub(new_version, text) + + if text != original_text: + file_path.write_text(text, encoding="utf-8") + return True + return False + + +def read_current_version() -> tuple[str, str]: + """Read construct.yaml as text and extract current SemVer. + + Returns (file_text, version_string). Exits if not found. + """ + text = CONSTRUCT.read_text(encoding="utf-8") + m = VERSION_LINE_RE.search(text) + if not m: + raise ValueError("Could not find version in construct.yaml") + return text, m.group("version") + + +def bump_construct_text(text: str, old_version: str, new_version: str) -> str: + """Return updated file text with bumped version, preserving YAML structure/comments. + + - Updates the `version: "X.Y.Z"` line. + - Updates the version inside `conclusion_text`, replacing either + `VERSION_NUMBER` or the previous explicit version if present. + """ + # 1) Update the explicit version line + def _repl_version(m: re.Match) -> str: + # Preserve original quoting and trailing comment/whitespace + return f"{m.group(1)}{m.group('quote')}{new_version}{m.group('quote')}{m.group('trailing')}" + + text = VERSION_LINE_RE.sub(_repl_version, text, count=1) + + # 2) Update the version inside conclusion_text if present. + def _repl_conclusion(m: re.Match) -> str: + quote = m.group("quote") or "" + body = m.group("quoted_body") if quote else (m.group("bare_body") or "") + if "VERSION_NUMBER" in body: + updated_body = body.replace("VERSION_NUMBER", new_version) + else: + updated_body = re.sub( + r"\b\d+\.\d+\.\d+\b", + new_version, + body, + count=1, + ) + return f"{m.group(1)}{quote}{updated_body}{quote}{m.group('trailing')}" + + text = CONCLUSION_LINE_RE.sub(_repl_conclusion, text, count=1) + return text + + +def bump_post_install_bat(new_version: str) -> None: + if not POST_INSTALL.exists(): + return + text = POST_INSTALL.read_text(encoding="utf-8") + if not PKG_VERSION_RE.search(text): + return + updated = PKG_VERSION_RE.sub(lambda m: f"{m.group(1)}{new_version}{m.group(3)}", text, count=1) + POST_INSTALL.write_text(updated, encoding="utf-8") + print(f"Updated post_install.bat PKG_VERSION to {new_version}") + + +def bump_setup_py(new_version: str) -> None: + """The version of the app's Python package in setup.py, when it is written there as X.Y.Z. + + The package in the installer and the one publish_pypi.yml publishes on PyPI then carry the release version. The line + endings of the file are kept. + """ + if not SETUP.exists(): + return + with SETUP.open(encoding="utf-8", newline="") as handle: + text = handle.read() + updated = SETUP_VERSION_RE.sub(lambda m: f"{m.group('head')}{m.group('quote')}{new_version}{m.group('quote')}", text, count=1) + if updated != text: + with SETUP.open("w", encoding="utf-8", newline="") as handle: + handle.write(updated) + print(f"Updated setup.py version to {new_version}") + +def bump_version_in_download_executable_md( + new_version: str, tag: str | None = None, not_built: list[tuple[tuple[str, ...], str]] | None = None +) -> None: + possible_download_md_paths = [ + ROOT / "docs" / "download_executable.md", + ROOT / ".tools" / "docs" / "download_executable.md" + ] + template_md = ROOT / ".tools" / "templates" / "download_executable_template.md" + + for download_md in possible_download_md_paths: + # We only want to update the existing files + if download_md.exists(): + # Replace download_executable.md with the template (but only if it exists) + if template_md.exists(): + # Remove existing download_executable.md if present + if download_md.exists(): + download_md.unlink() + # Copy the template to the docs folder using shutil for cross-platform support + shutil.copy(template_md, download_md) + else: + print("Template for download_executable.md not found! Skipping creation of download_executable.md") + return + + # This file contains placeholders, update them with the new version + text = download_md.read_text(encoding="utf-8") + updated_text = drop_unbuilt_buttons(replace_version_placeholder(text, new_version, tag), not_built or []) + if updated_text != text: + download_md.write_text(updated_text, encoding="utf-8") + print(f"Updated download_executable.md to version {new_version}") + else: + print("No version string found in download_executable.md to update.") + +def main() -> None: + parser = argparse.ArgumentParser( + description="Update project version across release artifacts.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=textwrap.dedent( + """\ + Example: + python .tools/python/bump_version.py 0.0.4 + python .tools/python/bump_version.py 0.0.4 --files README.md src/__init__.py + """ + ), + ) + parser.add_argument("new_version", help="SemVer version, e.g. 0.0.4") + parser.add_argument( + "--files", + nargs="+", + help="Additional files to update (e.g., README.md, __init__.py)" + ) + parser.add_argument( + "--tag", + default=os.environ.get("RELEASE_TAG") or None, + help="The release tag the download links point to: 0.0.4 or v0.0.4 (default: $RELEASE_TAG, else the version)", + ) + args = parser.parse_args() + + if not re.fullmatch(r"\d+\.\d+\.\d+", args.new_version): + sys.exit("Version must look like X.Y.Z") + if args.tag and args.tag not in (args.new_version, f"v{args.new_version}"): + sys.exit(f"The release tag {args.tag} does not match the version {args.new_version} (expected {args.new_version} or v{args.new_version})") + + text, current = read_current_version() + updated_text = bump_construct_text(text, current, args.new_version) + + if updated_text != text: + CONSTRUCT.write_text(updated_text, encoding="utf-8") + print(f"Bumped {current} -> {args.new_version}") + else: + print( + f"Project version already at {args.new_version}; " + "checking dependent versioned files." + ) + + # Also bump PKG_VERSION in post_install.bat + bump_post_install_bat(args.new_version) + + # The version of the app's Python package (setup.py), also the version publish_pypi.yml publishes on PyPI + bump_setup_py(args.new_version) + + # Update download_executable.md: the links point to the release tag, and a system that is not built has no button + bump_version_in_download_executable_md(args.new_version, args.tag, not_built_systems()) + + # Update additional files if specified + if args.files: + for file_path in args.files: + full_path = ROOT / file_path + if replace_version_in_file(full_path, current, args.new_version): + print(f"Updated {file_path}") + else: + print(f"No changes in {file_path}") + + +if __name__ == "__main__": + main() diff --git a/.tools/python/check_app_manifest.py b/.tools/python/check_app_manifest.py new file mode 100644 index 0000000..d6e19b9 --- /dev/null +++ b/.tools/python/check_app_manifest.py @@ -0,0 +1,104 @@ +"""Check labconstrictor-app.yaml, the optional description of an app for the LabConstrictor App Centre. + + python .tools/python/check_app_manifest.py [--repository-root .] + +Exit status: 0 = the file is valid, or there is no file (a GitHub warning says how to add one); +1 = the file is invalid (every problem is reported as a GitHub error annotation); +2 = the check itself could not run (for example the schema copy is missing). +The check never changes any file. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +import yaml +from jsonschema import Draft202012Validator + +MANIFEST_NAME = "labconstrictor-app.yaml" +SCHEMA_RELATIVE = Path(".tools/schema/labconstrictor-app.schema.json") +DOCS_HINT = "See .tools/docs/app_manifest.md." + + +class CheckError(Exception): + """The check could not run (not a problem with the manifest itself).""" + + +def load_schema(root: Path) -> dict[str, Any]: + """The vendored manifest schema. Raises CheckError when it is missing or not valid JSON.""" + path = root / SCHEMA_RELATIVE + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as err: + raise CheckError(f"cannot read the schema copy {SCHEMA_RELATIVE}: {err}") from err + + +def load_manifest(path: Path) -> Any: + """The parsed manifest. Raises ValueError with the YAML message when the file is not valid YAML.""" + try: + return yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as err: + raise ValueError(f"not valid YAML: {err}") from err + + +def schema_problems(manifest: Any, schema: dict[str, Any]) -> list[str]: + """One "path: message" line per way the manifest breaks the schema; empty when it is valid.""" + errors = sorted(Draft202012Validator(schema).iter_errors(manifest), key=lambda e: list(e.absolute_path)) + return [f"{'/'.join(str(p) for p in e.absolute_path) or 'manifest'}: {e.message}" for e in errors] + + +def referenced_paths(manifest: dict[str, Any]) -> list[str]: + """The repository files the manifest names: its icon and its screenshots.""" + paths = [manifest["icon"]] if "icon" in manifest else [] + return paths + [shot["path"] for shot in manifest.get("screenshots", [])] + + +def file_problems(manifest: dict[str, Any], root: Path) -> list[str]: + """One line per file the manifest names that does not exist in the repository.""" + return [f"{path}: file not found in the repository" for path in referenced_paths(manifest) if not (root / path).is_file()] + + +def annotate(level: str, message: str, title: str) -> None: + """Print a GitHub Actions annotation (shown on the run and on the file).""" + print(f"::{level} file={MANIFEST_NAME},title={title}::{message}") + + +def check(root: Path) -> int: + """Run the check; returns the exit status described at the top of this file.""" + manifest_path = root / MANIFEST_NAME + if not manifest_path.is_file(): + annotate("warning", f"{MANIFEST_NAME} is missing, so this app cannot be listed in the LabConstrictor App Centre. {DOCS_HINT}", "App Centre manifest missing") + return 0 + schema = load_schema(root) + try: + manifest = load_manifest(manifest_path) + except ValueError as err: + annotate("error", str(err), "App Centre manifest invalid") + return 1 + problems = schema_problems(manifest, schema) + if not problems: + problems = file_problems(manifest, root) + for problem in problems: + annotate("error", problem, "App Centre manifest invalid") + print(f"{MANIFEST_NAME}: {'invalid' if problems else 'valid'}") + return 1 if problems else 0 + + +def main() -> int: + """Command-line entry point.""" + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--repository-root", type=Path, default=Path(".")) + args = parser.parse_args() + try: + return check(args.repository_root.resolve()) + except CheckError as err: + print(f"::error title=App Centre check could not run::{err}") + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.tools/python/check_placeholders.py b/.tools/python/check_placeholders.py new file mode 100644 index 0000000..b06559f --- /dev/null +++ b/.tools/python/check_placeholders.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Stop a release whose installer would ship a template placeholder (CellMigrationLab/LabConstrictor#40). + +The repository initialisation (the LabConstrictor web form) replaces the template's placeholders with the app's names. A placeholder +it misses survives into the installer: `import PYTHON_PROJ_NAME` in post_install.sh / .bat made every installer of an app with Python +code in src/ fail at its last step. This script runs in the release workflow after the versioned files are updated and before anything +is committed or built, and fails with the file, the line and the fix when an initialisation placeholder is left in a file the +installer ships (app/**, construct.yaml, setup.py, environment.yaml), or when the repository is the raw, uninitialised template. + +Placeholders that are filled in later on purpose are not checked: BASE_PATH_KEYWORD (at install time), PYTHON_VERSION and +JUPYTERLAB_VERSION (by the requirements workflow). + +Usage: python .tools/python/check_placeholders.py [--repository-root PATH] +""" +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_23.md" + +# The placeholders the initialisation replaces (keys of conversion_table in LabConstrictor_streamlit's placeholders.py, +# plus the launcher icon paths it fills in itself). VERSION_NUMBER is also rewritten by bump_version.py, which runs before this check. +INIT_PLACEHOLDERS = ( + "LOWER_PROJ_NAME", + "PYTHON_PROJ_NAME", + "UNDERSCORED_PROJECT_NAME", + "PROJECT_NAME", + "VERSION_NUMBER", + "WELCOME_IMAGE", + "HEADER_IMAGE", + "ICON_IMAGE", + "GITHUB_OWNER", + "GITHUB_REPO_NAME", + "HIDE_CODE_DISABLED", + "ICON_IMAGE_PATH", + "ICON_ICO_IMAGE_PATH", + "ICON_ICNS_IMAGE_PATH", +) +SHIPPED_FILES = ("construct.yaml", "setup.py", "environment.yaml") +SHIPPED_FOLDERS = ("app",) +WELCOME_NOTEBOOK = "app/menuinst/Welcome.ipynb" +WELCOME_TEMPLATE = ".tools/templates/Welcome_template.ipynb" + + +def placeholder_pattern(name: str) -> re.Pattern[str]: + """A placeholder on its own or followed by '_' (PYTHON_PROJ_NAME_lc_tools), never inside a longer name (UNDERSCORED_PROJECT_NAME).""" + return re.compile(r"(? list[Path]: + files = [root / name for name in SHIPPED_FILES if (root / name).is_file()] + for folder in SHIPPED_FOLDERS: + if (root / folder).is_dir(): + files.extend(sorted(p for p in (root / folder).rglob("*") if p.is_file())) + return files + + +def leftover_placeholders(root: Path) -> list[str]: + problems = [] + for path in shipped_files(root): + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue # images, icons and other binary files + rel = path.relative_to(root).as_posix() + # The Welcome notebook is rebuilt from its template at every release: the fix belongs in the template. + where = f" (fix it in {WELCOME_TEMPLATE}, which this notebook is made from)" if rel == WELCOME_NOTEBOOK else "" + for number, line in enumerate(text.splitlines(), start=1): + for name, pattern in PATTERNS.items(): + if pattern.search(line): + problems.append(f"{rel}:{number}: the template placeholder {name} was never replaced{where}: {line.strip()[:160]}") + return problems + + +def check(root: Path) -> list[str]: + construct = root / "construct.yaml" + if construct.is_file() and re.search(r"^name:\s*UNDERSCORED_PROJECT_NAME\s*$", construct.read_text(encoding="utf-8"), re.MULTILINE): + return ["construct.yaml: this is the raw LabConstrictor template; initialise the repository with the LabConstrictor form before releasing it"] + return leftover_placeholders(root) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Fail when a template placeholder is left in a file the installer ships.") + parser.add_argument("--repository-root", type=Path, default=Path.cwd()) + args = parser.parse_args(argv) + problems = check(args.repository_root.resolve()) + if not problems: + print("No template placeholder is left in the files the installer ships.") + return 0 + print("The installer would be broken: these files still hold template placeholders.", file=sys.stderr) + for problem in problems: + print(f" {problem}", file=sys.stderr) + print( + "Replace each placeholder with your app's value (PYTHON_PROJ_NAME: the Python package of the app, usually its folder in src/; " + "PROJECT_NAME: the app name), " + f"commit, and publish the release again. See {DOCS_URL}", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.tools/python/lock_requirements.py b/.tools/python/lock_requirements.py new file mode 100644 index 0000000..c5834a2 --- /dev/null +++ b/.tools/python/lock_requirements.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Lock the merged requirements files: requirements*.txt -> requirements*.lock.txt. + +merge_requirements.py writes the requirements of the notebooks (requirements.txt, requirements_gpu.txt and the per-OS +requirements-.txt). Those files name the packages the notebooks need, but not the packages these depend on, so two +installations of the same release could get different versions. This script writes, next to each file, a lock file that lists +every package pip installs, each with its exact version, and post_install installs the lock file when the installer bundles one. + +How a lock file is made: +* `uv pip compile --universal`: one lock file that is valid on Windows, macOS and Linux (a package that only one platform needs carries + an environment marker, e.g. `colorama==0.4.6 ; sys_platform == 'win32'`). +* `--python-version` is the Python of environment.yaml. uv reads it as the lowest Python of the resolution, so a few packages can appear + twice with a `python_full_version` marker: pip installs the line that matches the Python of the installer. +* The conda packages of environment.yaml (jupyterlab, pip, setuptools, certifi, ...) are installed by the installer itself, so they are + not written to the lock file (their own dependencies are), and a conda pin such as `jupyterlab=4.4.0` constrains the resolution. +* The per-OS files are resolved with requirements.lock.txt as constraints, so a package that both files need gets the same version. +* Pip options of the requirements file (`--extra-index-url` of the GPU file, ...) are copied to the top of the lock file. + +A lock file is written again only when its requirements file, the Python or JupyterLab version (or this script's lock format) changed: +its header holds a fingerprint of those inputs. Re-running the script without such a change rewrites nothing, so a new release +installs the same versions as the previous one. To move every package to its newest version, delete the lock files and run the +workflow "Updates on notebook change" by hand (Actions > Run workflow). + +If a file cannot be locked (uv is missing, or the requirements cannot be resolved), the script prints a warning, removes the +out-of-date lock file of that file (an installer must never install versions that no longer match the requirements) and goes on: +the installer then installs the plain requirements file. The script itself always exits 0 for such a failure. +""" +from __future__ import annotations + +import argparse +import hashlib +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +import yaml + +# Bump when the uv arguments or the output change, so that every lock file is written again. +LOCK_FORMAT = "1" +BASE_INPUT = "requirements.txt" +GPU_INPUT = "requirements_gpu.txt" +OS_INPUTS = ("requirements-linux.txt", "requirements-windows.txt", "requirements-macos.txt") +INPUTS = (BASE_INPUT, GPU_INPUT, *OS_INPUTS) +FINGERPRINT_PREFIX = "# lock-input: sha256:" +# Pip options that choose where packages come from: copied to the top of the lock file, so pip finds the locked versions where uv found them. +INDEX_OPTION = re.compile(r"^\s*(--index-url|--extra-index-url|-i|--find-links|-f|--trusted-host)(\s|=)") +CONDA_SPEC = re.compile(r"^\s*([A-Za-z0-9_.-]+)\s*(?:(==?)\s*([0-9][A-Za-z0-9_.+!*-]*))?(?:=\S+)?\s*$") +PLACEHOLDER = re.compile(r"^[A-Z_]+$") + + +def lock_path(requirements: Path) -> Path: + """requirements.txt -> requirements.lock.txt (same folder).""" + return requirements.with_name(requirements.stem + ".lock.txt") + + +def read_environment(path: Path) -> tuple[str | None, list[str], list[str]]: + """(Python version, conda package names, pip constraints from exact conda pins) of environment.yaml.""" + if not path.is_file(): + return None, [], [] + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + python_version = None + names: list[str] = [] + constraints: list[str] = [] + for dependency in data.get("dependencies", []) or []: + if not isinstance(dependency, str): + continue # the `pip:` subsection of an environment file + match = CONDA_SPEC.match(dependency) + if match: + name, operator, version = match.group(1), match.group(2), match.group(3) + else: + # a spec with a range or alternatives (`pip>=24.2`): only its name is used + name, operator, version = re.split(r"[\s<>=!|,\[]", dependency.strip(), maxsplit=1)[0], None, None + if not name: + continue + if version and PLACEHOLDER.match(version): + version = None # the template itself (python=PYTHON_VERSION) + if name.lower() == "python": + python_version = version + continue + names.append(name) + if version: + # conda `name=1.2` means any 1.2.* release, `name==1.2` exactly 1.2 + constraints.append(f"{name}=={version}" if operator == "==" else f"{name}=={version.removesuffix('.*')}.*") + return python_version, sorted(set(names), key=str.lower), constraints + + +def normalized_requirements(text: str) -> str: + """The requirement and option lines of a requirements file (comments, such as the timestamp of merge_requirements.py, are ignored).""" + lines = [] + for line in text.replace("\r\n", "\n").split("\n"): + stripped = line.strip() + if stripped and not stripped.startswith("#"): + lines.append(stripped) + return "\n".join(lines) + + +def fingerprint(requirements_text: str, python_version: str, constraints: list[str], no_emit: list[str], extra_constraints: str) -> str: + payload = "\n---\n".join( + [LOCK_FORMAT, normalized_requirements(requirements_text), python_version, "\n".join(constraints), "\n".join(no_emit), extra_constraints] + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def current_fingerprint(lock: Path) -> str | None: + if not lock.is_file(): + return None + for line in lock.read_text(encoding="utf-8").splitlines(): + if line.startswith(FINGERPRINT_PREFIX): + return line[len(FINGERPRINT_PREFIX):].strip() + return None + + +def run_uv(requirements: Path, python_version: str, constraint_files: list[Path], no_emit: list[str]) -> str: + """The resolution of `requirements` (stdout of uv pip compile); raises RuntimeError with uv's message when it fails.""" + command = [ + sys.executable, "-m", "uv", "pip", "compile", str(requirements), + "--universal", "--python-version", python_version, + "--no-header", "--no-annotate", "--no-config", "--quiet", + ] + for constraint in constraint_files: + command += ["--constraint", str(constraint)] + for name in no_emit: + command += ["--no-emit-package", name] + try: + result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", check=False) + except OSError as exc: + raise RuntimeError(f"uv could not be started: {exc}") from exc + if result.returncode != 0: + message = (result.stderr or result.stdout).strip() or f"exit code {result.returncode}" + raise RuntimeError(message) + return result.stdout + + +def uv_version() -> str: + try: + result = subprocess.run([sys.executable, "-m", "uv", "--version"], capture_output=True, text=True, check=False) + except OSError: + return "uv" + # "uv 0.13.3 (502f93ca6 2026-10-19 x86_64-pc-windows-msvc)" -> "uv 0.13.3": the build details differ between computers + return " ".join(result.stdout.split()[:2]) or "uv" + + +def render_lock(requirements: Path, resolved: str, digest: str, python_version: str, uv: str) -> str: + options = [line.strip() for line in requirements.read_text(encoding="utf-8").splitlines() if INDEX_OPTION.match(line)] + packages = [line.rstrip() for line in resolved.replace("\r\n", "\n").split("\n") if line.strip() and not line.lstrip().startswith("#")] + header = [ + f"# Lock file of {requirements.name}: every package the installer installs with pip, with its exact version.", + f"# Written by .tools/python/lock_requirements.py ({uv}, universal resolution for Python {python_version}); do not edit it by hand.", + f"# It is written again only when {requirements.name}, the Python or JupyterLab version changes (see the fingerprint below).", + f"{FINGERPRINT_PREFIX}{digest}", + ] + body = options + ([""] if options else []) + packages + return "\n".join(header + [""] + body) + "\n" + + +def warn(message: str) -> None: + # `::warning::` shows the message on the summary page of the GitHub Actions run. + print(f"::warning::{message}", flush=True) + + +def lock_file( + requirements: Path, + python_version: str, + constraints: list[str], + no_emit: list[str], + base_lock: Path | None, + work_dir: Path, + uv: str, +) -> str: + """Lock one requirements file; returns what happened ("unchanged", "written", "failed").""" + lock = lock_path(requirements) + extra = base_lock.read_text(encoding="utf-8") if base_lock is not None and base_lock.is_file() else "" + digest = fingerprint(requirements.read_text(encoding="utf-8"), python_version, constraints, no_emit, normalized_requirements(extra)) + if current_fingerprint(lock) == digest: + print(f"{lock}: up to date (unchanged)") + return "unchanged" + constraint_files = [] + if constraints: + conda_constraints = work_dir / "conda_constraints.txt" + conda_constraints.write_text("\n".join(constraints) + "\n", encoding="utf-8") + constraint_files.append(conda_constraints) + if extra: + # Only the package lines: the pip options of the base lock are not constraints. + base_constraints = work_dir / "base_constraints.txt" + base_constraints.write_text( + "\n".join(line for line in extra.splitlines() if line.strip() and not line.startswith(("#", "-"))) + "\n", encoding="utf-8" + ) + constraint_files.append(base_constraints) + try: + resolved = run_uv(requirements, python_version, constraint_files, no_emit) + except RuntimeError as exc: + warn(f"{requirements} could not be locked, so the installer installs it without a lock file: {exc}") + if lock.exists(): + lock.unlink() + print(f"{lock}: removed (it no longer matches {requirements})") + return "failed" + with lock.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(render_lock(requirements, resolved, digest, python_version, uv)) + print(f"{lock}: written") + return "written" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Lock requirements*.txt into requirements*.lock.txt (every package with its exact version).") + parser.add_argument("--root", type=Path, default=Path("."), help="Folder with the requirements files and environment.yaml") + parser.add_argument("--environment", type=Path, default=None, help="Conda environment file (default: /environment.yaml)") + args = parser.parse_args(argv) + root: Path = args.root + environment = args.environment or root / "environment.yaml" + + python_version, conda_names, constraints = read_environment(environment) + if not python_version: + print(f"{environment}: no exact Python version (python=X.Y.Z), so nothing is locked.") + return 0 + no_emit = [name for name in conda_names if name.lower() not in {"git"}] + + # A lock file whose requirements file is gone is removed (the installer must not install it). + for name in INPUTS: + requirements = root / name + if not requirements.is_file() and lock_path(requirements).is_file(): + lock_path(requirements).unlink() + print(f"{lock_path(requirements)}: removed ({requirements} does not exist)") + + present = [root / name for name in INPUTS if (root / name).is_file()] + if not present: + print("No requirements files found: nothing to lock.") + return 0 + uv = uv_version() + results = {} + with tempfile.TemporaryDirectory() as temporary: + work_dir = Path(temporary) + for requirements in present: + base_lock = lock_path(root / BASE_INPUT) if requirements.name in OS_INPUTS else None + results[requirements.name] = lock_file(requirements, python_version, constraints, no_emit, base_lock, work_dir, uv) + failed = [name for name, status in results.items() if status == "failed"] + print(f"Lock files: {len(results) - len(failed)} of {len(results)} requirements files locked" + (f"; not locked: {', '.join(failed)}" if failed else "")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.tools/python/merge_requirements.py b/.tools/python/merge_requirements.py new file mode 100644 index 0000000..fe22142 --- /dev/null +++ b/.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/.tools/python/pypi_package.py b/.tools/python/pypi_package.py new file mode 100644 index 0000000..d7783b7 --- /dev/null +++ b/.tools/python/pypi_package.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Build the app's Python package (the code in src/) for PyPI, as .github/workflows/publish_pypi.yml does at each release. + +The workflow runs only when the repository variable PYPI_PUBLISH is "true" (PyPI) or "testpypi" (TestPyPI, a trial). This script: + +1. stops before building, with the reason, when the release cannot be published: no package in src/, a version that is not X.Y.Z, + a version that is already on the index, another workflow of the repository that also publishes to PyPI, or a setup.py that + still has a template placeholder; +2. writes the release version into setup.py of the checkout, without committing it: the release tag points to the commit before + the "Update version" commit of the release workflow, so the committed version cannot be trusted. The name is the one in + setup.py; `distribution.pip` of labconstrictor-app.yaml, when there is one, must be the same name; +3. builds the source distribution and the wheel (`python -m build`: the wheel is built from the source distribution, so a file + missing from it shows), and checks their name, version and dependencies. + +It never uploads: the next job of the workflow does, with PyPI trusted publishing (no token). + +Usage: + python .tools/python/pypi_package.py --version 1.2.3 [--index pypi|testpypi] [--outdir dist] [--github-output FILE] +""" +from __future__ import annotations + +import argparse +import email.parser +import re +import subprocess +import sys +import tarfile +import tomllib +import urllib.error +import urllib.request +import zipfile +from email.message import Message +from pathlib import Path +from typing import Any, Callable + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = "publish_pypi.yml" +DOCS = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/external_code_upload.md#4-publish-the-code-on-pypi-optional" +# --index: the value of PYPI_PUBLISH ("true" is PyPI) -> (label, address) +INDEXES = {"pypi": ("PyPI", "https://pypi.org"), "true": ("PyPI", "https://pypi.org"), "testpypi": ("TestPyPI", "https://test.pypi.org")} +VERSION_RE = re.compile(r"\d+\.\d+\.\d+") +# Text in a workflow that uploads to PyPI (the action of the template, or twine). +PUBLISH_MARKERS = ("pypa/gh-action-pypi-publish", "twine upload") +PLACEHOLDERS = ("PYTHON_PROJ_NAME", "VERSION_NUMBER", "PYTHON_VERSION") + + +class PackageError(Exception): + """A reason not to publish, written to the log of the workflow.""" + + +def normalise(name: str) -> str: + """The name as PyPI compares names (PEP 503): my_App.tools and my-app-tools are the same project.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def packages(root: Path) -> list[str]: + """The packages of src/: its folders with an __init__.py.""" + src = root / "src" + if not src.is_dir(): + return [] + return sorted(path.parent.name for path in src.glob("*/__init__.py")) + + +def other_publishers(root: Path) -> list[str]: + """The workflows of the repository, other than the template's, that upload to PyPI.""" + found = [] + folder = root / ".github" / "workflows" + for path in sorted(folder.glob("*.y*ml")) if folder.is_dir() else []: + if path.name == WORKFLOW: + continue + text = path.read_text(encoding="utf-8", errors="replace") + if any(marker in text for marker in PUBLISH_MARKERS): + found.append(path.relative_to(root).as_posix()) + return found + + +def manifest_pip_name(root: Path) -> str | None: + """`distribution.pip` of labconstrictor-app.yaml: the name of the package on PyPI, when the app gives one.""" + import yaml + + path = root / "labconstrictor-app.yaml" + if not path.is_file(): + return None + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as exc: + raise PackageError(f"labconstrictor-app.yaml is not valid YAML ({exc}); run the 'Check app manifest' workflow to see where") from exc + distribution = data.get("distribution") if isinstance(data, dict) else None + name = distribution.get("pip") if isinstance(distribution, dict) else None + return name.strip() if isinstance(name, str) and name.strip() else None + + +def _value_re(key: str) -> re.Pattern[str]: + return re.compile(rf"^(?P[ \t]*{key}\s*=\s*)(?P[\"'])(?P[^\"'\n]*)(?P=quote)", re.MULTILINE) + + +def setup_value(text: str, key: str) -> str | None: + """The first `key="value"` of setup.py (name, version), or None when it is not written there as a string.""" + match = _value_re(key).search(text) + return match.group("value") if match else None + + +def set_setup_value(text: str, key: str, value: str) -> str: + return _value_re(key).sub(lambda m: f"{m.group('head')}{m.group('quote')}{value}{m.group('quote')}", text, count=1) + + +def pyproject_project(root: Path) -> dict[str, Any] | None: + """The [project] table of pyproject.toml, when the package is described there (it then wins over setup.py).""" + path = root / "pyproject.toml" + if not path.is_file(): + return None + try: + project = tomllib.loads(path.read_text(encoding="utf-8")).get("project") + except tomllib.TOMLDecodeError as exc: + raise PackageError(f"pyproject.toml is not valid TOML: {exc}") from exc + return project if isinstance(project, dict) else None + + +def version_on_index(index: str, name: str, version: str, opener: Callable[..., Any] = urllib.request.urlopen) -> bool | None: + """True when the index already has this version of the project, False when not, None when the index could not be asked.""" + url = f"{INDEXES[index][1]}/pypi/{normalise(name)}/{version}/json" + try: + with opener(url, timeout=30) as response: + return bool(response.status == 200) + except urllib.error.HTTPError as exc: + return False if exc.code == 404 else None + except (urllib.error.URLError, OSError): + return None + + +def prepare(root: Path, version: str, index: str, check_index: bool = True) -> str: + """Check that the release can be published and write its version (and name) into setup.py; returns the name on the index.""" + if not VERSION_RE.fullmatch(version): + raise PackageError(f"The release version {version!r} is not X.Y.Z (the tag must be 1.2.3 or v1.2.3, as for the installers).") + found = packages(root) + if not found: + raise PackageError( + "There is no Python package in src/ (a folder with an __init__.py, for example src/my_app/__init__.py), so there is nothing to " + f"publish. Add your code to src/ (see .tools/docs/external_code_upload.md), or delete the repository variable PYPI_PUBLISH. {DOCS}" + ) + others = other_publishers(root) + if others: + raise PackageError( + f"{', '.join(others)} also publishes to PyPI: with PYPI_PUBLISH set, the release would be uploaded twice. Keep one: delete the " + f"repository variable PYPI_PUBLISH (your workflow keeps publishing), or delete your workflow (this one publishes at each release). {DOCS}" + ) + + pip_name = manifest_pip_name(root) + project = pyproject_project(root) + setup_path = root / "setup.py" + if project is not None and "name" in project: + # pyproject.toml describes the package: its name and version are used as they are, and must match. + name = str(project["name"]) + if pip_name and normalise(pip_name) != normalise(name): + raise PackageError(f"distribution.pip of labconstrictor-app.yaml is {pip_name}, but pyproject.toml names the package {name}: make them the same.") + if "version" in project.get("dynamic", []): + return name + if project.get("version") != version: + raise PackageError( + f"pyproject.toml gives the version {project.get('version')}, not the release version {version}: set `version = \"{version}\"` in " + "pyproject.toml, commit, and publish the release again." + ) + return name + if not setup_path.is_file(): + raise PackageError("There is no setup.py (nor a [project] table in pyproject.toml) to build the package from: restore the template's setup.py.") + + text = setup_path.read_bytes().decode("utf-8") # the line endings are kept when the version is written + left = [placeholder for placeholder in PLACEHOLDERS if placeholder in text and placeholder != "VERSION_NUMBER"] + if left: + raise PackageError( + f"setup.py still has the template placeholder {', '.join(left)}: PYTHON_PROJ_NAME is the name of the package (for example my_app), " + "PYTHON_VERSION the oldest Python series it runs on (for example 3.12). Replace it, commit, and publish the release again." + ) + setup_name = setup_value(text, "name") + if pip_name and setup_name and normalise(pip_name) != normalise(setup_name): + raise PackageError( + f"distribution.pip of labconstrictor-app.yaml is {pip_name}, but setup.py names the package {setup_name}: make them the same " + "(distribution.pip is the name the App Centre tells people to pip install; the package of src/ is published under setup.py's name)." + ) + package_name = setup_name or pip_name + if not package_name: + raise PackageError("setup.py has no name=\"...\" for the package: give it the name it should have on PyPI (and in distribution.pip).") + if check_index: + label = INDEXES[index][0] + exists = version_on_index(index, package_name, version) + if exists: + raise PackageError( + f"{label} already has {package_name} {version}, and a version can be uploaded only once (even after it was deleted). " + f"Publish a new release with a higher version (the installers are built for it too). " + f"{INDEXES[index][1]}/project/{normalise(package_name)}/{version}/" + ) + if exists is None: + print(f"WARNING: {label} could not be asked whether {package_name} {version} already exists; the upload fails if it does.") + + updated = set_setup_value(text, "version", version) + if updated != text: + # newline="" keeps the line endings of the file + with setup_path.open("w", encoding="utf-8", newline="") as handle: + handle.write(updated) + return package_name + + +def left_out_requirements(root: Path) -> list[str]: + """Lines of requirements.txt that the template's setup.py does not turn into dependencies (options, paths, URLs).""" + setup_text = (root / "setup.py").read_text(encoding="utf-8") if (root / "setup.py").is_file() else "" + path = root / "requirements.txt" + if "read_requirements()" not in setup_text or not path.is_file(): + return [] + try: + from packaging.requirements import InvalidRequirement, Requirement + except ImportError: + return [] + left = [] + for line in (raw.split("#", 1)[0].strip() for raw in path.read_text(encoding="utf-8").splitlines()): + if not line: + continue + try: + if Requirement(line).url is None: + continue + except InvalidRequirement: + pass + left.append(line) + return left + + +def build(root: Path, outdir: Path, isolation: bool = True) -> None: + """`python -m build`: the source distribution, then the wheel built from it.""" + command = [sys.executable, "-m", "build", "--outdir", str(outdir), *([] if isolation else ["--no-isolation"]), str(root)] + print("Running:", " ".join(command), flush=True) + result = subprocess.run(command) + if result.returncode: + raise PackageError("The package could not be built: see the output of `python -m build` above.") + + +def _headers(data: bytes) -> Message: + return email.parser.BytesParser().parsebytes(data, headersonly=True) + + +def read_metadata(outdir: Path) -> tuple[Message, Message, list[Path]]: + """The metadata of the wheel and of the source distribution in outdir, and the two files.""" + wheels = sorted(outdir.glob("*.whl")) + sdists = sorted(outdir.glob("*.tar.gz")) + if len(wheels) != 1 or len(sdists) != 1: + raise PackageError(f"Expected one wheel and one source distribution in {outdir}, found: {', '.join(p.name for p in sorted(outdir.iterdir())) or 'nothing'}") + with zipfile.ZipFile(wheels[0]) as archive: + member = next((n for n in archive.namelist() if n.count("/") == 1 and n.endswith(".dist-info/METADATA")), None) + if member is None: + raise PackageError(f"{wheels[0].name} has no METADATA") + wheel = _headers(archive.read(member)) + with tarfile.open(sdists[0]) as archive: + info = next((m for m in archive.getmembers() if m.name.count("/") == 1 and m.name.endswith("/PKG-INFO")), None) + handle = archive.extractfile(info) if info is not None else None + if handle is None: + raise PackageError(f"{sdists[0].name} has no PKG-INFO") + sdist = _headers(handle.read()) + return wheel, sdist, [sdists[0], wheels[0]] + + +def check(outdir: Path, name: str, version: str) -> list[str]: + """Check the built files; returns their names.""" + wheel, sdist, files = read_metadata(outdir) + for label, metadata in (("wheel", wheel), ("source distribution", sdist)): + if normalise(str(metadata.get("Name", ""))) != normalise(name): + raise PackageError(f"The {label} is named {metadata.get('Name')}, not {name}: setup.py or pyproject.toml set another name.") + if metadata.get("Version") != version: + raise PackageError(f"The {label} has the version {metadata.get('Version')}, not the release version {version}: setup.py or pyproject.toml set it.") + requirements = wheel.get_all("Requires-Dist") or [] + urls = [requirement for requirement in requirements if " @ " in requirement] + if urls: + raise PackageError( + f"PyPI refuses a package whose dependency is a URL: {'; '.join(urls)}. Publish that dependency on PyPI first and name it with a version, " + "or keep the URL in requirements.txt only (the installer still installs it)." + ) + if sdist.get_all("Requires-Dist") is not None and sorted(sdist.get_all("Requires-Dist") or []) != sorted(requirements): + raise PackageError( + "The wheel built from the source distribution has other dependencies than the source distribution: a file setup.py reads is not in " + "the source distribution (requirements.txt needs `include requirements.txt` in MANIFEST.in)." + ) + return [path.name for path in files] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Build and check the app's Python package (src/) for PyPI. Nothing is uploaded.") + parser.add_argument("--version", required=True, help="The release version, X.Y.Z (the tag without the v)") + parser.add_argument("--index", default="pypi", choices=sorted(INDEXES), help="pypi (or true, the value of PYPI_PUBLISH) or testpypi") + parser.add_argument("--outdir", default="dist", help="Where to write the two files (default: dist)") + parser.add_argument("--repository-root", default=str(ROOT)) + parser.add_argument("--github-output", help="Append name=, version= and url= to this file (GitHub Actions $GITHUB_OUTPUT)") + parser.add_argument("--no-isolation", action="store_true", help="Build with the setuptools already installed (no download)") + parser.add_argument("--offline", action="store_true", help="Do not ask the index whether the version exists") + args = parser.parse_args(argv) + + root = Path(args.repository_root).resolve() + outdir = Path(args.outdir) + if not outdir.is_absolute(): + outdir = root / outdir + label, address = INDEXES[args.index] + try: + name = prepare(root, args.version, args.index, check_index=not args.offline) + for line in left_out_requirements(root): + print(f"WARNING: the line `{line}` of requirements.txt is not a dependency the package can declare on {label} (an option, a path or a URL): left out.") + if outdir.exists() and any(outdir.iterdir()): + raise PackageError(f"{outdir} is not empty: remove it first, so that only this release is uploaded.") + build(root, outdir, isolation=not args.no_isolation) + files = check(outdir, name, args.version) + except PackageError as exc: + print(f"::error title=The package cannot be published::{exc}", file=sys.stderr) + print(f"ERROR: {exc}", file=sys.stderr) + return 1 + + url = f"{address}/project/{normalise(name)}/{args.version}/" + print(f"Built {name} {args.version} for {label}: {', '.join(files)}. The next job uploads it: {url}") + if args.github_output: + with open(args.github_output, "a", encoding="utf-8") as handle: + handle.write(f"name={name}\nversion={args.version}\nurl={url}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.tools/python/release_platforms.py b/.tools/python/release_platforms.py new file mode 100644 index 0000000..4083e6b --- /dev/null +++ b/.tools/python/release_platforms.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Which installers a release builds: the systems of `distribution.platforms` in labconstrictor-app.yaml (CellMigrationLab/LabConstrictor#42). + +The release workflow builds one installer per system. An app that cannot run on a system (TensorFlow 2.17+ has no wheels for Intel Macs, for +example) leaves that system out of `distribution.platforms`, and then: + * the release workflow does not build it (this script writes the build matrix of release_constructor.yml); + * the download page (.tools/docs/download_executable.md, written by bump_version.py) has no button for it. +Without labconstrictor-app.yaml, or without `distribution.platforms` in it, every system below is built, as before template 0.1.24. + +Usage: python .tools/python/release_platforms.py [--repository-root PATH] [--github-output FILE] +""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any, NamedTuple + +import yaml + +MANIFEST = "labconstrictor-app.yaml" +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_24.md" + + +class Build(NamedTuple): + platform: str # the name in distribution.platforms + os_name: str # matrix.os_name of release_constructor.yml (names the build job, its log and dist/ folder) + runner: str # the GitHub runner that builds it + files: tuple[str, ...] # how its installers end: - + label: str # for people: the download page and the messages + + +BUILDS = ( + Build("linux-x86_64", "linux", "ubuntu-latest", ("-Linux-x86_64.sh",), "Linux"), + Build("macos-arm64", "macos-arm64", "macos-15", ("-MacOSX-arm64.pkg", "-MacOSX-arm64.sh"), "Macs with Apple silicon (M1, M2, ...)"), + Build("macos-x86_64", "macos-intel", "macos-15-intel", ("-MacOSX-x86_64.pkg", "-MacOSX-x86_64.sh"), "Macs with an Intel processor"), + Build("windows-x86_64", "windows", "windows-latest", ("-Windows-x86_64.exe",), "Windows"), +) + + +def listed_platforms(root: Path) -> list[str] | None: + """`distribution.platforms` of the app manifest; None when there is no manifest or the key is left out (every system).""" + path = root / MANIFEST + if not path.is_file(): + return None + try: + data: Any = yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as exc: + raise ValueError(f"{MANIFEST} is not valid YAML: {exc}") from exc + distribution = data.get("distribution") if isinstance(data, dict) else None + platforms = distribution.get("platforms") if isinstance(distribution, dict) else None + if platforms is None: + return None + if not isinstance(platforms, list) or not all(isinstance(item, str) for item in platforms): + raise ValueError(f"distribution.platforms in {MANIFEST} must be a list of system names, such as [windows-x86_64, macos-arm64]") + return platforms + + +def builds(root: Path) -> list[Build]: + """The builds of a release, in the order of BUILDS. Raises ValueError when the manifest lists no system this template builds.""" + listed = listed_platforms(root) + if listed is None: + return list(BUILDS) + chosen = [build for build in BUILDS if build.platform in listed] + if not chosen: + known = ", ".join(build.platform for build in BUILDS) + raise ValueError( + f"distribution.platforms in {MANIFEST} lists {', '.join(listed) or 'nothing'}, and the release builds installers only for {known}. " + "Add at least one of them, or remove distribution.installer if the app has no installer." + ) + return chosen + + +def skipped_builds(root: Path) -> list[Build]: + """The systems the release does not build (none without distribution.platforms).""" + chosen = builds(root) + return [build for build in BUILDS if build not in chosen] + + +def matrix(chosen: list[Build]) -> dict[str, list[dict[str, str]]]: + return {"include": [{"os_name": build.os_name, "runner": build.runner} for build in chosen]} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Print the build matrix of the release: the systems of distribution.platforms in labconstrictor-app.yaml.") + parser.add_argument("--repository-root", type=Path, default=Path.cwd()) + parser.add_argument("--github-output", type=Path, help="append matrix= to this file (the GITHUB_OUTPUT of a workflow step)") + args = parser.parse_args(argv) + root = args.repository_root.resolve() + try: + chosen = builds(root) + listed = listed_platforms(root) + except ValueError as exc: + print(f"{exc} See {DOCS_URL}", file=sys.stderr) + return 1 + if listed is None: + print(f"Building every installer: {MANIFEST} does not list distribution.platforms.") + else: + print(f"Building the installers of distribution.platforms in {MANIFEST}: {', '.join(build.platform for build in chosen)}.") + for build in BUILDS: + if build not in chosen: + print(f" Not built: {build.platform} ({build.label}).") + for name in listed: + if name not in {build.platform for build in BUILDS}: + print(f" Not built: {name} (the release has no runner for it).") + value = json.dumps(matrix(chosen), separators=(",", ":")) + print(f"matrix={value}") + if args.github_output: + with args.github_output.open("a", encoding="utf-8") as handle: + handle.write(f"matrix={value}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.tools/python/sync_notebook_versions.py b/.tools/python/sync_notebook_versions.py new file mode 100644 index 0000000..b8c18ed --- /dev/null +++ b/.tools/python/sync_notebook_versions.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +""" +Extract the `current_version` variable from each notebook and update +`notebooks/notebook_latest_versions.yaml` accordingly. +""" +from __future__ import annotations + +import argparse +import ast +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +ROOT = Path(__file__).resolve().parents[2] +NOTEBOOKS_DIR = ROOT / "notebooks" +OUTPUT_FILE = NOTEBOOKS_DIR / "notebook_latest_versions.yaml" + + +@dataclass +class NotebookVersion: + category: str + name: str + version: str + path: Path + + +def iter_notebooks(paths: Iterable[Path] | None) -> Iterable[Path]: + """Yield notebook paths under NOTEBOOKS_DIR.""" + if paths: + for explicit in paths: + explicit = explicit.resolve() + if not explicit.exists(): + raise SystemExit(f"Notebook not found: {explicit}") + yield explicit + return + + for ipynb in NOTEBOOKS_DIR.glob("**/*.ipynb"): + if ipynb.name.startswith("."): + continue + yield ipynb + + +def extract_current_version(nb_path: Path) -> str | None: + """Return the value assigned to `current_version` inside the notebook.""" + try: + data = json.loads(nb_path.read_text(encoding="utf-8")) + except Exception as exc: # pragma: no cover - defensive + raise SystemExit(f"Failed reading {nb_path}: {exc}") from exc + + for cell in data.get("cells", []): + if cell.get("cell_type") != "code": + continue + + raw_source = "".join(cell.get("source", [])) + # Replace IPython magics and shell commands so ast.parse doesn't choke. + sanitized_lines = [] + for line in raw_source.splitlines(): + stripped = line.lstrip() + if stripped.startswith("!") or stripped.startswith("%"): + indent = line[: len(line) - len(stripped)] + sanitized_lines.append(f"{indent}pass") + else: + sanitized_lines.append(line) + source = "\n".join(sanitized_lines) + + try: + module = ast.parse(source) + except SyntaxError: + print(f"Your notebook {nb_path} contains invalid syntax. Skipping.") + continue + + for node in module.body: + if not isinstance(node, ast.Assign): + continue + + for target in node.targets: + if isinstance(target, ast.Name) and target.id == "current_version": + value = node.value + if isinstance(value, ast.Constant) and isinstance(value.value, str): + return value.value + return "0.0.0" + + +def discover_versions(paths: Iterable[Path] | None) -> tuple[list[NotebookVersion], list[str]]: + """Collect NotebookVersion objects for all notebooks of interest.""" + results: list[NotebookVersion] = [] + missing: list[str] = [] + + for nb_path in iter_notebooks(paths): + # Check if its a .ipynb file + if nb_path.suffix != ".ipynb": + continue + + try: + relative = nb_path.relative_to(NOTEBOOKS_DIR) + except ValueError: + raise SystemExit(f"{nb_path} is outside {NOTEBOOKS_DIR}") + + if relative.parts[0].startswith("."): + # Skip hidden directories + continue + + if len(relative.parts) < 2: + # Expect at least category/file + category = "root" + else: + category = relative.parts[0] + + version = extract_current_version(nb_path) + if not version: + missing.append(str(relative)) + continue + + name = nb_path.stem + results.append(NotebookVersion(category, name, version, nb_path)) + + return results, missing + + +def render_global_yaml(grouped: dict[str, dict[str, str]]) -> str: + lines: list[str] = [] + for category in sorted(grouped): + lines.append(f'"{category}":') + for name, version in grouped[category].items(): + lines.append(f' "{name}": "{version}"') + return "\n".join(lines) + "\n" + + +def group_versions(versions: Iterable[NotebookVersion]) -> dict[str, dict[str, str]]: + grouped: dict[str, dict[str, str]] = {} + for item in versions: + bucket = grouped.setdefault(item.category, {}) + bucket[item.name] = item.version + # Sort names to keep output stable + for category in grouped: + grouped[category] = dict(sorted(grouped[category].items())) + return grouped + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Update notebook_latest_versions.yaml from notebook metadata." + ) + parser.add_argument( + "paths", + nargs="*", + type=Path, + help="Optional notebook paths to update (defaults to all notebooks).", + ) + args = parser.parse_args() + + versions, missing = discover_versions(args.paths) + grouped = group_versions(versions) + + global_yaml = render_global_yaml(grouped) + OUTPUT_FILE.write_text(global_yaml, encoding="utf-8") + for item in versions: + print(f"{item.category}/{item.name}: {item.version}") + print(f"updated {OUTPUT_FILE.relative_to(ROOT)}") + if missing: + joined = "\n".join(f"- {item}" for item in sorted(missing)) + print( + "Notebooks missing `current_version` were skipped:\n" + f"{joined}" + ) + + +if __name__ == "__main__": + main() diff --git a/.tools/python/update_changelog.py b/.tools/python/update_changelog.py new file mode 100644 index 0000000..553cd77 --- /dev/null +++ b/.tools/python/update_changelog.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +""" +Script to automatically update changelog files when versions change in latest_version.yaml +""" + +import argparse +import os +import subprocess +from datetime import datetime +from pathlib import Path +from typing import Dict, Tuple + +import yaml + +def get_git_commit_info(): + """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=%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() + + # Get the remote origin URL to construct GitHub link + try: + remote_url = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8').strip() + # Convert SSH or HTTPS URL to GitHub web URL + if remote_url.startswith('git@github.com:'): + # SSH format: git@github.com:owner/repo.git + repo_path = remote_url.replace('git@github.com:', '').replace('.git', '') + elif 'github.com' in remote_url: + # HTTPS format: https://github.com/owner/repo.git + repo_path = remote_url.split('github.com/')[-1].replace('.git', '') + else: + repo_path = None + + github_commit_url = f"https://github.com/{repo_path}/commit/{commit_hash}" if repo_path else None + except subprocess.CalledProcessError: + github_commit_url = None + + return { + 'hash': commit_hash, + 'message': commit_message, + 'author': commit_author, + 'date': commit_date, + 'github_url': github_commit_url + } + except subprocess.CalledProcessError as e: + print(f"Error getting git info: {e}") + return None + +def flatten_versions(data) -> Tuple[Dict[str, str], Dict[str, str]]: + """Flatten possibly nested version mappings into notebook -> version.""" + versions: Dict[str, str] = {} + categories: Dict[str, str] = {} + + if not data: + return versions, categories + + for key, value in data.items(): + if isinstance(value, dict): + for sub_key, sub_value in value.items(): + versions[sub_key] = sub_value + categories[sub_key] = key + else: + versions[key] = value + categories.setdefault(key, None) + return versions, categories + + +def get_previous_version_file(version_file_path): + """Get the previous version of the version manifest from git""" + try: + previous_content = subprocess.check_output( + ['git', 'show', f'HEAD~1:{version_file_path}'], + text=True, + ) + data = yaml.safe_load(previous_content) or {} + return flatten_versions(data) + except subprocess.CalledProcessError: + return {}, {} + +def load_current_versions(version_file_path): + """Load current versions from the manifest file.""" + version_file = Path(version_file_path) + if version_file.exists(): + with open(version_file, 'r', encoding='utf-8') as f: + data = yaml.safe_load(f) or {} + return flatten_versions(data) + return {}, {} + + +def find_notebook_folder(root_path, project_name): + """Find the corresponding notebook folder for a project.""" + root_path = Path(root_path) + + for folder in root_path.iterdir(): + if folder.name == '__pycache__': + continue + if folder.is_dir(): + notebook_path = find_notebook_folder(folder, project_name) + if notebook_path: + return notebook_path + elif folder.stem == project_name and folder.suffix == '.ipynb': + return folder.parent + + return None + + +def create_or_update_changelog(project_name, old_version, new_version, commit_info, version_file_path, category=None): + """Create or update changelog file for a project.""" + folder_path = find_notebook_folder(Path(version_file_path).parent, project_name) + if folder_path is None: + print(f"Skipping changelog update for {project_name}: notebook folder not found.") + return + + changelog_path = folder_path / 'CHANGELOG.md' + + # Create changelog entry + entry_date = datetime.now().strftime('%Y-%m-%d') + + # Create hash field with link if GitHub URL is available + if commit_info.get('github_url'): + hash_field = f"[`{commit_info['hash'][:8]}`]({commit_info['github_url']})" + else: + hash_field = f"`{commit_info['hash'][:8]}`" + + changelog_entry = f""" +## [{new_version}] - {entry_date} + +### Changed +- Version updated from {old_version} to {new_version} + +**Commit Details:** +- Hash: {hash_field} +- Author: {commit_info['author']} +- Date: {commit_info['date']} +- Message: {commit_info['message']} + +--- +""" + + if changelog_path.exists(): + # Read existing changelog + with open(changelog_path, 'r', encoding='utf-8') as f: + content = f.read() + + # Find where to insert the new entry (after the title) + lines = content.split('\n') + insert_index = 0 + + # Look for the first ## heading or insert after title + for i, line in enumerate(lines): + if line.startswith('# '): + insert_index = i + 1 + # Skip any description lines until we find the first version entry + while insert_index < len(lines) and not lines[insert_index].startswith('## ['): + insert_index += 1 + break + + # Insert the new entry + lines.insert(insert_index, changelog_entry.strip()) + new_content = '\n'.join(lines) + + else: + # Create new changelog + new_content = f"""# Changelog - {project_name} + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +{changelog_entry.strip()} +""" + + # Write the updated changelog + with open(changelog_path, 'w', encoding='utf-8') as f: + f.write(new_content) + + print(f"Updated changelog for {project_name}: {changelog_path}") + +def main(): + """Main function to check for version changes and update changelogs""" + parser = argparse.ArgumentParser(description='Update changelog files when versions change') + parser.add_argument('version_file', help='Path to the latest_version.yaml file that changed') + + args = parser.parse_args() + version_file_path = args.version_file + + print(f"Processing version file: {version_file_path}") + + # Get git commit information + commit_info = get_git_commit_info() + if not commit_info: + print("Error: Could not get git commit information") + return + + # Load current and previous versions + current_versions, category_map = load_current_versions(version_file_path) + previous_versions, _ = get_previous_version_file(version_file_path) + + print(f"Current versions: {current_versions}") + print(f"Previous versions: {previous_versions}") + + # Check for changes + changes_found = False + for project_name, current_version in current_versions.items(): + previous_version = previous_versions.get(project_name, "0.0.0") + if current_version != previous_version: + print(f"Version change detected for {project_name}: {previous_version} -> {current_version}") + category = category_map.get(project_name) + create_or_update_changelog( + project_name, + previous_version, + current_version, + commit_info, + version_file_path, + category=category, + ) + changes_found = True + continue + + # Detect removed entries (optional) + removed_projects = set(previous_versions) - set(current_versions) + if removed_projects: + print(f"Projects removed from manifest: {', '.join(sorted(removed_projects))}") + + if not changes_found: + print("No version changes detected.") + else: + print("Changelog updates completed.") + +if __name__ == "__main__": + main() diff --git a/.tools/python/update_version_last_commit.py b/.tools/python/update_version_last_commit.py new file mode 100644 index 0000000..725f4b4 --- /dev/null +++ b/.tools/python/update_version_last_commit.py @@ -0,0 +1,155 @@ +import argparse +import subprocess +from pathlib import Path +from typing import Dict, Tuple + +import yaml + +def get_git_commit_info(): + """Get current commit hash, parent hash, and message""" + try: + commit_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip() + parent_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD^']).decode('utf-8').strip() + + # Get the remote origin URL to construct GitHub link + try: + remote_url = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8').strip() + # Convert SSH or HTTPS URL to GitHub web URL + if remote_url.startswith('git@github.com:'): + repo_path = remote_url.replace('git@github.com:', '').replace('.git', '') + elif 'github.com' in remote_url: + repo_path = remote_url.split('github.com/')[-1].replace('.git', '') + else: + repo_path = None + + github_commit_url = f"https://github.com/{repo_path}/commit/{commit_hash}" if repo_path else None + github_parent_url = f"https://github.com/{repo_path}/commit/{parent_hash}" if repo_path else None + except subprocess.CalledProcessError: + github_commit_url = None + github_parent_url = None + + return { + 'hash': commit_hash, + 'parent_hash': parent_hash, + 'github_url': github_commit_url, + 'github_parent_url': github_parent_url + } + except subprocess.CalledProcessError as e: + print(f"Error getting git info: {e}") + +def flatten_versions(data) -> Tuple[Dict[str, str], Dict[str, str]]: + versions: Dict[str, str] = {} + categories: Dict[str, str] = {} + + if not data: + return versions, categories + + for key, value in data.items(): + if isinstance(value, dict): + for sub_key, sub_value in value.items(): + versions[sub_key] = sub_value + categories[sub_key] = key + else: + versions[key] = value + categories.setdefault(key, None) + return versions, categories + + +def load_current_versions(version_file_path): + """Load current versions from the manifest.""" + version_file = Path(version_file_path) + if version_file.exists(): + with open(version_file, 'r', encoding='utf-8') as f: + data = yaml.safe_load(f) or {} + return flatten_versions(data) + return {}, {} + +def get_previous_version_file(version_file_path): + """Get the previous version of the manifest from git.""" + try: + previous_content = subprocess.check_output( + ['git', 'show', f'HEAD~1:{version_file_path}'], + text=True, + ) + data = yaml.safe_load(previous_content) or {} + return flatten_versions(data) + except subprocess.CalledProcessError: + return {}, {} + + +def find_notebook_folder(project_name, version_file_path, category=None): + """Locate the notebook directory for a project.""" + version_dir = Path(version_file_path).parent + if category: + project_folder = version_dir / category / project_name + if project_folder.exists(): + return project_folder + + for folder in version_dir.iterdir(): + if not folder.is_dir() or folder.name == '__pycache__': + continue + project_folder = folder / project_name + if project_folder.exists(): + return project_folder + return None + +def main(): + """Main function to check for version changes and update changelogs""" + parser = argparse.ArgumentParser(description='Update changelog files when versions change') + parser.add_argument('version_file', help='Path to the latest_version.yaml file that changed') + + args = parser.parse_args() + version_file_path = Path(args.version_file) + + print(f"Processing version file: {version_file_path}") + + # Get git commit information + commit_info = get_git_commit_info() + if not commit_info: + print("Error: Could not get git commit information") + return + + # Load current and previous versions + current_versions, category_map = load_current_versions(version_file_path) + previous_versions, _ = get_previous_version_file(version_file_path) + + print(f"Current versions: {current_versions}") + print(f"Previous versions: {previous_versions}") + + changes_found = False + for project_name, current_version in current_versions.items(): + previous_version = previous_versions.get(project_name, "0.0.0") + if current_version != previous_version: + print(f"Version change detected for {project_name}: {previous_version} -> {current_version}") + + folder = find_notebook_folder(project_name, version_file_path, category_map.get(project_name)) + if folder is None: + print(f"Skipping last-commit update for {project_name}: notebook folder not found.") + continue + + version_last_config_path = folder / "version_last_commit.yaml" + + # Load last commit info if it exists + last_commit_info = {} + if version_last_config_path.exists(): + with open(version_last_config_path, 'r', encoding='utf-8') as f: + last_commit_info = yaml.safe_load(f) or {} + + # Add the project into the last commit info + if project_name not in last_commit_info: + last_commit_info[project_name] = {previous_version: commit_info['parent_hash']} + else: + last_commit_info[project_name][previous_version] = commit_info['parent_hash'] + + with open(version_last_config_path, 'w', encoding='utf-8') as f: + yaml.dump(last_commit_info, f) + + changes_found = True + + if not changes_found: + print("No version changes detected.") + else: + print(f"Version's last commits updated on {version_file_path}") + +if __name__ == "__main__": + main() diff --git a/.tools/requirements.txt b/.tools/requirements.txt new file mode 100644 index 0000000..eb02274 --- /dev/null +++ b/.tools/requirements.txt @@ -0,0 +1,7 @@ +# Python 3.11 +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/README.md b/.tools/schema/README.md new file mode 100644 index 0000000..693a241 --- /dev/null +++ b/.tools/schema/README.md @@ -0,0 +1,8 @@ +# Schema copy + +`labconstrictor-app.schema.json` is a copy of the schema of the LabConstrictor App Centre manifest +(`labconstrictor-app.yaml`). The authority is the LabConstrictor site repository +(`schema/labconstrictor-app.schema.json`, published at +https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json). When that file changes, copy it here, +into `.template_sync/resources/` for the next template version, and into the repository initialiser +(`LabConstrictor_streamlit/schemas/`). diff --git a/.tools/schema/labconstrictor-app.schema.json b/.tools/schema/labconstrictor-app.schema.json new file mode 100644 index 0000000..1e67f94 --- /dev/null +++ b/.tools/schema/labconstrictor-app.schema.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$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://cellmigrationlab.github.io/LabConstrictor-Site/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/.tools/templates/Welcome_template.ipynb b/.tools/templates/Welcome_template.ipynb new file mode 100644 index 0000000..c5c8156 --- /dev/null +++ b/.tools/templates/Welcome_template.ipynb @@ -0,0 +1,717 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "335f15f8", + "metadata": {}, + "source": [ + "# Welcome to Fast4DRegPy! \n", + "---\n", + "\n", + "## How does it work?\n", + "\n", + "This welcome notebook provides two main features:\n", + "\n", + "### 1. Browse and Open Notebooks\n", + "\n", + "You will find below an interactive table with all available notebooks, each designed to facilitate a specific aspect of experiment management. Simply click on any \"Open the notebook\" button to launch it in JupyterLab.\n", + "\n", + "### 2. Check for Updates\n", + "\n", + "Stay up-to-date with the latest notebook versions! Run the cell below to compare your local notebooks with the latest versions in the app's GitHub repository. If the repository is private, enter your GitHub Personal Access Token and click \"Load Private GitHub Repo\". You can update any outdated notebook with a single click.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bd6a16d4", + "metadata": { + "cellView": "form", + "collapsed": false, + "jupyter": { + "source_hidden": true + }, + "jupyterlabHideCode": { + "locked": true + } + }, + "outputs": [], + "source": [ + "# Run this cell to see the interactive notebook list โฌ‡๏ธโฌ‡๏ธโฌ‡๏ธ\n", + "\n", + "from IPython.display import display, Markdown, HTML, Javascript, clear_output\n", + "from ipywidgets import widgets, GridspecLayout\n", + "from pathlib import Path\n", + "import subprocess\n", + "import requests\n", + "import tempfile\n", + "import zipfile\n", + "import base64\n", + "import shutil\n", + "import json\n", + "import yaml\n", + "import sys\n", + "\n", + "# Capture stdout, stderr, rich displays, figures, warnings, and tracebacks from widget callbacks.\n", + "_widget_callback_output_cell_1 = widgets.Output()\n", + "\n", + "\n", + "# Define notebooks with their metadata\n", + "notebooks = DICT_OF_NOTEBOOKS\n", + "\n", + "# Load the local information from all the notebooks\n", + "local_latest_version_path = Path(\"..\") / \"notebook_latest_versions.yaml\"\n", + "local_latest_versions = yaml.safe_load(local_latest_version_path.read_text())\n", + "\n", + "# Load the local construct information\n", + "construct_file_path = Path(\"..\") / \"construct.yaml\"\n", + "construct_info = yaml.safe_load(construct_file_path.read_text())\n", + "local_project_version = construct_info.get('version', '0.0.0')\n", + "\n", + "# Load the online information (GitHub) from all the notebooks\n", + "github_owner = \"GITHUB_OWNER\"\n", + "github_repo_name = \"GITHUB_REPO_NAME\"\n", + "github_branch = \"main\" # Change to \"dev\" if you want to check against dev branch\n", + "\n", + "def build_open_button(notebook_path: str, label: str = \"Open the notebook\") -> widgets.Widget:\n", + " normalized = Path(notebook_path).as_posix().lstrip(\"/\")\n", + "\n", + " button = widgets.Button(\n", + " description=label,\n", + " tooltip=f\"Open {normalized}\",\n", + " layout=widgets.Layout(width=\"auto\", min_width=\"140px\")\n", + " )\n", + " button.add_class(\"open-notebook-button\")\n", + "\n", + " js_output = widgets.Output(\n", + " layout=widgets.Layout(width=\"0px\", height=\"0px\", overflow=\"hidden\")\n", + " )\n", + "\n", + " def on_open_button_clicked(_):\n", + " js = f\"\"\"\n", + " (() => {{\n", + " const notebookPath = {json.dumps(normalized)};\n", + " const pathname = window.location.pathname;\n", + " const marker = \"/tree/\";\n", + " const treeIndex = pathname.indexOf(marker);\n", + "\n", + " if (treeIndex === -1) {{\n", + " window.open(notebookPath, \"_blank\");\n", + " return;\n", + " }}\n", + "\n", + " const prefix = pathname.slice(0, treeIndex + marker.length);\n", + " const currentNotebookPath = pathname.slice(treeIndex + marker.length);\n", + "\n", + " const currentParts = currentNotebookPath.split(\"/\").filter(Boolean);\n", + " if (currentParts.length > 0) {{\n", + " currentParts.pop();\n", + " }}\n", + "\n", + " const notebooksIndex = currentParts.indexOf(\"notebooks\");\n", + " const projectParts = notebooksIndex >= 0 ? currentParts.slice(0, notebooksIndex) : currentParts;\n", + "\n", + " const targetPath = [\n", + " ...projectParts,\n", + " ...notebookPath.split(\"/\").filter(Boolean)\n", + " ].join(\"/\");\n", + "\n", + " window.open(prefix + encodeURI(targetPath), \"_blank\");\n", + " }})();\n", + " \"\"\"\n", + " with js_output:\n", + " clear_output(wait=True)\n", + " display(Javascript(js))\n", + "\n", + " button.on_click(on_open_button_clicked)\n", + "\n", + " return widgets.VBox(\n", + " [button, js_output],\n", + " layout=widgets.Layout(width=\"100%\", min_width=\"0\", align_items=\"center\", justify_content=\"center\")\n", + " )\n", + "\n", + "def download_and_install_src(github_pat=None) -> None:\n", + " # Download the repository into a temporal foler\n", + " with tempfile.TemporaryDirectory() as tmpdir:\n", + " tmpdir_path = Path(tmpdir)\n", + "\n", + " staging_dir = tmpdir_path / \"managed_src_new\"\n", + " backup_dir = tmpdir_path / \"managed_src_old\"\n", + " \n", + " zip_path = tmpdir_path / \"repo.zip\"\n", + " extract_root = tmpdir_path / \"extract\"\n", + "\n", + " download_url = f\"https://api.github.com/repos/{github_owner}/{github_repo_name}/zipball/{github_branch}\"\n", + " headers = {\"Authorization\": f\"token {github_pat}\"} if github_pat else {}\n", + " response = requests.get(download_url, headers=headers, stream=True, timeout=60)\n", + " response.raise_for_status()\n", + "\n", + " with zip_path.open(\"wb\") as fh:\n", + " for chunk in response.iter_content(chunk_size=1024 * 1024):\n", + " if chunk:\n", + " fh.write(chunk)\n", + "\n", + " with zipfile.ZipFile(zip_path, \"r\") as zf:\n", + " zf.extractall(extract_root)\n", + "\n", + " extracted_roots = [p for p in extract_root.iterdir() if p.is_dir()]\n", + " if not extracted_roots:\n", + " raise RuntimeError(\"Could not find extracted repository root\")\n", + "\n", + " repo_root = extracted_roots[0]\n", + " downloaded_src_dir = repo_root / \"src\"\n", + "\n", + " if not downloaded_src_dir.exists():\n", + " raise RuntimeError(\"Downloaded repository does not contain a 'src' folder\")\n", + "\n", + " shutil.copytree(downloaded_src_dir, staging_dir)\n", + "\n", + " # Find the external code in a local folder\n", + " src_folder = Path(\"..\") / \"src\"\n", + "\n", + " try:\n", + " # Create a backup of the current src folder in case something goes wrong during the update process.\n", + " if src_folder.exists():\n", + " src_folder.rename(backup_dir)\n", + "\n", + " # Remove content in the src folder\n", + " if src_folder.exists():\n", + " shutil.rmtree(src_folder, ignore_errors=True)\n", + "\n", + " # Move the new src folder from the staging area to the src folder\n", + " staging_dir.rename(src_folder)\n", + "\n", + " # Install the external code with the new src folder's content\n", + " cmd = [\n", + " sys.executable,\n", + " \"-m\",\n", + " \"pip\",\n", + " \"install\",\n", + " \"..\",\n", + " \"--upgrade\",\n", + " \"--force-reinstall\"\n", + " ]\n", + " subprocess.check_call(cmd)\n", + "\n", + " # Once the new code is installed successfully, we can remove the backup folder since we don't need it anymore.\n", + " if backup_dir.exists():\n", + " shutil.rmtree(backup_dir)\n", + "\n", + " except Exception:\n", + " if src_folder.exists():\n", + " shutil.rmtree(src_folder, ignore_errors=True)\n", + "\n", + " if backup_dir.exists():\n", + " backup_dir.rename(src_folder)\n", + "\n", + " raise\n", + "\n", + "GRID_COLUMN_WIDTHS = (\n", + " \"minmax(0, 1.4fr) \" # Notebook Name\n", + " \"minmax(0, 1.4fr) \" # Notebook Topic\n", + " \"minmax(0, 2.8fr) \" # Description\n", + " \"minmax(85px, 0.8fr) \" # Local Version\n", + " \"minmax(100px, 1.2fr) \" # Status\n", + " \"minmax(70px, 0.7fr) \" # Update?\n", + " \"minmax(150px, 1.6fr)\" # Open Notebook\n", + ")\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", + " grid.layout.width = \"100%\"\n", + " grid.layout.min_width = \"0\"\n", + " grid.layout.grid_template_columns = GRID_COLUMN_WIDTHS\n", + " grid.layout.grid_auto_rows = \"auto\"\n", + " grid.layout.overflow = \"auto\"\n", + "\n", + "\n", + "def table_cell(value, align=\"center\", extra_class=\"\"):\n", + " \"\"\"Create a table cell that can shrink and wrap long scientific identifiers.\"\"\"\n", + " classes = [\"labconstrictor-table-cell\"]\n", + " if align == \"left\":\n", + " classes.append(\"labconstrictor-table-cell-left\")\n", + " else:\n", + " classes.append(\"labconstrictor-table-cell-center\")\n", + " if extra_class:\n", + " classes.append(extra_class)\n", + "\n", + " class_names = \" \".join(classes)\n", + "\n", + " return widgets.HTML(\n", + " value=f\"
{value}
\",\n", + " layout=widgets.Layout(width=\"100%\", min_width=\"0\"),\n", + " )\n", + "\n", + "\n", + "def table_header(value):\n", + " \"\"\"Create a responsive table header.\"\"\"\n", + " return widgets.HTML(\n", + " value=f\"
{value}
\",\n", + " layout=widgets.Layout(width=\"100%\", min_width=\"0\"),\n", + " )\n", + "\n", + "\n", + "def load_table(version_response, project_version_response, notebooks):\n", + " if version_response is None:\n", + " display(Markdown(\"โš ๏ธ Not checking versions. Could not access the version file from GitHub.\"))\n", + " online_latest_versions = local_latest_versions\n", + " else:\n", + " try:\n", + " online_latest_versions = yaml.safe_load(\n", + " base64.b64decode(version_response.json()['content']).decode('utf-8')\n", + " )\n", + " if not isinstance(online_latest_versions, dict):\n", + " display(Markdown(\"โš ๏ธ Not checking versions. The online version file format is invalid.\"))\n", + " online_latest_versions = local_latest_versions\n", + " except Exception as e:\n", + " display(Markdown(f\"โš ๏ธ Not checking versions. Could not parse version file: {e}\"))\n", + " online_latest_versions = local_latest_versions\n", + "\n", + " if project_version_response is None:\n", + " online_project_version = local_project_version\n", + " else:\n", + " try:\n", + " project_construct_info = yaml.safe_load(\n", + " base64.b64decode(project_version_response.json()['content']).decode('utf-8')\n", + " )\n", + " online_project_version = project_construct_info.get('version', '0.0.0')\n", + " except Exception as e:\n", + " display(Markdown(f\"โš ๏ธ Could not parse construct.yaml file: {e}\"))\n", + " online_project_version = local_project_version\n", + "\n", + " if online_project_version != local_project_version:\n", + " display(Markdown(f\"โŒ The project version is outdated. Local version: {local_project_version}, Online version: {online_project_version}\"))\n", + " display(Markdown(\"Please update the project to the latest version by following the update instructions. Until you update the project, you will not be able to update individual notebooks.\"))\n", + " project_needs_update = True\n", + " else:\n", + " display(Markdown(f\"โœ… The project version is up-to-date. Version: {local_project_version}\"))\n", + " project_needs_update = False\n", + "\n", + " # Check if there is external code and in case it is, check the version of the external code\n", + " src_change_path = Path(\"..\") / \"src_change.yaml\"\n", + " if src_change_path.exists():\n", + " # Load local src change info\n", + " local_src_change_info = yaml.safe_load(src_change_path.read_text())\n", + " local_src_date = local_src_change_info.get('src_last_modified', '1970-01-01_00:00:00')\n", + "\n", + " # Load online src change info\n", + " src_change_url = f\"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/.tools/meta/src_change.yaml?ref={github_branch}\"\n", + " try:\n", + " src_headers = {}\n", + " if globals().get('private_repository', False):\n", + " token_widget = globals().get('github_token')\n", + " token_value = token_widget.value if token_widget else ''\n", + " if token_value:\n", + " src_headers = {\"Authorization\": f\"token {token_value}\"}\n", + " src_change_response = requests.get(src_change_url, headers=src_headers)\n", + " if src_change_response.status_code == 200:\n", + " online_src_change_info = yaml.safe_load(\n", + " base64.b64decode(src_change_response.json()['content']).decode('utf-8')\n", + " )\n", + " online_src_date = online_src_change_info.get('src_last_modified', '1970-01-01_00:00:00')\n", + "\n", + " if online_src_date != local_src_date:\n", + " display(Markdown(f\"โš ๏ธ The source code has been updated since you last updated the notebooks.\"))\n", + " display(Markdown(\"Please click on the button bellow to update the source code to the latest version.\"))\n", + " \n", + " update_src_button = widgets.Button(description=\"Update Source Code\", button_style='warning')\n", + " src_update_output = widgets.HTML(\"\")\n", + "\n", + " def on_update_src_button_clicked(b):\n", + " src_update_output.value = \"\"\n", + " try:\n", + " src_pat = None\n", + " if globals().get('private_repository', False):\n", + " token_widget = globals().get('github_token')\n", + " src_pat = token_widget.value if token_widget else None\n", + " src_update_output.value += \"โณ Updating source code...
\"\n", + " download_and_install_src(github_pat=src_pat)\n", + " # Update the local src change info with the online info since we just updated to that version\n", + " src_change_path.write_text(yaml.dump(online_src_change_info, default_flow_style=False))\n", + " # Update the local version info to trigger the notebook update check and show the correct status in the grid without needing to refresh the page\n", + " local_latest_version_path.write_text(yaml.dump(online_latest_versions, default_flow_style=False))\n", + " src_update_output.value += \"โœ… Source code updated successfully!
\"\n", + " src_update_output.value += \"Please restart the notebook kernel to apply the changes, and then re-run this cell to check for notebook updates.
\"\n", + " src_update_output.value += \"To restart the kernel, go to the menu bar and click on Kernel -> Restart Kernel.\"\n", + " except Exception as e:\n", + " src_update_output.value += f\"โŒ Failed to update source code: {e}\"\n", + "\n", + " update_src_button.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(on_update_src_button_clicked))\n", + " display(\n", + " Markdown(\"---\"),\n", + " update_src_button, \n", + " src_update_output,\n", + " Markdown(\"---\")\n", + " )\n", + " else:\n", + " display(Markdown(f\"โœ… The source code is up to date!\"))\n", + " else:\n", + " display(Markdown(f\"โš ๏ธ Could not access external code control file from GitHub (HTTP {src_change_response.status_code}). Not checking for source code updates.\"))\n", + " except Exception as e:\n", + " display(Markdown(f\"โš ๏ธ Could not access external code control file from GitHub: {e}. Not checking for source code updates.\"))\n", + "\n", + " # Go through all the notebooks and compare versions\n", + " num_rows = len(notebooks)\n", + " grid = GridspecLayout(1 + num_rows, 7)\n", + " apply_grid_layout(grid)\n", + " grip_output = widgets.HTML()\n", + "\n", + " # Add custom CSS for responsive table styling\n", + " display(widgets.HTML(\"\"\"\n", + " \n", + " \"\"\"))\n", + "\n", + "\n", + " grid[0, 0] = table_header(\"Notebook Name\")\n", + " grid[0, 1] = table_header(\"Notebook Topic\")\n", + " grid[0, 2] = table_header(\"Description\")\n", + " grid[0, 3] = table_header(\"Local Version\")\n", + " grid[0, 4] = table_header(\"Status\")\n", + " grid[0, 5] = table_header(\"Update?\")\n", + " grid[0, 6] = table_header(\"Open Notebook\")\n", + "\n", + " needs_update = False\n", + "\n", + " idx = 1\n", + " nb = {}\n", + " \n", + " for main_folder in online_latest_versions:\n", + " if main_folder in local_latest_versions:\n", + " for subfolder in online_latest_versions[main_folder]:\n", + " # Find the notebook path from the notebooks list\n", + " notebook_found = False\n", + " for n in notebooks:\n", + " if subfolder in n['path']:\n", + " nb = n\n", + " notebook_found = True\n", + " break\n", + "\n", + " if not notebook_found:\n", + " continue\n", + " \n", + " grid[idx, 0] = table_cell(nb[\"name\"])\n", + " grid[idx, 1] = table_cell(main_folder)\n", + " \n", + " if nb:\n", + " grid[idx, 2] = table_cell(nb[\"description\"], align=\"left\")\n", + " else:\n", + " grid[idx, 2] = table_cell(\"-\")\n", + "\n", + " if subfolder in local_latest_versions.get(main_folder, {}):\n", + " online_version = online_latest_versions[main_folder][subfolder]\n", + " local_version = local_latest_versions[main_folder][subfolder]\n", + " \n", + " grid[idx, 3] = table_cell(local_version)\n", + "\n", + " if project_needs_update:\n", + " grid[idx, 4] = table_cell(\"โŒ Project Outdated\")\n", + " grid[idx, 5] = table_cell(\"-\")\n", + " elif online_version == local_version:\n", + " grid[idx, 4] = table_cell(\"โœ… Up-to-date\")\n", + " grid[idx, 5] = table_cell(\"-\")\n", + " else:\n", + " grid[idx, 4] = table_cell(f\"โŒ Needs Update to {online_version}\")\n", + " \n", + " def button_update(main_folder, subfolder, row_idx):\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", + " 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 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", + " 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", + "\n", + " update_button.on_click(_widget_callback_output_cell_1.capture(clear_output=True, wait=True)(button_update(main_folder, subfolder, row_idx=idx)))\n", + "\n", + " grid[idx, 5] = update_button\n", + "\n", + " needs_update = True\n", + " else:\n", + " grid[idx, 3] = table_cell(\"Not Found\")\n", + " grid[idx, 4] = table_cell(\"โŒ Missing Notebook\")\n", + " needs_update = True\n", + "\n", + " # Open button (centered)\n", + " grid[idx, 6] = build_open_button(nb[\"path\"]) \n", + "\n", + " idx += 1\n", + " else:\n", + " for subfolder in online_latest_versions[main_folder]:\n", + " grid[idx, 0] = table_cell(subfolder)\n", + " grid[idx, 1] = table_cell(main_folder)\n", + " grid[idx, 2] = table_cell(\"-\")\n", + " grid[idx, 3] = table_cell(\"Not Found\")\n", + " grid[idx, 4] = table_cell(\"โŒ Missing Notebook\")\n", + " grid[idx, 5] = table_cell(\"-\")\n", + " grid[idx, 6] = table_cell(\"-\")\n", + " needs_update = True\n", + "\n", + " idx += 1\n", + "\n", + " \n", + " if needs_update:\n", + " display(Markdown(\"โš ๏ธ Some notebooks need to be updated.\"))\n", + " else:\n", + " display(Markdown(\"โœ… All notebooks are up-to-date.\"))\n", + "\n", + " apply_grid_layout(grid)\n", + " display(grid, grip_output)\n", + "\n", + "version_file_path = \"notebooks/notebook_latest_versions.yaml\"\n", + "version_url = f\"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/{version_file_path}?ref={github_branch}\"\n", + "\n", + "project_version_file_path = \"construct.yaml\"\n", + "project_version_url = f\"https://api.github.com/repos/{github_owner}/{github_repo_name}/contents/{project_version_file_path}?ref={github_branch}\"\n", + "try:\n", + " version_response = requests.get(version_url)\n", + " project_version_response = requests.get(project_version_url)\n", + " error = False\n", + "except Exception as e:\n", + " load_table(None, None, notebooks)\n", + " error = True\n", + "\n", + "# Debug: show status and raw response if not 200\n", + "if not error and version_response.status_code != 200:\n", + " private_repository = True\n", + " explanation = widgets.HTML(\n", + " value=f\"\"\"\n", + " It looks like your repository might be private, please provide a Personal Access Token (PAT) to access it.\n", + " If you don't have one, you can create it by following this guide.\n", + " \"\"\"\n", + " )\n", + "\n", + " github_token = widgets.Password(\n", + " value=\"\",\n", + " description=\"*Personal Access Token:\",\n", + " placeholder=\"e.g. ghp_XXXXXXXXXXXXXXXXXXXX\",\n", + " style={'description_width': 'initial'},\n", + " layout=widgets.Layout(width='99%')\n", + " )\n", + " \n", + " test_button = widgets.Button(\n", + " description=\"Load Private GitHub Repo\",\n", + " button_style='success',\n", + " style={'description_width': 'initial'},\n", + " layout=widgets.Layout(width='99%')\n", + " )\n", + "\n", + " output_area = widgets.HTML()\n", + " table_area = widgets.Output()\n", + "\n", + " def on_test_button_clicked(b):\n", + " headers = {\n", + " \"Authorization\": f\"token {github_token.value}\"\n", + " }\n", + " auth_version_response = requests.get(version_url, headers=headers) \n", + " auth_project_version_response = requests.get(project_version_url, headers=headers)\n", + " if auth_version_response.status_code == 200 and auth_project_version_response.status_code == 200: \n", + " output_area.value = \"โœ… Successfully accessed private repository!\"\n", + " with table_area:\n", + " clear_output()\n", + " load_table(auth_version_response, auth_project_version_response, notebooks)\n", + " else:\n", + " output_area.value = f\"โŒ Failed to access private repository (HTTP {auth_version_response.status_code}).\"\n", + " output_area.value += f\"
{auth_version_response.text[:500]}
\"\n", + " with table_area:\n", + " clear_output()\n", + " load_table(None, None, notebooks)\n", + " test_button.on_click(on_test_button_clicked)\n", + "\n", + " display(explanation, github_token, test_button, output_area, table_area)\n", + "elif not error:\n", + " private_repository = False\n", + " load_table(version_response, project_version_response, notebooks)\n", + "\n", + "# Display callback-generated output directly below this cell.\n", + "display(_widget_callback_output_cell_1)\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "labchronicle", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.tools/templates/download_executable_template.md b/.tools/templates/download_executable_template.md new file mode 100644 index 0000000..ad74982 --- /dev/null +++ b/.tools/templates/download_executable_template.md @@ -0,0 +1,286 @@ + +# โฌ‡๏ธ Install Fast4DRegPy Locally + +Choose your operating system and follow the instructions below to install Fast4DRegPy on your computer. + +
+ + ๐ŸชŸ CLICK HERE TO DISPLAY WINDOWS GUIDELINES + + +## 1. Click the button to download Fast4DRegPy executable + + + Download for Windows + + +## 2. Run the executable + +Double-click the downloaded file to start the installation process. It might happen that Windows shows a `Windows protected your PC` dialog. If that happens, click on `More info` and then `Run anyway`, like on the image bellow. + +![Windows Protected your PC](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Windows_Protected_your_PC.png) + +After that, follow the on-screen prompts to complete the installation. + +> This process may take around 6-8 minutes, don't worry you will only need to this once. + +> Also, during the process a command prompt window will open, this is normal. Do NOT close it! + +![Installation Dialog](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Windows_Installation_Dialog.gif) + +## 3. Launch Fast4DRegPy + +After installation, you can launch Fast4DRegPy from your desktop app or from the Start Menu: + +![Launch Fast4DRegPy](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Windows_Launch.gif) + +Then, start using it following the instructions on the [Usage of Notebooks After Installation](./notebook_usage.md) guide. + +--- +
+ + + +
+ + ๐Ÿง CLICK HERE TO DISPLAY UBUNTU GUIDELINES + + +## 1. Click the button to download Fast4DRegPy executable + + + Download for Linux + + +## 2. Run the executable + +### Option 1: Using terminal (recommended) + +1.- Open a terminal on the folder where you downloaded the file. + +2.- Copy and paste the following command: + +```bash +bash Fast4DRegPy-VERSION_NUMBER-Linux-x86_64.sh +``` + +3.- Click Enter to run the command. + +### Option 2: Using file explorer + +1.- Open the file explorer and navigate to the folder where you downloaded the file. + +2.- Right-click on the file and select `Properties`. + +3.- At the bottom, check the box that says `Executable as Program`. + +4.- Close the properties window, right-click the file and choose `Run as a Program` to run it. + +## 3. Follow the installation prompts + +## 4. Launch Fast4DRegPy + +After installation, you can launch Fast4DRegPy from your applications menu and start using it following the instructions on the [Usage of Notebooks After Installation](./notebook_usage.md) guide. + +--- +
+ + + +
+ + ๐ŸŽ CLICK HERE TO DISPLAY MACOS GUIDELINES + + +## 1. Choose your installation strategy + +First of all, you will need to choose whether you want to install it with **(A) a graphical user interface** or with **(B) the command line**: + +
+ + A. Using the graphical user interface + + +## 2. Download the `.pkg` file + +> **How to know which one should I download?** +> 1. Click the Apple menu in the top-left corner of your screen. +> 2. Select About This Mac. +> 3. A window will pop up displaying your Macโ€™s information. Look into the `Chip` or `Processor` field. If `Intel` is mentioned, then download the Intel option. Otherwise, if `Mx` (e.g. M1 or M2) is mentioned, then download the ARM64 option. + + + Download for Mac ARM64 + + +or + + + Download for Mac Intel + + + +## 3. Install the package + +Follow the guidelines shown on the following GIF or the instructions bellow: + +![MacOS PKG Installation](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/MacOS_Install_Pkg.gif) + +1. Double-click the downloaded file to start the installation process. It might give some errors, as shown bellow, go to `Settings > Privacy & Security > Security` and there the Fast4DRegPy package should appear. Click on `Open Anyway`. +2. After that, follow the on-screen prompts to complete the installation. + > This process may take around 6-8 minutes, don't worry you will only need to do this once. + + > We recommend you choosing `Install only for me`. + +## 4. Launch Fast4DRegPy + +After installation, you can launch Fast4DRegPy from your Applications folder and start using it following the instructions on the [Usage of Notebooks After Installation](./notebook_usage.md) guide. + +
+ +
+ + B. Using the command line + + +## 2. Download the `.sh` file + +> **How to know which one should I download?** +> 1. Click the Apple menu in the top-left corner of your screen. +> 2. Select About This Mac. +> 3. A window will pop up displaying your Macโ€™s information. Look into the `Chip` or `Processor` field. If `Intel` is mentioned, then download the Intel option. Otherwise, if `Mx` (e.g. M1 or M2) is mentioned, then download the ARM64 option. + + + Download for Mac ARM64 + + +or + + + Download for Mac Intel + + + +## 3. Install the package + +Follow the guidelines shown on the following GIF or the instructions bellow: + +![MacOS Installation Dialog](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/MacOS_Install_Bash.gif) + +1. Open a terminal on the folder where you downloaded the file. +2. Copy and paste the following command: + ```bash + bash Fast4DRegPy-VERSION_NUMBER-MacOSX-ARCHITECTURE.sh + ``` +3. Click Enter to run the command. +4. Follow the on-screen prompts to complete the installation. + > This process may take around 6-8 minutes, don't worry you will only need to do this once. + +## 4. Launch Fast4DRegPy + +After installation, you can launch Fast4DRegPy from your Applications folder and start using it following the instructions on the [Usage of Notebooks After Installation](./notebook_usage.md) guide. + +
+ +
+ +--- + +# ๐Ÿ—‘๏ธ Uninstall Fast4DRegPy + + +
+ + ๐ŸชŸ CLICK HERE TO DISPLAY WINDOWS GUIDELINES + + +## 1. Go to the `Installed apps` settings + +You can do it clicking `Uninstall` in the Start Menu like on the image bellow: + +![Uninstall Fast4DRegPy](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/Windows_Uninstall.png) + +or by directly going to `Settings` > `Apps` > `Installed apps`. + +## 2. Uninstall Fast4DRegPy + +Once there, search for `Fast4DRegPy` and click the three dots on the right and select `Uninstall`. + +--- +
+ + + +
+ + ๐Ÿง CLICK HERE TO DISPLAY UBUNTU GUIDELINES + + +## 1. Go to the installation folder + +The default installation folder is: + +``` +~/fast4dregpy` +``` + +You can navigate to this folder using your file explorer or terminal. + +## 2. Run the uninstall script + +### Option 1: Using terminal (recommended) + +1.- Open a terminal on the installation folder. + +2.- Copy and paste the following command: + +```bash +bash uninstall.sh +``` + +3.- Click Enter to run the command. + +### Option 2: Using file explorer + +2.- Right-click on the `uninstall.sh` file and select `Properties`. + +3.- At the bottom, check the box that says `Executable as Program`. + +4.- Close the properties window, right-click the file and choose `Run as a Program` to run it. + +--- +
+ + + +
+ + ๐ŸŽ CLICK HERE TO DISPLAY MACOS GUIDELINES + + +![MacOS Uninstall](https://github.com/CellMigrationLab/LabConstrictor/blob/doc_source/MacOS_Uninstall.gif) + +## 1. Uninstall the App + +1.- Go to the `Applications` folder. +2.- Find Fast4DRegPy and delete it. + +## 2. Uninstall Fast4DRegPy folder + +1.- On the installation process, you chose a folder where you would install Fast4DRegPy. Find it. +2.- Delete that complete folder. + +## 3. Check that the uninstallation has been correctly done + +1.- Go to your `Trash` folder. +2.- Check that both Fast4DRegPy App and folder are there. + +
+ + +--- + + \ No newline at end of file diff --git a/.tools/templates/hide_code_cells.py b/.tools/templates/hide_code_cells.py new file mode 100644 index 0000000..a26705f --- /dev/null +++ b/.tools/templates/hide_code_cells.py @@ -0,0 +1,104 @@ +"""Utility to hide code cells in Jupyter notebooks by updating metadata.""" +from __future__ import annotations + +import argparse +from pathlib import Path +from typing import Iterable + +import nbformat + +# Metadata values required to hide code cells in supported viewers. +CELL_VIEW_VALUE = "form" +COLLAPSED_VALUE = False +SOURCE_HIDDEN_VALUE = True + +# Placeholder for repository initialisiation that enables or disables this script. +DISABLED = HIDE_CODE_DISABLED + + +def collect_notebooks(root: Path) -> Iterable[Path]: + """Yield every notebook under root (recursively for directories).""" + if root.is_file(): + if root.suffix == ".ipynb": + yield root + return + + for path in root.rglob("*.ipynb"): + if path.is_file(): + yield path + + +def hide_code_cells(notebook_path: Path) -> bool: + """Apply metadata updates to every code cell in the given notebook.""" + notebook = nbformat.read(notebook_path, as_version=nbformat.NO_CONVERT) + changed = False + + for cell in notebook.cells: + if cell.get("cell_type") != "code": + continue + + # Remove saved output + if cell.get("outputs"): + cell["outputs"] = [] + changed = True + if cell.get("execution_count") is not None: + cell["execution_count"] = None + changed = True + + metadata = cell.setdefault("metadata", {}) + + if metadata.get("cellView") != CELL_VIEW_VALUE: + metadata["cellView"] = CELL_VIEW_VALUE + changed = True + + if metadata.get("collapsed") != COLLAPSED_VALUE: + metadata["collapsed"] = COLLAPSED_VALUE + changed = True + + jupyter_meta = metadata.get("jupyter") if isinstance(metadata.get("jupyter"), dict) else {} + if jupyter_meta.get("source_hidden") != SOURCE_HIDDEN_VALUE: + jupyter_meta["source_hidden"] = SOURCE_HIDDEN_VALUE + metadata["jupyter"] = jupyter_meta + changed = True + + jupyterlab_meta = metadata.get("jupyterlabHideCode") if isinstance(metadata.get("jupyterlabHideCode"), dict) else {} + if jupyterlab_meta.get("locked") != True: + jupyterlab_meta["locked"] = True + metadata["jupyterlabHideCode"] = jupyterlab_meta + changed = True + + if changed: + nbformat.write(notebook, notebook_path) + + return changed + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Hide the code cells in notebooks under the given path.") + parser.add_argument("path", type=Path, help="File or directory to process for Jupyter notebooks") + return parser.parse_args() + + +def main() -> None: + args = parse_args() + notebooks = list(collect_notebooks(args.path)) + + if DISABLED: + print("Hiding code cells is disabled for this repository.") + print("To enable, set HIDE_CODE_DISABLED to False in app/python_scripts/hide_code_cells.py") + print("or go to https://labconstrictor-form.streamlit.app/ and initialise your repository again but with hiding code cells enabled.") + return + + if not notebooks: + print("No notebooks found.") + return + + for notebook_path in notebooks: + if hide_code_cells(notebook_path): + print(f"Updated {notebook_path}") + else: + print(f"No changes needed for {notebook_path}") + + +if __name__ == "__main__": + main() diff --git a/.tools/templates/requirements.yaml b/.tools/templates/requirements.yaml new file mode 100644 index 0000000..48bb019 --- /dev/null +++ b/.tools/templates/requirements.yaml @@ -0,0 +1,6 @@ +dependencies: +- pandas==2.2.2 +- ipython==7.34.0 +- tqdm==4.67.1 +description: This notebook is for ... +python_version: 3.11.1 \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 625b208..44c026b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,8 +4,9 @@ Fast4DRegPy reimplements the Fiji plugin [Fast4DReg](https://github.com/CellMigrationLab/Fast4DReg) in Python, with NanoPyx doing the cross-correlation that NanoJ does in Fiji. **Fiji is the reference:** a change is correct when it matches what the original Fiji macro -does, not when it looks more elegant. User documentation: -`README.md`, `docs/fiji_compatibility.md`, `docs/validation.md`. +does, not when it looks more elegant. User documentation: `README.md` and +`docs/` (start at `docs/index.md`); keep `docs/workflow.md` and +`docs/python.md` in step with the API and the notebook. ## Setup and checks @@ -44,6 +45,10 @@ Fiji above 0.99999. | `tests/test_zenodo_*.py` | extracts of the published movie and its Fiji result | | `validation/full_movie/` | full-movie data loading, reference fitting, metrics, reporting and CLI | | `validation/fiji/` | Fiji runner and fixture-generation tools | +| `src/fast4dreg_lc_tools/` | the napari / Fiji tools of the app: only call the public API | +| `lc_tests/`, `tests/test_lc_tools.py` | the tool cases (also used by LabConstrictor's napari and Fiji checks) and their accuracy test | +| `notebooks/Fast4DRegApp/` | the app's notebook and the pinned environment of the app (`requirements.yaml`) | +| `app/`, `.tools/`, `.template_sync/`, `construct.yaml`, `environment.yaml`, `setup.py`, `requirements*.txt` | LabConstrictor template files that build the installers; changed by the template-sync pull requests, not by hand (`setup.py` is the exception: see its docstring) | ## Conventions that must not change @@ -83,6 +88,15 @@ Fiji above 0.99999. extract is cropped in Y, so XY drift must come from the full-field extract. Do not replace published or Fiji-generated fixtures with regenerated data. +## Releases + +`version` in `pyproject.toml` must equal the release tag before a release is +published (the PyPI step stops otherwise). Keep `requires-python` and the +dependencies in `pyproject.toml`; `setup.py` deliberately has neither (they +would override `pyproject.toml` on PyPI). The app's pinned environment is +`notebooks/Fast4DRegApp/requirements.yaml`; the tools' tables need `pandas` +there. + ## Rules - Reject invalid input or unsupported settings with a clear error. Never @@ -130,4 +144,5 @@ limited to what is needed to run without a screen (`patch_macro.py`). tests pass for them. Out of scope unless agreed first: true 3D correlation; rotation, scaling or -non-rigid registration; a GUI or napari plugin; GPU selection. +non-rigid registration; a GUI beyond the notebook and the napari / Fiji tools; +GPU selection. diff --git a/CHANGELOG.md b/CHANGELOG.md index fd026c5..bc2714a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- Fast4DRegPy is also a LabConstrictor app: each release builds installers + for Windows, macOS and Linux that open the notebook + (`notebooks/Fast4DRegApp/Fast4DRegApp.ipynb`) and add the tools + **Correct drift (time-lapse)** and **Align channels** to napari and Fiji + (`src/fast4dreg_lc_tools/`, tested in `lc_tests/` and + `tests/test_lc_tools.py`). Releases can also publish `fast4dregpy` on PyPI. +- `fast4dreg.__version__` is read from the installed package metadata. +- The notebook offers every Fast4DReg setting (time averaging, maximum + expected drift, crop output, extend Z, reslice, output type) and its install + cell works in Google Colab. +- New documentation in `docs/`: installation, step-by-step workflow with every + setting, napari and Fiji, Python guide, troubleshooting, development and + releases; timings against the Fiji macro in `docs/validation.md`. - Split drift estimation, translation helpers and full-movie validation into smaller modules without changing the default registration algorithm. - `backend="unthreaded"` now raises an explicit error when used with diff --git a/MANIFEST.in b/MANIFEST.in index a09dc6b..dd36db8 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -8,3 +8,8 @@ recursive-include tests/data *.npz *.json *.md # so the sdist test suite is self-contained. prune tests/data/zenodo_xyzt exclude tests/test_zenodo_xyzt.py + +# The source distribution of the app's Python package (setup.py, src/, README.md, LICENSE) also carries requirements.txt: +# setup.py reads the dependencies from it when pip builds the package from the source distribution. +include requirements.txt +include lc_tests/make_fixtures.py diff --git a/README.md b/README.md index 8baa1b4..a8a985a 100644 --- a/README.md +++ b/README.md @@ -1,168 +1,170 @@ +
+ +Fast4DReg logo + # Fast4DRegPy -Fast4DRegPy is the Python implementation of -[Fast4DReg](https://github.com/CellMigrationLab/Fast4DReg), the Fiji tool for -correcting drift in 2D and 3D time-lapse microscopy and aligning channels in -multichannel images. It follows the same projection-based workflow and uses -[NanoPyx](https://github.com/HenriquesLab/NanoPyx) for cross-correlation, in -the role NanoJ has in the Fiji implementation. +**Drift correction for 2D and 3D time-lapse microscopy, and channel alignment, in Python.** +*The projection-based workflow of the Fiji tool Fast4DReg, as a Python package, a desktop app and tools for napari and Fiji.* -The implementation has been checked against the complete published Fast4DReg -synthetic movie. Across all 25 timepoints, its drift table differs from a fresh -Fiji Fast4DReg run by at most 0.0047 pixels on any axis. The lowest whole-volume -Pearson correlation between the two corrected outputs is 0.9999993. The full -comparison, including per-frame errors and difference images, is in -[docs/validation.md](docs/validation.md). +[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE) +[![Paper](https://img.shields.io/badge/paper-J%20Cell%20Sci%202023-blue)](https://doi.org/10.1242/jcs.260728) +[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/CellMigrationLab/Fast4DRegPy/blob/main/notebooks/Fast4DRegApp/Fast4DRegApp.ipynb) +[![LabConstrictor app](https://img.shields.io/badge/app-LabConstrictor-orange)](https://cellmigrationlab.github.io/LabConstrictor-Site/) -## Installation +
-Fast4DRegPy supports Python 3.10โ€“3.13. +--- -```bash -python -m pip install "fast4dregpy @ git+https://github.com/CellMigrationLab/Fast4DRegPy" -``` +## What is Fast4DRegPy? -The distribution is called `fast4dregpy`; the Python package is imported as -`fast4dreg`. +Long time-lapse acquisitions drift: the stage moves, the focus creeps, the +sample settles. Fast4DRegPy measures that drift and removes it, in X, Y and Z, +for 2D and 3D movies. It also aligns the channels of multichannel images, +which helps with microscopes whose channels are offset from each other. -## Drift correction +It is the Python version of [Fast4DReg](https://github.com/CellMigrationLab/Fast4DReg), +the Fiji tool, and follows the same steps: it makes intensity projections, +measures the shift between them by cross-correlation (with +[NanoPyx](https://github.com/HenriquesLab/NanoPyx), in the role NanoJ has in +Fiji) and translates each frame by that shift. -```python -from fast4dreg import load_tiff, register_time, save_drift_csv, save_tiff +![Fast4DReg pipeline](docs/assets/Fast4DReg-methodDescription.png) -image = load_tiff("timelapse.tif") # here: T, Z, Y, X +*The Fast4DReg pipeline. XY drift is measured on projections over Z and +corrected first; Z drift is then measured on side projections of the +XY-corrected movie. Figure from the +[Fast4DReg repository](https://github.com/CellMigrationLab/Fast4DReg).* -corrected, shifts = register_time( - image, - axes="TZYX", - correct_xy=True, - correct_z=True, - workers=4, -) +**Same results as Fiji.** On the complete published Fast4DReg test movie +(25 timepoints, 69 slices, 416 ร— 416 pixels), the drift found by Fast4DRegPy +differs from a fresh Fiji Fast4DReg run by at most 0.005 pixels on any axis, +and the corrected movies have a correlation of 0.9999993. See +[the validation](docs/validation.md). -save_tiff("timelapse_registered.tif", corrected, axes="TZYX") -save_drift_csv("timelapse_drift.csv", shifts) -``` +--- -The `axes` string is required. It tells Fast4DRegPy what each array dimension -means, for example `"TYX"`, `"TZYX"` or `"CTZYX"`. Dimensions are never -guessed from shape. - -`shifts` has one row per timepoint. Values are the translation applied to the -frame, in `(dz, dy, dx)` pixel order. With multichannel time series, drift is -measured on `reference_channel` and the same translation is applied to every -channel. - -For 3D data Fast4DRegPy follows the Fiji sequence: measure XY drift, correct -XY, build the axial projection from that corrected stack, then measure Z drift. - -### Registration options - -| Parameter | Default | Meaning | -| --- | --- | --- | -| `correct_xy`, `correct_z` | `True`, `False` | choose which drift components to correct | -| `projection` | `"max"` | `"max"` or `"mean"` projection | -| `reference` | `"first"` | compare with the first or previous frame | -| `time_averaging` | `1` | average frames in blocks before estimation | -| `max_expected_drift` | `0` | search radius in pixels; 0 uses the full correlation map | -| `axial_projection_axis` | `"Y"` | Fiji Top (`"Y"`) or Left (`"X"`) reslice | -| `crop_output` | `False` | crop to the region present in every frame | -| `extend_z` | `False` | pad Z before applying Z translations | -| `interpolation` | `"imagej"` | ImageJ-compatible bicubic; `"scipy"` is also available | -| `output_dtype` | `"float32"` | return float32 or explicitly round to the input dtype | -| `backend` | `"threaded"` | NanoPyx estimator backend for the direct estimation path | -| `workers` | `1` | number of independent volumes transformed concurrently | - -The `unthreaded` NanoPyx backend is available when -`time_averaging=1` and `max_expected_drift=0`. Fiji-compatible time -averaging and bounded searches use NanoPyx's compiled correlation primitives -directly, so requesting `backend="unthreaded"` with either of those modes -raises an error rather than silently ignoring the setting. - -Fiji exposes separate XY and Z values for projection, reference, averaging and -search radius. Fast4DRegPy currently uses one value for both. See -[docs/fiji_compatibility.md](docs/fiji_compatibility.md) for the exact mapping -and the remaining differences. - -## Channel alignment +## Quickstart -```python -from fast4dreg import register_channels - -corrected, shifts = register_channels( - image, - axes="CZYX", - reference_channel=0, - correct_z=True, -) -``` +Choose how you want to use it: + +### ๐Ÿ–ฅ๏ธ Desktop app (no Python needed) + +Download the installer for Windows, macOS or Linux from the +[latest release](https://github.com/CellMigrationLab/Fast4DRegPy/releases). +The app opens the Fast4DRegPy notebook in JupyterLab: choose a file, set the +options, press **Run registration**. How to install and open an app: +[Install an app](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/install/) and +[Open and use an app](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/using-apps/). + +### ๐Ÿ”ฌ In napari or Fiji + +The app adds two tools to napari and Fiji, **Correct drift (time-lapse)** and +**Align channels**, which work on the image you have open. Install the app, +then the LabConstrictor plugin once: +[napari](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/napari/) or +[Fiji](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/fiji/). +How to use them: [napari and Fiji](docs/napari_fiji.md). + +### ๐ŸŒ In the browser -All channels must be in one array with a `C` axis. Channel-shift estimation -expects a single timepoint. +Run the notebook in Google Colab, nothing to install: +[Open in Colab](https://colab.research.google.com/github/CellMigrationLab/Fast4DRegPy/blob/main/notebooks/Fast4DRegApp/Fast4DRegApp.ipynb). -## Registration quality +### ๐Ÿ In Python -The package includes the measurements used in the Fast4DReg paper: +```bash +python -m pip install "fast4dregpy @ git+https://github.com/CellMigrationLab/Fast4DRegPy" +``` ```python -from fast4dreg import evaluate_registration, save_validation_csv +from fast4dreg import load_tiff, register_time, save_drift_csv, save_tiff -rows = evaluate_registration(corrected, axes="TZYX", analysis="max") -save_validation_csv("registration_quality.csv", rows) +image = load_tiff("timelapse.tif") # here: T, Z, Y, X +corrected, shifts = register_time(image, axes="TZYX", correct_xy=True, correct_z=True) +save_tiff("timelapse_registered.tif", corrected, axes="TZYX") +save_drift_csv("timelapse_drift.csv", shifts) # dz, dy, dx per timepoint ``` -`evaluate_registration` reports mSSIM, PSNR, Pearson correlation, the -historical NRMSE calculation used in the paper, and a conventional NRMSE under -a separate name. Image-based helpers include temporal standard-deviation -projections, three-frame overlays, line profiles, kymographs and -signal-to-background ratios. +More in [the Python guide](docs/python.md). Once a release is on PyPI, +`python -m pip install fast4dregpy` works too. -## Notebook +--- -`notebooks/Fast4DRegApp.ipynb` is a small interface for loading a TIFF, -running registration, viewing the drift and saving the outputs. +## Key capabilities -```bash -python -m pip install "fast4dregpy[notebook] @ git+https://github.com/CellMigrationLab/Fast4DRegPy" -``` +* **2D and 3D time-lapse drift correction**, in XY, in Z, or both. +* **Channel alignment** of 2D and 3D multichannel images. +* **The Fast4DReg settings:** projection (max or mean), reference frame (first + or previous), time averaging, maximum expected drift, crop output, extend + stack in Z. [How they map to the Fiji dialog](docs/fiji_compatibility.md). +* **Registration quality:** mSSIM, PSNR, Pearson correlation and NRMSE as in + the Fast4DReg paper, temporal colour overlays and kymographs. +* **Drift tables** as CSV files, one row per timepoint or channel. +* **Fast:** on the published test movie, half the time of the Fiji macro with + 4 workers on the same computer ([timings](docs/validation.md#speed)). -## Validation and performance +--- -The published large-drift movie contains 25 timepoints, 69 Z planes and -416 ร— 416 pixels per plane. Fast4DRegPy has been compared frame by frame with -both the known synthetic drift and a fresh run of the original Fiji macro; -see [docs/validation.md](docs/validation.md). +## โš ๏ธ Three things to get right -On the 2-CPU GitHub Actions runner used for the recorded timing comparison, -Fast4DRegPy took 19.5 s with one transform worker and 14.9 s with four. The -Fiji macro reported 41 s on the same runner. These numbers describe that run, -not a general speed guarantee. +1. **Say what each dimension is.** Fast4DRegPy never guesses the axes of an + image from its shape: you give them (`TYX`, `TZYX`, `CZYX`...). A wrong + axes string is refused with the image's shape. +2. **One timepoint for channel alignment; one channel's drift for all.** + Channel alignment works on a single timepoint. For a multichannel + time-lapse, the drift is measured on the reference channel and the same + correction is applied to every channel. +3. **Z drift needs enough slices.** Z drift is measured on side projections of + the stack. On stacks of about 10 slices or fewer it may not be found at + all; check the `dz` column of the drift table. -## Development +More in [Troubleshooting](docs/troubleshooting.md). -```bash -git clone https://github.com/CellMigrationLab/Fast4DRegPy -cd Fast4DRegPy -python -m pip install -e ".[dev]" -python -m ruff check src tests benchmarks validation -python -m pytest -q -``` +--- + +## Documentation + +**Start here** +* [Documentation index](docs/index.md) +* [Installation](docs/installation.md) +* [Step-by-step workflow and every setting](docs/workflow.md) + +**Use it** +* [napari and Fiji](docs/napari_fiji.md) +* [Python guide](docs/python.md) +* [Troubleshooting and known issues](docs/troubleshooting.md) -The normal test suite runs on Python 3.10โ€“3.13. The full published-movie -comparison is intentionally separate because it downloads a 1.5 GB archive; -instructions are in [validation/README.md](validation/README.md). +**How it compares with Fiji** +* [Fiji compatibility](docs/fiji_compatibility.md) +* [Validation and speed](docs/validation.md) + +**Develop** +* [Development and releases](docs/development.md) + +--- ## Citation -If you use Fast4DRegPy, please cite Fast4DReg and NanoPyx: +If you use Fast4DRegPy, please cite Fast4DReg, NanoJ and NanoPyx: -> Pylvรคnรคinen JW et al. **Fast4DReg โ€“ fast registration of 4D microscopy -> datasets.** *Journal of Cell Science* 136, jcs260728 (2023). +> Pylvรคnรคinen JW, Laine RF, Saraiva BMS, Ghimire S, Follain G, Henriques R, +> Jacquemet G. **Fast4DReg โ€“ fast registration of 4D microscopy datasets.** +> *Journal of Cell Science* 136 (4), jcs260728 (2023). > https://doi.org/10.1242/jcs.260728 +> Laine RF, Tosheva KL, Gustafsson N, et al. **NanoJ: a high-performance +> open-source super-resolution microscopy toolbox.** *Journal of Physics D: +> Applied Physics* 52 (16), 163001 (2019). https://doi.org/10.1088/1361-6463/ab0261 + > Saraiva BM et al. **Efficiently accelerated bioimage analysis with NanoPyx, > a Liquid Engine-powered Python framework.** *Nature Methods* 22, 283โ€“286 > (2025). https://doi.org/10.1038/s41592-024-02562-6 -Fast4DRegPy is released under the MIT license. See -[CHANGELOG.md](CHANGELOG.md) for release notes. +The desktop app and the napari and Fiji tools are built with +[LabConstrictor](https://cellmigrationlab.github.io/LabConstrictor-Site/). + +Fast4DRegPy is released under the [MIT license](LICENSE). The Fast4DReg logo +and pipeline figure come from the +[Fast4DReg repository](https://github.com/CellMigrationLab/Fast4DReg) (MIT). +Release notes: [CHANGELOG.md](CHANGELOG.md). diff --git a/app/bash_bat_scripts/post_install.bat b/app/bash_bat_scripts/post_install.bat new file mode 100644 index 0000000..f02f768 --- /dev/null +++ b/app/bash_bat_scripts/post_install.bat @@ -0,0 +1,251 @@ +@ECHO OFF +SETLOCAL EnableExtensions DisableDelayedExpansion + +SET "LOG_FILE=%PREFIX%\menuinst_debug.log" +SET "PYTHON_EXE=%PREFIX%\python.exe" +SET "PROJECT_ROOT=%PREFIX%\Fast4DRegPy" +SET "BASE_REQUIREMENTS=%PROJECT_ROOT%\requirements.txt" +SET "GPU_REQUIREMENTS=%PROJECT_ROOT%\requirements_gpu.txt" +SET "SELECTED_REQUIREMENTS=%BASE_REQUIREMENTS%" +SET "NVIDIA_SMI=" +SET "CA_BUNDLE=" +SET "FAILURE_MESSAGE=" +SET "CERTIFI_PATH_FILE=%TEMP%\labconstrictor_certifi_%RANDOM%_%RANDOM%.txt" + +> "%LOG_FILE%" echo Running post_install + +IF NOT EXIST "%PYTHON_EXE%" ( + SET "FAILURE_MESSAGE=Bundled Python executable was not found at %PYTHON_EXE%." + GOTO :fail +) +IF NOT EXIST "%PROJECT_ROOT%\launch_jupyter.py" ( + SET "FAILURE_MESSAGE=TLS-resilient launcher was not found at %PROJECT_ROOT%\launch_jupyter.py." + GOTO :fail +) +IF NOT EXIST "%BASE_REQUIREMENTS%" ( + SET "FAILURE_MESSAGE=Base requirements file was not found at %BASE_REQUIREMENTS%." + GOTO :fail +) + +REM pip 24.2+ uses the operating-system trust store by default. Some Windows +REM certificate stores contain malformed entries that OpenSSL cannot parse. +REM Keep verification enabled while opting out of system trust for installer +REM pip operations and using an explicit verified CA bundle. +SET "PIP_USE_DEPRECATED=legacy-certs" + +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --print-ca-bundle > "%CERTIFI_PATH_FILE%" 2>> "%LOG_FILE%" +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Unable to locate a verified CA bundle." + GOTO :fail +) +SET /P "CA_BUNDLE="<"%CERTIFI_PATH_FILE%" +DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 + +IF NOT DEFINED CA_BUNDLE ( + SET "FAILURE_MESSAGE=No verified CA bundle could be selected." + GOTO :fail +) +IF NOT EXIST "%CA_BUNDLE%" ( + SET "FAILURE_MESSAGE=Selected CA bundle does not exist: %CA_BUNDLE%" + GOTO :fail +) + +SET "PIP_CERT=%CA_BUNDLE%" +SET "REQUESTS_CA_BUNDLE=%CA_BUNDLE%" +SET "CURL_CA_BUNDLE=%CA_BUNDLE%" +echo Using verified CA bundle for installer network operations: "%CA_BUNDLE%" >> "%LOG_FILE%" + +IF EXIST "%GPU_REQUIREMENTS%" ( + CALL :detect_nvidia_smi + IF DEFINED NVIDIA_SMI ( + echo NVIDIA GPU utility detected, installing GPU requirements from "%GPU_REQUIREMENTS%" >> "%LOG_FILE%" + SET "SELECTED_REQUIREMENTS=%GPU_REQUIREMENTS%" + ) ELSE ( + echo NVIDIA GPU not detected, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" + ) +) ELSE ( + echo GPU requirements file not found, installing CPU requirements from "%BASE_REQUIREMENTS%" >> "%LOG_FILE%" +) + +REM A lock file (requirements*.lock.txt next to the requirements file: every package with its exact version, written by +REM .tools/python/lock_requirements.py) is installed instead of the requirements file when the installer bundles one. +SET "SELECTED_LOCK=%SELECTED_REQUIREMENTS:~0,-4%.lock.txt" +IF EXIST "%SELECTED_LOCK%" SET "SELECTED_REQUIREMENTS=%SELECTED_LOCK%" +echo Installing requirements from "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m pip install -r "%SELECTED_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application requirements installation failed." + GOTO :fail +) + +SET "WINDOWS_REQUIREMENTS=%PROJECT_ROOT%\requirements-windows.txt" +IF EXIST "%PROJECT_ROOT%\requirements-windows.lock.txt" SET "WINDOWS_REQUIREMENTS=%PROJECT_ROOT%\requirements-windows.lock.txt" +IF EXIST "%PROJECT_ROOT%\requirements-windows.txt" ( + echo Installing Windows-specific requirements from "%WINDOWS_REQUIREMENTS%". >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install -r "%WINDOWS_REQUIREMENTS%" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Windows-specific requirements installation failed." + GOTO :fail + ) +) + +REM External Python code is optional in LabConstrictor projects. If setup.py is +REM bundled, install it without a temporary build environment and verify that +REM the generated import package is usable. Otherwise continue without it. +IF EXIST "%PROJECT_ROOT%\setup.py" ( + echo Found setup.py, installing Fast4DRegPy package locally without build isolation. >> "%LOG_FILE%" + "%PYTHON_EXE%" -m pip install --no-deps --no-build-isolation "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Fast4DRegPy package installation failed." + GOTO :fail + ) + + REM Tools first, only for an app whose package ships a tools module: the package may import labconstrictor_tools at module level, + REM so labconstrictor-tools is installed BEFORE the import check below. A failed install is only a WARNING, see :install_lc_tools at the end of this file. + CALL :install_lc_tools + + "%PYTHON_EXE%" -c "import fast4dreg; print('Fast4DRegPy import successful:', fast4dreg.__file__)" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Installed Fast4DRegPy package could not be imported as fast4dreg." + GOTO :fail + ) +) ELSE ( + echo No setup.py detected; this project does not bundle an optional Python package. >> "%LOG_FILE%" +) + +REM Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge). +REM If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +REM This step must never fail the installation. LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). +REM labconstrictor-tools is installed by :install_lc_tools, called above before the import check of the package (it sets LC_TOOLS_PIN, LC_TOOLS_SPEC and LC_TOOLS_READY). +SET "LC_APP_VERSION=" +IF EXIST "%PROJECT_ROOT%\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\construct.yaml"`) DO SET "LC_APP_VERSION=%%~B" +IF NOT DEFINED LC_APP_VERSION ( + SET "LC_APP_VERSION=0" + echo WARNING: no version: line at the start of a line in construct.yaml - registering the tools with version 0. >> "%LOG_FILE%" +) +REM Hosts of the app: the app's labconstrictor-app.yaml (bundled by construct.yaml extra_files) goes to Tools with --app-manifest, so that +REM Napari, Fiji and QuPath list the app only in the hosts its hosts: line names. Without the file the app is +REM registered without hosts (every host lists it) and the log says so (see the lines after "Found ... registering" below). +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('fast4dreg_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF NOT ERRORLEVEL 1 ( + echo Found fast4dreg_lc_tools: registering the tools of Fast4DRegPy 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 Fast4DRegPy is registered without hosts. 'Fast4DRegPy' 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%" + REM labconstrictor-tools was installed before the import check (:install_lc_tools): register only if that worked (errorlevel 1 otherwise). + "%PYTHON_EXE%" -c "import sys; sys.exit(0 if sys.argv[1] == '1' else 1)" "%LC_TOOLS_READY%" >> "%LOG_FILE%" 2>&1 + IF NOT ERRORLEVEL 1 IF DEFINED LC_APP_MANIFEST "%PYTHON_EXE%" -m labconstrictor_tools register --name "Fast4DRegPy" --prefix "%PREFIX%" --module fast4dreg_lc_tools --version "%LC_APP_VERSION%" --display-name "Fast4DRegPy" --app-manifest "%LC_APP_MANIFEST%" >> "%LOG_FILE%" 2>&1 + IF NOT ERRORLEVEL 1 IF NOT DEFINED LC_APP_MANIFEST "%PYTHON_EXE%" -m labconstrictor_tools register --name "Fast4DRegPy" --prefix "%PREFIX%" --module fast4dreg_lc_tools --version "%LC_APP_VERSION%" --display-name "Fast4DRegPy" >> "%LOG_FILE%" 2>&1 + IF ERRORLEVEL 1 echo WARNING: tool registration failed - see the pip and register output above in this file; Fast4DRegPy itself is installed. >> "%LOG_FILE%" +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\include_path.py" --path "%PREFIX%" --files "%PROJECT_ROOT%\notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher path preparation failed." + GOTO :fail +) + +"%PYTHON_EXE%" "%PROJECT_ROOT%\hide_code_cells.py" "%PROJECT_ROOT%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Notebook metadata preparation failed." + GOTO :fail +) + +REM Keep conda verification enabled, but avoid the Windows trust store that +REM failed during installation. Conda accepts a CA bundle path for ssl_verify. +echo Configuring conda to use verified CA bundle: "%CA_BUNDLE%" >> "%LOG_FILE%" +"%PYTHON_EXE%" -m conda config --system --set ssl_verify "%CA_BUNDLE%" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: Could not configure conda with the selected CA bundle. The application launcher still has its own verified fallback. >> "%LOG_FILE%" +) + +REM Validate TLS and Jupyter imports before creating shortcuts or registering +REM the application. +"%PYTHON_EXE%" "%PROJECT_ROOT%\launch_jupyter.py" --self-test >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Launcher preflight failed. See menuinst_debug.log and launcher_debug.log." + GOTO :fail +) +echo Launcher preflight completed successfully. >> "%LOG_FILE%" + +"%PYTHON_EXE%" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Python installation diagnostics failed." + GOTO :fail +) + +"%PYTHON_EXE%" -c "from menuinst.api import install; import os; print(install(os.path.join(r'%PREFIX%', 'Fast4DRegPy', 'notebook_launcher.json')))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + SET "FAILURE_MESSAGE=Application shortcut creation failed." + GOTO :fail +) + +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\Fast4DRegPy" +SET "UNINSTALL_EXE=%PREFIX%\Uninstall-Fast4DRegPy.exe" +SET "DISPLAY_ICON=%PROJECT_ROOT%\logo.ico" +SET "DISPLAY_VERSION=0.5.0" +SET "PUBLISHER=CellMigrationLab" +echo Registering Fast4DRegPy in Windows Apps list >> "%LOG_FILE%" +reg add "%ARP_KEY%" /v DisplayName /d "Fast4DRegPy" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayVersion /d "%DISPLAY_VERSION%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v Publisher /d "%PUBLISHER%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v InstallLocation /d "%PREFIX%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v DisplayIcon /d "%DISPLAY_ICON%" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v UninstallString /d "\"%UNINSTALL_EXE%\"" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v QuietUninstallString /d "\"%UNINSTALL_EXE%\" /S" /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoModify /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 +reg add "%ARP_KEY%" /v NoRepair /t REG_DWORD /d 1 /f >> "%LOG_FILE%" 2>&1 + +echo Post-install completed successfully. >> "%LOG_FILE%" +echo Post-install completed successfully. +ENDLOCAL +EXIT /B 0 + +:fail +IF EXIST "%CERTIFI_PATH_FILE%" DEL /Q "%CERTIFI_PATH_FILE%" >NUL 2>&1 +IF NOT DEFINED FAILURE_MESSAGE SET "FAILURE_MESSAGE=Post-install failed for an unknown reason." +echo ERROR: %FAILURE_MESSAGE% >> "%LOG_FILE%" +echo ERROR: %FAILURE_MESSAGE% +echo See "%LOG_FILE%" for details. +ENDLOCAL +EXIT /B 1 + +:detect_nvidia_smi +FOR %%P IN ( + "%ProgramFiles%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%ProgramW6432%\NVIDIA Corporation\NVSMI\nvidia-smi.exe" + "%SystemRoot%\System32\nvidia-smi.exe" + "%SystemRoot%\Sysnative\nvidia-smi.exe" +) DO ( + IF NOT DEFINED NVIDIA_SMI IF EXIST "%%~P" SET "NVIDIA_SMI=%%~P" +) +IF DEFINED NVIDIA_SMI GOTO :EOF + +FOR /F "delims=" %%I IN ('where.exe nvidia-smi.exe 2^>NUL') DO ( + IF NOT DEFINED NVIDIA_SMI SET "NVIDIA_SMI=%%~fI" +) +GOTO :EOF + +:install_lc_tools +REM Optional (LabConstrictor tools bridge): install labconstrictor-tools when the app's package ships a module named _lc_tools. +REM Called before the import check of the package, which may import labconstrictor_tools at module level. +REM This step must never fail the installation: a failure is logged as a WARNING and LC_TOOLS_READY stays 0 (no registration later). +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.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('fast4dreg_lc_tools') else 1)" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 GOTO :EOF +echo Found fast4dreg_lc_tools: installing labconstrictor-tools before the import check of Fast4DRegPy. >> "%LOG_FILE%" +REM LC_TOOLS_SPEC goes to pip as one argument through Python: cmd.exe never re-parses it (a quote or & in it cannot run anything). +"%PYTHON_EXE%" -c "import os, subprocess, sys; sys.exit(subprocess.call([sys.executable, '-m', 'pip', 'install', os.environ['LC_TOOLS_SPEC']]))" >> "%LOG_FILE%" 2>&1 +IF ERRORLEVEL 1 ( + echo WARNING: labconstrictor-tools could not be installed - see the pip output above in this file; the tools of Fast4DRegPy will not be registered ^(the import check fails only if the package needs labconstrictor-tools at import time^). >> "%LOG_FILE%" + GOTO :EOF +) +SET "LC_TOOLS_READY=1" +GOTO :EOF diff --git a/app/bash_bat_scripts/post_install.sh b/app/bash_bat_scripts/post_install.sh new file mode 100644 index 0000000..fe999d1 --- /dev/null +++ b/app/bash_bat_scripts/post_install.sh @@ -0,0 +1,153 @@ +#!/bin/bash +set -euo pipefail + +LOG_FILE="$PREFIX/menuinst_debug.log" +PYTHON_EXE="$PREFIX/bin/python" +PROJECT_ROOT="$PREFIX/Fast4DRegPy" +BASE_REQUIREMENTS="$PROJECT_ROOT/requirements.txt" +GPU_REQUIREMENTS="$PROJECT_ROOT/requirements_gpu.txt" +SELECTED_REQUIREMENTS="$BASE_REQUIREMENTS" + +echo "Running post_install" > "$LOG_FILE" + +fail() { + echo "ERROR: $1" | tee -a "$LOG_FILE" >&2 + exit 1 +} + +[ -x "$PYTHON_EXE" ] || fail "Bundled Python executable was not found at $PYTHON_EXE." +[ -f "$PROJECT_ROOT/launch_jupyter.py" ] || fail "TLS-resilient launcher was not found at $PROJECT_ROOT/launch_jupyter.py." +[ -f "$BASE_REQUIREMENTS" ] || fail "Base requirements file was not found at $BASE_REQUIREMENTS." + +# pip 24.2+ uses system certificates by default. Opt out for installer pip +# operations and use an explicit verified CA bundle instead. +export PIP_USE_DEPRECATED=legacy-certs +CA_BUNDLE="$("$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --print-ca-bundle 2>> "$LOG_FILE")" +[ -s "$CA_BUNDLE" ] || fail "No valid verified CA bundle could be selected: $CA_BUNDLE" + +export PIP_CERT="$CA_BUNDLE" +export REQUESTS_CA_BUNDLE="$CA_BUNDLE" +export CURL_CA_BUNDLE="$CA_BUNDLE" +echo "Using verified CA bundle for installer network operations: $CA_BUNDLE" >> "$LOG_FILE" + +if [ -f "$GPU_REQUIREMENTS" ]; then + if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "macOS detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + elif command -v nvidia-smi >/dev/null 2>&1; then + echo "NVIDIA GPU detected, installing GPU requirements from $GPU_REQUIREMENTS" >> "$LOG_FILE" + SELECTED_REQUIREMENTS="$GPU_REQUIREMENTS" + else + echo "NVIDIA GPU not detected, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" + fi +else + echo "GPU requirements file not found, installing CPU requirements from $BASE_REQUIREMENTS" >> "$LOG_FILE" +fi + +# A lock file (requirements*.lock.txt next to the requirements file: every package with its exact version, written by +# .tools/python/lock_requirements.py) is installed instead of the requirements file when the installer bundles one. +locked_requirements() { + if [ -f "${1%.txt}.lock.txt" ]; then echo "${1%.txt}.lock.txt"; else echo "$1"; fi +} +SELECTED_REQUIREMENTS="$(locked_requirements "$SELECTED_REQUIREMENTS")" +echo "Installing requirements from $SELECTED_REQUIREMENTS" >> "$LOG_FILE" +"$PYTHON_EXE" -m pip install -r "$SELECTED_REQUIREMENTS" >> "$LOG_FILE" 2>&1 + +if [[ "${OSTYPE:-}" == "darwin"* ]]; then + echo "Detected macOS platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-macos.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$(locked_requirements "$PROJECT_ROOT/requirements-macos.txt")" >> "$LOG_FILE" 2>&1 + fi +elif [[ "${OSTYPE:-}" == "linux-gnu"* ]]; then + echo "Detected Linux platform" >> "$LOG_FILE" + if [ -f "$PROJECT_ROOT/requirements-linux.txt" ]; then + "$PYTHON_EXE" -m pip install -r "$(locked_requirements "$PROJECT_ROOT/requirements-linux.txt")" >> "$LOG_FILE" 2>&1 + fi +else + echo "Unknown platform: ${OSTYPE:-unset}" >> "$LOG_FILE" +fi + +# External Python code is optional. Verify the generated package only when the +# constructor bundled setup.py and src/. +if [ -f "$PROJECT_ROOT/setup.py" ]; then + echo "Found setup.py, installing Fast4DRegPy package locally without build isolation" >> "$LOG_FILE" + "$PYTHON_EXE" -m pip install --no-deps --no-build-isolation "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + # Tools first, only for an app whose package ships a _lc_tools module: the app package may import labconstrictor_tools + # at module level, so labconstrictor-tools must be installed BEFORE the import check below. A failed install is only a WARNING + # (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.2" + LC_TOOLS_MODULE="fast4dreg_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 + echo "Found $LC_TOOLS_MODULE: installing labconstrictor-tools before the import check of Fast4DRegPy" >> "$LOG_FILE" || : + if "$PYTHON_EXE" -m pip install "${LC_TOOLS_SPEC:-https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${LC_TOOLS_PIN}.zip}" >> "$LOG_FILE" 2>&1; then + LC_TOOLS_READY=1 + else + echo "WARNING: labconstrictor-tools could not be installed - see the pip output above in this file; the tools of Fast4DRegPy will not be registered (the import check below fails only if the package needs labconstrictor-tools at import time)." >> "$LOG_FILE" || : + fi + fi + "$PYTHON_EXE" -c "import fast4dreg; print('Fast4DRegPy import successful:', fast4dreg.__file__)" >> "$LOG_FILE" 2>&1 +else + echo "No setup.py detected; this project does not bundle an optional Python package." >> "$LOG_FILE" +fi + + +# --- Optional: expose the app's tools to Napari, Fiji and the command line (LabConstrictor tools bridge) ------------------- +# If the app's package ships a module named _lc_tools, install labconstrictor-tools and register that module. +# This step must never fail the installation. LC_TOOLS_SPEC can point to another source (wheel, git URL, mirror). +# 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 Fast4DRegPy 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." + LC_APP_VERSION=0 + fi + # Hosts of the app: the app's labconstrictor-app.yaml (bundled by construct.yaml extra_files) goes to Tools with --app-manifest, so that + # Napari, Fiji and QuPath list the app only in the hosts its hosts: line names. Without the file the app is registered + # without hosts (every host lists it) and the log says so, with the sentence Tools uses for it. Tools itself reads the file: a manifest + # without a hosts: line (or with an invalid one) is answered by Tools, whose message goes to this log. + LC_APP_MANIFEST="$PROJECT_ROOT/labconstrictor-app.yaml" + LC_HOSTS_ARGS=() + LC_NO_HOSTS="'Fast4DRegPy' declares no hosts, so it is listed in every host; register it with --app-manifest (or --hosts) to choose" + if [ ! -f "$LC_APP_MANIFEST" ]; then + lc_note "WARNING: $LC_APP_MANIFEST was not found (add labconstrictor-app.yaml to extra_files in construct.yaml), so Fast4DRegPy is registered without hosts. $LC_NO_HOSTS" + else + LC_HOSTS_ARGS=(--app-manifest "$LC_APP_MANIFEST") + lc_note "Passing the hosts of $LC_APP_MANIFEST to Tools (--app-manifest); Tools logs the same sentence if the file declares no hosts." + fi + if [ "${LC_TOOLS_READY:-0}" = 1 ] \ + && "$PYTHON_EXE" -m labconstrictor_tools register --name "Fast4DRegPy" --prefix "$PREFIX" \ + --module "$LC_TOOLS_MODULE" --version "$LC_APP_VERSION" --display-name "Fast4DRegPy" ${LC_HOSTS_ARGS[@]+"${LC_HOSTS_ARGS[@]}"} >> "$LOG_FILE" 2>&1; then + lc_note "Tools registered (labconstrictor-tools list shows them)." + else + lc_note "WARNING: tool registration failed - see the pip and register output above in this file; Fast4DRegPy itself is installed." + fi +fi + +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PROJECT_ROOT/notebook_launcher.json" --keyword "BASE_PATH_KEYWORD" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/pre_uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/include_path.py" --path "$PREFIX" --files "$PREFIX/uninstall.sh" --keyword "BASE_PATH" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" "$PROJECT_ROOT/hide_code_cells.py" "$PROJECT_ROOT" >> "$LOG_FILE" 2>&1 + +# Keep conda verification enabled while avoiding the system certificate store +# that failed. Conda accepts a CA bundle path for ssl_verify. +if ! "$PYTHON_EXE" -m conda config --system --set ssl_verify "$CA_BUNDLE" >> "$LOG_FILE" 2>&1; then + echo "WARNING: Could not configure conda with the selected CA bundle. The launcher still has its own verified fallback." >> "$LOG_FILE" +fi + +# Do not create the application shortcut unless launcher preflight succeeds. +"$PYTHON_EXE" "$PROJECT_ROOT/launch_jupyter.py" --self-test >> "$LOG_FILE" 2>&1 +echo "Launcher preflight completed successfully." >> "$LOG_FILE" + +"$PYTHON_EXE" -c "import os, sys; print('Python:', sys.executable); print('Prefix:', os.environ.get('PREFIX'))" >> "$LOG_FILE" 2>&1 +"$PYTHON_EXE" -c "from menuinst.api import install; import os; print(install(os.path.join('$PREFIX', 'Fast4DRegPy', 'notebook_launcher.json')))" >> "$LOG_FILE" 2>&1 + +echo "Post-install completed successfully." >> "$LOG_FILE" + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi diff --git a/app/bash_bat_scripts/pre_uninstall.bat b/app/bash_bat_scripts/pre_uninstall.bat new file mode 100644 index 0000000..076d0f2 --- /dev/null +++ b/app/bash_bat_scripts/pre_uninstall.bat @@ -0,0 +1,9 @@ +@ECHO ON +echo Running pre-uninstall +"%PREFIX%\python.exe" -m labconstrictor_tools unregister --name "Fast4DRegPy" --prefix "%PREFIX%" >NUL 2>&1 +IF ERRORLEVEL 1 IF EXIST "%USERPROFILE%\.labconstrictor\apps\Fast4DRegPy.json" echo WARNING: could not remove Fast4DRegPy from the LabConstrictor tools list; if Napari or Fiji still list it, delete the files %USERPROFILE%\.labconstrictor\apps\Fast4DRegPy.json and Fast4DRegPy.schema.json. 1>&2 +"%PREFIX%\python.exe" -c "from menuinst.api import remove; import os; remove(os.path.join(r'%PREFIX%', 'Fast4DRegPy', 'notebook_launcher.json'))" +SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\Fast4DRegPy" +reg delete "%ARP_KEY%" /f >NUL 2>&1 +echo Pre-uninstall completed! +SetLocal EnableDelayedExpansion diff --git a/app/bash_bat_scripts/pre_uninstall.sh b/app/bash_bat_scripts/pre_uninstall.sh new file mode 100644 index 0000000..3579c29 --- /dev/null +++ b/app/bash_bat_scripts/pre_uninstall.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e +echo "Running pre_uninstall" +# best effort: a failure must not stop the uninstall, but it is reported (a stale entry can stay in the Napari/Fiji list) +if ! "BASE_PATH/bin/python" -m labconstrictor_tools unregister --name "Fast4DRegPy" --prefix "BASE_PATH" > /dev/null 2>&1; then + LC_ENTRY="${LC_HOME:-$HOME/.labconstrictor}/apps/Fast4DRegPy" + if [ -e "$LC_ENTRY.json" ]; then + echo "WARNING: could not remove Fast4DRegPy from the LabConstrictor tools list; if Napari or Fiji still list it, delete the files $LC_ENTRY.json and $LC_ENTRY.schema.json." >&2 + fi +fi +"BASE_PATH/bin/python" -c "from menuinst.api import remove; import os; remove(os.path.join(r'BASE_PATH', 'Fast4DRegPy', 'notebook_launcher.json'))" diff --git a/app/bash_bat_scripts/uninstall.sh b/app/bash_bat_scripts/uninstall.sh new file mode 100644 index 0000000..fe7291a --- /dev/null +++ b/app/bash_bat_scripts/uninstall.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +PREFIX="BASE_PATH" +echo "Uninstalling Fast4DRegPy from $PREFIX" +if [ -f "$PREFIX/pre_uninstall.sh" ]; then + # best effort: shortcut/registry cleanup must not stop the removal, but a failure must be visible + if ! bash "$PREFIX/pre_uninstall.sh"; then + echo "WARNING: pre-uninstall cleanup failed (see the messages above); shortcuts or the tools registry entry may remain." >&2 + fi +fi +if ! rm -rf -- "$PREFIX"; then + echo "ERROR: could not remove $PREFIX; Fast4DRegPy is only partly uninstalled. Close anything using it and delete that folder manually." >&2 + exit 1 +fi + +echo "Fast4DRegPy removed." + +if [ -t 0 ]; then + echo + read -rp "Press Enter to close the installer..." _ +fi \ No newline at end of file diff --git a/app/logo/fast4dregpy.icns b/app/logo/fast4dregpy.icns new file mode 100644 index 0000000..81adc02 Binary files /dev/null and b/app/logo/fast4dregpy.icns differ diff --git a/app/logo/fast4dregpy.ico b/app/logo/fast4dregpy.ico new file mode 100644 index 0000000..0c75c1d Binary files /dev/null and b/app/logo/fast4dregpy.ico differ diff --git a/app/logo/fast4dregpy.png b/app/logo/fast4dregpy.png new file mode 100644 index 0000000..7ce7cfd Binary files /dev/null and b/app/logo/fast4dregpy.png differ diff --git a/app/logo/fast4dregpy_banner.png b/app/logo/fast4dregpy_banner.png new file mode 100644 index 0000000..90f6903 Binary files /dev/null and b/app/logo/fast4dregpy_banner.png differ diff --git a/app/logo/fast4dregpy_header.png b/app/logo/fast4dregpy_header.png new file mode 100644 index 0000000..c0add2e Binary files /dev/null and b/app/logo/fast4dregpy_header.png differ diff --git a/app/menuinst/notebook_launcher.json b/app/menuinst/notebook_launcher.json new file mode 100644 index 0000000..1a93844 --- /dev/null +++ b/app/menuinst/notebook_launcher.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://schemas.conda.org/menuinst/menuinst-1-1-3.schema.json", + "menu_name": "Fast4DRegPy", + "menu_items": [ + { + "name": "Fast4DRegPy", + "description": "Launch Fast4DRegPy in its packaged JupyterLab environment.", + "activate": true, + "terminal": true, + "working_dir": "{{ HOME }}", + "command": [ + "{{ PYTHON }}", + "{{ PREFIX }}/Fast4DRegPy/launch_jupyter.py", + "{{ PREFIX }}/Fast4DRegPy/notebooks/Welcome.ipynb" + ], + "platforms": { + "win": { + "icon": "BASE_PATH_KEYWORD/Fast4DRegPy/fast4dregpy.ico", + "command": [ + "{{ PYTHON }}", + "{{ PREFIX }}/Fast4DRegPy/launch_jupyter.py", + "{{ PREFIX }}/Fast4DRegPy/notebooks/Welcome.ipynb", + "&", + "exit" + ] + }, + "linux": { + "icon": "BASE_PATH_KEYWORD/Fast4DRegPy/fast4dregpy.png" + }, + "osx": { + "icon": "BASE_PATH_KEYWORD/Fast4DRegPy/fast4dregpy.icns" + } + } + } + ] +} diff --git a/app/python_scripts/hide_code_cells.py b/app/python_scripts/hide_code_cells.py new file mode 100644 index 0000000..35524e1 --- /dev/null +++ b/app/python_scripts/hide_code_cells.py @@ -0,0 +1,104 @@ +"""Utility to hide code cells in Jupyter notebooks by updating metadata.""" +from __future__ import annotations + +import argparse +from pathlib import Path +from typing import Iterable + +import nbformat + +# Metadata values required to hide code cells in supported viewers. +CELL_VIEW_VALUE = "form" +COLLAPSED_VALUE = False +SOURCE_HIDDEN_VALUE = True + +# Placeholder for repository initialisiation that enables or disables this script. +DISABLED = False + + +def collect_notebooks(root: Path) -> Iterable[Path]: + """Yield every notebook under root (recursively for directories).""" + if root.is_file(): + if root.suffix == ".ipynb": + yield root + return + + for path in root.rglob("*.ipynb"): + if path.is_file(): + yield path + + +def hide_code_cells(notebook_path: Path) -> bool: + """Apply metadata updates to every code cell in the given notebook.""" + notebook = nbformat.read(notebook_path, as_version=nbformat.NO_CONVERT) + changed = False + + for cell in notebook.cells: + if cell.get("cell_type") != "code": + continue + + # Remove saved output + if cell.get("outputs"): + cell["outputs"] = [] + changed = True + if cell.get("execution_count") is not None: + cell["execution_count"] = None + changed = True + + metadata = cell.setdefault("metadata", {}) + + if metadata.get("cellView") != CELL_VIEW_VALUE: + metadata["cellView"] = CELL_VIEW_VALUE + changed = True + + if metadata.get("collapsed") != COLLAPSED_VALUE: + metadata["collapsed"] = COLLAPSED_VALUE + changed = True + + jupyter_meta = metadata.get("jupyter") if isinstance(metadata.get("jupyter"), dict) else {} + if jupyter_meta.get("source_hidden") != SOURCE_HIDDEN_VALUE: + jupyter_meta["source_hidden"] = SOURCE_HIDDEN_VALUE + metadata["jupyter"] = jupyter_meta + changed = True + + jupyterlab_meta = metadata.get("jupyterlabHideCode") if isinstance(metadata.get("jupyterlabHideCode"), dict) else {} + if jupyterlab_meta.get("locked") != True: + jupyterlab_meta["locked"] = True + metadata["jupyterlabHideCode"] = jupyterlab_meta + changed = True + + if changed: + nbformat.write(notebook, notebook_path) + + return changed + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Hide the code cells in notebooks under the given path.") + parser.add_argument("path", type=Path, help="File or directory to process for Jupyter notebooks") + return parser.parse_args() + + +def main() -> None: + args = parse_args() + notebooks = list(collect_notebooks(args.path)) + + if DISABLED: + print("Hiding code cells is disabled for this repository.") + print("To enable, set False to False in app/python_scripts/hide_code_cells.py") + print("or go to https://labconstrictor-form.streamlit.app/ and initialise your repository again but with hiding code cells enabled.") + return + + if not notebooks: + print("No notebooks found.") + return + + for notebook_path in notebooks: + if hide_code_cells(notebook_path): + print(f"Updated {notebook_path}") + else: + print(f"No changes needed for {notebook_path}") + + +if __name__ == "__main__": + main() diff --git a/app/python_scripts/include_path.py b/app/python_scripts/include_path.py new file mode 100644 index 0000000..ed94b7b --- /dev/null +++ b/app/python_scripts/include_path.py @@ -0,0 +1,29 @@ +import argparse +import os + +def replace_keyword_in_files(path, files, keyword): + # Check if we are on windows and if so, replace each \ with / + if os.name == "nt": + path = path.replace("\\", "/") + + for file_path in files: + if not os.path.isfile(file_path): + print(f"File not found: {file_path}") + continue + with open(file_path, 'r', encoding='utf-8') as f: + content = f.read() + new_content = content.replace(keyword, path) + with open(file_path, 'w', encoding='utf-8') as f: + f.write(new_content) + print(f"Updated: {file_path}") + +def main(): + parser = argparse.ArgumentParser(description="Replace a keyword with a path in multiple files.") + parser.add_argument('--path', required=True, help='Path to insert') + parser.add_argument('--files', nargs='+', required=True, help='List of files to modify') + parser.add_argument('--keyword', required=True, help='Keyword to replace') + args = parser.parse_args() + replace_keyword_in_files(args.path, args.files, args.keyword) + +if __name__ == "__main__": + main() diff --git a/app/python_scripts/launch_jupyter.py b/app/python_scripts/launch_jupyter.py new file mode 100644 index 0000000..c6a689e --- /dev/null +++ b/app/python_scripts/launch_jupyter.py @@ -0,0 +1,329 @@ +"""TLS-resilient JupyterLab launcher for Fast4DRegPy. + +Certificate handling is configured before JupyterLab imports Tornado. On +Windows this prevents one malformed certificate-store entry from terminating +the application. Certificate and hostname verification remain enabled in every +supported mode. +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import re +import shutil +import ssl +import sys +import tempfile +import traceback +from datetime import datetime, timezone +from importlib import metadata +from pathlib import Path + +PROJECT_DISPLAY_NAME = "Fast4DRegPy" +SCRIPT_DIR = Path(__file__).resolve().parent +_INSTALLED_LAYOUT = (SCRIPT_DIR / "notebooks").is_dir() +if _INSTALLED_LAYOUT: + APP_ROOT = SCRIPT_DIR + PREFIX = APP_ROOT.parent +else: + # Repository layout: app/python_scripts/launch_jupyter.py + repository_root = SCRIPT_DIR.parents[1] + APP_ROOT = repository_root if (repository_root / "notebooks").is_dir() else SCRIPT_DIR + PREFIX = APP_ROOT +DEFAULT_NOTEBOOK = APP_ROOT / "notebooks" / "Welcome.ipynb" +LOG_PATH = PREFIX / "launcher_debug.log" + + +def _write_log(message: str, *, console: bool = True) -> None: + timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") + line = f"[{timestamp}] {message}" + if console: + print(message, flush=True) + try: + with LOG_PATH.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except OSError: + # Logging must never prevent the application from launching. + pass + + +def _package_version(name: str) -> str: + try: + return metadata.version(name) + except metadata.PackageNotFoundError: + return "not installed" + + +def _project_ca_bundle_environment_variable() -> str: + normalized = re.sub(r"[^A-Za-z0-9]+", "_", PROJECT_DISPLAY_NAME).strip("_").upper() + return f"{normalized or 'LABCONSTRICTOR_APP'}_CA_BUNDLE" + + +def _probe_ssl() -> None: + """Create a verified client context without making a network request.""" + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) + if context.verify_mode != ssl.CERT_REQUIRED: + raise RuntimeError("TLS certificate verification is unexpectedly disabled.") + if not context.check_hostname: + raise RuntimeError("TLS hostname verification is unexpectedly disabled.") + + +def _inject_truststore() -> None: + """Route Python SSL contexts through the operating-system trust API.""" + import truststore + + truststore.inject_into_ssl() + + +def _select_ca_bundle() -> Path: + """Choose an explicit CA bundle for verified installer and runtime fallback.""" + for variable in ( + _project_ca_bundle_environment_variable(), + "LABCONSTRICTOR_CA_BUNDLE", + "SSL_CERT_FILE", + "REQUESTS_CA_BUNDLE", + "CURL_CA_BUNDLE", + ): + candidate = os.environ.get(variable, "").strip() + if candidate: + path = Path(candidate).expanduser() + if path.is_file(): + return path.resolve() + + import certifi + + return Path(certifi.where()).resolve() + + +def _install_bundle_fallback(bundle: Path) -> None: + """Use a verified PEM bundle without enumerating the Windows cert store.""" + original_context_type = ssl.SSLContext + + def create_context( + purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH, + *, + cafile: str | os.PathLike[str] | None = None, + capath: str | os.PathLike[str] | None = None, + cadata: str | bytes | None = None, + ) -> ssl.SSLContext: + if purpose == ssl.Purpose.SERVER_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_CLIENT) + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + elif purpose == ssl.Purpose.CLIENT_AUTH: + context = original_context_type(ssl.PROTOCOL_TLS_SERVER) + else: + raise ValueError(purpose) + + if cafile or capath or cadata: + context.load_verify_locations( + cafile=os.fspath(cafile) if cafile else None, + capath=os.fspath(capath) if capath else None, + cadata=cadata, + ) + else: + context.load_verify_locations(cafile=str(bundle)) + + keylogfile = os.environ.get("SSLKEYLOGFILE") + if keylogfile and hasattr(context, "keylog_filename"): + context.keylog_filename = keylogfile + return context + + ssl.create_default_context = create_context # type: ignore[assignment] + ssl._create_default_https_context = create_context # type: ignore[attr-defined] + os.environ["SSL_CERT_FILE"] = str(bundle) + os.environ.setdefault("REQUESTS_CA_BUNDLE", str(bundle)) + os.environ.setdefault("CURL_CA_BUNDLE", str(bundle)) + + +def configure_tls() -> tuple[str, list[str]]: + """Prepare TLS before Jupyter/Tornado imports and return mode plus notes.""" + notes: list[str] = [] + + try: + if "truststore" not in getattr(ssl.SSLContext, "__module__", ""): + _inject_truststore() + _probe_ssl() + return "native truststore", notes + except Exception as exc: + notes.append(f"Native truststore activation failed: {exc}") + + try: + bundle = _select_ca_bundle() + _install_bundle_fallback(bundle) + _probe_ssl() + notes.append(f"Using verified CA bundle fallback: {bundle}") + return "verified CA bundle fallback", notes + except Exception as exc: + notes.append(f"CA bundle fallback failed: {exc}") + raise RuntimeError("Unable to create a verified TLS context. " + " | ".join(notes)) from exc + + +def _diagnostics(tls_mode: str, notes: list[str]) -> dict[str, object]: + return { + "status": "ok", + "application": PROJECT_DISPLAY_NAME, + "tls_mode": tls_mode, + "notes": notes, + "ca_bundle_override_variable": _project_ca_bundle_environment_variable(), + "python": sys.version.split()[0], + "python_executable": sys.executable, + "openssl": ssl.OPENSSL_VERSION, + "platform": platform.platform(), + "jupyterlab": _package_version("jupyterlab"), + "jupyter_server": _package_version("jupyter-server"), + "tornado": _package_version("tornado"), + "truststore": _package_version("truststore"), + "pip_system_certs": _package_version("pip-system-certs"), + "certifi": _package_version("certifi"), + "prefix": str(PREFIX), + "log": str(LOG_PATH), + } + + +def _show_error_dialog(message: str) -> None: + if os.name != "nt": + return + try: + import tkinter as tk + from tkinter import messagebox + + root = tk.Tk() + root.withdraw() + messagebox.showerror(f"{PROJECT_DISPLAY_NAME} could not start", message) + root.destroy() + except Exception: + pass + + +def _wait_for_enter() -> None: + """Keep the terminal window open until the user has read it, then let it close. + + The menu shortcut runs the launcher in a terminal window; without this the window + closes (or stays open, on Windows) as soon as JupyterLab stops. + """ + stream = sys.stdin + if stream is None or not stream.isatty(): + return + try: + input("\nPress Enter to close this window...") + except (EOFError, KeyboardInterrupt): + pass + + +def run_jupyter(notebook: Path) -> int: + if not notebook.is_file(): + raise FileNotFoundError(f"Welcome notebook not found: {notebook}") + + # The app's own kernel must win over a user-level "python3" kernelspec (`ipykernel install --user`), which Jupyter + # otherwise prefers: the notebook would run in another Python and fail with "No module named ". Set, not + # setdefault: a JUPYTER_PREFER_ENV_PATH=0 of the user would bring the problem back. + os.environ["JUPYTER_PREFER_ENV_PATH"] = "1" + + # Import only after configure_tls() has completed. Tornado creates SSL + # contexts during import on some versions. + from jupyterlab.labapp import main + + home = Path.home().resolve() + try: + notebook.resolve().relative_to(home) + root_dir = home + except ValueError: + # All-users installations can live outside the home directory. + root_dir = PREFIX.resolve() + + # A fresh, empty workspace folder for every launch: JupyterLab restores the open + # tabs of its workspaces, and the default folder (~/.jupyter/lab/workspaces) is + # shared by every app, so notebooks of other apps (and of earlier sessions) would + # open next to the Welcome notebook. Settings and themes are kept: they are stored + # in the user settings folder, not in the workspaces. + workspaces_dir = Path(tempfile.mkdtemp(prefix="labconstrictor-workspaces-")) + sys.argv = [ + "jupyter-lab", + str(notebook.resolve()), + "--ServerApp.ip=127.0.0.1", + f"--ServerApp.root_dir={root_dir}", + "--ServerApp.shutdown_no_activity_timeout=30", + "--FileContentsManager.always_delete_dir=True", + f"--LabApp.workspaces_dir={workspaces_dir}", + ] + try: + result = main() + finally: + shutil.rmtree(workspaces_dir, ignore_errors=True) + return int(result or 0) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=f"Launch {PROJECT_DISPLAY_NAME} in its packaged JupyterLab environment safely." + ) + parser.add_argument("notebook", nargs="?", type=Path, default=DEFAULT_NOTEBOOK) + parser.add_argument( + "--self-test", + action="store_true", + help="Validate TLS and Jupyter imports without starting the server.", + ) + parser.add_argument( + "--print-ca-bundle", + action="store_true", + help="Print the selected verified CA bundle path and exit.", + ) + parser.add_argument( + "--no-wait", + action="store_true", + help="Exit when JupyterLab stops, without asking to press Enter.", + ) + args = parser.parse_args(argv) + result = _launch(args) + if not (args.no_wait or args.self_test or args.print_ca_bundle): + _wait_for_enter() + return result + + +def _launch(args: argparse.Namespace) -> int: + try: + if args.print_ca_bundle: + print(_select_ca_bundle(), flush=True) + return 0 + + _write_log("Starting application launcher") + tls_mode, notes = configure_tls() + _write_log(f"TLS mode: {tls_mode}") + for note in notes: + # Recovery details remain available in launcher_debug.log and + # self-test JSON without alarming users during a normal launch. + _write_log(note, console=False) + + import jupyterlab.labapp # noqa: F401 + import tornado.netutil # noqa: F401 + + diagnostics = _diagnostics(tls_mode, notes) + if args.self_test: + print(json.dumps(diagnostics, indent=2), flush=True) + _write_log("Launcher self-test completed successfully") + return 0 + + _write_log(f"Opening notebook: {args.notebook}") + return run_jupyter(args.notebook) + except KeyboardInterrupt: + _write_log("Launcher interrupted by user") + return 130 + except Exception as exc: + details = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + _write_log(details.rstrip()) + friendly = ( + f"{PROJECT_DISPLAY_NAME} could not start, but no certificate-store changes are required.\n\n" + f"A diagnostic log was written to:\n{LOG_PATH}\n\n" + f"Technical message: {exc}" + ) + print("\n" + friendly, file=sys.stderr, flush=True) + _show_error_dialog(friendly) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/construct.yaml b/construct.yaml new file mode 100644 index 0000000..c5a388a --- /dev/null +++ b/construct.yaml @@ -0,0 +1,31 @@ +name: Fast4DRegPy +version: 0.5.0 +environment_file: environment.yaml +installer_type: all +license_file: LICENSE +welcome_image: app/logo/fast4dregpy_banner.png +header_image: app/logo/fast4dregpy_header.png +icon_image: app/logo/fast4dregpy.png +conclusion_text: Thank you! You have successfully installed Fast4DRegPy 0.5.0. +keep_pkgs: false +register_python: false +initialize_conda: false +extra_files: +- app/logo/fast4dregpy.icns: Fast4DRegPy/fast4dregpy.icns +- app/logo/fast4dregpy.ico: Fast4DRegPy/fast4dregpy.ico +- app/logo/fast4dregpy.png: Fast4DRegPy/fast4dregpy.png +- app/bash_bat_scripts/pre_uninstall.sh: pre_uninstall.sh +- app/bash_bat_scripts/uninstall.sh: uninstall.sh +- app/menuinst/Welcome.ipynb: Fast4DRegPy/notebooks/Welcome.ipynb +- app/menuinst/notebook_launcher.json: Fast4DRegPy/notebook_launcher.json +- app/python_scripts/hide_code_cells.py: Fast4DRegPy/hide_code_cells.py +- app/python_scripts/include_path.py: Fast4DRegPy/include_path.py +- app/python_scripts/launch_jupyter.py: Fast4DRegPy/launch_jupyter.py +- construct.yaml: Fast4DRegPy/construct.yaml +- notebooks/notebook_latest_versions.yaml: Fast4DRegPy/notebook_latest_versions.yaml +- requirements.txt: Fast4DRegPy/requirements.txt +- requirements_gpu.txt: Fast4DRegPy/requirements_gpu.txt +post_install: app/bash_bat_scripts/post_install.bat # [win] +post_install: app/bash_bat_scripts/post_install.sh # [unix] +pre_uninstall: app/bash_bat_scripts/pre_uninstall.bat # [win] +pre_uninstall: app/bash_bat_scripts/pre_uninstall.sh # [unix] diff --git a/docs/assets/Fast4DReg-logo.png b/docs/assets/Fast4DReg-logo.png new file mode 100644 index 0000000..e1d3ffb Binary files /dev/null and b/docs/assets/Fast4DReg-logo.png differ diff --git a/docs/assets/Fast4DReg-methodDescription.png b/docs/assets/Fast4DReg-methodDescription.png new file mode 100644 index 0000000..df64440 Binary files /dev/null and b/docs/assets/Fast4DReg-methodDescription.png differ diff --git a/docs/assets/fiji_align_channels.png b/docs/assets/fiji_align_channels.png new file mode 100644 index 0000000..4779357 Binary files /dev/null and b/docs/assets/fiji_align_channels.png differ diff --git a/docs/assets/fiji_correct_drift_form.png b/docs/assets/fiji_correct_drift_form.png new file mode 100644 index 0000000..a582d97 Binary files /dev/null and b/docs/assets/fiji_correct_drift_form.png differ diff --git a/docs/assets/napari_correct_drift.png b/docs/assets/napari_correct_drift.png new file mode 100644 index 0000000..b8cfad0 Binary files /dev/null and b/docs/assets/napari_correct_drift.png differ diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..6cf9e93 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,102 @@ +# Development and releases + +[โฌ…๏ธ Documentation index](index.md) + +## Set up and test + +```bash +git clone https://github.com/CellMigrationLab/Fast4DRegPy +cd Fast4DRegPy +python -m pip install -e ".[dev]" +python -m ruff check src tests benchmarks validation lc_tests +python -m pytest -q +``` + +The test suite runs on Python 3.10โ€“3.13 in about 10 seconds. NanoPyx (pinned +to 2.1.4) is a real dependency of the tests: it is never mocked. Rules for +changes to the registration code are in [AGENTS.md](../AGENTS.md). + +The full comparison on the published movie is separate because it downloads a +1.5 GB archive: [validation/README.md](../validation/README.md) and +[Validation](validation.md). + +## The napari and Fiji tools + +`src/fast4dreg_lc_tools/` declares the tools with +[LabConstrictor Tools](https://cellmigrationlab.github.io/LabConstrictor-Tools/): +typed functions whose forms napari and Fiji generate. They only call the +public API of `fast4dreg`. To test them, install `labconstrictor-tools` (the +version the installer pins, `LC_TOOLS_PIN` in +`app/bash_bat_scripts/post_install.sh`) and `pandas`: + +```bash +pin=$(sed -n 's/^ *LC_TOOLS_PIN="\(.*\)"$/\1/p' app/bash_bat_scripts/post_install.sh) +python -m pip install pandas "https://github.com/CellMigrationLab/LabConstrictor-Tools/archive/refs/tags/${pin}.zip" +python -m pytest -q tests/test_lc_tools.py +cd lc_tests && python make_fixtures.py fixtures && labconstrictor-tools test --module fast4dreg_lc_tools --cases cases.json +``` + +The tests workflow runs both. What the cases check: +[lc_tests/README.md](../lc_tests/README.md). How to write tools: +[the authoring guide](https://cellmigrationlab.github.io/LabConstrictor-Tools/AUTHORING/). + +## The desktop app + +The files that build the app come from the +[LabConstrictor template](https://github.com/CellMigrationLab/LabConstrictor): +`app/`, `.tools/`, `.template_sync/`, `construct.yaml`, `environment.yaml`, +`setup.py`, `requirements*.txt` and the workflows `release_constructor.yml`, +`publish_pypi.yml`, `update_on_*`, `sync_template.yml` and +`check_app_manifest.yml`. The weekly template-sync pull request keeps them up +to date; do not edit them by hand. Two files are this repository's own: + +- `setup.py` is what the installer uses (it ships only `setup.py` and `src/`). + It has no `python_requires` or `install_requires`, which would override + `pyproject.toml` in the package on PyPI. +- `labconstrictor-app.yaml` describes the app for the + [App Centre](https://cellmigrationlab.github.io/LabConstrictor-Site/apps/): + summary, hosts (`notebook`, `napari`, `fiji`), icon, `distribution.pip`. + Guide: [Describe your app](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/app-manifest/). + +The app's Python environment is pinned in +`notebooks/Fast4DRegApp/requirements.yaml`. When it changes on `main`, a +workflow regenerates `requirements.txt` and the lock files. The installer +images and the icon are in `app/logo/` (from the Fast4DReg logo). + +The template's own guides are in [.tools/docs](../.tools/docs/README.md) and +on the [LabConstrictor website](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/). + +## Releases + +A release builds the installers for Windows, macOS and Linux and, once +publishing is switched on, uploads the package to PyPI, with the version of +the release tag. + +1. Set `version = "X.Y.Z"` in `pyproject.toml` and add the release notes to + `CHANGELOG.md`. Commit to `main`. +2. Publish a GitHub release with the tag `vX.Y.Z`. +3. The **Build Release Installers** workflow writes the version into + `setup.py` and `construct.yaml` and attaches the installers to the + release. The **Publish the Python package to PyPI** workflow uploads + `fast4dregpy` X.Y.Z. It stops, without uploading anything, if the version + in `pyproject.toml` differs from the tag. + +Details: [Create executable installers](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/executable-creation/). + +### Switch on PyPI publishing (once) + +1. On [pypi.org](https://pypi.org/manage/account/publishing/), add a pending + trusted publisher: owner `CellMigrationLab`, repository `Fast4DRegPy`, + workflow `publish_pypi.yml`, environment `pypi`. +2. In the repository settings, *Secrets and variables > Actions > Variables*, + add `PYPI_PUBLISH` with the value `true` (`testpypi` for a trial on + TestPyPI). + +No token is stored. Step by step: +[.tools/docs/external_code_upload.md](../.tools/docs/external_code_upload.md#4-publish-the-code-on-pypi-optional). + +### List the app in the App Centre (once) + +After the first release with installers, +[submit the repository](https://cellmigrationlab.github.io/LabConstrictor-Site/submit/) +to the LabConstrictor App Centre. Later releases appear there by themselves. diff --git a/docs/fiji_compatibility.md b/docs/fiji_compatibility.md index 69a426e..c27c5ea 100644 --- a/docs/fiji_compatibility.md +++ b/docs/fiji_compatibility.md @@ -1,5 +1,7 @@ # Fiji compatibility +[โฌ…๏ธ Documentation index](index.md) + Fast4DRegPy follows the registration sequence in the Fiji Fast4DReg `time_estimate+apply.ijm` macro and uses ImageJ-compatible interpolation for the default transform path. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..3441a55 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,51 @@ +# Fast4DRegPy documentation + +Whether you want to correct one movie with a few clicks or build drift +correction into your own analysis, start here. + +## Choose your path + +### ๐Ÿ”ฌ I want to correct my images + +1. **Install it:** [Installation](installation.md): the desktop app, Google + Colab, or the napari / Fiji tools. +2. **Prepare your image and run it:** [Step-by-step workflow](workflow.md), + which also explains every setting. +3. **Something looks wrong?** [Troubleshooting and known issues](troubleshooting.md). + +Working in napari or Fiji? See [napari and Fiji](napari_fiji.md). + +### ๐Ÿ I write Python + +1. [Installation](installation.md#python) +2. [Python guide](python.md): `register_time`, `register_channels`, measuring + and applying separately, registration quality. +3. [Fiji compatibility](fiji_compatibility.md): how each Fiji setting maps to + Fast4DRegPy, and the few deliberate differences. + +### ๐Ÿงช I want to know how close it is to Fiji + +[Validation and speed](validation.md): the complete published Fast4DReg movie, +frame by frame, against Fiji and against the known drift, and timings on the +same computer. + +### ๐Ÿ› ๏ธ I maintain Fast4DRegPy + +[Development and releases](development.md): tests, the napari / Fiji tools, +building the app and publishing on PyPI. + +## Full documentation map + +- [Installation](installation.md) +- [Step-by-step workflow and settings](workflow.md) +- [napari and Fiji](napari_fiji.md) +- [Python guide](python.md) +- [Troubleshooting and known issues](troubleshooting.md) +- [Fiji compatibility](fiji_compatibility.md) +- [Validation and speed](validation.md) +- [Development and releases](development.md) + +Fast4DRegPy is the Python version of +[Fast4DReg](https://github.com/CellMigrationLab/Fast4DReg) (Fiji). The desktop +app and the napari / Fiji tools are built with +[LabConstrictor](https://cellmigrationlab.github.io/LabConstrictor-Site/). diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..f01571d --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,84 @@ +# Installation + +[โฌ…๏ธ Documentation index](index.md) + +There are four ways to use Fast4DRegPy. They run the same code and give the +same results. + +| | What you get | You need | +|---|---|---| +| [Desktop app](#desktop-app) | the Fast4DRegPy notebook, in its own JupyterLab | Windows, macOS or Linux; no Python | +| [napari and Fiji](#napari-and-fiji) | two tools on the image you have open | the desktop app, and the LabConstrictor plugin once | +| [Google Colab](#google-colab) | the notebook in the browser | a Google account | +| [Python](#python) | the `fast4dreg` package for your own scripts | Python 3.10โ€“3.13 | + +## Desktop app + +The app is built with [LabConstrictor](https://cellmigrationlab.github.io/LabConstrictor-Site/): +it brings its own Python, so nothing else needs to be installed. + +1. Open the [latest release](https://github.com/CellMigrationLab/Fast4DRegPy/releases) + and download the installer for your computer: `.exe` for Windows, `.pkg` + for macOS (Apple silicon or Intel), `.sh` for Linux. +2. Run it. Installing takes about 6โ€“8 minutes and needs an internet + connection; you do it once. Windows may show *Windows protected your PC*: + click **More info**, then **Run anyway**. +3. Open **Fast4DRegPy** from the Start menu, Launchpad or your applications + menu. JupyterLab opens with the Fast4DRegPy notebook. + +The LabConstrictor website has the same steps with pictures for each system: +[Install an app](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/install/), +[Open and use an app](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/using-apps/) and +[If the app does not start](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/troubleshooting-installed-app/). + +Then follow the [step-by-step workflow](workflow.md). + +## napari and Fiji + +Installing the desktop app also makes its two tools, **Correct drift +(time-lapse)** and **Align channels**, available to napari and Fiji. Each +program needs the LabConstrictor plugin, installed once per computer: + +- napari: [Install the napari plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/napari/) +- Fiji: [Install the Fiji plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/fiji/) + +The tools run in the app's own Python: napari and Fiji do not need +Fast4DRegPy, NanoPyx or anything else. How to use them: +[napari and Fiji](napari_fiji.md). (QuPath is not offered: drift correction +of time-lapse movies is not a QuPath task.) + +This is separate from the original +[Fast4DReg Fiji plugin](https://github.com/CellMigrationLab/Fast4DReg), which +you can keep using; the two give the same drift (see [Validation](validation.md)). + +## Google Colab + +[Open the notebook in Colab](https://colab.research.google.com/github/CellMigrationLab/Fast4DRegPy/blob/main/notebooks/Fast4DRegApp/Fast4DRegApp.ipynb) +and run the cells from the top. The first cell installs Fast4DRegPy and +connects your Google Drive; put your TIFF files in your Drive and give their +path under `/content/gdrive/MyDrive/`. + +## Python + +Fast4DRegPy supports Python 3.10โ€“3.13. Use a virtual environment or a conda +environment. + +```bash +python -m pip install "fast4dregpy @ git+https://github.com/CellMigrationLab/Fast4DRegPy" +``` + +Once a release is published on PyPI: + +```bash +python -m pip install fast4dregpy +``` + +Extras: `fast4dregpy[notebook]` adds JupyterLab, ipywidgets and matplotlib for +the notebook; `fast4dregpy[validation]` adds matplotlib for the validation +figures. + +The distribution is called `fast4dregpy`; the package is imported as +`fast4dreg`. It depends on [NanoPyx](https://github.com/HenriquesLab/NanoPyx) +2.1.4 (exactly this version), NumPy 2, SciPy, scikit-image and tifffile. + +Next: the [Python guide](python.md). diff --git a/docs/napari_fiji.md b/docs/napari_fiji.md new file mode 100644 index 0000000..f7452ba --- /dev/null +++ b/docs/napari_fiji.md @@ -0,0 +1,103 @@ +# Fast4DRegPy in napari and Fiji + +[โฌ…๏ธ Documentation index](index.md) + +The Fast4DRegPy app adds two tools to napari and Fiji: + +- **Correct drift (time-lapse)**: corrects the drift of the open time-lapse + and gives the corrected movie and the drift table. +- **Align channels**: aligns the channels of the open image on a reference + channel and gives the aligned image and the shift of each channel. + +They run Fast4DRegPy in the app's own Python, through +[LabConstrictor](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/image-software/): +napari and Fiji do not need Fast4DRegPy, NanoPyx or anything else. They give +the same results as the notebook and the Python package (checked on the +published Fast4DReg movie: identical corrected voxels). + +## Install (once) + +1. Install the [Fast4DRegPy app](installation.md#desktop-app). +2. Install the LabConstrictor plugin of the program you use: + [napari plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/napari/) or + [Fiji plugin](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/fiji/). + +The plugin finds every LabConstrictor app installed on the computer. What +each program can do with the tools of an app: +[What works where](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/capabilities/). + +## In napari + +1. Open your movie (*File > Open*), or choose a file in the form. +2. Open *Plugins > LabConstrictor tools*, choose **Fast4DRegPy**, then the tool. +3. Choose the image layer and type its **Axes**. A napari layer is usually + `TYX` (2D time-lapse) or `TZYX` (3D); napari shows multichannel images as + one layer per channel, so for **Align channels** give a file with a C axis. +4. Click **Run**. The corrected movie appears as a new layer + (`Fast4DRegPy:registered`) with the same sliders, and the drift table opens + below the viewer. + +![Correct drift in napari](assets/napari_correct_drift.png) + +*Correct drift (time-lapse) in napari: the form on the right, the corrected +movie, and the drift table with one row per timepoint (translation applied, in +pixels).* + +## In Fiji + +1. Open your movie. +2. Run *Plugins > LabConstrictor > LabConstrictor Tools...*, choose + **Fast4DRegPy**, then the tool. +3. Choose the image and type its **Axes**. Fiji sends a hyperstack in the + order T, Z, C, Y, X and leaves out the dimensions of size 1: a 3D + time-lapse is `TZYX`, a 2D one `TYX`, a 3D composite image `ZCYX`. +4. Click **OK**. Progress is shown in the status bar and the Log window. The + corrected image opens in a new window and the drift table in a Results + window. + +![The Correct drift form in Fiji](assets/fiji_correct_drift_form.png) + +*The form of Correct drift (time-lapse) in Fiji. Advanced settings are at the +bottom.* + +![Align channels in Fiji](assets/fiji_align_channels.png) + +*Align channels in Fiji on a 3-channel image: the aligned stack and the shift +of each channel.* + +## The settings + +The forms have the settings of the [notebook](workflow.md#the-settings), with +the same names, plus **Axes**. The **Reference channel** is counted from 0 +(Fiji counts channels from 1: Fiji's channel 1 is 0 here). + +## Good to know + +- **A corrected movie with several dimensions opens in Fiji as one long + stack.** Use *Image > Hyperstacks > Stack to Hyperstack*, with the numbers + of slices and frames of your movie, to get the sliders back. napari keeps + the dimensions. +- **Corrected images are 32-bit** (`float32`) unless you choose the output type + `input` (advanced settings). +- **The result is a copy.** Your image is not changed. The result files + (TIFF and CSV) are kept in `~/.labconstrictor/results/`, one folder per run; + `labconstrictor-tools prune` removes old runs and keeps the newest 20. +- **Large movies:** napari and Fiji send the whole image to the app. A movie + of several GB needs that much free memory twice (the image and its + corrected copy). +- **Image with exactly 3 or 4 planes in Fiji** (for example 3 channels): the + result needs a version of the LabConstrictor tools that includes + [LabConstrictor-Tools#163](https://github.com/CellMigrationLab/LabConstrictor-Tools/pull/163); + with an older one, Fiji cannot open it (napari can). +- **QuPath** is not offered for Fast4DRegPy. + +## Without napari or Fiji + +The same tools run from a terminal, with the app's Python +(`labconstrictor-tools run Fast4DRegPy correct_drift image=movie.tif axes=TZYX +correct_z=true`), and the napari panel's *Copy as command* gives that line for +your last run. See the +[LabConstrictor tools documentation](https://cellmigrationlab.github.io/LabConstrictor-Tools/). + +For developers: the tools are declared in `src/fast4dreg_lc_tools/` and tested +in `lc_tests/` (see [Development](development.md)). diff --git a/docs/python.md b/docs/python.md new file mode 100644 index 0000000..9441e2b --- /dev/null +++ b/docs/python.md @@ -0,0 +1,125 @@ +# Python guide + +[โฌ…๏ธ Documentation index](index.md) + +Install the package (see [Installation](installation.md)). The distribution is +called `fast4dregpy`; the Python package is imported as `fast4dreg`. + +## Drift correction + +```python +from fast4dreg import load_tiff, register_time, save_drift_csv, save_tiff + +image = load_tiff("timelapse.tif") # here: T, Z, Y, X + +corrected, shifts = register_time( + image, + axes="TZYX", + correct_xy=True, + correct_z=True, + workers=4, +) + +save_tiff("timelapse_registered.tif", corrected, axes="TZYX") +save_drift_csv("timelapse_drift.csv", shifts) +``` + +The `axes` string is required. It tells Fast4DRegPy what each array dimension +means, for example `"TYX"`, `"TZYX"` or `"CTZYX"`. Dimensions are never +guessed from shape. + +`shifts` has one row per timepoint. Values are the translation applied to the +frame, in `(dz, dy, dx)` pixel order: the same quantity as Fiji's drift table +(`X-Drift` = `dx`, `Y-Drift` = `dy`, Z table `Y-Drift` = `dz`). With +multichannel time series, drift is measured on `reference_channel` and the +same translation is applied to every channel. + +For 3D data Fast4DRegPy follows the Fiji sequence: measure XY drift, correct +XY, build the axial projection from that corrected stack, then measure Z drift. + +### Registration options + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `correct_xy`, `correct_z` | `True`, `False` | choose which drift components to correct | +| `projection` | `"max"` | `"max"` or `"mean"` projection | +| `reference` | `"first"` | compare with the first or previous frame | +| `time_averaging` | `1` | average frames in blocks before estimation | +| `max_expected_drift` | `0` | search radius in pixels; 0 uses the full correlation map | +| `axial_projection_axis` | `"Y"` | Fiji Top (`"Y"`) or Left (`"X"`) reslice | +| `crop_output` | `False` | crop to the region present in every frame | +| `extend_z` | `False` | pad Z before applying Z translations | +| `interpolation` | `"imagej"` | ImageJ-compatible bicubic; `"scipy"` is also available | +| `output_dtype` | `"float32"` | return float32 or explicitly round to the input dtype (`"input"`) | +| `backend` | `"threaded"` | NanoPyx estimator backend for the direct estimation path | +| `workers` | `1` | number of independent volumes transformed concurrently; never changes the result | + +What each setting does, in words: [Workflow and settings](workflow.md#the-settings). + +The `unthreaded` NanoPyx backend is available when `time_averaging=1` and +`max_expected_drift=0`. Fiji-compatible time averaging and bounded searches use +NanoPyx's compiled correlation primitives directly, so requesting +`backend="unthreaded"` with either of those modes raises an error rather than +silently ignoring the setting. + +Fiji exposes separate XY and Z values for projection, reference, averaging and +search radius. Fast4DRegPy currently uses one value for both. See +[Fiji compatibility](fiji_compatibility.md) for the exact mapping and the +remaining differences. + +### Measure and apply separately + +`register_time` is `estimate_time_drift` followed by `apply_drift`. Call them +separately to measure the drift on one channel or file and apply it to +another, as Fiji's `time_apply` does: + +```python +from fast4dreg import apply_drift, estimate_time_drift, load_drift_csv + +shifts = estimate_time_drift(reference_movie, axes="TZYX", correct_z=True) +other_corrected = apply_drift(other_channel, shifts, axes="TZYX") + +shifts = load_drift_csv("timelapse_drift.csv") # a table saved earlier +``` + +## Channel alignment + +```python +from fast4dreg import register_channels + +corrected, shifts = register_channels( + image, + axes="CZYX", + reference_channel=0, + correct_z=True, +) +``` + +All channels must be in one array with a `C` axis. Channel-shift estimation +expects a single timepoint. `estimate_channel_shifts` and +`apply_channel_shifts` split the two steps, as `channel_estimate+apply` and +`channel_apply` do in Fiji. + +## Registration quality + +The package includes the measurements used in the Fast4DReg paper: + +```python +from fast4dreg import evaluate_registration, save_validation_csv + +rows = evaluate_registration(corrected, axes="TZYX", analysis="max") +save_validation_csv("registration_quality.csv", rows) +``` + +`evaluate_registration` reports mSSIM, PSNR, Pearson correlation, the +historical NRMSE calculation used in the paper, and a conventional NRMSE under +a separate name. Image-based helpers include temporal standard-deviation +projections (`temporal_standard_deviation`), three-frame overlays +(`temporal_color_overlay`), line profiles, kymographs +(`registration_kymograph`) and signal-to-background ratios. + +## Reproducible numbers + +NanoPyx sums in parallel, so drift estimates can differ by about 0.001 pixel +between runs. Set `OMP_NUM_THREADS=1` before importing `fast4dreg` to get the +same numbers every time. `workers` never changes the result. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..4eacfe8 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,90 @@ +# Troubleshooting and known issues + +[โฌ…๏ธ Documentation index](index.md) + +Fast4DRegPy stops with a message rather than return a result it cannot +trust. Most messages say what to change. + +## Messages + +**`axes='...' has N entries, but image has M dimensions`** (napari / Fiji: +*The image has shape (...)*): the axes do not match the image. Give one letter +per dimension, in the order of the file: see +[the axes table](workflow.md#before-you-start). A Fiji hyperstack is saved as +T, Z, C, Y, X without the dimensions of size 1. + +**`... needs a Z axis` / `have no T axis` / `have no C axis`:** Z correction +needs a 3D image; drift correction needs a T axis; channel alignment needs a +C axis. + +**`time_averaging=N leaves fewer than two averaged blocks`:** the movie has +too few frames for that averaging. Use a smaller value (1 measures every +frame). Fiji silently reports zero drift in this case. + +**`the correlation peak ... lies at the edge of the max_expected_drift=N +search window`:** the drift is larger than the maximum expected drift (for Z, +in stretched axial pixels). Raise it, or set it to 0 to search the whole +correlation map. Fiji writes NaN or a clipped value in this case. + +**`reference_channel=N is outside the available range`:** channels are +counted from 0. In Fiji, channel 1 is 0 here. + +**`backend='unthreaded' is not available with time_averaging > 1 or +max_expected_drift > 0`:** keep the default `threaded` backend for these +settings. + +## Results that look wrong + +**The drift has sudden jumps.** A frame was matched to the wrong structure. +Try the `mean` projection (better for noisy images), time averaging, or a +maximum expected drift a little above the real drift. + +**The Z drift stays at 0 although the sample moves in Z.** The stack may have +too few slices: on about 10 slices or fewer, Z drift may not be measured. With +20 slices or more it is. Check that Z correction is ticked and that the axes +put Z where it is in the file. + +**The corrected movie still drifts slowly (live samples).** Compare with the +previous frame (`reference: previous`) instead of the first. + +**Black borders.** Moving the frames brings in empty pixels. Tick **Crop +output** to keep only the region present in every frame (this also changes +the Z estimate, as in Fiji). + +**Planes missing at the top or bottom after Z correction.** Tick **Extend Z** +(*Extend stack to fit*). + +**Numbers differ slightly between runs** (about 0.001 pixel). NanoPyx sums in +parallel; set the environment variable `OMP_NUM_THREADS=1` for identical +numbers every time. + +**Out of memory.** The corrected movie is 32-bit, twice the size of a 16-bit +input. Choose the output type `input`, use fewer workers, or crop the movie +first. + +## napari and Fiji + +**Fast4DRegPy is not in the list of apps.** Install the +[Fast4DRegPy app](installation.md#desktop-app) first, then click *Rescan apps* +(napari) or restart Fiji. The plugin's own help: +[napari](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/napari/), +[Fiji](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/fiji/). + +**The corrected movie opens in Fiji as one long stack.** Use *Image > +Hyperstacks > Stack to Hyperstack*. See [napari and Fiji](napari_fiji.md#good-to-know). + +**The desktop app does not start or install.** See +[If the app does not start](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/troubleshooting-installed-app/) +on the LabConstrictor website. + +## Known differences from the Fiji macro + +- One set of projection, reference, averaging and search settings for both XY + and Z (Fiji can use different values). +- Errors instead of NaN, clipped or zero drift (above). +- *Save RAM* is close to `output_dtype="input"` but not bit-identical. + +Details: [Fiji compatibility](fiji_compatibility.md). + +Still stuck? [Open an issue](https://github.com/CellMigrationLab/Fast4DRegPy/issues) +with the message, the axes and the shape of your image, and the settings. diff --git a/docs/validation.md b/docs/validation.md index 7ca35f5..aa33e95 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -1,5 +1,7 @@ # Validation +[โฌ…๏ธ Documentation index](index.md) + Fast4DRegPy is tested at three levels: small synthetic unit tests, fixtures generated by the real Fiji/ImageJ code, and the complete published Fast4DReg large-drift movie. @@ -77,6 +79,37 @@ two pixels smaller in Y and X; its common region is identical to the fresh Fiji output after uint16 conversion. Fast4DRegPy with `crop_output=True` produces the fresh Fiji dimensions. +## Speed + +The same movie, the same settings as the Fiji run (maximum projection, first +frame, no averaging, automatic search, Top reslice, XY and Z correction, crop +output) and `OMP_NUM_THREADS=1`, timed on one computer: 4 CPUs, 15 GB of +memory, Linux. Fiji is the original `time_estimate+apply.ijm` macro run +headless in ImageJ 1.53t with the Fast4DReg plugin built from source +(`validation/fiji/compare_with_fiji.py`). "Through napari or Fiji" is the +**Correct drift (time-lapse)** tool run by the LabConstrictor worker of the +installed app (`labconstrictor-tools run`), which is what napari and Fiji +call: it includes reading the TIFF and writing the 32-bit result. + +| How | 1 worker | 4 workers | +| --- | ---: | ---: | +| Fiji Fast4DReg macro (time it reports; 34 s with Java start-up) | 32 s | โ€” | +| Fast4DRegPy, Python | 40.4 s | 16.0 s | +| Fast4DRegPy through napari or Fiji (the tool) | 41.8 s | 18.3 s | + +With 4 workers Fast4DRegPy took half the time of the Fiji macro; with 1 worker +it was slower than Fiji on this computer. On the 2-CPU GitHub runner above, +the order was different (Fiji 41 s, Fast4DRegPy 19.5 s with 1 worker): timings +depend on the machine, so measure on yours. `workers` never changes the +result. Fiji's peak memory was 4.2 GB; Fast4DRegPy's 5.5 GB, because the +corrected movie is kept as 32-bit. + +Going through napari or Fiji adds 1.5โ€“2.5 s here, and changes nothing in the +result: the tool's drift table is identical to the Python one and differs +from the fresh Fiji run by at most 0.0047 pixels; without cropping, its +corrected movie is voxel-for-voxel identical to Python's, and the drift passes the strict gate +(0.0047 pixels from Fiji, 0.11 pixels from the known drift). + ## Small Fiji-generated fixtures The automated test suite includes outputs made by the real Fiji macro and diff --git a/docs/workflow.md b/docs/workflow.md new file mode 100644 index 0000000..f2bb8e1 --- /dev/null +++ b/docs/workflow.md @@ -0,0 +1,160 @@ +# Step-by-step workflow + +[โฌ…๏ธ Documentation index](index.md) + +This page follows a movie from the file to the corrected result, in the +notebook of the [desktop app or Colab](installation.md). The napari and Fiji +tools have the same settings: see [napari and Fiji](napari_fiji.md). + +## How the correction works + +Fast4DRegPy follows the steps of the Fiji tool +[Fast4DReg](https://github.com/CellMigrationLab/Fast4DReg): + +**XY correction (2D and 3D)** + +1. For each timepoint, the volume is projected over Z (maximum or average + intensity), which gives a 2D movie. A 2D movie is used as it is. +2. The shift between each frame and the reference frame is measured by + cross-correlation: the position of the peak of the cross-correlation map is + the shift. The reference is either the first frame or the previous one. +3. Each frame is translated by its shift. + +**Z correction (3D only)** + +4. The XY-corrected movie is projected from the side (along Y, Fiji's *Top*, + or along X, *Left*), which gives a 2D movie of Z against X (or Y). +5. The Z shift is measured on that movie in the same way. +6. Each volume is translated in Z. + +![Fast4DReg pipeline](assets/Fast4DReg-methodDescription.png) + +*Figure from the [Fast4DReg repository](https://github.com/CellMigrationLab/Fast4DReg).* + +Channel alignment measures the shift of each channel against a reference +channel in the same way, for one timepoint. + +## Before you start + +**Time-lapse drift correction** needs one movie: a 2D (T, Y, X) or 3D +(T, Z, Y, X) time-lapse, optionally with channels. The drift is measured on one +channel (the *reference channel*) and the same correction is applied to all +channels. Choose the channel with the most stable structures, for example the +endothelium rather than the migrating cancer cells. + +Unlike the Fiji macro, you do not need to split the channels: give the +multichannel movie and its axes (for example `TCZYX`). To measure the drift on +one file and apply it to another, use Python (`estimate_time_drift` then +`apply_drift`, see the [Python guide](python.md#measure-and-apply-separately)). + +**Channel alignment** needs one timepoint with all channels in one file: a 2D +(C, Y, X) or 3D (C, Z, Y, X) image. Combine separate channel files first. + +**The file** is a TIFF. In Fiji, *File > Save As > Tiff...* keeps the +dimensions of a hyperstack. + +**The axes.** Fast4DRegPy never guesses what the dimensions of your image +are: you give one letter per dimension, in the order of the file. + +| Your image | Axes | +|---|---| +| 2D time-lapse | `TYX` | +| 3D time-lapse | `TZYX` | +| 3D time-lapse with channels, saved by Fiji | `TZCYX` | +| 2D image with channels | `CYX` | +| 3D image with channels, saved by Fiji | `ZCYX` | + +Fiji saves hyperstacks in the order T, Z, C, Y, X and leaves out the +dimensions of size 1. If the axes do not match the image, Fast4DRegPy stops +and tells you the image's shape. + +**Z drift needs enough slices.** On stacks of about 10 slices or fewer, Z drift +may not be found at all (the `dz` column stays near 0). With 20 slices or +more it is measured reliably. + +## Running it in the notebook + +1. Open the app (or the notebook in Colab) and run the cells from the top. +2. In **TIFF path**, give the path of your file. In Colab, the file must be in + your Google Drive: `/content/gdrive/MyDrive/...`. +3. In **Axes**, give the axes of the file (table above). +4. In **Mode**, choose **time** (drift correction of a time-lapse) or + **channels** (channel alignment). +5. Set the options (next section). The defaults suit most fixed samples. +6. Click **Run registration**. + +The notebook draws the drift (dz, dy, dx) against time and saves next to the +input file: + +| File | Contents | +|---|---| +| `_registered.tif` | the corrected image, same axes as the input | +| `_drift.csv` | one row per timepoint (or channel): `index, dz, dy, dx`, the translation applied, in pixels | +| `_validation_before.csv`, `_after.csv` | registration quality before and after (time mode, when **Validate** is ticked): mSSIM, PSNR, Pearson correlation, NRMSE per frame | + +Existing files are not replaced unless **Overwrite outputs** is ticked. + +The drift table holds the same quantity as Fiji's drift table: `dx` is Fiji's +`X-Drift`, `dy` its `Y-Drift`, and `dz` the `Y-Drift` of Fiji's Z table. + +## The settings + +The names in brackets are the names in the Fiji Fast4DReg dialog and in +Python. + +- **Correct XY / Correct Z** (*xy-drift correction*, *z-drift correction*; + `correct_xy`, `correct_z`): which drift to correct. Z correction needs a Z + axis. +- **Projection** (*Projection type*; `projection`): `max` (maximum intensity) + or `mean` (average intensity) projection used to measure the drift. Average + usually works better for very noisy images. +- **Reference** (*Reference frame*; `reference`): `first` compares every frame + with the first one: best for fixed samples. `previous` compares every frame + with the one before: best for live samples, where slow drift overlays the + faster motion of the sample. +- **Time averaging** (`time_averaging`): the number of frames averaged + together before the drift is measured. 1 measures every frame, which follows + the drift closely but is sensitive to noise; a larger value averages out + noise but samples the drift more coarsely (it is then interpolated). If the + averaging leaves a single block of frames, Fast4DRegPy stops with an error + (Fiji returns zero drift there): use a smaller value. +- **Max expected drift** (*Maximum expected drift*; `max_expected_drift`): the + largest drift you expect between the first and the last frame, in pixels. + 0 lets the algorithm search the whole correlation map. Only change it if the + estimated drift has wrong, too large jumps. If the drift reaches this limit, + Fast4DRegPy stops with an error instead of returning a clipped value (Fiji + writes NaN or a clipped value there). +- **Crop output** (`crop_output`): crop away the black border created by + moving the frames, keeping the region present in every frame. As in Fiji, + cropping happens before Z is measured, so it can change the Z estimate. +- **Extend Z** (*Extend stack to fit*; `extend_z`): add slices so that no plane + is lost when the volumes move up or down. +- **Reslice** (*Reslice mode*; `axial_projection_axis`): the side projection + used for Z: *Top* (Y) or *Left* (X). +- **Reference channel** (`reference_channel`): the channel the drift is + measured on (time mode), or the channel the others are aligned to (channels + mode). Counted from 0. +- **Output type** (`output_dtype`): `float32` keeps the interpolated values; + `input` rounds them back to the type of the image (for example 16-bit), + which halves the size of the result. This is close to Fiji's *Save RAM*, + but not identical. +- **Workers** (`workers`): how many volumes are moved at the same time. Never + changes the result; more is faster and uses more memory. +- **Backend** (`backend`): the NanoPyx implementation used to measure the + drift. Keep `threaded`. + +Fiji can use different projection, reference, averaging and search settings +for XY and Z; Fast4DRegPy uses one value for both. Details: +[Fiji compatibility](fiji_compatibility.md). + +## Check the result + +- **Look at the drift plot.** A smooth curve is expected for stage drift. + Isolated jumps usually mean a wrong match: try `mean` projection, time + averaging, or a maximum expected drift. +- **Look at the corrected movie.** Structures that do not move should stay in + place. +- **Compare the quality tables** (time mode): mSSIM and Pearson correlation + between frames should go up after correction. + +Problems and their fixes: [Troubleshooting](troubleshooting.md). diff --git a/environment.yaml b/environment.yaml new file mode 100644 index 0000000..9deea1d --- /dev/null +++ b/environment.yaml @@ -0,0 +1,16 @@ +name: fast4dregpy +channels: +- conda-forge +- bioconda +- nodefaults +dependencies: +- python=3.12 +- conda +- git +- pip>=24.2 +- setuptools +- wheel +- menuinst>=2 +- truststore>=0.10.4 +- certifi +- jupyterlab=4.4.0 diff --git a/labconstrictor-app.yaml b/labconstrictor-app.yaml new file mode 100644 index 0000000..be01e70 --- /dev/null +++ b/labconstrictor-app.yaml @@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://cellmigrationlab.github.io/LabConstrictor-Site/schema/labconstrictor-app.schema.json +schema: 1 +name: Fast4DRegPy +summary: 'Correct drift in 2D and 3D time-lapse microscopy and align channels: the Python version of Fiji''s Fast4DReg.' +description: |- + Fast4DRegPy measures and corrects drift in 2D and 3D time-lapse images, and aligns the channels of multichannel images. It follows the projection-based workflow of the Fiji tool Fast4DReg and uses NanoPyx for the cross-correlation. + + On the published Fast4DReg test movie, its drift table differs from Fiji's by less than 0.005 pixels on every axis. +kind: analysis +hosts: +- notebook +- napari +- fiji +distribution: + installer: true + pip: fast4dregpy +icon: app/logo/fast4dregpy.png diff --git a/lc_tests/README.md b/lc_tests/README.md new file mode 100644 index 0000000..ac7c6c0 --- /dev/null +++ b/lc_tests/README.md @@ -0,0 +1,27 @@ +# Tests of the napari and Fiji tools + +The tools are declared in `src/fast4dreg_lc_tools/` and run in the app's own +environment through the LabConstrictor tools worker. They need +`labconstrictor-tools` (the app installer installs it) and `pandas` for their +tables. + +```bash +cd lc_tests +python make_fixtures.py fixtures +labconstrictor-tools check --module fast4dreg_lc_tools +labconstrictor-tools test --module fast4dreg_lc_tools --cases cases.json +``` + +`make_fixtures.py` writes four small images cut out of one random scene at +known whole-pixel offsets (Y and X sizes differ, so an axis swap shows): +a 2D and a 3D time-lapse, and a 2D and a 3D multichannel image. The 3D +images have 20 slices: with about 10, Fast4DRegPy does not measure the Z drift. + +`cases.json` runs each tool on them and checks what the hosts rely on: the +shape and type of the corrected image, the columns and rows of the drift +table, and the clear refusals (axes that do not fit the image, Z correction +without a Z axis, a reference channel the image does not have). The napari +and Fiji UI checks of LabConstrictor use the same cases. + +`tests/test_lc_tools.py` checks, on the same images, that the tools find the +known drift within 0.4 px, so that a sign or axis error cannot pass. diff --git a/lc_tests/cases.json b/lc_tests/cases.json new file mode 100644 index 0000000..2d6fea2 --- /dev/null +++ b/lc_tests/cases.json @@ -0,0 +1,37 @@ +[ + {"tool": "correct_drift", "inputs": {"image": "fixtures/drift_tyx.tif", "axes": "TYX"}, + "comment": "2D time-lapse: the corrected movie and one drift row per timepoint", + "expect": {"max_seconds": 120, "progress_events_min": 1, "results": { + "registered": {"shape": [5, 80, 96], "dtype": "float32"}, + "drift": {"columns": ["timepoint", "dz", "dy", "dx"], "rows": 5, "cells": {"dz[0]": 0.0, "dy[0]": 0.0, "dx[0]": 0.0}}}}}, + {"tool": "correct_drift", "inputs": {"image": "fixtures/drift_tzyx.tif", "axes": "TZYX", "correct_z": true}, + "comment": "3D time-lapse with Z drift", + "expect": {"max_seconds": 180, "results": { + "registered": {"shape": [4, 20, 64, 72], "dtype": "float32"}, + "drift": {"columns": ["timepoint", "dz", "dy", "dx"], "rows": 4}}}}, + {"tool": "correct_drift", "inputs": {"image": "fixtures/drift_tyx.tif", "axes": "TYX", "output_dtype": "input"}, + "comment": "rounded back to the type of the image", + "expect": {"max_seconds": 120, "results": {"registered": {"shape": [5, 80, 96], "dtype": "uint16"}}}}, + {"tool": "correct_drift", "inputs": {"image": "fixtures/drift_tzyx.tif", "axes": "TYX"}, + "comment": "axes that do not fit the image are refused with its shape", + "expect": {"status": "FAILED", "code": "bad_axes", "message_contains": "(4, 20, 64, 72)"}}, + {"tool": "correct_drift", "inputs": {"image": "fixtures/drift_tyx.tif", "axes": "TYX", "correct_z": true}, + "comment": "Z correction without a Z axis is refused, never skipped", + "expect": {"status": "FAILED", "code": "bad_axes", "message_contains": "Z axis"}}, + {"tool": "correct_drift", "inputs": {"image": "fixtures/channels_cyx.tif", "axes": "CYX"}, + "comment": "a time-lapse tool needs a T axis", + "expect": {"status": "FAILED", "code": "bad_axes", "message_contains": "T axis"}}, + {"tool": "align_channels", "inputs": {"image": "fixtures/channels_cyx.tif", "axes": "CYX"}, + "comment": "2D channels aligned on channel 0", + "expect": {"max_seconds": 120, "progress_events_min": 1, "results": { + "aligned": {"shape": [3, 80, 96], "dtype": "float32"}, + "channel_shifts": {"columns": ["channel", "dz", "dy", "dx"], "rows": 3, "cells": {"dy[0]": 0.0, "dx[0]": 0.0}}}}}, + {"tool": "align_channels", "inputs": {"image": "fixtures/channels_zcyx.tif", "axes": "ZCYX", "correct_z": true}, + "comment": "a 3D composite in Fiji's order Z C Y X", + "expect": {"max_seconds": 180, "results": { + "aligned": {"shape": [20, 2, 64, 72], "dtype": "float32"}, + "channel_shifts": {"columns": ["channel", "dz", "dy", "dx"], "rows": 2}}}}, + {"tool": "align_channels", "inputs": {"image": "fixtures/channels_cyx.tif", "axes": "CYX", "reference_channel": 5}, + "comment": "a reference channel the image does not have is refused", + "expect": {"status": "FAILED", "code": "invalid_settings"}} +] diff --git a/lc_tests/make_fixtures.py b/lc_tests/make_fixtures.py new file mode 100644 index 0000000..f3aaa74 --- /dev/null +++ b/lc_tests/make_fixtures.py @@ -0,0 +1,90 @@ +"""Write the small images the tool cases use, each with a known drift. + + python make_fixtures.py fixtures + +Every image is cut out of one larger random scene (smoothed noise plus a few +bright, asymmetric spots, fixed seed), each frame or channel at a known integer +offset, so the translation that corrects it is known exactly. Y and X sizes +differ, so a swap of the axes shows. KNOWN lists the translation (dz, dy, dx) +that brings each frame or channel back onto the first or reference one, the +same quantity as Fast4DRegPy's drift table. +""" + +import sys +from pathlib import Path + +import numpy as np +import tifffile +from scipy import ndimage + +# Offsets of the cut-outs in the scene, (z, y, x) per frame or channel. +TIME_OFFSETS = [(0, 0, 0), (0, 2, -3), (0, 5, -1), (0, 3, 4), (0, -2, 6)] +TIME_Z_OFFSETS = [(0, 0, 0), (1, 2, -1), (2, 3, 1), (1, -1, 3)] +CHANNEL_OFFSETS = [(0, 0, 0), (0, 3, -2), (0, -2, 4)] +CHANNEL_Z_OFFSETS = [(0, 0, 0), (2, 2, -3)] + +# The translation applied to frame t: its offset minus the offset of frame 0. +KNOWN = { + "drift_tyx.tif": [(0, y, x) for _, y, x in TIME_OFFSETS], + "drift_tzyx.tif": list(TIME_Z_OFFSETS), + "channels_cyx.tif": [(0, y, x) for _, y, x in CHANNEL_OFFSETS], + "channels_zcyx.tif": list(CHANNEL_Z_OFFSETS), +} + + +def scene(shape: tuple[int, ...], seed: int) -> np.ndarray: + """Smoothed noise with a few bright spots of different sizes, as uint16.""" + rng = np.random.default_rng(seed) + image = ndimage.gaussian_filter(rng.random(shape), 2.0) + spots = np.zeros(shape) + for _ in range(12): + spots[tuple(rng.integers(4, s - 4) for s in shape)] = rng.uniform(5, 20) + image += ndimage.gaussian_filter(spots, 1.5) + image -= image.min() + return (image / image.max() * 4000 + 100).astype(np.uint16) + + +def cut(volume: np.ndarray, offset: tuple[int, int, int], size: tuple[int, int, int]): + """The block of `size` that starts `offset` away from the centre region.""" + margin = 8 + z0, y0, x0 = (margin + o for o in offset) + return volume[z0 : z0 + size[0], y0 : y0 + size[1], x0 : x0 + size[2]] + + +def write(folder: Path) -> None: + folder.mkdir(parents=True, exist_ok=True) + flat = scene((20, 112, 128), seed=1) + frames = [cut(flat, o, (1, 80, 96))[0] for o in TIME_OFFSETS] + tifffile.imwrite( + folder / "drift_tyx.tif", + np.stack(frames), + imagej=True, + metadata={"axes": "TYX"}, + ) + + volume = scene((38, 96, 104), seed=2) # 20 slices: Z drift is not measured on ~10 + frames = [cut(volume, o, (20, 64, 72)) for o in TIME_Z_OFFSETS] + tifffile.imwrite( + folder / "drift_tzyx.tif", + np.stack(frames), + imagej=True, + metadata={"axes": "TZYX"}, + ) + + channels = [cut(flat, o, (1, 80, 96))[0] for o in CHANNEL_OFFSETS] + tifffile.imwrite( + folder / "channels_cyx.tif", + np.stack(channels), + imagej=True, + metadata={"axes": "CYX"}, + ) + + channels = [cut(volume, o, (20, 64, 72)) for o in CHANNEL_Z_OFFSETS] + zcyx = np.stack(channels, axis=1) # Z C Y X, the order Fiji saves a composite + tifffile.imwrite( + folder / "channels_zcyx.tif", zcyx, imagej=True, metadata={"axes": "ZCYX"} + ) + + +if __name__ == "__main__": + write(Path(sys.argv[1] if len(sys.argv) > 1 else "fixtures")) diff --git a/notebooks/Fast4DRegApp.ipynb b/notebooks/Fast4DRegApp/Fast4DRegApp.ipynb similarity index 72% rename from notebooks/Fast4DRegApp.ipynb rename to notebooks/Fast4DRegApp/Fast4DRegApp.ipynb index 1ddff79..015a364 100644 --- a/notebooks/Fast4DRegApp.ipynb +++ b/notebooks/Fast4DRegApp/Fast4DRegApp.ipynb @@ -15,8 +15,18 @@ "metadata": {}, "outputs": [], "source": [ - "# Uncomment in Google Colab after the package is published or replace with the GitHub URL.\n", - "# %pip install -q 'fast4dregpy[notebook]'" + "# @title Install Fast4DRegPy (Google Colab only)\n", + "# In the Fast4DRegPy app and in your own Python, the package is already installed.\n", + "import sys\n", + "\n", + "if 'google.colab' in sys.modules:\n", + " !pip install -q \"fast4dregpy[notebook] @ git+https://github.com/CellMigrationLab/Fast4DRegPy\"\n", + " from google.colab import drive\n", + "\n", + " drive.mount('/content/gdrive')\n", + " print('Fast4DRegPy installed; your Google Drive is under /content/gdrive/MyDrive')\n", + "else:\n", + " print('Not on Google Colab: using the installed Fast4DRegPy')\n" ] }, { @@ -45,7 +55,10 @@ "source": [ "## Registration app\n", "\n", - "Enter a TIFF path accessible to the notebook. For Colab, mount Google Drive first and use a Drive path." + "Enter the path of a TIFF file and its **axes** (one letter per dimension: T time, Z slices, C channels, Y, X; for example `TZYX`). ", + "Choose **time** to correct the drift of a time-lapse, or **channels** to align the channels of one timepoint. ", + "Every setting is explained in the [workflow guide](https://github.com/CellMigrationLab/Fast4DRegPy/blob/main/docs/workflow.md). ", + "The results are saved next to the input file. In Colab, use a path in your Google Drive (`/content/gdrive/MyDrive/...`).\n" ] }, { @@ -62,6 +75,12 @@ "reference = widgets.Dropdown(options=['first', 'previous'], value='first', description='Reference:')\n", "correct_xy = widgets.Checkbox(value=True, description='Correct XY')\n", "correct_z = widgets.Checkbox(value=False, description='Correct Z')\n", + "time_averaging = widgets.BoundedIntText(value=1, min=1, max=1000, description='Time averaging:', style={'description_width': 'initial'})\n", + "max_expected_drift = widgets.BoundedIntText(value=0, min=0, max=100000, description='Max expected drift (px):', style={'description_width': 'initial'})\n", + "crop_output = widgets.Checkbox(value=False, description='Crop output')\n", + "extend_z = widgets.Checkbox(value=False, description='Extend Z (stack to fit)')\n", + "reslice = widgets.Dropdown(options=[('Top (Y)', 'Y'), ('Left (X)', 'X')], value='Y', description='Reslice:')\n", + "output_dtype = widgets.Dropdown(options=['float32', 'input'], value='float32', description='Output type:')\n", "backend = widgets.Dropdown(options=['threaded', 'unthreaded'], value='threaded', description='Backend:')\n", "workers = widgets.BoundedIntText(value=4, min=1, max=64, description='Workers:')\n", "overwrite = widgets.Checkbox(value=False, description='Overwrite outputs')\n", @@ -84,12 +103,20 @@ " projection=projection.value,\n", " correct_xy=correct_xy.value,\n", " correct_z=correct_z.value,\n", + " axial_projection_axis=reslice.value,\n", + " max_expected_drift=max_expected_drift.value,\n", + " output_dtype=output_dtype.value,\n", " backend=backend.value,\n", " workers=workers.value,\n", " )\n", " if mode.value == 'time':\n", " corrected, shifts = register_time(\n", - " image, reference=reference.value, **settings\n", + " image,\n", + " reference=reference.value,\n", + " time_averaging=time_averaging.value,\n", + " crop_output=crop_output.value,\n", + " extend_z=extend_z.value,\n", + " **settings,\n", " )\n", " else:\n", " corrected, shifts = register_channels(image, **settings)\n", @@ -138,8 +165,10 @@ "\n", "run_button.on_click(run_registration)\n", "display(widgets.VBox([\n", - " image_path, axes, mode, reference_channel, projection, reference, backend, workers,\n", + " image_path, axes, mode, reference_channel,\n", " widgets.HBox([correct_xy, correct_z]),\n", + " projection, reference, time_averaging, max_expected_drift, reslice,\n", + " widgets.HBox([crop_output, extend_z]), output_dtype, backend, workers,\n", " widgets.HBox([validate, validation_analysis, overwrite]), run_button, output\n", "]))" ] diff --git a/notebooks/Fast4DRegApp/requirements.yaml b/notebooks/Fast4DRegApp/requirements.yaml new file mode 100644 index 0000000..18a25bd --- /dev/null +++ b/notebooks/Fast4DRegApp/requirements.yaml @@ -0,0 +1,14 @@ +dependencies: +- nanopyx==2.1.4 +- numpy==2.5.5 +- scipy==1.18.1 +- scikit-image==0.26.0 +- tifffile==2026.11.12 +- matplotlib==3.11.2 +- ipywidgets==8.1.9 +- pandas==3.1.1 +description: "Fast4DRegPy: correct drift in 2D and 3D time-lapse images and align channels, with the projection-based workflow of Fiji's Fast4DReg." +linux_dependencies: [] +macos_dependencies: [] +python_version: "3.12" +windows_dependencies: [] diff --git a/pyproject.toml b/pyproject.toml index 0766b0a..ff8139c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,6 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "fast4dregpy" +# Before each release, set this to the version of the release tag (v0.6.0 -> "0.6.0"): the release publishes the +# package on PyPI with this version and stops, without uploading, if it differs from the tag. version = "0.5.0" description = "Python implementation of Fast4DReg using NanoPyx for projection-based microscopy registration" readme = "README.md" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9165568 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,12 @@ +# Generated by .tools/python/merge_requirements.py on 2026-11-16T20:06:02.943253Z +# Source files: notebooks/Fast4DRegApp/requirements.yaml +# --- +nanopyx==2.1.4 +numpy==2.5.5 +scipy==1.18.1 +scikit-image==0.26.0 +tifffile==2026.11.12 +matplotlib==3.11.2 +ipywidgets==8.1.9 +pandas==3.1.1 +jl-hidecode==0.0.1 diff --git a/requirements_gpu.txt b/requirements_gpu.txt new file mode 100644 index 0000000..f47cf70 --- /dev/null +++ b/requirements_gpu.txt @@ -0,0 +1,13 @@ +# Generated by .tools/python/merge_requirements.py on 2026-11-16T20:06:02.943879Z +# Source files: notebooks/Fast4DRegApp/requirements.yaml +# Target accelerator: NVIDIA GPU +# --- +nanopyx==2.1.4 +numpy==2.5.5 +scipy==1.18.1 +scikit-image==0.26.0 +tifffile==2026.11.12 +matplotlib==3.11.2 +ipywidgets==8.1.9 +pandas==3.1.1 +jl-hidecode==0.0.1 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..98e7cf6 --- /dev/null +++ b/setup.py @@ -0,0 +1,17 @@ +"""The Python package of the app, as the LabConstrictor installer installs it (src/, see .tools/docs/external_code_upload.md). + +pyproject.toml describes the package fast4dregpy for pip and PyPI (name, version, Python versions, dependencies); when it is +present, its values win. The installer ships only this file and src/, so this file says just enough to install the code: +the import name, the version and where the packages are. Each release writes its version here (.tools/python/bump_version.py). + +Unlike the template's setup.py, it gives no python_requires and no install_requires: those would override the ones of +pyproject.toml in the package on PyPI (the installer installs the dependencies itself, from requirements.txt). +""" +from setuptools import find_packages, setup + +setup( + name="fast4dreg", + version="0.5.0", + package_dir={"": "src"}, + packages=find_packages(where="src"), +) diff --git a/src/fast4dreg/__init__.py b/src/fast4dreg/__init__.py index e77df9d..0717647 100644 --- a/src/fast4dreg/__init__.py +++ b/src/fast4dreg/__init__.py @@ -52,4 +52,17 @@ "temporal_standard_deviation", ] -__version__ = "0.5.0" +def _installed_version() -> str: + """The version of the installed distribution: ``fast4dregpy`` from PyPI, or + ``fast4dreg`` as the LabConstrictor installer installs it from setup.py.""" + from importlib.metadata import PackageNotFoundError, version + + for distribution in ("fast4dregpy", "fast4dreg"): + try: + return version(distribution) + except PackageNotFoundError: + continue + return "0+unknown" + + +__version__ = _installed_version() diff --git a/src/fast4dreg_lc_tools/__init__.py b/src/fast4dreg_lc_tools/__init__.py new file mode 100644 index 0000000..2027e14 --- /dev/null +++ b/src/fast4dreg_lc_tools/__init__.py @@ -0,0 +1,283 @@ +"""Fast4DRegPy in napari, Fiji and on the command line (LabConstrictor tools). + +The LabConstrictor installer finds this module next to the package `fast4dreg` +and registers its tools for the hosts listed in labconstrictor-app.yaml. The +tools only call the public API of `fast4dreg`; the science is there, not here. + +napari and Fiji hand over the image as an array without saying what its +dimensions are, and Fast4DRegPy never guesses them, so each tool asks for the +axes. Fiji saves a hyperstack in the order T Z C Y X and leaves out the +dimensions of size 1. + +Only `labconstrictor_tools` and the standard library are imported at module +level: hosts import this module to list the tools. The app's installer installs +`labconstrictor_tools`; the rest of `fast4dreg` does not need it. +""" + +from typing import Annotated, Literal + +from labconstrictor_tools import ( + Advanced, + Description, + Group, + Image, + ImageOut, + Label, + Min, + Name, + TableOut, + ToolError, + progress, + tool, +) + +AXES_HELP = ( + "One letter per dimension of the image, in order: T time, Z slices, " + "C channels, Y and X. From Fiji (dimensions of size 1 left out): TYX, TZYX, " + "TCYX, TZCYX. A napari layer usually is TYX or TZYX." +) +WORKERS_HELP = ( + "Number of volumes transformed at the same time. Never changes the result; " + "more uses more memory. 1 is safe." +) +INTERPOLATION_HELP = ( + "imagej: ImageJ bicubic, as in Fiji Fast4DReg. scipy: SciPy spline interpolation." +) +OUTPUT_DTYPE_HELP = ( + "float32 keeps the interpolated values; input rounds them back to the type " + "of the image." +) +AXIAL_HELP = "The reslice used to measure Z drift: Y as Fiji's 'Top', X as 'Left'." + +DECIMALS = 4 + +Axes = Annotated[str, Label("Axes"), Description(AXES_HELP)] + + +def _axes(image, axes: str, needs: str) -> str: + """The axes as Fast4DRegPy reads them, or a message the person can act on.""" + from fast4dreg.axes import normalize_axes + + try: + normalized = normalize_axes(image, axes) + except (TypeError, ValueError) as error: + shape = tuple(image.shape) + raise ToolError( + "bad_axes", + f"{error}. The image has shape {shape}: give one letter per dimension.", + ) from error + if needs not in normalized: + raise ToolError( + "bad_axes", f"Axes {normalized} have no {needs} axis; this tool needs one." + ) + return normalized + + +def _shift_table(shifts, index_name: str) -> dict: + """The (dz, dy, dx) translation applied to each timepoint or channel, in px. + + Rounded to 0.0001 px: the shifts are float32, whose last digits are noise. + """ + return { + index_name: list(range(len(shifts))), + "dz": [round(float(row[0]), DECIMALS) for row in shifts], + "dy": [round(float(row[1]), DECIMALS) for row in shifts], + "dx": [round(float(row[2]), DECIMALS) for row in shifts], + } + + +@tool("Correct drift (time-lapse)") +def correct_drift( + image: Annotated[Image, Description("The 2D or 3D time-lapse to correct.")], + axes: Axes = "TZYX", + correct_xy: Annotated[ + bool, + Group("What to correct"), + Label("Correct XY drift"), + Description("Measure and correct the drift in X and Y."), + ] = True, + correct_z: Annotated[ + bool, + Group("What to correct"), + Label("Correct Z drift"), + Description("Needs a Z axis."), + ] = False, + projection: Annotated[ + Literal["max", "mean"], + Group("Drift estimation"), + Description("The projection the drift is measured on."), + ] = "max", + reference: Annotated[ + Literal["first", "previous"], + Group("Drift estimation"), + Description( + "first: compare every frame with the first. " + "previous: with the frame before (slow drift)." + ), + ] = "first", + time_averaging: Annotated[ + int, + Min(1), + Group("Drift estimation"), + Description( + "Average this many frames before measuring; 1 measures every frame." + ), + ] = 1, + max_expected_drift: Annotated[ + int, + Min(0), + Group("Drift estimation"), + Label("Max expected drift (px)"), + Description("Search radius in pixels; 0 searches the whole correlation map."), + ] = 0, + crop_output: Annotated[ + bool, + Group("Output"), + Description( + "Crop to the region present in every frame, as Fiji's 'Crop output' " + "(it also changes the Z estimate)." + ), + ] = False, + extend_z: Annotated[ + bool, + Group("Output"), + Label("Extend Z"), + Description("Pad Z so that Z translations keep every plane."), + ] = False, + reference_channel: Annotated[ + int, + Min(0), + Advanced(), + Description( + "The channel the drift is measured on, from 0; used when there is a C axis." + ), + ] = 0, + axial_projection_axis: Annotated[ + Literal["Y", "X"], Advanced(), Description(AXIAL_HELP) + ] = "Y", + interpolation: Annotated[ + Literal["imagej", "scipy"], Advanced(), Description(INTERPOLATION_HELP) + ] = "imagej", + output_dtype: Annotated[ + Literal["float32", "input"], Advanced(), Description(OUTPUT_DTYPE_HELP) + ] = "float32", + workers: Annotated[int, Min(1), Advanced(), Description(WORKERS_HELP)] = 1, +) -> tuple[Annotated[ImageOut, Name("registered")], Annotated[TableOut, Name("drift")]]: + """Measure the drift of a time-lapse and correct it, as Fiji's Fast4DReg does. + + The table gives, for each timepoint, the translation applied (dz, dy, dx) in pixels. + """ + from fast4dreg import register_time + + normalized = _axes(image, axes, "T") + if correct_z and "Z" not in normalized: + raise ToolError( + "bad_axes", + f"Correct Z drift needs a Z axis; the axes {normalized} have none.", + ) + progress(0.05, "measuring and correcting the drift") + try: + corrected, shifts = register_time( + image, + axes=normalized, + reference_channel=reference_channel, + projection=projection, + reference=reference, + correct_xy=correct_xy, + correct_z=correct_z, + axial_projection_axis=axial_projection_axis, + time_averaging=time_averaging, + max_expected_drift=max_expected_drift, + interpolation=interpolation, + crop_output=crop_output, + extend_z=extend_z, + output_dtype=output_dtype, + workers=workers, + ) + except ValueError as error: # a setting the image does not allow, or a failed fit + raise ToolError("invalid_settings", str(error)) from error + return corrected, _shift_table(shifts, "timepoint") + + +@tool("Align channels") +def align_channels( + image: Annotated[ + Image, Description("A 2D or 3D image with several channels, one timepoint.") + ], + axes: Annotated[ + str, + Label("Axes"), + Description( + "One letter per dimension, in order: C channels, Z slices, Y and X. " + "A Fiji composite is CYX, or ZCYX with slices." + ), + ] = "ZCYX", + reference_channel: Annotated[ + int, Min(0), Description("The channel the others are aligned to, from 0.") + ] = 0, + correct_xy: Annotated[ + bool, + Group("What to correct"), + Label("Align in XY"), + Description("Measure and correct the shifts in X and Y."), + ] = True, + correct_z: Annotated[ + bool, + Group("What to correct"), + Label("Align in Z"), + Description("Needs a Z axis."), + ] = False, + projection: Annotated[ + Literal["max", "mean"], + Group("Shift estimation"), + Description("The projection the shifts are measured on."), + ] = "max", + max_expected_drift: Annotated[ + int, + Min(0), + Group("Shift estimation"), + Label("Max expected shift (px)"), + Description("Search radius in pixels; 0 searches the whole correlation map."), + ] = 0, + axial_projection_axis: Annotated[ + Literal["Y", "X"], Advanced(), Description(AXIAL_HELP) + ] = "Y", + interpolation: Annotated[ + Literal["imagej", "scipy"], Advanced(), Description(INTERPOLATION_HELP) + ] = "imagej", + output_dtype: Annotated[ + Literal["float32", "input"], Advanced(), Description(OUTPUT_DTYPE_HELP) + ] = "float32", + workers: Annotated[int, Min(1), Advanced(), Description(WORKERS_HELP)] = 1, +) -> tuple[ + Annotated[ImageOut, Name("aligned")], Annotated[TableOut, Name("channel_shifts")] +]: + """Align the channels of a multichannel image on a reference channel. + + The table gives, for each channel, the translation applied (dz, dy, dx) in pixels. + """ + from fast4dreg import register_channels + + normalized = _axes(image, axes, "C") + if correct_z and "Z" not in normalized: + raise ToolError( + "bad_axes", f"Align in Z needs a Z axis; the axes {normalized} have none." + ) + progress(0.05, "measuring and correcting the channel shifts") + try: + aligned, shifts = register_channels( + image, + axes=normalized, + reference_channel=reference_channel, + projection=projection, + correct_xy=correct_xy, + correct_z=correct_z, + axial_projection_axis=axial_projection_axis, + max_expected_drift=max_expected_drift, + interpolation=interpolation, + output_dtype=output_dtype, + workers=workers, + ) + except ValueError as error: + raise ToolError("invalid_settings", str(error)) from error + return aligned, _shift_table(shifts, "channel") diff --git a/tests/test_lc_tools.py b/tests/test_lc_tools.py new file mode 100644 index 0000000..d3462bc --- /dev/null +++ b/tests/test_lc_tools.py @@ -0,0 +1,110 @@ +"""The napari / Fiji tools (src/fast4dreg_lc_tools): axes, sign and table layout. + +The tools only pass the image and the settings to the public API, so these tests +check what the bridge adds: the axes a host sends, the drift table and the clear +refusals. The fixtures of lc_tests/ are cut out of one scene at known integer +offsets (Y and X sizes differ), so an axis swap or a sign error shows as a +drift of at least 1 pixel. Precision is checked against Fiji elsewhere. + +They need labconstrictor-tools, which the app installer installs; the tests +workflow installs the version the installer pins. +""" + +import sys +from pathlib import Path + +import numpy as np +import pytest +import tifffile + +pytest.importorskip( + "labconstrictor_tools", reason="labconstrictor-tools is not installed" +) +from labconstrictor_tools import ToolError + +import fast4dreg_lc_tools as tools + +LC_TESTS = Path(__file__).resolve().parents[1] / "lc_tests" +sys.path.insert(0, str(LC_TESTS)) +import make_fixtures # noqa: E402 + +TOLERANCE_PX = 0.4 # the shifts are whole pixels, at least 1 apart + + +@pytest.fixture(scope="module") +def fixtures(tmp_path_factory): + folder = tmp_path_factory.mktemp("lc_fixtures") + make_fixtures.write(folder) + return folder + + +def table_shifts(table, index_name): + assert list(table) == [index_name, "dz", "dy", "dx"] + assert table[index_name] == list(range(len(table["dz"]))) + return np.column_stack([table["dz"], table["dy"], table["dx"]]) + + +@pytest.mark.parametrize( + ("name", "axes", "correct_z"), + [("drift_tyx.tif", "TYX", False), ("drift_tzyx.tif", "TZYX", True)], +) +def test_correct_drift_finds_the_known_drift(fixtures, name, axes, correct_z): + image = tifffile.imread(fixtures / name) + corrected, table = tools.correct_drift(image, axes=axes, correct_z=correct_z) + assert corrected.shape == image.shape + assert corrected.dtype == np.float32 + shifts = table_shifts(table, "timepoint") + np.testing.assert_allclose(shifts, make_fixtures.KNOWN[name], atol=TOLERANCE_PX) + + +@pytest.mark.parametrize( + ("name", "axes", "correct_z"), + [("channels_cyx.tif", "CYX", False), ("channels_zcyx.tif", "ZCYX", True)], +) +def test_align_channels_finds_the_known_shifts(fixtures, name, axes, correct_z): + image = tifffile.imread(fixtures / name) + aligned, table = tools.align_channels(image, axes=axes, correct_z=correct_z) + assert aligned.shape == image.shape + shifts = table_shifts(table, "channel") + np.testing.assert_allclose(shifts, make_fixtures.KNOWN[name], atol=TOLERANCE_PX) + + +def test_lower_case_axes_are_accepted(fixtures): + image = tifffile.imread(fixtures / "drift_tyx.tif") + _, table = tools.correct_drift(image, axes="tyx") + shifts = table_shifts(table, "timepoint") + np.testing.assert_allclose( + shifts, make_fixtures.KNOWN["drift_tyx.tif"], atol=TOLERANCE_PX + ) + + +@pytest.mark.parametrize( + ("tool", "name", "axes", "settings", "words"), + [ + (tools.correct_drift, "drift_tzyx.tif", "TYX", {}, "(4, 20, 64, 72)"), + (tools.correct_drift, "drift_tyx.tif", "TYQ", {}, "unsupported axes"), + (tools.correct_drift, "drift_tyx.tif", "TYX", {"correct_z": True}, "Z axis"), + (tools.correct_drift, "channels_cyx.tif", "CYX", {}, "T axis"), + (tools.align_channels, "drift_tyx.tif", "TYX", {}, "C axis"), + ( + tools.align_channels, + "channels_cyx.tif", + "CYX", + {"correct_z": True}, + "Z axis", + ), + ], +) +def test_axes_that_do_not_fit_are_refused(fixtures, tool, name, axes, settings, words): + image = tifffile.imread(fixtures / name) + with pytest.raises(ToolError) as caught: + tool(image, axes=axes, **settings) + assert caught.value.code == "bad_axes" + assert words in str(caught.value) + + +def test_a_setting_fast4dregpy_refuses_is_a_tool_error(fixtures): + image = tifffile.imread(fixtures / "channels_cyx.tif") + with pytest.raises(ToolError) as caught: + tools.align_channels(image, axes="CYX", reference_channel=5) + assert caught.value.code == "invalid_settings"