From 50a47b91047f03b27a938f8336f02e6b034fc5be Mon Sep 17 00:00:00 2001 From: Robin Date: Wed, 19 Nov 2025 16:10:51 -0500 Subject: [PATCH 1/9] Initial work for pre_uninstall --- constructor/briefcase.py | 112 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 105 insertions(+), 7 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 32b5679a..baee3845 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -2,12 +2,15 @@ Logic to build installers using Briefcase. """ +from __future__ import annotations + import logging import re -import sys import shutil +import sys import sysconfig import tempfile +from functools import cached_property from pathlib import Path from subprocess import run @@ -86,17 +89,108 @@ def get_bundle_app_name(info, name): return bundle, app_name + def get_license(info): - """ Retrieve the specified license as a dict or return a placeholder if not set. """ + """Retrieve the specified license as a dict or return a placeholder if not set.""" if "license_file" in info: return {"file": info["license_file"]} # We cannot return an empty string because that results in an exception on the briefcase side. return {"text": "TODO"} + +class UninstallBat: + """Represents a pre-uninstall batch script handler for the MSI installers. + This is intended to handle both the user specified 'pre_uninstall' bat script + and also the 'pre_uninstall_script' passed to briefcase by merging them into one. + """ + + def __init__(self, dst: Path, user_script: str | None): + """ + Parameters + ---------- + dst : Path + Destination directory where the generated `pre_uninstall.bat` file + will be written. + user_script : str | None + Optional path (string) to a user-provided `.bat` file configured + via the `pre_uninstall` setting in the installer configuration. + If provided, the file must adhere to the schema. + """ + self._dst = dst + + self.user_script = None + if user_script: + user_script_path = Path(user_script) + if not self.is_bat_file(user_script_path): + raise ValueError( + f"The entry '{user_script}' configured via 'pre_uninstall' " + "must be a path to an existing .bat file." + ) + self.user_script = user_script_path + self._encoding = "utf-8" # TODO: Do we want to use utf-8-sig? + + def is_bat_file(self, file_path: Path) -> bool: + return file_path.is_file() and file_path.suffix.lower() == ".bat" + + def user_script_as_list(self) -> list[str]: + """Read user script.""" + if not self.user_script: + return [] + with open(self.user_script, encoding=self._encoding, newline=None) as f: + return f.read().splitlines() + + def sanitize_input(self, input_list: list[str]) -> list[str]: + """Sanitizes the input, adds a safe exit if necessary. + Assumes the contents of the input represents the contents of a .bat-file. + """ + return ["exit /b" if line.strip().lower() == "exit" else line for line in input_list] + + def create(self) -> None: + """Create the pre uninstall script. This merges includes the 'pre_uninstall' that may + may have been specified at installer creation. + """ + header = [ + "@echo off", + "setlocal enableextensions enabledelayedexpansion", + 'set "_SELF=%~f0"', + 'set "_HERE=%~dp0"', + "", + "rem === Pre-uninstall script ===", + ] + + # TODO: Create unique labels using uuid to avoid collisions + + user_bat: list[str] = [] + + if self.user_script: + # user_script: list = self.sanitize(self.user_script_as_list()) + # TODO: Embed user script and run it as a subroutine. + # Add error handling using unique labels with 'goto' + user_bat += [ + "rem User supplied with a script", + ] + + # The main part of the bat-script here + tail = [ + 'echo "hello from the script"', + "pause", + ] + final_lines = header + [""] + user_bat + [""] + tail + + with open(self.file_path, "w", encoding=self._encoding, newline="\r\n") as f: + # Python will write \n as \r\n since we have set the 'newline' argument above. + f.writelines(line + "\n" for line in final_lines) + + @cached_property + def file_path(self) -> Path: + """The absolute path to the generated `pre_uninstall.bat` file.""" + return self._dst / "pre_uninstall.bat" + + # Create a Briefcase configuration file. Using a full TOML writer rather than a Jinja # template allows us to avoid escaping strings everywhere. -def write_pyproject_toml(tmp_dir, info): +def write_pyproject_toml(tmp_dir, info, uninstall_bat): name, version = get_name_version(info) bundle, app_name = get_bundle_app_name(info, name) @@ -113,6 +207,7 @@ def write_pyproject_toml(tmp_dir, info): "use_full_install_path": False, "install_launcher": False, "post_install_script": str(BRIEFCASE_DIR / "run_installation.bat"), + "pre_uninstall_script": uninstall_bat.file_path, } }, } @@ -124,11 +219,15 @@ def write_pyproject_toml(tmp_dir, info): def create(info, verbose=False): - if sys.platform != 'win32': + if sys.platform != "win32": raise Exception(f"Invalid platform '{sys.platform}'. Only Windows is supported.") tmp_dir = Path(tempfile.mkdtemp()) - write_pyproject_toml(tmp_dir, info) + + uninstall_bat = UninstallBat(info.get("pre_uninstall", None), tmp_dir) + uninstall_bat.create() + + write_pyproject_toml(tmp_dir, info, uninstall_bat) external_dir = tmp_dir / EXTERNAL_PACKAGE_PATH external_dir.mkdir() @@ -145,8 +244,7 @@ def create(info, verbose=False): briefcase = Path(sysconfig.get_path("scripts")) / "briefcase.exe" if not briefcase.exists(): raise FileNotFoundError( - f"Dependency 'briefcase' does not seem to be installed.\n" - f"Tried: {briefcase}" + f"Dependency 'briefcase' does not seem to be installed.\nTried: {briefcase}" ) logger.info("Building installer") run( From 9663143081eeedece066244459b1eff9a0c6b7d5 Mon Sep 17 00:00:00 2001 From: Robin Date: Thu, 20 Nov 2025 10:02:58 -0500 Subject: [PATCH 2/9] Add tests for initial setup --- constructor/briefcase.py | 12 ++++-- tests/test_briefcase.py | 84 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 91 insertions(+), 5 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index baee3845..8bb05b76 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -147,9 +147,13 @@ def sanitize_input(self, input_list: list[str]) -> list[str]: return ["exit /b" if line.strip().lower() == "exit" else line for line in input_list] def create(self) -> None: - """Create the pre uninstall script. This merges includes the 'pre_uninstall' that may - may have been specified at installer creation. + """Create the bat script for uninstallation. The script will also include the contents from the file the user + may have specified in the yaml-file via 'pre_uninstall'. + When this function is called, the directory 'dst' specified at class instantiation must exist. """ + if not self._dst.exists(): + raise FileNotFoundError(f"The directory {self._dst} must exist in order to create the file.") + header = [ "@echo off", "setlocal enableextensions enabledelayedexpansion", @@ -172,11 +176,11 @@ def create(self) -> None: ] # The main part of the bat-script here - tail = [ + main_bat = [ 'echo "hello from the script"', "pause", ] - final_lines = header + [""] + user_bat + [""] + tail + final_lines = header + [""] + user_bat + [""] + main_bat with open(self.file_path, "w", encoding=self._encoding, newline="\r\n") as f: # Python will write \n as \r\n since we have set the 'newline' argument above. diff --git a/tests/test_briefcase.py b/tests/test_briefcase.py index 36cb1ce8..2170366b 100644 --- a/tests/test_briefcase.py +++ b/tests/test_briefcase.py @@ -1,6 +1,9 @@ import pytest +import re +from pathlib import Path +from constructor.briefcase import get_bundle_app_name, get_name_version, UninstallBat -from constructor.briefcase import get_bundle_app_name, get_name_version +THIS_DIR = Path(__file__).parent @pytest.mark.parametrize( @@ -99,3 +102,82 @@ def test_rdi_invalid_package(rdi): def test_name_no_alphanumeric(name): with pytest.raises(ValueError, match=f"Name '{name}' contains no alphanumeric characters"): get_bundle_app_name({}, name) + +@pytest.mark.parametrize( + "test_path", + [ + Path("foo"), # relative path + THIS_DIR, # absolute path of current test file + THIS_DIR / "subdir", # absolute path to subdirectory + Path.cwd() / "foo", # absolute path relative to working dir + ], +) +def test_uninstall_bat_file_path(test_path): + """Test that various directory inputs work as expected.""" + uninstall_bat = UninstallBat(test_path, user_script=None) + assert uninstall_bat.file_path == test_path / 'pre_uninstall.bat' + +@pytest.mark.parametrize("bat_file_name", ['foo.bat', 'bar.BAT']) +def test_bat_file_works(tmp_path, bat_file_name): + """Test that both .bat and .BAT works and is considered a bat file.""" + uninstall_bat = UninstallBat(tmp_path, user_script=None) + with open(uninstall_bat.file_path, 'w') as f: + f.write("Hello") + uninstall_bat.is_bat_file(uninstall_bat.file_path) + +@pytest.mark.parametrize("bat_file_name", ['foo.bat', 'bar.BAT', 'foo.txt', 'bar']) +def test_invalid_user_script(tmp_path, bat_file_name): + """Verify we get an exception if the user specifies an invalid type of pre_uninstall script.""" + expected = f"The entry '{bat_file_name}' configured via 'pre_uninstall' must be a path to an existing .bat file." + with pytest.raises(ValueError, match=expected): + UninstallBat(tmp_path, user_script = bat_file_name) + +def test_sanitize_input_simple(): + """Test sanitize simple list.""" + items = ['foo', 'txt', 'exit'] + ubat = UninstallBat(Path('foo'), user_script=None) + assert ubat.sanitize_input(items) == ['foo', 'txt', 'exit /b'] + +def test_sanitize_input_from_file(tmp_path): + """Test sanitize input, also add a mix of newlines.""" + bat_file = tmp_path / 'test.bat' + with open(bat_file, 'w') as f: + f.writelines(['echo 1\n', 'exit\r\n', 'echo 2\n\n']) + ubat = UninstallBat(tmp_path, user_script=bat_file) + user_script = ubat.user_script_as_list() + sanitized = ubat.sanitize_input(user_script) + assert sanitized == ['echo 1', 'exit /b', '', 'echo 2', ''] + +def test_create_without_dir(tmp_path): + """Verify we get an exception if the target directory does not exist""" + dir_that_doesnt_exist = tmp_path / 'foo' + ubat = UninstallBat(dir_that_doesnt_exist, user_script = None) + expected = f"The directory {dir_that_doesnt_exist} must exist in order to create the file." + with pytest.raises(FileNotFoundError, match=re.escape(expected)): + ubat.create() + +def test_create(tmp_path): + """Verify the contents of the uninstall script looks as expected.""" + # TODO: Since we don't merge the user script right now, we need to account for this + # when it's been added. + + bat_file = tmp_path / 'test.bat' + with open(bat_file, 'w') as f: + f.writelines(['echo 1\n', 'exit\r\n', 'echo 2\n\n']) + ubat = UninstallBat(tmp_path, user_script=bat_file) + ubat.create() + with open(ubat.file_path) as f: + contents = f.readlines() + expected = [ + '@echo off\n', + 'setlocal enableextensions enabledelayedexpansion\n', + 'set "_SELF=%~f0"\n', + 'set "_HERE=%~dp0"\n', + '\n', + 'rem === Pre-uninstall script ===\n', + '\n', 'rem User supplied with a script\n', + '\n', + 'echo "hello from the script"\n', + 'pause\n' + ] + assert contents == expected From aad10acb5258d5fb312ace6e7c06da9724b77bc2 Mon Sep 17 00:00:00 2001 From: Robin Date: Thu, 20 Nov 2025 13:32:53 -0500 Subject: [PATCH 3/9] A few fixes --- constructor/briefcase.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 8bb05b76..586e36bf 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -159,6 +159,7 @@ def create(self) -> None: "setlocal enableextensions enabledelayedexpansion", 'set "_SELF=%~f0"', 'set "_HERE=%~dp0"', + r'set "PREFIX=%_HERE%\..\"', "", "rem === Pre-uninstall script ===", ] @@ -178,6 +179,8 @@ def create(self) -> None: # The main part of the bat-script here main_bat = [ 'echo "hello from the script"', + 'echo %_SELF%', + 'echo %_HERE%', "pause", ] final_lines = header + [""] + user_bat + [""] + main_bat @@ -211,7 +214,7 @@ def write_pyproject_toml(tmp_dir, info, uninstall_bat): "use_full_install_path": False, "install_launcher": False, "post_install_script": str(BRIEFCASE_DIR / "run_installation.bat"), - "pre_uninstall_script": uninstall_bat.file_path, + "pre_uninstall_script": str(uninstall_bat.file_path), } }, } @@ -228,7 +231,7 @@ def create(info, verbose=False): tmp_dir = Path(tempfile.mkdtemp()) - uninstall_bat = UninstallBat(info.get("pre_uninstall", None), tmp_dir) + uninstall_bat = UninstallBat(tmp_dir, info.get("pre_uninstall", None)) uninstall_bat.create() write_pyproject_toml(tmp_dir, info, uninstall_bat) From 13e2cbebdd9d33b137b7ae64d16d3c85a3c197a1 Mon Sep 17 00:00:00 2001 From: Robin Date: Thu, 20 Nov 2025 13:36:41 -0500 Subject: [PATCH 4/9] Add batfile as a docstring right now --- constructor/briefcase.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 586e36bf..2d348ff7 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -176,6 +176,26 @@ def create(self) -> None: "rem User supplied with a script", ] + + # TODO, this works (almost) + """ + echo "Preparing uninstallation..." + echo %_SELF% + echo %_HERE% + set "INSTDIR=%_HERE%\.." + set "CONDA_FLAGS=--remove-config-files=user" + set "CONDA_EXE=_conda.exe" + "%INSTDIR%\%CONDA_EXE%" constructor uninstall %CONDA_FLAGS% --prefix "%INSTDIR%" + if errorlevel 1 ( + echo [ERROR] %CONDA_EXE% failed with exit code %errorlevel%. + pause + exit /b %errorlevel% + ) + RMDIR /Q /S "%INSTDIR%" + echo [INFO] %CONDA_EXE% completed successfully. + pause + + """ # The main part of the bat-script here main_bat = [ 'echo "hello from the script"', From b7898b5f5ce96b4550d12f057c175605d46608d9 Mon Sep 17 00:00:00 2001 From: Robin Date: Thu, 20 Nov 2025 13:50:12 -0500 Subject: [PATCH 5/9] Pre-commit and add script --- constructor/briefcase.py | 40 +++++++++++++++++----------------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 2d348ff7..b44da193 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -152,7 +152,9 @@ def create(self) -> None: When this function is called, the directory 'dst' specified at class instantiation must exist. """ if not self._dst.exists(): - raise FileNotFoundError(f"The directory {self._dst} must exist in order to create the file.") + raise FileNotFoundError( + f"The directory {self._dst} must exist in order to create the file." + ) header = [ "@echo off", @@ -176,31 +178,23 @@ def create(self) -> None: "rem User supplied with a script", ] - # TODO, this works (almost) - """ - echo "Preparing uninstallation..." - echo %_SELF% - echo %_HERE% - set "INSTDIR=%_HERE%\.." - set "CONDA_FLAGS=--remove-config-files=user" - set "CONDA_EXE=_conda.exe" - "%INSTDIR%\%CONDA_EXE%" constructor uninstall %CONDA_FLAGS% --prefix "%INSTDIR%" - if errorlevel 1 ( - echo [ERROR] %CONDA_EXE% failed with exit code %errorlevel%. - pause - exit /b %errorlevel% - ) - RMDIR /Q /S "%INSTDIR%" - echo [INFO] %CONDA_EXE% completed successfully. - pause - - """ # The main part of the bat-script here main_bat = [ - 'echo "hello from the script"', - 'echo %_SELF%', - 'echo %_HERE%', + 'echo "Preparing uninstallation..."', + "echo %_SELF%", + "echo %_HERE%", + r'set "INSTDIR=%_HERE%\.."', + 'set "CONDA_FLAGS=--remove-config-files=user"', + 'set "CONDA_EXE=_conda.exe"', + r'"%INSTDIR%\%CONDA_EXE%" constructor uninstall %CONDA_FLAGS% --prefix "%INSTDIR%"', + "if errorlevel 1 (", + " echo [ERROR] %CONDA_EXE% failed with exit code %errorlevel%.", + " pause", + " exit /b %errorlevel%", + ")", + 'rem RMDIR /Q /S "%INSTDIR%"', + "echo [INFO] %CONDA_EXE% completed successfully.", "pause", ] final_lines = header + [""] + user_bat + [""] + main_bat From 9a6923146b1364b14796e31d85f5fbe0e7fb543e Mon Sep 17 00:00:00 2001 From: Robin Date: Fri, 21 Nov 2025 15:25:29 -0500 Subject: [PATCH 6/9] Add working uninstallation --- constructor/briefcase.py | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index b44da193..39ce2c1a 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -159,15 +159,11 @@ def create(self) -> None: header = [ "@echo off", "setlocal enableextensions enabledelayedexpansion", - 'set "_SELF=%~f0"', 'set "_HERE=%~dp0"', - r'set "PREFIX=%_HERE%\..\"', "", "rem === Pre-uninstall script ===", ] - # TODO: Create unique labels using uuid to avoid collisions - user_bat: list[str] = [] if self.user_script: @@ -175,27 +171,39 @@ def create(self) -> None: # TODO: Embed user script and run it as a subroutine. # Add error handling using unique labels with 'goto' user_bat += [ - "rem User supplied with a script", + "rem User supplied a script", ] - # TODO, this works (almost) - # The main part of the bat-script here + """ + The goal is to remove most of the files except for the directory '_installer' where + the bat-files are located. This is because the MSI Installer needs to call these bat-files + after 'pre_uninstall_script' is finished, in order to finish with the uninstallation. + """ main_bat = [ 'echo "Preparing uninstallation..."', - "echo %_SELF%", - "echo %_HERE%", r'set "INSTDIR=%_HERE%\.."', - 'set "CONDA_FLAGS=--remove-config-files=user"', 'set "CONDA_EXE=_conda.exe"', - r'"%INSTDIR%\%CONDA_EXE%" constructor uninstall %CONDA_FLAGS% --prefix "%INSTDIR%"', + r'"%INSTDIR%\%CONDA_EXE%" menuinst --prefix "%INSTDIR%" --remove' + r'"%INSTDIR%\%CONDA_EXE%" remove -p "%INSTDIR%" --keep-env --all -y', "if errorlevel 1 (", " echo [ERROR] %CONDA_EXE% failed with exit code %errorlevel%.", - " pause", " exit /b %errorlevel%", ")", - 'rem RMDIR /Q /S "%INSTDIR%"', + "", "echo [INFO] %CONDA_EXE% completed successfully.", - "pause", + r'set "PKGS=%INSTDIR%\pkgs"', + 'if exist "%PKGS%" (', + ' echo [INFO] Removing "%PKGS%" ...', + ' rmdir /s /q "%PKGS%"', + " echo [INFO] Done.", + ")", + "", + r'set "NONADMIN=%INSTDIR%\.nonadmin"', + 'if exist "%NONADMIN%" (', + ' echo [INFO] Removing file "%NONADMIN%" ...', + ' del /f /q "%NONADMIN%"', + ")", + "", ] final_lines = header + [""] + user_bat + [""] + main_bat From 3dc6e480dd0ad7b0651107280f91e07b4737fc7a Mon Sep 17 00:00:00 2001 From: Robin Date: Fri, 21 Nov 2025 15:38:03 -0500 Subject: [PATCH 7/9] Update test and add missing comma-sign --- constructor/briefcase.py | 2 +- tests/test_briefcase.py | 30 ++++++++++++++++++++++++++---- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 39ce2c1a..08debe96 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -183,7 +183,7 @@ def create(self) -> None: 'echo "Preparing uninstallation..."', r'set "INSTDIR=%_HERE%\.."', 'set "CONDA_EXE=_conda.exe"', - r'"%INSTDIR%\%CONDA_EXE%" menuinst --prefix "%INSTDIR%" --remove' + r'"%INSTDIR%\%CONDA_EXE%" menuinst --prefix "%INSTDIR%" --remove', r'"%INSTDIR%\%CONDA_EXE%" remove -p "%INSTDIR%" --keep-env --all -y', "if errorlevel 1 (", " echo [ERROR] %CONDA_EXE% failed with exit code %errorlevel%.", diff --git a/tests/test_briefcase.py b/tests/test_briefcase.py index 2170366b..eec158cc 100644 --- a/tests/test_briefcase.py +++ b/tests/test_briefcase.py @@ -171,13 +171,35 @@ def test_create(tmp_path): expected = [ '@echo off\n', 'setlocal enableextensions enabledelayedexpansion\n', - 'set "_SELF=%~f0"\n', 'set "_HERE=%~dp0"\n', '\n', 'rem === Pre-uninstall script ===\n', - '\n', 'rem User supplied with a script\n', '\n', - 'echo "hello from the script"\n', - 'pause\n' + 'rem User supplied a script\n', + '\n', + 'echo "Preparing uninstallation..."\n', + 'set "INSTDIR=%_HERE%\\.."\n', + 'set "CONDA_EXE=_conda.exe"\n', + '"%INSTDIR%\\%CONDA_EXE%" menuinst --prefix "%INSTDIR%" --remove\n', + '"%INSTDIR%\\%CONDA_EXE%" remove -p "%INSTDIR%" --keep-env --all -y\n', + 'if errorlevel 1 (\n', + ' echo [ERROR] %CONDA_EXE% failed with exit code %errorlevel%.\n', + ' exit /b %errorlevel%\n', + ')\n', + '\n', + 'echo [INFO] %CONDA_EXE% completed successfully.\n', + 'set "PKGS=%INSTDIR%\\pkgs"\n', + 'if exist "%PKGS%" (\n', + ' echo [INFO] Removing "%PKGS%" ...\n', + ' rmdir /s /q "%PKGS%"\n', + ' echo [INFO] Done.\n', + ')\n', + '\n', + 'set "NONADMIN=%INSTDIR%\\.nonadmin"\n', + 'if exist "%NONADMIN%" (\n', + ' echo [INFO] Removing file "%NONADMIN%" ...\n', + ' del /f /q "%NONADMIN%"\n', + ')\n', + '\n', ] assert contents == expected From 4e6606a0ec7f1f2ca8a36258a30bc2a8ba807131 Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 24 Nov 2025 09:39:59 -0500 Subject: [PATCH 8/9] Improve documentation and fixing language --- constructor/briefcase.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 08debe96..7ec3de41 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -100,9 +100,10 @@ def get_license(info): class UninstallBat: - """Represents a pre-uninstall batch script handler for the MSI installers. - This is intended to handle both the user specified 'pre_uninstall' bat script - and also the 'pre_uninstall_script' passed to briefcase by merging them into one. + """Represents a pre-uninstall batch file handler for the MSI installers. + This class handles both an optional user script together with a default uininstallation, + by creating one, merged batch file. + The created file is designed for the briefcase specific config entry 'pre_uninstall_script'. """ def __init__(self, dst: Path, user_script: str | None): @@ -110,12 +111,11 @@ def __init__(self, dst: Path, user_script: str | None): Parameters ---------- dst : Path - Destination directory where the generated `pre_uninstall.bat` file - will be written. + Destination directory where the file `pre_uninstall.bat` will be written. user_script : str | None - Optional path (string) to a user-provided `.bat` file configured - via the `pre_uninstall` setting in the installer configuration. - If provided, the file must adhere to the schema. + Optional path (string) to an existing user-provided batch file. + If provided, the file must adhere to the schema, in particular, + as 'pre_uninstall' is defined. """ self._dst = dst @@ -134,7 +134,7 @@ def is_bat_file(self, file_path: Path) -> bool: return file_path.is_file() and file_path.suffix.lower() == ".bat" def user_script_as_list(self) -> list[str]: - """Read user script.""" + """Read user script into a list.""" if not self.user_script: return [] with open(self.user_script, encoding=self._encoding, newline=None) as f: @@ -142,12 +142,12 @@ def user_script_as_list(self) -> list[str]: def sanitize_input(self, input_list: list[str]) -> list[str]: """Sanitizes the input, adds a safe exit if necessary. - Assumes the contents of the input represents the contents of a .bat-file. + Assumes the contents of the input represents the contents of a batch file. """ return ["exit /b" if line.strip().lower() == "exit" else line for line in input_list] def create(self) -> None: - """Create the bat script for uninstallation. The script will also include the contents from the file the user + """Create the batch file for uninstallation. The script will also include the contents from the file the user may have specified in the yaml-file via 'pre_uninstall'. When this function is called, the directory 'dst' specified at class instantiation must exist. """ @@ -176,8 +176,8 @@ def create(self) -> None: """ The goal is to remove most of the files except for the directory '_installer' where - the bat-files are located. This is because the MSI Installer needs to call these bat-files - after 'pre_uninstall_script' is finished, in order to finish with the uninstallation. + the batch files are located. This is because the MSI Installer needs these batch files + to exist after 'pre_uninstall_script' is finished, in order to finish with the uninstallation. """ main_bat = [ 'echo "Preparing uninstallation..."', From 702f8ef42800706630a97824f9871befbb3c9726 Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 24 Nov 2025 11:08:47 -0500 Subject: [PATCH 9/9] Fix code clarity and removal of 'envs' dir --- constructor/briefcase.py | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/constructor/briefcase.py b/constructor/briefcase.py index 7ec3de41..79914e1f 100644 --- a/constructor/briefcase.py +++ b/constructor/briefcase.py @@ -147,8 +147,8 @@ def sanitize_input(self, input_list: list[str]) -> list[str]: return ["exit /b" if line.strip().lower() == "exit" else line for line in input_list] def create(self) -> None: - """Create the batch file for uninstallation. The script will also include the contents from the file the user - may have specified in the yaml-file via 'pre_uninstall'. + """Create the batch file. If a `user_script` was defined at class instantiation, the batch file + will also include the contents from that file. When this function is called, the directory 'dst' specified at class instantiation must exist. """ if not self._dst.exists(): @@ -175,14 +175,24 @@ def create(self) -> None: ] """ - The goal is to remove most of the files except for the directory '_installer' where - the batch files are located. This is because the MSI Installer needs these batch files - to exist after 'pre_uninstall_script' is finished, in order to finish with the uninstallation. + The goal is to remove most of the files except for files such as the + directory named '_installer' which the MSI installer expects to exist when + it performs the uninstallation. """ - main_bat = [ - 'echo "Preparing uninstallation..."', + main_bat = [ # Prep + "echo Preparing uninstallation...", r'set "INSTDIR=%_HERE%\.."', 'set "CONDA_EXE=_conda.exe"', + ] + main_bat += [ # Removal of 'envs' directory + r'set "ENVS_DIR=%INSTDIR%\envs"', + 'if exist "%ENVS_DIR%" (', + ' echo [INFO] Removing "%ENVS_DIR%" ...', + r' "%INSTDIR%\%CONDA_EXE%" constructor uninstall --prefix "%INSTDIR%\envs"', + " echo [INFO] Done.", + ")", + ] + main_bat += [ # Removal of Start Menus and base env r'"%INSTDIR%\%CONDA_EXE%" menuinst --prefix "%INSTDIR%" --remove', r'"%INSTDIR%\%CONDA_EXE%" remove -p "%INSTDIR%" --keep-env --all -y', "if errorlevel 1 (", @@ -190,6 +200,8 @@ def create(self) -> None: " exit /b %errorlevel%", ")", "", + ] + main_bat += [ # Removal of 'pkgs' directory "echo [INFO] %CONDA_EXE% completed successfully.", r'set "PKGS=%INSTDIR%\pkgs"', 'if exist "%PKGS%" (', @@ -198,6 +210,8 @@ def create(self) -> None: " echo [INFO] Done.", ")", "", + ] + main_bat += [ # Removal of .nonadmin r'set "NONADMIN=%INSTDIR%\.nonadmin"', 'if exist "%NONADMIN%" (', ' echo [INFO] Removing file "%NONADMIN%" ...', @@ -205,8 +219,8 @@ def create(self) -> None: ")", "", ] - final_lines = header + [""] + user_bat + [""] + main_bat + final_lines = header + [""] + user_bat + [""] + main_bat with open(self.file_path, "w", encoding=self._encoding, newline="\r\n") as f: # Python will write \n as \r\n since we have set the 'newline' argument above. f.writelines(line + "\n" for line in final_lines)