From 9e4345efc1d10fd87502070a619e86c56a16c023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20Hidalgo?= <47150974+IvanHCenalmor@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:21:03 +0200 Subject: [PATCH] Fix placeholder issues --- .github/workflows/tests.yml | 28 ++++ app.py | 217 +----------------------------- initializer.py | 254 ++++++++++++++++++++++++++++++++++++ tests/test_initializer.py | 184 ++++++++++++++++++++++++++ 4 files changed, 467 insertions(+), 216 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 initializer.py create mode 100644 tests/test_initializer.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..623c48a --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,28 @@ +name: Tests + +# Weekly as well: tests/test_initializer.py initialises the template's current main, so a placeholder added to the +# template that this form does not replace yet (LabConstrictor#40) fails here even when nothing changed in this repository. +on: + push: + branches: [main] + pull_request: + schedule: + - cron: "17 5 * * 1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: "3.11" + - name: Install the form's requirements + run: pip install -r requirements.txt + - name: Tests (the initializer test downloads the template's main) + run: python -m unittest discover -s tests -v diff --git a/app.py b/app.py index a091242..c2ea3d2 100644 --- a/app.py +++ b/app.py @@ -19,6 +19,7 @@ import os import manifest_form +from initializer import initialize_project, replace_in_file st.set_page_config(page_title="LabConstrictor", page_icon="🐍", @@ -87,9 +88,6 @@ def validate_repo_format(repo_url): return True return False -def to_python_project_name(project_name: str) -> str: - return project_name.lower().replace(" ", "_").replace("-", "_").replace(".", "_") - def validate_requirements(uploaded_requirements): # First read the requirements.yaml content try: @@ -304,14 +302,6 @@ def handle_remove_error(func, path, exc_info): else: raise exc_info[1] -def replace_in_file(file_path, old, new): - with open(file_path, 'r', encoding='utf-8') as file: - content = file.read() - content = content.replace(old, str(new).strip()) - with open(file_path, 'w', encoding='utf-8') as file: - file.write(content) - - def synchronize_welcome_template(repo_path): welcome_template_path = repo_path / ".tools" / "templates" / "Welcome_template.ipynb" if not welcome_template_path.exists(): @@ -337,42 +327,6 @@ def synchronize_welcome_template(repo_path): return True -def capture_yaml_key_lines(yaml_text: str, key: str): - """Return all lines whose trimmed content starts with ':'.""" - prefix = f"{key}:" - captured = [] - for line in yaml_text.splitlines(): - stripped = line.lstrip() - if stripped.startswith(prefix): - indent = line[: len(line) - len(stripped)] - captured.append(f"{indent}{stripped}") - return captured - - -def restore_yaml_duplicate_keys(serialized_text: str, key: str, preserved_lines): - """Replace the serialized ':' line with the preserved lines (i.e., duplicates).""" - if not preserved_lines: - return serialized_text - key_prefix = f"{key}:" - output_lines = [] - inserted = False - for line in serialized_text.splitlines(): - stripped = line.lstrip() - if stripped.startswith(key_prefix): - if not inserted: - output_lines.extend(preserved_lines) - inserted = True - continue - output_lines.append(line) - - if not inserted: - output_lines.extend(preserved_lines) - - if serialized_text.endswith("\n"): - return "\n".join(output_lines) + "\n" - return "\n".join(output_lines) - - def create_icns(img, output_path): # Function taken from: https://github.com/jojomondag/PNG_to_ico_to_icns_converter/blob/main/PNG_to_ico_to_icns_converter.py # Define the icon types and sizes @@ -409,175 +363,6 @@ def create_icns(img, output_path): f.write(icns_header) f.write(icns_data) -def initialize_project(repo_path, project_name, version, hide_code, - welcome_image_path, header_image_path, icon_image_path, - ico_image_path, icns_image_path, - github_owner, github_repo_name): - - # Copy and replace template files into their final locations - template_to_location = { - ".tools/templates/hide_code_cells.py": "app/python_scripts/hide_code_cells.py" - } - - for template_path, final_path in template_to_location.items(): - shutil.copyfile(repo_path / template_path, repo_path / final_path) - - # Define the conversion dictionary - proyectname_lower = project_name.lower() - python_project_name = to_python_project_name(project_name) - conversion_dict = { - "LOWER_PROJ_NAME": { - "environment.yaml": proyectname_lower, - ".tools/templates/download_executable_template.md": proyectname_lower, - }, - "PYTHON_PROJ_NAME": { - "setup.py": python_project_name, - ".tools/docs/external_code_upload.md": python_project_name, - ".tools/templates/Welcome_template.ipynb": python_project_name, - }, - "UNDERSCORED_PROJECT_NAME": { - "construct.yaml": project_name.replace(" ", "_"), - "app/bash_bat_scripts/pre_uninstall.bat": project_name.replace(" ", "_"), - "app/bash_bat_scripts/post_install.bat": project_name.replace(" ", "_"), - }, - "PROJECT_NAME": { - "construct.yaml": project_name, - "app/menuinst/notebook_launcher.json": project_name, - "app/bash_bat_scripts/post_install.bat": project_name, - "app/bash_bat_scripts/post_install.sh": project_name, - "app/bash_bat_scripts/pre_uninstall.bat": project_name, - "app/bash_bat_scripts/pre_uninstall.sh": project_name, - "app/bash_bat_scripts/uninstall.sh": project_name, - ".tools/templates/Welcome_template.ipynb": project_name, - ".tools/templates/download_executable_template.md": project_name, - ".tools/python/bump_constructor.py": project_name, - }, - "VERSION_NUMBER": { - "construct.yaml": version, - "app/bash_bat_scripts/post_install.bat": version, - "setup.py": version, - }, - "WELCOME_IMAGE": { - "construct.yaml": welcome_image_path, - }, - "HEADER_IMAGE": { - "construct.yaml": header_image_path, - }, - "ICON_IMAGE": { - "construct.yaml": icon_image_path, - }, - "GITHUB_OWNER": { - "app/bash_bat_scripts/post_install.bat": github_owner, - ".tools/templates/download_executable_template.md": github_owner, - }, - "GITHUB_REPO_NAME": { - ".tools/templates/download_executable_template.md": github_repo_name, - }, - "HIDE_CODE_DISABLED": { - "app/python_scripts/hide_code_cells.py": hide_code, - } - } - - # Replace placeholders in files - for placeholder, files in conversion_dict.items(): - for file_path, replacement in files.items(): - replace_in_file(repo_path / file_path, placeholder, replacement) - - package_dir = repo_path / "src" / python_project_name - package_dir.mkdir(parents=True, exist_ok=True) - init_file = package_dir / "__init__.py" - if not init_file.exists(): - init_file.write_text("", encoding="utf-8") - - # Update the notebook launcher JSON file to set the icons if needed - notebook_launcher_path = repo_path / "app" / "menuinst" / "notebook_launcher.json" - if notebook_launcher_path.exists(): - with open(notebook_launcher_path, "r", encoding="utf-8") as f: - launcher_data = f.read() - if icon_image_path: - launcher_data = launcher_data.replace("ICON_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{icon_image_path.name}") - else: - launcher_data = launcher_data.replace("ICON_IMAGE_PATH", f"") - if ico_image_path: - launcher_data = launcher_data.replace("ICON_ICO_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{ico_image_path.name}") - else: - launcher_data = launcher_data.replace("ICON_ICO_IMAGE_PATH", f"") - if icns_image_path: - launcher_data = launcher_data.replace("ICON_ICNS_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{icns_image_path.name}") - else: - launcher_data = launcher_data.replace("ICON_ICNS_IMAGE_PATH", f"") - with open(notebook_launcher_path, "w", encoding="utf-8") as f: - f.write(launcher_data) - - # Update the construct.yaml extra_files to include the images if they were provided - # Read the construct.yaml to check if images need to be set - construct_path = repo_path / "construct.yaml" - construct_raw_text = construct_path.read_text(encoding="utf-8") - post_install_lines = capture_yaml_key_lines(construct_raw_text, "post_install") - pre_uninstall_lines = capture_yaml_key_lines(construct_raw_text, "pre_uninstall") - construct_data = yaml.safe_load(construct_raw_text) - if construct_data is None: - construct_data = {} - extra_files = construct_data.get("extra_files") - if extra_files is None: - extra_files = [] - construct_data["extra_files"] = extra_files - - - # Check if the welcome, header, icon images were provided and in case they were not, set them to empty in the construct.yaml - if not welcome_image_path: - construct_data.pop("welcome_image", None) - if not header_image_path: - construct_data.pop("header_image", None) - if not icon_image_path: - construct_data.pop("icon_image", None) - - # 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) - - # Check if the images paths are provided and not already in the list¨ - image_mappings = [ icon_image_path, ico_image_path, icns_image_path ] - - for src_path in image_mappings: - if src_path: - dest_path = f"{project_name}/{src_path.name}" - if src_path and str(src_path) not in existing_sources and dest_path not in existing_dests: - normalized_items.append({str(src_path): dest_path}) - - # 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 - - # Write back the updated construct.yaml - construct_serialized = yaml.dump(construct_data, sort_keys=False) - construct_serialized = restore_yaml_duplicate_keys( - construct_serialized, "post_install", post_install_lines - ) - construct_serialized = restore_yaml_duplicate_keys( - construct_serialized, "pre_uninstall", pre_uninstall_lines - ) - construct_path.write_text(construct_serialized, encoding="utf-8") - def enqueue_pull_request(repo_url, personal_access_token, input_dict): github_owner, github_repo_name = repo_url.rstrip('/').split('/')[-2:] diff --git a/initializer.py b/initializer.py new file mode 100644 index 0000000..1261bff --- /dev/null +++ b/initializer.py @@ -0,0 +1,254 @@ +"""Initialise a repository created from the LabConstrictor template: replace the template's placeholders. + +Kept apart from app.py (no Streamlit import) so that tests/test_initializer.py can run it on the real template. +""" +from __future__ import annotations + +import shutil + +import yaml + + +def to_python_project_name(project_name: str) -> str: + return project_name.lower().replace(" ", "_").replace("-", "_").replace(".", "_") + + +def replace_in_file(file_path, old, new): + # newline="" keeps the file's own line endings (CRLF in the .bat files) on every OS. + with open(file_path, 'r', encoding='utf-8', newline='') as file: + content = file.read() + content = content.replace(old, str(new).strip()) + with open(file_path, 'w', encoding='utf-8', newline='') as file: + file.write(content) + + +def capture_yaml_key_lines(yaml_text: str, key: str): + """Return all lines whose trimmed content starts with ':'.""" + prefix = f"{key}:" + captured = [] + for line in yaml_text.splitlines(): + stripped = line.lstrip() + if stripped.startswith(prefix): + indent = line[: len(line) - len(stripped)] + captured.append(f"{indent}{stripped}") + return captured + + +def restore_yaml_duplicate_keys(serialized_text: str, key: str, preserved_lines): + """Replace the serialized ':' line with the preserved lines (i.e., duplicates).""" + if not preserved_lines: + return serialized_text + key_prefix = f"{key}:" + output_lines = [] + inserted = False + for line in serialized_text.splitlines(): + stripped = line.lstrip() + if stripped.startswith(key_prefix): + if not inserted: + output_lines.extend(preserved_lines) + inserted = True + continue + output_lines.append(line) + + if not inserted: + output_lines.extend(preserved_lines) + + if serialized_text.endswith("\n"): + return "\n".join(output_lines) + "\n" + return "\n".join(output_lines) + + +def placeholder_map(project_name, version, hide_code, welcome_image_path, header_image_path, + icon_image_path, github_owner, github_repo_name): + """The placeholders of the LabConstrictor template and, for each one, the files it is replaced in and its value. + + The keys are replaced in this order: UNDERSCORED_PROJECT_NAME must come before PROJECT_NAME, which it contains. + Every template file that the installer ships must be listed for each placeholder it holds: a placeholder left + in one of them breaks the installer (issue CellMigrationLab/LabConstrictor#40). tests/test_initializer.py + initialises the current template and fails when one is left. + """ + proyectname_lower = project_name.lower() + python_project_name = to_python_project_name(project_name) + return { + "LOWER_PROJ_NAME": { + "environment.yaml": proyectname_lower, + ".tools/templates/download_executable_template.md": proyectname_lower, + }, + "PYTHON_PROJ_NAME": { + "setup.py": python_project_name, + ".tools/docs/external_code_upload.md": python_project_name, + ".tools/templates/Welcome_template.ipynb": python_project_name, + # The import check and the _lc_tools module name of the installer (template 0.1.16 and later). + "app/bash_bat_scripts/post_install.sh": python_project_name, + "app/bash_bat_scripts/post_install.bat": python_project_name, + }, + "UNDERSCORED_PROJECT_NAME": { + "construct.yaml": project_name.replace(" ", "_"), + "app/bash_bat_scripts/pre_uninstall.bat": project_name.replace(" ", "_"), + "app/bash_bat_scripts/post_install.bat": project_name.replace(" ", "_"), + }, + "PROJECT_NAME": { + "construct.yaml": project_name, + "app/menuinst/notebook_launcher.json": project_name, + "app/bash_bat_scripts/post_install.bat": project_name, + "app/bash_bat_scripts/post_install.sh": project_name, + "app/bash_bat_scripts/pre_uninstall.bat": project_name, + "app/bash_bat_scripts/pre_uninstall.sh": project_name, + "app/bash_bat_scripts/uninstall.sh": project_name, + ".tools/templates/Welcome_template.ipynb": project_name, + ".tools/templates/download_executable_template.md": project_name, + ".tools/python/bump_constructor.py": project_name, + # PROJECT_DISPLAY_NAME of the JupyterLab launcher (its window titles and error messages). + "app/python_scripts/launch_jupyter.py": project_name, + }, + "VERSION_NUMBER": { + "construct.yaml": version, + "app/bash_bat_scripts/post_install.bat": version, + "setup.py": version, + }, + "WELCOME_IMAGE": { + "construct.yaml": welcome_image_path, + }, + "HEADER_IMAGE": { + "construct.yaml": header_image_path, + }, + "ICON_IMAGE": { + "construct.yaml": icon_image_path, + }, + "GITHUB_OWNER": { + "app/bash_bat_scripts/post_install.bat": github_owner, + ".tools/templates/download_executable_template.md": github_owner, + }, + "GITHUB_REPO_NAME": { + ".tools/templates/download_executable_template.md": github_repo_name, + }, + "HIDE_CODE_DISABLED": { + "app/python_scripts/hide_code_cells.py": hide_code, + } + } + + +def initialize_project(repo_path, project_name, version, hide_code, + welcome_image_path, header_image_path, icon_image_path, + ico_image_path, icns_image_path, + github_owner, github_repo_name): + + # Copy and replace template files into their final locations + template_to_location = { + ".tools/templates/hide_code_cells.py": "app/python_scripts/hide_code_cells.py" + } + + for template_path, final_path in template_to_location.items(): + shutil.copyfile(repo_path / template_path, repo_path / final_path) + + conversion_dict = placeholder_map( + project_name=project_name, + version=version, + hide_code=hide_code, + welcome_image_path=welcome_image_path, + header_image_path=header_image_path, + icon_image_path=icon_image_path, + github_owner=github_owner, + github_repo_name=github_repo_name, + ) + python_project_name = to_python_project_name(project_name) + + # Replace placeholders in files + for placeholder, files in conversion_dict.items(): + for file_path, replacement in files.items(): + replace_in_file(repo_path / file_path, placeholder, replacement) + + package_dir = repo_path / "src" / python_project_name + package_dir.mkdir(parents=True, exist_ok=True) + init_file = package_dir / "__init__.py" + if not init_file.exists(): + init_file.write_text("", encoding="utf-8") + + # Update the notebook launcher JSON file to set the icons if needed + notebook_launcher_path = repo_path / "app" / "menuinst" / "notebook_launcher.json" + if notebook_launcher_path.exists(): + with open(notebook_launcher_path, "r", encoding="utf-8") as f: + launcher_data = f.read() + if icon_image_path: + launcher_data = launcher_data.replace("ICON_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{icon_image_path.name}") + else: + launcher_data = launcher_data.replace("ICON_IMAGE_PATH", f"") + if ico_image_path: + launcher_data = launcher_data.replace("ICON_ICO_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{ico_image_path.name}") + else: + launcher_data = launcher_data.replace("ICON_ICO_IMAGE_PATH", f"") + if icns_image_path: + launcher_data = launcher_data.replace("ICON_ICNS_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{icns_image_path.name}") + else: + launcher_data = launcher_data.replace("ICON_ICNS_IMAGE_PATH", f"") + with open(notebook_launcher_path, "w", encoding="utf-8") as f: + f.write(launcher_data) + + # Update the construct.yaml extra_files to include the images if they were provided + # Read the construct.yaml to check if images need to be set + construct_path = repo_path / "construct.yaml" + construct_raw_text = construct_path.read_text(encoding="utf-8") + post_install_lines = capture_yaml_key_lines(construct_raw_text, "post_install") + pre_uninstall_lines = capture_yaml_key_lines(construct_raw_text, "pre_uninstall") + construct_data = yaml.safe_load(construct_raw_text) + if construct_data is None: + construct_data = {} + extra_files = construct_data.get("extra_files") + if extra_files is None: + extra_files = [] + construct_data["extra_files"] = extra_files + + + # Check if the welcome, header, icon images were provided and in case they were not, set them to empty in the construct.yaml + if not welcome_image_path: + construct_data.pop("welcome_image", None) + if not header_image_path: + construct_data.pop("header_image", None) + if not icon_image_path: + construct_data.pop("icon_image", None) + + # 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) + + # Check if the images paths are provided and not already in the list¨ + image_mappings = [ icon_image_path, ico_image_path, icns_image_path ] + + for src_path in image_mappings: + if src_path: + dest_path = f"{project_name}/{src_path.name}" + if src_path and str(src_path) not in existing_sources and dest_path not in existing_dests: + normalized_items.append({str(src_path): dest_path}) + + # 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 + + # Write back the updated construct.yaml + construct_serialized = yaml.dump(construct_data, sort_keys=False) + construct_serialized = restore_yaml_duplicate_keys( + construct_serialized, "post_install", post_install_lines + ) + construct_serialized = restore_yaml_duplicate_keys( + construct_serialized, "pre_uninstall", pre_uninstall_lines + ) + construct_path.write_text(construct_serialized, encoding="utf-8") diff --git a/tests/test_initializer.py b/tests/test_initializer.py new file mode 100644 index 0000000..bdd6336 --- /dev/null +++ b/tests/test_initializer.py @@ -0,0 +1,184 @@ +"""Tests for initializer: initialising the real LabConstrictor template leaves no placeholder behind (LabConstrictor#40). + +The template is read from LC_TEMPLATE_DIR when it is set (a checkout of CellMigrationLab/LabConstrictor), otherwise downloaded +from the template's main branch. The tests that need it are skipped when neither is available (offline), never failed. +""" + +from __future__ import annotations + +import io +import os +import re +import shutil +import sys +import tempfile +import unittest +import urllib.request +import zipfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import initializer # noqa: E402 + +TEMPLATE_ZIP = "https://github.com/CellMigrationLab/LabConstrictor/archive/refs/heads/main.zip" +PROJECT = "My Cool-App 2.0" +PACKAGE = "my_cool_app_2_0" + +# Placeholders that initialisation must replace (the keys of placeholder_map, plus the launcher icon paths it fills in itself). +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", +) +# Not shipped by the installer, or about placeholders rather than holding one. +SKIPPED_PREFIXES = (".git/", ".template_sync/", "tests/", ".tools/docs/") +# Placeholders the template fills in later, at release time, on purpose: (file, placeholder). +LATER = { + (".tools/templates/download_executable_template.md", "VERSION_NUMBER"), # bump_version.py + (".tools/templates/Welcome_template.ipynb", "GITHUB_OWNER"), # bump_Welcome_notebook.py + (".tools/templates/Welcome_template.ipynb", "GITHUB_REPO_NAME"), + (".tools/templates/hide_code_cells.py", "HIDE_CODE_DISABLED"), # the template copy; the app copy is filled in + (".tools/python/bump_version.py", "VERSION_NUMBER"), # the scripts that do the release-time replacing + (".tools/python/bump_Welcome_notebook.py", "GITHUB_OWNER"), + (".tools/python/bump_Welcome_notebook.py", "GITHUB_REPO_NAME"), +} + + +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[str]: + found = [] + for path in sorted(repo.rglob("*")): + rel = path.relative_to(repo).as_posix() + if not path.is_file() or rel.startswith(SKIPPED_PREFIXES): + continue + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + for name in INIT_PLACEHOLDERS: + if (rel, name) not in LATER and placeholder_pattern(name).search(text): + found.append(f"{rel}: {name}") + return found + + +def template_source() -> Path | None: + """The template folder: LC_TEMPLATE_DIR, or main downloaded once into a temporary folder (None when offline).""" + given = os.environ.get("LC_TEMPLATE_DIR") + if given: + return Path(given) + if getattr(template_source, "cache", None): + return template_source.cache # type: ignore[attr-defined] + try: + with urllib.request.urlopen(TEMPLATE_ZIP, timeout=60) as response: + data = response.read() + except OSError: + return None + target = Path(tempfile.mkdtemp(prefix="lc_template_")) + with zipfile.ZipFile(io.BytesIO(data)) as archive: + archive.extractall(target) + (root,) = [p for p in target.iterdir() if p.is_dir()] + template_source.cache = root # type: ignore[attr-defined] + return root + + +class PlaceholderMapTests(unittest.TestCase): + """Offline checks of the map itself.""" + + def setUp(self) -> None: + self.mapping = initializer.placeholder_map( + project_name=PROJECT, version="0.0.1", hide_code=False, welcome_image_path=None, header_image_path=None, + icon_image_path=None, github_owner="someone", github_repo_name="my-cool-app", + ) + + def test_the_post_install_scripts_get_the_package_name(self) -> None: + for script in ("app/bash_bat_scripts/post_install.sh", "app/bash_bat_scripts/post_install.bat"): + self.assertEqual(self.mapping["PYTHON_PROJ_NAME"][script], PACKAGE) + + def test_the_launcher_gets_the_display_name(self) -> None: + self.assertEqual(self.mapping["PROJECT_NAME"]["app/python_scripts/launch_jupyter.py"], PROJECT) + + def test_underscored_project_name_is_replaced_before_project_name(self) -> None: + keys = list(self.mapping) + self.assertLess(keys.index("UNDERSCORED_PROJECT_NAME"), keys.index("PROJECT_NAME")) + + +class RealTemplateTests(unittest.TestCase): + """Initialise the current template exactly as the web form does, then look for what was left.""" + + repo: Path + + @classmethod + def setUpClass(cls) -> None: + source = template_source() + if source is None: + raise unittest.SkipTest("the LabConstrictor template is not available offline: set LC_TEMPLATE_DIR") + cls._tmp = tempfile.TemporaryDirectory() + cls.repo = Path(cls._tmp.name) / "repo" + shutil.copytree(source, cls.repo, ignore=shutil.ignore_patterns(".git")) + initializer.initialize_project( + repo_path=cls.repo, project_name=PROJECT, version="0.0.1", hide_code=False, + welcome_image_path=None, header_image_path=None, icon_image_path=None, ico_image_path=None, icns_image_path=None, + github_owner="someone", github_repo_name="my-cool-app", + ) + + @classmethod + def tearDownClass(cls) -> None: + cls._tmp.cleanup() + + def test_no_placeholder_is_left(self) -> None: + self.assertEqual(leftover_placeholders(self.repo), [], "add these files to placeholder_map in initializer.py") + + def test_the_installer_imports_the_package_that_src_holds(self) -> None: + self.assertTrue((self.repo / "src" / PACKAGE / "__init__.py").is_file()) + sh = (self.repo / "app/bash_bat_scripts/post_install.sh").read_text(encoding="utf-8") + bat = (self.repo / "app/bash_bat_scripts/post_install.bat").read_text(encoding="utf-8") + for text in (sh, bat): + self.assertIn(f"import {PACKAGE};", text) + self.assertIn(f"{PACKAGE}_lc_tools", text) + self.assertRegex((self.repo / "setup.py").read_text(encoding="utf-8"), rf"name\s*=\s*[\"']{PACKAGE}[\"']") + + def test_the_launcher_names_the_app(self) -> None: + text = (self.repo / "app/python_scripts/launch_jupyter.py").read_text(encoding="utf-8") + self.assertIn(f'PROJECT_DISPLAY_NAME = "{PROJECT}"', text) + + def test_the_bat_files_keep_their_line_endings(self) -> None: + source = template_source() + assert source is not None + for rel in ("app/bash_bat_scripts/post_install.bat", "app/bash_bat_scripts/pre_uninstall.bat"): + before = (source / rel).read_bytes() + after = (self.repo / rel).read_bytes() + self.assertEqual(b"\r\n" in before, b"\r\n" in after, rel) + + +class LeftoverDetectionTests(unittest.TestCase): + """The detector itself: what it reports and what it leaves alone.""" + + def test_it_reports_a_placeholder_and_its_lc_tools_form_but_not_longer_names(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + repo = Path(tmp) + (repo / "app").mkdir() + (repo / "app/a.sh").write_text('M="PYTHON_PROJ_NAME_lc_tools"\n', encoding="utf-8") + (repo / "app/b.bat").write_text("SET X=UNDERSCORED_PROJECT_NAME\n", encoding="utf-8") + (repo / "app/c.txt").write_text("PROJECT_ROOT and MY_PROJECT_NAME_X are fine\n", encoding="utf-8") + (repo / ".tools/docs").mkdir(parents=True) + (repo / ".tools/docs/x.md").write_text("PYTHON_PROJ_NAME is explained here\n", encoding="utf-8") + self.assertEqual(leftover_placeholders(repo), ["app/a.sh: PYTHON_PROJ_NAME", "app/b.bat: UNDERSCORED_PROJECT_NAME"]) + + +if __name__ == "__main__": + unittest.main()