diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index b3f3435..0505771 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -2,6 +2,9 @@ name: Windows build on: workflow_dispatch: + pull_request: + branches: + - main push: branches: - main diff --git a/README.md b/README.md index 0d2da8b..c52a721 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,8 @@ the official mod page when possible. Steam auto-detection is unavailable. The selected folder must contain `Cities2.exe`; mod files still go to the game's AppData folders. - Offers an advanced **Build trusted source** flow when the official CS2 - modding toolchain, the required .NET SDK, and npm are available. + modding toolchain, its required .NET Runtime, the required .NET SDK, and npm + are available. - Blocks path traversal, archive symlinks, encrypted entries, oversized packages, and suspicious compression ratios. - Installs compiled mods transactionally into: @@ -47,14 +48,30 @@ the user deliberately chooses **Build trusted source**, SkylineDock: 1. Detects the solution, .NET SDK version, UI projects, build scripts, and CS2 environment requirements. -2. Verifies the Steam game installation, `CSII_TOOLPATH`, `dotnet`, and `npm`. -3. Extracts a validated copy into a temporary build directory. -4. Redirects normal toolchain output through `CSII_USERDATAPATH` so an - unvalidated build does not go directly into the live game folder. -5. Runs a reproducible `npm ci` when a locked UI project is present, followed +2. Verifies the selected game installation, auto-detects its official modding + toolchain, checks `dotnet` and `npm`, and reads the toolchain's own + `runtimeconfig.json` to detect the exact .NET Runtime family it needs. +3. If a component is missing, shows a customer-friendly one-time setup guide + with official download links, including Unity license activation when the + game toolchain pauses for it; no environment-variable setup is required. +4. Extracts a validated copy into a temporary build directory. +5. Redirects both user-data and local-mod output with immutable MSBuild + properties so an unvalidated build does not go directly into the live game + folder. +6. Adds an out-of-tree MSBuild hook that resolves Unity's `mscorlib.dll` and + `System.Memory.dll` from the selected CS2 installation. The mod's source + archive is not modified. +7. Runs a reproducible `npm ci` when a locked UI project is present, followed by a Release build of the solution. -6. Scans the output again and installs it transactionally only if it looks like - a compiled CS2 mod. +8. Scans the output again and installs it transactionally only if it looks like + a compiled CS2 mod. If a command fails, a complete diagnostic log is saved + under `%LOCALAPPDATA%\SkylineDock\logs`. + +Some official CS2 toolchain releases still target .NET Runtime 6.0 even when a +newer .NET SDK is installed. .NET major versions are side-by-side, so a newer +runtime does not automatically satisfy that requirement. SkylineDock reads the +installed toolchain and links the customer directly to the matching x64 Runtime +when it is missing. This mode executes MSBuild and npm-controlled code with the current Windows user's permissions. The temporary directory prevents common accidental writes; diff --git a/pyproject.toml b/pyproject.toml index ebf679c..77ec17b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "skylinedock" -version = "0.2.0.dev2" +version = "0.2.0.dev4" description = "Safe drag-and-drop mod installer for Cities: Skylines II" readme = "README.md" requires-python = ">=3.11" diff --git a/skylinedock/__init__.py b/skylinedock/__init__.py index 8f4b607..80daca0 100644 --- a/skylinedock/__init__.py +++ b/skylinedock/__init__.py @@ -5,4 +5,4 @@ __all__ = ["ArchiveScanner", "PackageKind", "ScanReport", "SourceType"] -__version__ = "0.2.0.dev2" +__version__ = "0.2.0.dev4" diff --git a/skylinedock/app.py b/skylinedock/app.py index bad8830..a82079a 100644 --- a/skylinedock/app.py +++ b/skylinedock/app.py @@ -1,5 +1,6 @@ from __future__ import annotations +from datetime import datetime, timezone import threading import tempfile import webbrowser @@ -20,7 +21,7 @@ from .installer import InstallError, build_install_plan, install from .models import PackageKind, ScanReport from .scanner import ArchiveScanner -from .settings import AppSettings, load_settings, save_settings +from .settings import AppSettings, default_settings_path, load_settings, save_settings from .source_builder import ( SourceBuildError, build_trusted_source, @@ -43,6 +44,11 @@ "danger": "#FF6B7A", } +UNITY_LICENSE_URL = "https://docs.unity.com/en-us/hub/manage-license" +NODE_DOWNLOAD_URL = "https://nodejs.org/en/download" +DOTNET_DOWNLOAD_URL = "https://dotnet.microsoft.com/en-us/download/dotnet" +DOTNET_RUNTIME_DOWNLOAD_URL = "https://dotnet.microsoft.com/en-us/download/dotnet/{family}" + class SkylineDockApp: def __init__(self, initial_path: str | None = None) -> None: @@ -437,11 +443,7 @@ def _build_source(self) -> None: return if not prerequisites.ready: - messagebox.showerror( - "Source build requirements", - "SkylineDock cannot build this source yet:\n\n" - + "\n".join(f"• {issue}" for issue in prerequisites.issues), - ) + self._show_build_requirements(inspection, prerequisites) return warnings = "\n".join(f"• {warning}" for warning in inspection.warnings) @@ -475,12 +477,189 @@ def worker() -> None: plan = build_install_plan(result.compiled_report) destination = install(plan) self.root.after(0, lambda: self._source_build_succeeded(destination)) - except (SourceBuildError, InstallError, OSError) as exc: + except SourceBuildError as exc: + message = str(exc) + log_path = self._save_source_build_log(exc.diagnostic_log) + if log_path is not None: + message += f"\n\nFull diagnostic log:\n{log_path}" + self.root.after(0, lambda message=message: self._source_build_failed(message)) + except (InstallError, OSError) as exc: message = str(exc) self.root.after(0, lambda message=message: self._source_build_failed(message)) threading.Thread(target=worker, daemon=True).start() + def _show_build_requirements(self, inspection, prerequisites) -> None: + """Explain missing build tools without exposing environment-variable setup.""" + + dialog = tk.Toplevel(self.root) + dialog.withdraw() + dialog.title("One-time setup required") + dialog.configure(bg=COLORS["background"]) + dialog.resizable(False, False) + dialog.transient(self.root) + + content = tk.Frame(dialog, bg=COLORS["background"], padx=28, pady=24) + content.pack(fill=BOTH, expand=True) + tk.Label( + content, + text="A one-time setup is needed to build this source mod", + bg=COLORS["background"], + fg=COLORS["text"], + font=("Segoe UI Semibold", 15), + ).pack(anchor="w") + tk.Label( + content, + text=( + "These free components are only needed when building source code. " + "Ready-to-install mods do not need them." + ), + bg=COLORS["background"], + fg=COLORS["muted"], + font=("Segoe UI", 9), + justify=LEFT, + wraplength=610, + ).pack(anchor="w", pady=(5, 18)) + + missing_toolchain = prerequisites.tool_path is None + missing_npm = bool(inspection.ui_directories) and prerequisites.npm_executable is None + missing_dotnet = prerequisites.dotnet_executable is None + missing_runtimes = prerequisites.missing_dotnet_runtimes + requirement_number = 1 + + if missing_toolchain: + self._add_requirement( + content, + f"{requirement_number}. Install the Cities: Skylines II Modding Toolchain", + "Open the game, go to Options → Modding, then install or repair all " + "required tools. If installation waits for a Unity license, open Unity Hub, " + "sign in, then choose Licenses → Add license → Get a free personal license. " + "Return to the game and wait for every item to show a green check.", + "Unity license guide", + UNITY_LICENSE_URL, + ) + requirement_number += 1 + + if missing_npm: + self._add_requirement( + content, + f"{requirement_number}. Install Node.js LTS", + "Download the Windows installer and keep the default options. npm is included " + "with Node.js; it does not need to be installed separately.", + "Download Node.js", + NODE_DOWNLOAD_URL, + ) + requirement_number += 1 + + if missing_dotnet: + version = inspection.dotnet_sdk_version or "a compatible current version" + self._add_requirement( + content, + f"{requirement_number}. Install the .NET SDK", + f"Install .NET SDK {version} or a compatible newer SDK for Windows.", + "Download .NET SDK", + DOTNET_DOWNLOAD_URL, + ) + requirement_number += 1 + + for runtime in missing_runtimes: + self._add_requirement( + content, + f"{requirement_number}. Install .NET Runtime {runtime.family} (x64)", + "The CS2 ModPostProcessor targets " + f"{runtime.framework} {runtime.version}. A newer major runtime does not " + "replace this requirement automatically. Install the latest patch in the " + f"{runtime.family} family; other installed .NET versions can remain.", + f"Download .NET {runtime.family} Runtime", + DOTNET_RUNTIME_DOWNLOAD_URL.format(family=runtime.family), + ) + requirement_number += 1 + + other_issues = [] + if not prerequisites.windows_supported: + other_issues.append("Source builds are currently supported on Windows only.") + if prerequisites.steam_game_path is None: + other_issues.append( + "Choose the folder containing Cities2.exe in SkylineDock before building." + ) + if other_issues: + tk.Label( + content, + text="\n".join(f"• {issue}" for issue in other_issues), + bg=COLORS["background"], + fg=COLORS["warning"], + font=("Segoe UI", 9), + justify=LEFT, + wraplength=610, + ).pack(anchor="w", pady=(0, 14)) + + tk.Label( + content, + text=( + "When installation is complete, restart SkylineDock, load the package again, " + "and click Build trusted source. SkylineDock will detect the tools automatically." + ), + bg=COLORS["panel_alt"], + fg=COLORS["text"], + font=("Segoe UI Semibold", 9), + justify=LEFT, + wraplength=590, + padx=14, + pady=12, + ).pack(fill=X, pady=(2, 18)) + ttk.Button( + content, + text="Close", + style="Primary.TButton", + command=dialog.destroy, + ).pack(anchor="e") + + dialog.update_idletasks() + x = self.root.winfo_rootx() + max( + 0, (self.root.winfo_width() - dialog.winfo_width()) // 2 + ) + y = self.root.winfo_rooty() + max( + 0, (self.root.winfo_height() - dialog.winfo_height()) // 2 + ) + dialog.geometry(f"+{x}+{y}") + dialog.deiconify() + dialog.grab_set() + + @staticmethod + def _add_requirement( + parent: tk.Widget, + title: str, + explanation: str, + button_text: str, + url: str, + ) -> None: + panel = tk.Frame(parent, bg=COLORS["panel_alt"], padx=14, pady=12) + panel.pack(fill=X, pady=(0, 10)) + copy = tk.Frame(panel, bg=COLORS["panel_alt"]) + copy.pack(side=LEFT, fill=X, expand=True) + tk.Label( + copy, + text=title, + bg=COLORS["panel_alt"], + fg=COLORS["text"], + font=("Segoe UI Semibold", 10), + ).pack(anchor="w") + tk.Label( + copy, + text=explanation, + bg=COLORS["panel_alt"], + fg=COLORS["muted"], + font=("Segoe UI", 9), + justify=LEFT, + wraplength=430, + ).pack(anchor="w", pady=(3, 0)) + ttk.Button( + panel, + text=button_text, + style="Secondary.TButton", + command=lambda: webbrowser.open(url), + ).pack(side=RIGHT, padx=(16, 0)) + def _source_build_succeeded(self, destination: Path) -> None: self.status_badge.configure(text="BUILT & INSTALLED", bg=COLORS["good"], fg="#07111A") self.footer.configure(text=f"Installed: {destination}", fg=COLORS["good"]) @@ -500,6 +679,21 @@ def _source_build_failed(self, message: str) -> None: self.open_button.configure(state="normal") messagebox.showerror("Source build failed", message) + @staticmethod + def _save_source_build_log(log_text: str | None) -> Path | None: + if not log_text: + return None + + try: + log_directory = default_settings_path().parent / "logs" + log_directory.mkdir(parents=True, exist_ok=True) + timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S-%fZ") + log_path = log_directory / f"source-build-{timestamp}.log" + log_path.write_text(log_text, encoding="utf-8") + except OSError: + return None + return log_path + def _set_details(self, value: str) -> None: self.details.configure(state="normal") self.details.delete("1.0", END) diff --git a/skylinedock/source_builder.py b/skylinedock/source_builder.py index aaca3cd..52ca2f8 100644 --- a/skylinedock/source_builder.py +++ b/skylinedock/source_builder.py @@ -5,6 +5,7 @@ import re import shutil import subprocess +import textwrap import zipfile from collections.abc import Callable from dataclasses import dataclass, field @@ -17,7 +18,21 @@ class SourceBuildError(RuntimeError): - pass + def __init__(self, message: str, diagnostic_log: str | None = None) -> None: + super().__init__(message) + self.diagnostic_log = diagnostic_log + + +@dataclass(frozen=True, slots=True) +class DotNetRuntimeRequirement: + framework: str + version: str + source: Path + + @property + def family(self) -> str: + parts = self.version.split(".") + return ".".join(parts[:2]) if len(parts) >= 2 else self.version @dataclass(slots=True) @@ -40,6 +55,7 @@ class SourceBuildPrerequisites: tool_path: Path | None dotnet_executable: str | None npm_executable: str | None + missing_dotnet_runtimes: list[DotNetRuntimeRequirement] = field(default_factory=list) issues: list[str] = field(default_factory=list) @property @@ -98,17 +114,31 @@ def check_source_build_prerequisites( "Cities: Skylines II was not detected in Steam; choose the game folder manually." ) - tool_value = os.environ.get("CSII_TOOLPATH") - tool_path = Path(tool_value).expanduser() if tool_value else None - if tool_path is None or not (tool_path / "Mod.props").is_file() or not (tool_path / "Mod.targets").is_file(): + tool_path = _find_modding_toolchain(selected_game_path) + if tool_path is None: issues.append( "The official CS2 modding toolchain is missing or CSII_TOOLPATH is not configured." ) dotnet = shutil.which("dotnet") + missing_dotnet_runtimes: list[DotNetRuntimeRequirement] = [] if dotnet is None: version = inspection.dotnet_sdk_version or "the required .NET SDK" issues.append(f"dotnet was not found; install {version} or a compatible newer SDK.") + elif tool_path is not None: + requirements = _find_toolchain_runtime_requirements(tool_path) + installed_runtimes = _list_dotnet_runtimes(dotnet) + missing_dotnet_runtimes = [ + requirement + for requirement in requirements + if not _runtime_requirement_is_satisfied(requirement, installed_runtimes) + ] + for requirement in missing_dotnet_runtimes: + issues.append( + "The CS2 ModPostProcessor requires " + f"{requirement.framework} {requirement.family}; install the .NET " + f"{requirement.family} x64 Runtime." + ) npm = shutil.which("npm") if inspection.ui_directories and npm is None: @@ -120,10 +150,95 @@ def check_source_build_prerequisites( tool_path=tool_path, dotnet_executable=dotnet, npm_executable=npm, + missing_dotnet_runtimes=missing_dotnet_runtimes, issues=issues, ) +def _find_modding_toolchain(game_path: Path | None) -> Path | None: + """Find the official toolchain without requiring customers to configure Windows.""" + + candidates: list[Path] = [] + configured = os.environ.get("CSII_TOOLPATH", "").strip().strip('"') + if configured: + candidates.append(Path(configured).expanduser()) + + if game_path is not None: + candidates.extend( + [ + game_path / "Cities2_Data" / "Content" / "Game" / ".ModdingToolchain", + game_path / ".ModdingToolchain", + ] + ) + + for candidate in candidates: + if (candidate / "Mod.props").is_file() and (candidate / "Mod.targets").is_file(): + return candidate.resolve() + return None + + +def _find_toolchain_runtime_requirements(tool_path: Path) -> list[DotNetRuntimeRequirement]: + """Read framework requirements for build-time executables in the official toolchain.""" + + requirements: list[DotNetRuntimeRequirement] = [] + configs = sorted(tool_path.rglob("ModPostProcessor.runtimeconfig.json")) + for config in configs: + try: + runtime_options = json.loads(config.read_text(encoding="utf-8-sig"))["runtimeOptions"] + except (OSError, KeyError, TypeError, ValueError, UnicodeError): + continue + + frameworks: list[dict[str, object]] = [] + framework = runtime_options.get("framework") + if isinstance(framework, dict): + frameworks.append(framework) + configured_frameworks = runtime_options.get("frameworks") + if isinstance(configured_frameworks, list): + frameworks.extend(item for item in configured_frameworks if isinstance(item, dict)) + + for item in frameworks: + name = item.get("name") + version = item.get("version") + if isinstance(name, str) and isinstance(version, str): + requirement = DotNetRuntimeRequirement(name, version, config) + if requirement not in requirements: + requirements.append(requirement) + return requirements + + +def _list_dotnet_runtimes(dotnet: str) -> set[tuple[str, str]]: + try: + completed = subprocess.run( + [dotnet, "--list-runtimes"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + timeout=15, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return set() + + runtimes: set[tuple[str, str]] = set() + for line in completed.stdout.splitlines(): + match = re.match(r"^(\S+)\s+(\d+(?:\.\d+){1,3})\s+\[", line.strip()) + if match: + runtimes.add((match.group(1), match.group(2))) + return runtimes + + +def _runtime_requirement_is_satisfied( + requirement: DotNetRuntimeRequirement, + installed: set[tuple[str, str]], +) -> bool: + return any( + framework == requirement.framework and version.startswith(f"{requirement.family}.") + for framework, version in installed + ) + + def build_trusted_source( report: ScanReport, work_root: str | Path, @@ -155,9 +270,14 @@ def build_trusted_source( source_dir.mkdir(parents=True, exist_ok=True) user_data_dir.mkdir(parents=True, exist_ok=True) _copy_source(report, source_dir) + msbuild_overlay = _write_msbuild_overlay(root) env = os.environ.copy() env["CSII_USERDATAPATH"] = str(user_data_dir) + # Mod.props reads CSII_LOCALMODSPATH independently from CSII_USERDATAPATH. + # Redirect both so a trusted-source build cannot deploy into the player's + # live Mods directory before SkylineDock has scanned and approved it. + env["CSII_LOCALMODSPATH"] = str(user_data_dir / "Mods") if prerequisites.tool_path: env["CSII_TOOLPATH"] = str(prerequisites.tool_path) @@ -190,6 +310,9 @@ def build_trusted_source( "--configuration", "Release", "--nologo", + f"--property:UserDataPath={user_data_dir}", + f"--property:LocalModsPath={user_data_dir / 'Mods'}", + f"--property:CustomAfterMicrosoftCommonTargets={msbuild_overlay}", ] _execute(command_runner, command, project_root, env, logs) @@ -204,7 +327,8 @@ def build_trusted_source( if not candidates: raise SourceBuildError( - "The build completed but did not produce a valid mod in the redirected Mods folder." + "The build completed but did not produce a valid mod in the redirected Mods folder.", + diagnostic_log="\n\n".join(logs), ) expected = inspection.mod_name.casefold() @@ -214,11 +338,73 @@ def build_trusted_source( ) if compiled is None: names = ", ".join(item.display_name for item in candidates) - raise SourceBuildError(f"The build produced multiple ambiguous mods: {names}") + raise SourceBuildError( + f"The build produced multiple ambiguous mods: {names}", + diagnostic_log="\n\n".join(logs), + ) return SourceBuildResult(compiled.source_path, compiled, logs) +def _write_msbuild_overlay(root: Path) -> Path: + """Create an out-of-tree MSBuild hook for official CS2 runtime references. + + The desktop .NET Framework reference pack and Unity's mscorlib share the + same assembly identity. ResolveAssemblyReference may choose the desktop + copy even when a mod points at the game DLL. The game's System.Memory is a + facade that expects Span and Index in Unity's mscorlib, so compiling + against the desktop copy produces CS0518/CS0656 failures. + """ + + overlay = root / "skylinedock.cs2.targets" + overlay.write_text( + textwrap.dedent( + """\ + + + + + + false + + + + + false + $(ManagedPath)\\mscorlib.dll + + + + + + + false + + + + + false + $(ManagedPath)\\System.Memory.dll + + + + + + + """ + ), + encoding="utf-8", + ) + return overlay + + def _inspect_zip(report: ScanReport) -> SourceBuildInspection: with zipfile.ZipFile(report.source_path) as archive: entries = { @@ -364,8 +550,31 @@ def _execute( result = runner(command, cwd, env) logs.append(f"> {' '.join(command)}\n{result.output}".rstrip()) if result.return_code != 0: - tail = result.output[-4_000:] - raise SourceBuildError(f"Build command failed ({result.return_code}):\n{tail}") + raise SourceBuildError( + _summarize_command_failure(result), + diagnostic_log="\n\n".join(logs), + ) + + +def _summarize_command_failure(result: CommandResult) -> str: + if result.return_code in {-2147450730, 0x80008096}: + return ( + "A CS2 build tool could not start because its required .NET Runtime is missing. " + "Close SkylineDock, install the runtime named by the toolchain setup screen, " + "then try again." + ) + + lines = [line.strip() for line in result.output.splitlines() if line.strip()] + interesting = [ + line + for line in lines + if re.search(r"\b(error|failed|exception|exited with code)\b", line, re.IGNORECASE) + ] + selected = interesting[-20:] if interesting else lines[-20:] + excerpt = "\n".join(line[:1_200] for line in selected) + if not excerpt: + excerpt = "The command returned no diagnostic output." + return f"Build command failed ({result.return_code}):\n{excerpt}" def _run_command(command: list[str], cwd: Path, env: dict[str, str]) -> CommandResult: diff --git a/tests/test_source_builder.py b/tests/test_source_builder.py index b5f34a6..d6a1834 100644 --- a/tests/test_source_builder.py +++ b/tests/test_source_builder.py @@ -4,6 +4,7 @@ import unittest import zipfile from pathlib import Path +from unittest.mock import patch from skylinedock.models import PackageKind from skylinedock.scanner import ArchiveScanner @@ -97,13 +98,93 @@ def test_accepts_a_manually_selected_game_folder(self) -> None: self.assertEqual(game.resolve(), prerequisites.steam_game_path) self.assertFalse(any("selected game folder" in issue for issue in prerequisites.issues)) + def test_finds_toolchain_inside_selected_game_folder(self) -> None: + game = self.root / "Cities Skylines II" + game.mkdir() + (game / "Cities2.exe").write_bytes(b"MZ") + tools = game / "Cities2_Data" / "Content" / "Game" / ".ModdingToolchain" + tools.mkdir(parents=True) + (tools / "Mod.props").write_text("") + (tools / "Mod.targets").write_text("") + + prerequisites = check_source_build_prerequisites( + inspect_source_build(self.report), + game_path=game, + ) + + self.assertEqual(tools.resolve(), prerequisites.tool_path) + self.assertFalse(any("CSII_TOOLPATH" in issue for issue in prerequisites.issues)) + + def test_reports_the_exact_runtime_required_by_the_toolchain(self) -> None: + game = self.root / "Cities Skylines II" + game.mkdir() + (game / "Cities2.exe").write_bytes(b"MZ") + tools = game / "Cities2_Data" / "Content" / "Game" / ".ModdingToolchain" + processor = tools / "ModPostProcessor" + processor.mkdir(parents=True) + (tools / "Mod.props").write_text("") + (tools / "Mod.targets").write_text("") + (processor / "ModPostProcessor.runtimeconfig.json").write_text( + '{"runtimeOptions":{"tfm":"net6.0","framework":' + '{"name":"Microsoft.NETCore.App","version":"6.0.0"}}}' + ) + + with ( + patch("skylinedock.source_builder.shutil.which", side_effect=lambda name: name), + patch( + "skylinedock.source_builder._list_dotnet_runtimes", + return_value={("Microsoft.NETCore.App", "8.0.29")}, + ), + ): + prerequisites = check_source_build_prerequisites( + inspect_source_build(self.report), + game_path=game, + ) + + self.assertEqual(1, len(prerequisites.missing_dotnet_runtimes)) + self.assertEqual("6.0", prerequisites.missing_dotnet_runtimes[0].family) + self.assertTrue(any("6.0 x64 Runtime" in issue for issue in prerequisites.issues)) + + def test_accepts_an_installed_runtime_from_the_required_family(self) -> None: + game = self.root / "Cities Skylines II" + game.mkdir() + (game / "Cities2.exe").write_bytes(b"MZ") + tools = game / "Cities2_Data" / "Content" / "Game" / ".ModdingToolchain" + processor = tools / "ModPostProcessor" + processor.mkdir(parents=True) + (tools / "Mod.props").write_text("") + (tools / "Mod.targets").write_text("") + (processor / "ModPostProcessor.runtimeconfig.json").write_text( + '{"runtimeOptions":{"framework":' + '{"name":"Microsoft.NETCore.App","version":"6.0.0"}}}' + ) + + with ( + patch("skylinedock.source_builder.shutil.which", side_effect=lambda name: name), + patch( + "skylinedock.source_builder._list_dotnet_runtimes", + return_value={ + ("Microsoft.NETCore.App", "6.0.36"), + ("Microsoft.NETCore.App", "8.0.29"), + }, + ), + ): + prerequisites = check_source_build_prerequisites( + inspect_source_build(self.report), + game_path=game, + ) + + self.assertEqual([], prerequisites.missing_dotnet_runtimes) + self.assertFalse(any("6.0 x64 Runtime" in issue for issue in prerequisites.issues)) + def test_build_redirects_output_and_validates_compiled_mod(self) -> None: commands: list[list[str]] = [] + work_root = (self.root / "work").resolve() def fake_runner(command: list[str], cwd: Path, env: dict[str, str]) -> CommandResult: commands.append(command) if "build" in command: - output = Path(env["CSII_USERDATAPATH"]) / "Mods" / "Traffic" + output = Path(env["CSII_LOCALMODSPATH"]) / "Traffic" output.mkdir(parents=True) (output / "Traffic.dll").write_bytes(b"MZ compiled") (output / "Traffic.mjs").write_text("export {};") @@ -111,7 +192,7 @@ def fake_runner(command: list[str], cwd: Path, env: dict[str, str]) -> CommandRe result = build_trusted_source( self.report, - self.root / "work", + work_root, trusted_source_confirmed=True, prerequisites=self.prerequisites(), runner=fake_runner, @@ -121,6 +202,47 @@ def fake_runner(command: list[str], cwd: Path, env: dict[str, str]) -> CommandRe self.assertEqual("Traffic", result.compiled_report.display_name) self.assertEqual("ci", commands[0][1]) self.assertEqual("build", commands[1][1]) + self.assertIn( + f"--property:UserDataPath={work_root / 'build-user-data'}", + commands[1], + ) + self.assertIn( + f"--property:LocalModsPath={work_root / 'build-user-data' / 'Mods'}", + commands[1], + ) + overlay_argument = next( + argument + for argument in commands[1] + if argument.startswith("--property:CustomAfterMicrosoftCommonTargets=") + ) + overlay_path = Path(overlay_argument.split("=", 1)[1]) + overlay = overlay_path.read_text(encoding="utf-8") + self.assertIn("SkylineDockUseGameRuntimeReferences", overlay) + self.assertIn("$(ManagedPath)\\mscorlib.dll", overlay) + self.assertIn("$(ManagedPath)\\System.Memory.dll", overlay) + self.assertEqual( + work_root / "build-user-data" / "Mods", + result.output_directory.parent, + ) + + def test_failed_command_keeps_a_full_diagnostic_log(self) -> None: + def fake_runner(command: list[str], cwd: Path, env: dict[str, str]) -> CommandResult: + if command[1] == "ci": + return CommandResult(0, "npm completed") + return CommandResult(1, "first detail\nerror CS0518: System.Index is missing") + + with self.assertRaises(SourceBuildError) as caught: + build_trusted_source( + self.report, + self.root / "work", + trusted_source_confirmed=True, + prerequisites=self.prerequisites(), + runner=fake_runner, + ) + + self.assertIn("CS0518", str(caught.exception)) + self.assertIn("npm completed", caught.exception.diagnostic_log or "") + self.assertIn("first detail", caught.exception.diagnostic_log or "") if __name__ == "__main__":