diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml index 38c99dc..0c5dabe 100644 --- a/.template_sync/manifest.yaml +++ b/.template_sync/manifest.yaml @@ -1,4 +1,4 @@ -template_version: 0.1.44 +template_version: 0.1.45 migrations: - from: 0.0.0 to: 0.0.1 @@ -138,3 +138,6 @@ migrations: - from: 0.1.43 to: 0.1.44 script: migrations/v0_1_43_to_v0_1_44.py + - from: 0.1.44 + to: 0.1.45 + script: migrations/v0_1_44_to_v0_1_45.py diff --git a/.template_sync/migrations/v0_1_44_to_v0_1_45.py b/.template_sync/migrations/v0_1_44_to_v0_1_45.py new file mode 100644 index 0000000..a7d1a06 --- /dev/null +++ b/.template_sync/migrations/v0_1_44_to_v0_1_45.py @@ -0,0 +1,158 @@ +"""Template 0.1.44 -> 0.1.45: one entry per app in Windows "Installed apps", which the uninstaller removes. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_45.md + +post_install.bat wrote its own "Installed apps" entry (key ) next to the one constructor writes for the installer (key and name +" (Python 3.x 64-bit)"), both pointing to the same Uninstall-.exe. The uninstaller removes only the first entry whose +uninstaller is its own, and Windows lists the shorter key first: after an uninstall the "(Python ...)" entry stayed, and removing it failed +because its uninstaller was gone. Now post_install.bat writes no entry, and the release names constructor's one entry after the app +(uninstall_name) with the repository owner as publisher (company), as the removed block did; the version and the icon come from the installer. + +What this changes in an app repository (each step is independent, idempotent, never deletes a file and never raises for a customised file): + +1. .tools/python/bump_constructor.py is replaced by the 0.1.45 file when it is still the template file last shipped (the 0.1.44 copy; + compared with LF line endings; the file keeps its own line endings). A changed file stays as it is (SKIPPED, with what to do by hand). +2. The Windows Apps-list block of app/bash_bat_scripts/post_install.bat (the template's lines, with the app's names) is replaced by three + REM lines. A block changed by hand stays as it is (SKIPPED, with what to do by hand). + +construct.yaml is not changed here: bump_constructor.py writes uninstall_name and company at the next release. Both changes reach users with +the app's next release; an app installed before it keeps two entries until it is uninstalled (the design note says how to remove the stale one). +""" +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_45.md" +TAG = "[migration 0.1.45]" +RESOURCE_ROOT = Path(__file__).resolve().parents[1] / "resources" / "v0_1_44_to_v0_1_45" +PREVIOUS_ROOT = RESOURCE_ROOT / "previous" + +BUMP = Path(".tools/python/bump_constructor.py") +POST_INSTALL_BAT = Path("app/bash_bat_scripts/post_install.bat") +FILES = (BUMP,) + +BUMP_BY_HAND = ( + "after save_construct_surgical, write the top-level lines uninstall_name: and company: in " + "construct.yaml, as set_windows_apps_entry of the template's script does" +) +BAT_BY_HAND = ( + "delete the block that starts with SET \"ARP_KEY=...\" and ends with the reg add ... /v NoRepair line (constructor writes the " + "installer's own entry)" +) + +# The 0.1.33-0.1.44 template block; the placeholders the initialisation fills in match the app's values (one line each, no quotes). +OLD_ARP_TEMPLATE = ( + 'SET "ARP_KEY=HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNDERSCORED_PROJECT_NAME"', + 'SET "UNINSTALL_EXE=%PREFIX%\\Uninstall-UNDERSCORED_PROJECT_NAME.exe"', + "REM Windows Apps list: the version of this installer (the version: line of the bundled construct.yaml, written by each release),", + "REM and the app icon the installer copied (the first .ico in the app folder); no icon entry when there is none.", + 'SET "DISPLAY_VERSION=VERSION_NUMBER"', + 'IF EXIST "%PROJECT_ROOT%\\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\\construct.yaml"`) DO SET "DISPLAY_VERSION=%%~B"', + 'SET "DISPLAY_ICON="', + 'FOR %%I IN ("%PROJECT_ROOT%\\*.ico") DO IF NOT DEFINED DISPLAY_ICON SET "DISPLAY_ICON=%%~fI"', + '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', + 'IF DEFINED DISPLAY_ICON 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', +) +NEW_ARP_LINES = ( + 'REM Windows "Installed apps": the installer\'s own entry, which constructor writes after this script (uninstall_name, company and version of', + "REM construct.yaml; the release sets the first two, see bump_constructor.py) and its uninstaller removes. This script writes no entry: a second", + 'REM one pointing to the same uninstaller was left behind by it, as " (Python 3.x 64-bit)" with an uninstaller that was gone.', +) +PLACEHOLDERS = ("UNDERSCORED_PROJECT_NAME", "PROJECT_NAME", "VERSION_NUMBER", "GITHUB_OWNER") + + +def old_arp_pattern() -> re.Pattern[str]: + """The old block with each placeholder as 'any text on the line without a quote', and LF or CRLF between the lines.""" + lines = [] + for line in OLD_ARP_TEMPLATE: + escaped = re.escape(line) + for name in PLACEHOLDERS: + escaped = escaped.replace(name, '[^"\\r\\n]*') + lines.append(escaped) + return re.compile("^" + r"\r?\n".join(lines) + r"(?=\r?\n|\Z)", re.MULTILINE) + + +OLD_ARP = old_arp_pattern() + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def lf_text(path: Path) -> str: + return path.read_bytes().decode("utf-8").replace("\r\n", "\n") + + +def app_name_in(template_lf: str, text_lf: str) -> str | None: + """The app name the initialisation put in place of every PROJECT_NAME of `template_lf` when `text_lf` is that file, else None.""" + pieces = template_lf.split("PROJECT_NAME") + if len(pieces) == 1: + return "" if text_lf == template_lf else None + if not text_lf.startswith(pieces[0]): + return None + rest = text_lf[len(pieces[0]) :] + end = rest.find(pieces[1]) + name = rest[:end] if end >= 0 else None + if name is None or "\n" in name or '"' in name: + return None + return name if template_lf.replace("PROJECT_NAME", name) == text_lf else None + + +def replace_bump(path: Path) -> str: + data = path.read_bytes().decode("utf-8") + newline = "\r\n" if "\r\n" in data else "\n" + text = data.replace("\r\n", "\n") + template_new = lf_text(RESOURCE_ROOT / BUMP) + if app_name_in(template_new, text) is not None: + return "unchanged: already up to date" + name = app_name_in(lf_text(PREVIOUS_ROOT / BUMP), text) + if name is None: + return f"SKIPPED: customised (not the 0.1.44 template file), so it was left unchanged. By hand: {BUMP_BY_HAND}. See {DOCS_URL}" + new = template_new.replace("PROJECT_NAME", name) if name else template_new + path.write_bytes(new.replace("\n", newline).encode("utf-8")) + return "updated: replaced by the 0.1.45 file (the release names the Windows Installed apps entry)" + + +def remove_apps_entry(path: Path) -> str: + text = path.read_bytes().decode("utf-8") + if NEW_ARP_LINES[0] in text: + return "unchanged: already writes no Installed apps entry of its own" + matches = list(OLD_ARP.finditer(text)) + if len(matches) != 1: + return f"SKIPPED: no template Apps-list block (changed by hand), so it was left unchanged. By hand: {BAT_BY_HAND}. See {DOCS_URL}" + newline = "\r\n" if "\r\n" in text else "\n" + match = matches[0] + path.write_bytes((text[: match.start()] + newline.join(NEW_ARP_LINES) + text[match.end() :]).encode("utf-8")) + return "updated: writes no Installed apps entry of its own (the installer's entry is the only one, and the uninstaller removes it)" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Apply the 0.1.45 changes (idempotent, never raises for a customised file, creates and deletes nothing).""" + _ = context + changed = 0 + for relative, step in ((BUMP, replace_bump), (POST_INSTALL_BAT, remove_apps_entry)): + path = repo_root / relative + if not path.is_file(): + log(f"{relative}: not present in this repository (nothing was created)") + continue + try: + status = step(path) + except (OSError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + changed += status.startswith("updated") + log(f"{relative}: {status}") + if changed: + log(f"done: {changed} change(s). They reach users with the next release of the app. See {DOCS_URL}") + else: + log("done: no repository changes were required.") diff --git a/.template_sync/resources/v0_1_44_to_v0_1_45/.tools/python/bump_constructor.py b/.template_sync/resources/v0_1_44_to_v0_1_45/.tools/python/bump_constructor.py new file mode 100644 index 0000000..e28a55b --- /dev/null +++ b/.template_sync/resources/v0_1_44_to_v0_1_45/.tools/python/bump_constructor.py @@ -0,0 +1,374 @@ +import json +import os +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 "PROJECT_NAME" + +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 + + +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 = "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 + 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 set_top_level_key(text: str, key: str, value: str) -> str: + """`text` with the top-level line `key: value` (JSON quoting is valid YAML): the existing line is replaced, or the line is added before + extra_files: (at the end when there is none).""" + line = f"{key}: {json.dumps(value, ensure_ascii=False)}" + pattern = re.compile(rf"^{re.escape(key)}:.*$", re.MULTILINE) + if pattern.search(text): + return pattern.sub(lambda _: line, text, count=1) + match = re.search(r"^extra_files:", text, re.MULTILINE) + if match: + return text[: match.start()] + line + "\n" + text[match.start() :] + return text.rstrip("\n") + "\n" + line + "\n" + + +def set_windows_apps_entry(text: str, project_folder: str, owner: str | None) -> str: + """Name the installer's one entry in Windows "Installed apps" (constructor writes it, and its uninstaller removes it). + + uninstall_name is the app's name (constructor's default adds "(Python 3.x 64-bit)"), and company, shown as the publisher, is the + repository owner (GITHUB_REPOSITORY_OWNER of the release workflow). Without a project folder or an owner, that line is left as it is. + """ + if project_folder and project_folder != "PROJECT" + "_NAME": # split: the initialisation fills in every whole placeholder of this file + text = set_top_level_key(text, "uninstall_name", project_folder) + debug(f"Windows Installed apps entry: {project_folder}") + if owner: + text = set_top_level_key(text, "company", owner) + debug(f"Windows Installed apps publisher: {owner}") + return text + + +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) + text = construct_path.read_text(encoding="utf-8") + named = set_windows_apps_entry(text, extract_project_folder(data.get("extra_files", [])), os.environ.get("GITHUB_REPOSITORY_OWNER")) + if named != text: + construct_path.write_text(named, encoding="utf-8") + print(f"Added {ntbk_added} notebook(s) and {src_added} source file(s) to extra_files.") + +if __name__ == "__main__": + main() diff --git a/.template_sync/resources/v0_1_44_to_v0_1_45/previous/.tools/python/bump_constructor.py b/.template_sync/resources/v0_1_44_to_v0_1_45/previous/.tools/python/bump_constructor.py new file mode 100644 index 0000000..dcbbbb5 --- /dev/null +++ b/.template_sync/resources/v0_1_44_to_v0_1_45/previous/.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 "PROJECT_NAME" + +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 + + +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 = "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 + 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/docs/migration_0_1_45.md b/.tools/docs/migration_0_1_45.md new file mode 100644 index 0000000..629c2bb --- /dev/null +++ b/.tools/docs/migration_0_1_45.md @@ -0,0 +1,43 @@ +# Template 0.1.45: one entry per app in Windows "Installed apps" + +Design note for the 0.1.45 migration (`.template_sync/migrations/v0_1_44_to_v0_1_45.py`). + +## Why + +On Windows, an installed app had two entries in *Settings > Apps > Installed apps*: the one `post_install.bat` wrote (key ``, shown as +the app's name) and the one constructor writes for every installer (key and name ` (Python 3.x 64-bit)`). Both pointed to +the same `Uninstall-.exe`. The uninstaller removes only the first entry whose uninstaller is its own, and Windows lists the shorter key +first, so after an uninstall the "(Python ...)" entry stayed. Removing it failed: its uninstaller was gone. Testers of LabConstrictor-CAREamics +0.0.5 found it on two Windows 11 computers. + +Constructor writes its entry after `post_install` runs, so `post_install` cannot change it. The fix is one entry, the installer's own: + +* `post_install.bat` writes no entry any more. +* At each release, `.tools/python/bump_constructor.py` writes two lines in `construct.yaml`: `uninstall_name: ""` (the entry's name; constructor's + default adds the version and "(Python 3.x 64-bit)") and `company: ""` (shown as the publisher; `GITHUB_REPOSITORY_OWNER` of the + release workflow), as the removed block did. The version comes from `construct.yaml` and the icon from the installer, as before. + An installer built outside the release workflow has constructor's default name and publisher. + +## What changes in an app repository + +* `.tools/python/bump_constructor.py` is replaced by the 0.1.45 file when it is still the template file last shipped (with the app's name in + place of `PROJECT_NAME`). A file you changed is left as it is, and the sync log says what to do by hand. +* In `app/bash_bat_scripts/post_install.bat`, the Windows Apps-list block (from `SET "ARP_KEY=...` to the `reg add ... /v NoRepair` line) is + replaced by three `REM` lines. A block you changed is left as it is, and the sync log says what to do by hand. + +`construct.yaml` changes at the next release. Both changes reach users with the app's next release. + +## An app installed before + +Its uninstaller is the old one. After uninstalling it, a stale " (Python 3.x 64-bit)" entry may stay. To remove it, run in +PowerShell (it lists the entries of the app first; replace `` with the app's name): + +``` +Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall | Where-Object { $_.GetValue('DisplayName') -like '**' } | Select-Object PSChildName, @{n='Uninstaller';e={$_.GetValue('UninstallString')}} +``` + +then, for an entry whose uninstaller file no longer exists: + +``` +Remove-Item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\" +``` diff --git a/.tools/python/bump_constructor.py b/.tools/python/bump_constructor.py index dcbbbb5..e28a55b 100644 --- a/.tools/python/bump_constructor.py +++ b/.tools/python/bump_constructor.py @@ -1,3 +1,5 @@ +import json +import os import sys from pathlib import Path import yaml @@ -311,6 +313,34 @@ def sort_key(item): return ntbk_added, src_added +def set_top_level_key(text: str, key: str, value: str) -> str: + """`text` with the top-level line `key: value` (JSON quoting is valid YAML): the existing line is replaced, or the line is added before + extra_files: (at the end when there is none).""" + line = f"{key}: {json.dumps(value, ensure_ascii=False)}" + pattern = re.compile(rf"^{re.escape(key)}:.*$", re.MULTILINE) + if pattern.search(text): + return pattern.sub(lambda _: line, text, count=1) + match = re.search(r"^extra_files:", text, re.MULTILINE) + if match: + return text[: match.start()] + line + "\n" + text[match.start() :] + return text.rstrip("\n") + "\n" + line + "\n" + + +def set_windows_apps_entry(text: str, project_folder: str, owner: str | None) -> str: + """Name the installer's one entry in Windows "Installed apps" (constructor writes it, and its uninstaller removes it). + + uninstall_name is the app's name (constructor's default adds "(Python 3.x 64-bit)"), and company, shown as the publisher, is the + repository owner (GITHUB_REPOSITORY_OWNER of the release workflow). Without a project folder or an owner, that line is left as it is. + """ + if project_folder and project_folder != "PROJECT" + "_NAME": # split: the initialisation fills in every whole placeholder of this file + text = set_top_level_key(text, "uninstall_name", project_folder) + debug(f"Windows Installed apps entry: {project_folder}") + if owner: + text = set_top_level_key(text, "company", owner) + debug(f"Windows Installed apps publisher: {owner}") + return text + + def main(): construct_path = Path("construct.yaml") if len(sys.argv) < 2 else Path(sys.argv[1]) notebooks_root = Path("notebooks").resolve() @@ -334,6 +364,10 @@ def main(): # Write using surgical update to preserve platform-specific scripts save_construct_surgical(construct_path, data, original_text) + text = construct_path.read_text(encoding="utf-8") + named = set_windows_apps_entry(text, extract_project_folder(data.get("extra_files", [])), os.environ.get("GITHUB_REPOSITORY_OWNER")) + if named != text: + construct_path.write_text(named, encoding="utf-8") print(f"Added {ntbk_added} notebook(s) and {src_added} source file(s) to extra_files.") if __name__ == "__main__": diff --git a/app/bash_bat_scripts/post_install.bat b/app/bash_bat_scripts/post_install.bat index 4a90081..bb83847 100644 --- a/app/bash_bat_scripts/post_install.bat +++ b/app/bash_bat_scripts/post_install.bat @@ -182,25 +182,9 @@ IF ERRORLEVEL 1 ( GOTO :fail ) -SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" -SET "UNINSTALL_EXE=%PREFIX%\Uninstall-UNDERSCORED_PROJECT_NAME.exe" -REM Windows Apps list: the version of this installer (the version: line of the bundled construct.yaml, written by each release), -REM and the app icon the installer copied (the first .ico in the app folder); no icon entry when there is none. -SET "DISPLAY_VERSION=VERSION_NUMBER" -IF EXIST "%PROJECT_ROOT%\construct.yaml" FOR /F "usebackq tokens=1,* delims=: " %%A IN (`findstr /B /C:"version:" "%PROJECT_ROOT%\construct.yaml"`) DO SET "DISPLAY_VERSION=%%~B" -SET "DISPLAY_ICON=" -FOR %%I IN ("%PROJECT_ROOT%\*.ico") DO IF NOT DEFINED DISPLAY_ICON SET "DISPLAY_ICON=%%~fI" -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 -IF DEFINED DISPLAY_ICON 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 +REM Windows "Installed apps": the installer's own entry, which constructor writes after this script (uninstall_name, company and version of +REM construct.yaml; the release sets the first two, see bump_constructor.py) and its uninstaller removes. This script writes no entry: a second +REM one pointing to the same uninstaller was left behind by it, as " (Python 3.x 64-bit)" with an uninstaller that was gone. echo Post-install completed successfully. >> "%LOG_FILE%" echo Post-install completed successfully. diff --git a/tests/_v0_1_44.py b/tests/_v0_1_44.py index 192cbaf..438daa2 100644 --- a/tests/_v0_1_44.py +++ b/tests/_v0_1_44.py @@ -10,6 +10,8 @@ from pathlib import Path from types import ModuleType +from _v0_1_45 import before_0_1_45 + ROOT = Path(__file__).resolve().parents[1] MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_43_to_v0_1_44.py" @@ -25,6 +27,7 @@ def _migration() -> ModuleType: def before_0_1_44(relative: Path | str, data: bytes) -> bytes: """`data` (a live template file at `relative`) without the 0.1.44 change; any other file is returned as it is.""" + data = before_0_1_45(relative, data) migration = _migration() relative = Path(relative) if relative not in migration.FILES: diff --git a/tests/_v0_1_45.py b/tests/_v0_1_45.py new file mode 100644 index 0000000..85a3132 --- /dev/null +++ b/tests/_v0_1_45.py @@ -0,0 +1,41 @@ +"""Helper of the tests: a live template file as it was before template 0.1.45. + +Template 0.1.45 replaces bump_constructor.py whole (FILES of the migration) and removes the Windows Apps-list block of post_install.bat. The tests +of the older migrations compare with the live files; `before_0_1_45` gives the bytes of a live file without the 0.1.45 change, so they keep +checking what they checked. The 0.1.45 change is tested in test_template_sync_0_1_45.py. +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parents[1] +MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_44_to_v0_1_45.py" + + +def _migration() -> ModuleType: + spec = importlib.util.spec_from_file_location("migration_0_1_45_for_older_tests", MIGRATION_PATH) + if spec is None or spec.loader is None: + raise RuntimeError(f"Unable to load {MIGRATION_PATH}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def before_0_1_45(relative: Path | str, data: bytes) -> bytes: + """`data` (a live template file at `relative`) without the 0.1.45 change; any other file is returned as it is.""" + migration = _migration() + relative = Path(relative) + text = data.decode("utf-8") + newline = "\r\n" if "\r\n" in text else "\n" + if relative in migration.FILES: + if text.replace("\r\n", "\n") != (migration.RESOURCE_ROOT / relative).read_bytes().decode("utf-8").replace("\r\n", "\n"): + return data + previous = (migration.PREVIOUS_ROOT / relative).read_bytes().decode("utf-8").replace("\r\n", "\n") + return previous.replace("\n", newline).encode("utf-8") + if relative == migration.POST_INSTALL_BAT: + new_block = newline.join(migration.NEW_ARP_LINES) + if new_block in text: + return text.replace(new_block, newline.join(migration.OLD_ARP_TEMPLATE)).encode("utf-8") + return data diff --git a/tests/smoke/post_install_hosts.py b/tests/smoke/post_install_hosts.py index 83ae60d..ea39a90 100644 --- a/tests/smoke/post_install_hosts.py +++ b/tests/smoke/post_install_hosts.py @@ -34,7 +34,7 @@ ("UNDERSCORED_PROJECT_NAME", "Demo_App"), ("PYTHON_PROJ_NAME", "demoapp"), ("PROJECT_NAME", APP), - ("VERSION_NUMBER", "0.0.1"), # the initialisation value; construct.yaml says 1.2.3 (the Apps list must show 1.2.3) + ("VERSION_NUMBER", "0.0.1"), # the initialisation value; construct.yaml says 1.2.3 ("GITHUB_OWNER", "CellMigrationLab"), ) SETUP_PY = 'from setuptools import find_packages, setup\nsetup(name="demoapp", version="1.2.3", package_dir={"": "src"}, packages=find_packages("src"))\n' @@ -157,19 +157,30 @@ def check_undeclared(name: str, entry: dict[str, object], log: str) -> None: def check_apps_list(prefix: Path) -> None: - """Windows: the Apps-list entry has the version of construct.yaml (1.2.3, not the initialisation value) and the copied .ico.""" - key = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\Demo_App" - found: dict[str, str] = {} - for value in ("DisplayVersion", "DisplayIcon"): - out = subprocess.run(["reg", "query", key, "/v", value], capture_output=True, text=True, check=False).stdout - line = next((row for row in out.splitlines() if row.strip().startswith(value)), "") - found[value] = line.split("REG_SZ", 1)[1].strip() if "REG_SZ" in line else "" - subprocess.run(["reg", "delete", key, "/f"], capture_output=True, check=False) - if found["DisplayVersion"] != "1.2.3": - raise AssertionError(f"Apps list: DisplayVersion {found['DisplayVersion']!r}, expected the construct.yaml version 1.2.3") - if Path(found["DisplayIcon"]) != prefix / APP / "demo_app.ico": - raise AssertionError(f"Apps list: DisplayIcon {found['DisplayIcon']!r}, expected {prefix / APP / 'demo_app.ico'}") - print(f"OK Windows Apps list: version 1.2.3, icon {found['DisplayIcon']}", flush=True) + """Windows: post_install writes no "Installed apps" entry of its own (template 0.1.45). The installer's own entry, written by constructor, + is the only one; a second one pointing to the same uninstaller was left behind by the uninstaller.""" + if sys.platform != "win32": # also tells mypy that winreg is used on Windows only + return + import winreg + + root = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" + stray = [] + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, root) as uninstall: + for index in range(winreg.QueryInfoKey(uninstall)[0]): + name = winreg.EnumKey(uninstall, index) + with winreg.OpenKey(uninstall, name) as key: + try: + command = str(winreg.QueryValueEx(key, "UninstallString")[0]) + except OSError: + continue + if name == "Demo_App" or str(prefix).lower() in command.lower(): + stray.append(f"{name}: {command}") + except FileNotFoundError: + pass + if stray: + raise AssertionError(f"post_install wrote an Installed apps entry of its own: {stray}") + print("OK Windows Installed apps: post_install wrote no entry of its own (the installer's entry is the only one)", flush=True) def install_case(script: Path, prefix: Path, lc_home: Path) -> tuple[dict[str, object], str]: diff --git a/tests/test_template_sync_0_1_35.py b/tests/test_template_sync_0_1_35.py index d95a0e8..5cc3fdb 100644 --- a/tests/test_template_sync_0_1_35.py +++ b/tests/test_template_sync_0_1_35.py @@ -103,9 +103,10 @@ def test_install_says_how_to_uninstall_on_each_system(self) -> None: def test_the_names_in_the_uninstall_steps_are_those_the_installer_creates(self) -> None: construct = lf(ROOT / "construct.yaml") self.assertIn("app/bash_bat_scripts/uninstall.sh: uninstall.sh", construct, "uninstall.sh is shipped in the install folder") - bat = lf(ROOT / "app/bash_bat_scripts/post_install.bat") - self.assertIn('SET "UNINSTALL_EXE=%PREFIX%\\Uninstall-UNDERSCORED_PROJECT_NAME.exe"', bat) - self.assertIn("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\", bat, "the app is in the Installed apps list") + # constructor names the uninstaller Uninstall-.exe and lists the installer in Installed apps (template 0.1.45: one entry, named by + # the uninstall_name line that bump_constructor.py writes at each release) + self.assertIn("name: UNDERSCORED_PROJECT_NAME", construct, "the uninstaller is Uninstall-.exe") + self.assertIn('set_top_level_key(text, "uninstall_name"', lf(ROOT / ".tools/python/bump_constructor.py"), "the app is in the Installed apps list") def test_no_user_page_links_to_the_download_stub_for_uninstalling_or_to_authoring_on_github(self) -> None: for path in user_pages(): diff --git a/tests/test_template_sync_0_1_43.py b/tests/test_template_sync_0_1_43.py index a33b537..bd8dd98 100644 --- a/tests/test_template_sync_0_1_43.py +++ b/tests/test_template_sync_0_1_43.py @@ -55,10 +55,12 @@ def test_the_manifest_lists_the_migration_and_the_version(self) -> None: def test_the_older_tests_see_the_0_1_42_pin(self) -> None: from _v0_1_43 import before_0_1_43 + from _v0_1_44 import before_0_1_44 for relative in (SH, BAT): with self.subTest(file=str(relative)): - self.assertEqual(before_0_1_43(relative, live(relative)), live(relative).replace(NEW.encode(), OLD.encode())) + expected = before_0_1_44(relative, live(relative)).replace(NEW.encode(), OLD.encode()) # without the later changes, 0.1.45 included + self.assertEqual(before_0_1_43(relative, live(relative)), expected) self.assertEqual(before_0_1_43("construct.yaml", NEW.encode()), NEW.encode()) diff --git a/tests/test_template_sync_0_1_45.py b/tests/test_template_sync_0_1_45.py new file mode 100644 index 0000000..9573ada --- /dev/null +++ b/tests/test_template_sync_0_1_45.py @@ -0,0 +1,168 @@ +"""Tests of the 0.1.45 migration: one entry per app in Windows "Installed apps" (post_install.bat writes none; the release names the installer's).""" +from __future__ import annotations + +import importlib.util +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +from types import ModuleType + +import yaml + +ROOT = Path(__file__).resolve().parents[1] +MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_44_to_v0_1_45.py" +APP = "Cool App" +FILLED = (("UNDERSCORED_PROJECT_NAME", "Cool_App"), ("PROJECT_NAME", APP), ("VERSION_NUMBER", "0.0.1"), ("GITHUB_OWNER", "SomeLab")) + + +def load(path: Path, name: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +MIGRATION = load(MIGRATION_PATH, "migration_0_1_45") +BUMP_MODULE = load(ROOT / ".tools/python/bump_constructor.py", "bump_constructor_0_1_45") +BUMP, BAT = MIGRATION.BUMP, MIGRATION.POST_INSTALL_BAT + + +def live(relative: Path) -> bytes: + return (ROOT / relative).read_bytes() + + +def filled(data: bytes) -> bytes: + """A template file as the initialisation leaves it in an app (placeholders filled in, longest first).""" + text = data.decode("utf-8") + for name, value in FILLED: + text = text.replace(name, value) + return text.encode("utf-8") + + +class TemplateTests(unittest.TestCase): + def test_post_install_writes_no_installed_apps_entry(self) -> None: + text = live(BAT).decode("utf-8") + self.assertNotIn("ARP_KEY", text) + self.assertNotIn("CurrentVersion\\Uninstall", text) + self.assertIn("\r\n".join(MIGRATION.NEW_ARP_LINES), text) + self.assertIn("\r\n", text, "post_install.bat stays CRLF") + + def test_the_resource_is_the_live_file_and_the_previous_one_is_the_0_1_44_file(self) -> None: + self.assertEqual(live(BUMP), (MIGRATION.RESOURCE_ROOT / BUMP).read_bytes()) + from _v0_1_45 import before_0_1_45 + + self.assertEqual(before_0_1_45(BUMP, live(BUMP)), (MIGRATION.PREVIOUS_ROOT / BUMP).read_bytes()) + self.assertNotIn(b"uninstall_name", (MIGRATION.PREVIOUS_ROOT / BUMP).read_bytes()) + restored = before_0_1_45(BAT, live(BAT)).decode("utf-8") + self.assertTrue(MIGRATION.OLD_ARP.search(restored), "the older tests see the 0.1.44 block") + + def test_the_manifest_lists_the_migration_and_the_version(self) -> None: + text = (ROOT / ".template_sync/manifest.yaml").read_text(encoding="utf-8") + self.assertRegex(text, r"template_version: 0\.1\.(4[5-9]|[5-9][0-9])\b") + self.assertIn("script: migrations/v0_1_44_to_v0_1_45.py", text) + self.assertTrue((ROOT / ".tools/docs/migration_0_1_45.md").is_file()) + self.assertIn(".tools/docs/migration_0_1_45.md", MIGRATION_PATH.read_text(encoding="utf-8")) + + +class ReleaseNamesTheEntryTests(unittest.TestCase): + """bump_constructor.py writes uninstall_name and company in construct.yaml (valid YAML, replaced on the next release, not duplicated).""" + + CONSTRUCT = "name: Cool_App\nversion: 1.2.3\nregister_python: false\nextra_files:\n- app/menuinst/Welcome.ipynb: Cool App/notebooks/Welcome.ipynb\n" + + def test_both_lines_are_added_before_extra_files_and_read_as_yaml(self) -> None: + text = BUMP_MODULE.set_windows_apps_entry(self.CONSTRUCT, APP, "Some Lab") + data = yaml.safe_load(text) + self.assertEqual((data["uninstall_name"], data["company"]), (APP, "Some Lab")) + self.assertLess(text.index("uninstall_name:"), text.index("extra_files:")) + again = BUMP_MODULE.set_windows_apps_entry(text, "Other", "Lab: two") + self.assertEqual(again.count("uninstall_name:"), 1) + self.assertEqual(yaml.safe_load(again)["company"], "Lab: two") + + def test_without_an_owner_or_a_name_nothing_is_written(self) -> None: + self.assertEqual(BUMP_MODULE.set_windows_apps_entry(self.CONSTRUCT, "PROJECT" + "_NAME", None), self.CONSTRUCT) + self.assertNotIn("company", BUMP_MODULE.set_windows_apps_entry(self.CONSTRUCT, APP, "")) + + def test_the_script_names_the_entry_in_a_repository(self) -> None: + repo = Path(tempfile.mkdtemp(prefix="lc_0_1_45_bump_")) + self.addCleanup(shutil.rmtree, repo, True) + (repo / "construct.yaml").write_text(self.CONSTRUCT, encoding="utf-8") + (repo / "requirements.txt").write_text("", encoding="utf-8") + script = repo / "bump_constructor.py" + script.write_bytes(filled(live(BUMP))) + env = dict(os.environ, GITHUB_REPOSITORY_OWNER="SomeLab") + result = subprocess.run([sys.executable, str(script)], cwd=repo, env=env, capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + data = yaml.safe_load((repo / "construct.yaml").read_text(encoding="utf-8")) + self.assertEqual((data["uninstall_name"], data["company"]), (APP, "SomeLab")) + + +class MigrationTests(unittest.TestCase): + def setUp(self) -> None: + self.repo = Path(tempfile.mkdtemp(prefix="lc_0_1_45_")) + from _v0_1_45 import before_0_1_45 + + for relative in (BUMP, BAT): + target = self.repo / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(filled(before_0_1_45(relative, live(relative)))) + + def tearDown(self) -> None: + shutil.rmtree(self.repo, ignore_errors=True) + + def run_migration(self) -> str: + out = StringIO() + with redirect_stdout(out): + MIGRATION.migrate(self.repo, {}) + return out.getvalue() + + def test_an_app_of_0_1_44_gets_the_template_files_and_a_second_run_changes_nothing(self) -> None: + log = self.run_migration() + for relative in (BUMP, BAT): + with self.subTest(file=str(relative)): + self.assertEqual((self.repo / relative).read_bytes(), filled(live(relative))) + self.assertIn("2 change(s)", log) + self.assertIn("no repository changes were required", self.run_migration()) + + def test_lf_line_endings_are_kept(self) -> None: + bat = self.repo / BAT + bat.write_bytes(bat.read_bytes().replace(b"\r\n", b"\n")) + self.run_migration() + self.assertEqual(bat.read_bytes(), filled(live(BAT)).replace(b"\r\n", b"\n")) + + def test_changed_files_are_left_alone_with_what_to_do(self) -> None: + bump, bat = self.repo / BUMP, self.repo / BAT + bump.write_bytes(bump.read_bytes() + b"# mine\n") + bat.write_bytes(bat.read_bytes().replace(b"/v Publisher", b"/v Vendor")) + before = (bump.read_bytes(), bat.read_bytes()) + log = self.run_migration() + self.assertEqual((bump.read_bytes(), bat.read_bytes()), before) + self.assertEqual(log.count("SKIPPED"), 2, log) + self.assertIn("By hand: delete the block", log) + + def test_missing_files_are_not_created(self) -> None: + (self.repo / BAT).unlink() + log = self.run_migration() + self.assertIn(f"{BAT}: not present in this repository", log) + self.assertFalse((self.repo / BAT).exists()) + + def test_the_sync_script_runs_the_migration_from_0_1_44(self) -> None: + shutil.copytree(ROOT / ".template_sync", self.repo / ".template_sync") + manifest = self.repo / ".template_sync/manifest.yaml" + manifest.write_text(re.sub(r"template_version: [0-9.]+", "template_version: 0.1.45", manifest.read_text(encoding="utf-8")), encoding="utf-8") + command = [sys.executable, str(self.repo / ".template_sync/sync.py"), "--from-version", "0.1.44", "--to-version", "0.1.45", "--repository-root", str(self.repo)] + result = subprocess.run(command, capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("[migration 0.1.45]", result.stdout) + self.assertEqual((self.repo / BAT).read_bytes(), filled(live(BAT))) + + +if __name__ == "__main__": + unittest.main()