diff --git a/Build.bat b/Build.bat index e0a926944..b5eb0b3d7 100644 --- a/Build.bat +++ b/Build.bat @@ -9,31 +9,32 @@ echo ========================================== echo L E O N I D A - Game Builder echo ========================================== echo. -set "PY=" +set "PY_EXE=" +set "PY_ARG=" for %%V in (3.14 3.13 3.12 3) do ( - if not defined PY ( - py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=py -%%V" + if not defined PY_EXE ( + py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && (set "PY_EXE=py" & set "PY_ARG=-%%V") ) ) -if not defined PY ( +if not defined PY_EXE ( where python >nul 2>nul && ( - python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=python" + python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY_EXE=python" ) ) rem No Python on PATH: look for a per-user install (python.org or winget, "Add to PATH" unticked), else offer to install one. -if not defined PY call :find_user_python -if not defined PY call :offer_python -if not defined PY ( +if not defined PY_EXE call :find_user_python +if not defined PY_EXE call :offer_python +if not defined PY_EXE ( echo Python 3.12 or newer is needed: https://www.python.org/downloads/ echo Tick "Add python.exe to PATH" during setup, then run Build.bat again. - pause + if not defined LEONIDA_NO_PAUSE pause exit /b 1 ) -%PY% -I "%~dp0make_game.py" %* +"%PY_EXE%" %PY_ARG% -I "%~dp0make_game.py" %* set "RC=%ERRORLEVEL%" echo. if "%RC%"=="0" (echo Done.) else (echo The build stopped. Read the message above.) -pause +if not defined LEONIDA_NO_PAUSE pause exit /b %RC% rem ---- Helpers (only reached by "call"; the script exits above) ---- @@ -45,9 +46,9 @@ for /f "delims=" %%D in ('dir /b /ad /o-n "%LOCALAPPDATA%\Programs\Python\Python exit /b 0 :try_python -if defined PY exit /b 0 -if not exist %1 exit /b 0 -%1 -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set PY="%~1" +if defined PY_EXE exit /b 0 +if not exist "%~1" exit /b 0 +"%~1" -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY_EXE=%~1" exit /b 0 rem Ask first, then install Python 3.12 for this user only (no admin): winget if present, else the pinned @@ -62,7 +63,10 @@ where winget >nul 2>nul && goto :py_winget :py_download set "PYURL=https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe" set "PYSHA=67B5635E80EA51072B87941312D00EC8927C4DB9BA18938F7AD2D27B328B95FB" -set "PYEXE=%TEMP%\leonida-python-3.12.10-amd64.exe" +set "PYTMP=%TEMP%" +if not defined PYTMP set "PYTMP=%LOCALAPPDATA%\Temp" +if not defined PYTMP set "PYTMP=%~dp0" +set "PYEXE=%PYTMP%\leonida-python-3.12.10-amd64.exe" if defined LEONIDA_PY_INSTALL_DRYRUN goto :py_dry_download echo Downloading Python 3.12.10 from python.org ... powershell -NoProfile -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -UseBasicParsing -Uri $env:PYURL -OutFile $env:PYEXE; if ((Get-FileHash -Algorithm SHA256 -LiteralPath $env:PYEXE).Hash -ine $env:PYSHA) { Remove-Item -LiteralPath $env:PYEXE -Force; exit 3 }" @@ -89,7 +93,7 @@ if defined LEONIDA_PY_INSTALL_DRYRUN goto :py_dry_winget echo Installing Python 3.12 with winget ... call %PYWG% call :find_user_python -if defined PY exit /b 0 +if defined PY_EXE exit /b 0 echo winget did not install Python; trying the python.org installer instead. goto :py_download diff --git a/Mods.bat b/Mods.bat index 5b7da57f0..f4c9e9fd7 100644 --- a/Mods.bat +++ b/Mods.bat @@ -3,24 +3,38 @@ title Leonida - Mod Manager rem Double-click to open the mod manager window. It manages \mods and never touches the game package. setlocal cd /d "%~dp0" -set "PY=" +set "PY_EXE=" +set "PY_ARG=" for %%V in (3.14 3.13 3.12 3) do ( - if not defined PY ( - py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=py -%%V" + if not defined PY_EXE ( + py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && (set "PY_EXE=py" & set "PY_ARG=-%%V") ) ) -if not defined PY ( +if not defined PY_EXE ( where python >nul 2>nul && ( - python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=python" + python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY_EXE=python" ) ) -if not defined PY ( +if not defined PY_EXE call :find_user_python +if not defined PY_EXE ( echo Python 3.12 or newer is needed: https://www.python.org/downloads/ echo Tick "Add python.exe to PATH" during setup. - pause + if not defined LEONIDA_NO_PAUSE pause exit /b 1 ) -%PY% -I "%~dp0tools\leonida_mods.py" gui %* +"%PY_EXE%" %PY_ARG% -I "%~dp0tools\leonida_mods.py" gui %* set "RC=%ERRORLEVEL%" -if not "%RC%"=="0" pause +if not "%RC%"=="0" ( + if not defined LEONIDA_NO_PAUSE pause +) exit /b %RC% + +:find_user_python +for /f "delims=" %%D in ('dir /b /ad /o-n "%LOCALAPPDATA%\Programs\Python\Python3*" 2^>nul') do call :try_python "%LOCALAPPDATA%\Programs\Python\%%D\python.exe" +exit /b 0 + +:try_python +if defined PY_EXE exit /b 0 +if not exist "%~1" exit /b 0 +"%~1" -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY_EXE=%~1" +exit /b 0 diff --git a/tests/test_win_launchers.py b/tests/test_win_launchers.py new file mode 100644 index 000000000..6be777663 --- /dev/null +++ b/tests/test_win_launchers.py @@ -0,0 +1,133 @@ +"""Tests for Build.bat and Mods.bat quoted per-user Python lookup and non-interactive pause control. + + python -I tests/test_win_launchers.py +""" +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +BUILD_BAT = ROOT / "Build.bat" +MODS_BAT = ROOT / "Mods.bat" + +FAKE_PY_CS = r""" +using System; +using System.IO; +using System.Text; + +public class FakePython { + public static int Main(string[] args) { + if (args.Length >= 2 && args[0] == "-c") { + return Environment.GetEnvironmentVariable("FAKE_PY_OLD") == "1" ? 1 : 0; + } + string log = Environment.GetEnvironmentVariable("FAKE_PY_LOG"); + if (!string.IsNullOrEmpty(log)) { + File.WriteAllLines(log, args, Encoding.UTF8); + } + string rc = Environment.GetEnvironmentVariable("FAKE_PY_RC"); + return string.IsNullOrEmpty(rc) ? 0 : int.Parse(rc); + } +} +""" + + +class WinLaunchersTests(unittest.TestCase): + def test_static_quoting_and_no_pause_guards(self) -> None: + build_txt = BUILD_BAT.read_text(encoding="utf-8") + mods_txt = MODS_BAT.read_text(encoding="utf-8") + for txt in (build_txt, mods_txt): + self.assertIn('set "PY_EXE=', txt) + self.assertIn('set "PY_EXE=%~1"', txt) + self.assertNotIn('set PY="%~1"', txt) + self.assertIn("LEONIDA_NO_PAUSE", txt) + self.assertIn(":find_user_python", mods_txt) + self.assertIn("if not defined PYTMP", build_txt) + + @unittest.skipUnless(os.name == "nt" and shutil.which("powershell.exe"), "requires Windows cmd.exe and PowerShell") + def test_per_user_python_discovery_with_ampersand_and_exit_propagation(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + repo = root / "repo" + (repo / "tools").mkdir(parents=True) + shutil.copy2(BUILD_BAT, repo / "Build.bat") + shutil.copy2(MODS_BAT, repo / "Mods.bat") + (repo / "make_game.py").write_text("# stub\n", encoding="utf-8", newline="\n") + (repo / "tools" / "leonida_mods.py").write_text("# stub\n", encoding="utf-8", newline="\n") + + local_app = root / "user & test" + py_dir = local_app / "Programs" / "Python" / "Python313" + py_dir.mkdir(parents=True) + plain_stub = root / "fake_py.exe" + + ps_base = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"] + ps_env = {**os.environ, "FAKE_PY_EXE": str(plain_stub), "FAKE_PY_CS": FAKE_PY_CS} + ps_env["PSModulePath"] = str(Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/Modules") + compile_cmd = ( + "$ErrorActionPreference = 'Stop'; " + "Add-Type -OutputAssembly $env:FAKE_PY_EXE -OutputType ConsoleApplication -TypeDefinition $env:FAKE_PY_CS" + ) + subprocess.run([*ps_base, "-Command", compile_cmd], env=ps_env, check=True, timeout=60) + shutil.move(str(plain_stub), str(py_dir / "python.exe")) + + sys32 = str(Path(os.environ["SystemRoot"]) / "System32") + clean_env = { + "SystemRoot": os.environ["SystemRoot"], + "ComSpec": os.environ.get("ComSpec", os.path.join(sys32, "cmd.exe")), + "PATH": sys32, + "LOCALAPPDATA": str(local_app), + "TEMP": str(root), + "TMP": str(root), + "LEONIDA_NO_PAUSE": "1", + "LEONIDA_PY_INSTALL_DRYRUN": "1", + } + + log_build = root / "build.args" + r_build = subprocess.run( + ["cmd.exe", "/c", "call", str(repo / "Build.bat"), "--out", "D:\\Out Dir"], + env={**clean_env, "FAKE_PY_LOG": str(log_build), "FAKE_PY_RC": "0"}, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(r_build.returncode, 0, r_build.stdout + r_build.stderr) + self.assertEqual( + log_build.read_text(encoding="utf-8-sig").splitlines(), + ["-I", str(repo / "make_game.py"), "--out", "D:\\Out Dir"], + ) + + log_mods = root / "mods.args" + r_mods = subprocess.run( + ["cmd.exe", "/c", "call", str(repo / "Mods.bat"), "--check"], + env={**clean_env, "FAKE_PY_LOG": str(log_mods), "FAKE_PY_RC": "5"}, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(r_mods.returncode, 5, r_mods.stdout + r_mods.stderr) + self.assertEqual( + log_mods.read_text(encoding="utf-8-sig").splitlines(), + ["-I", str(repo / "tools" / "leonida_mods.py"), "gui", "--check"], + ) + + # Without a qualifying Python, Mods.bat exits 1 cleanly without hanging on pause. + r_missing = subprocess.run( + ["cmd.exe", "/c", "call", str(repo / "Mods.bat")], + env={**clean_env, "FAKE_PY_OLD": "1"}, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(r_missing.returncode, 1, r_missing.stdout + r_missing.stderr) + self.assertIn("Python 3.12 or newer is needed", r_missing.stdout + r_missing.stderr) + + +if __name__ == "__main__": + unittest.main()