"""GUI script patch definitions, one folder per change under patches/gui///. patch.jsonc id, title, target script, features, game versions verified on, and the edits; comments explain the change and why the local server cannot provide it .nut edit fragments named by `edits`: the stock text to find and its replacement Fragment files hold the exact script text followed by one terminating newline, which is not part of the fragment. Line endings are normalised to "\\n" here; `apply` matches regardless of the script's line endings (stock scripts mix "\\r\\n" and "\\n") and writes replacements with the script's dominant line ending. Same rules as packages/patcher/src/gui-patch-definition.ts. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path from . import jsonc PATCH_FILE = "patch.jsonc" ALLOWED_KEYS = frozenset({"id", "title", "file", "features", "verified_on", "edits"}) ENDPOINT_PLACEHOLDER = "{{LOCAL_ENDPOINT}}" @dataclass(frozen=True) class GuiEdit: find: str replace: str @dataclass(frozen=True) class GuiPatch: identifier: str title: str file: str features: tuple[str, ...] verified_on: tuple[str, ...] edits: tuple[GuiEdit, ...] directory: Path def load_gui_patches(root: Path) -> list[GuiPatch]: patches = [_read(path.parent) for path in sorted(root.rglob(PATCH_FILE))] seen: dict[str, Path] = {} for patch in patches: if patch.identifier in seen: raise ValueError(f"two GUI patches use id {patch.identifier!r}: {seen[patch.identifier]} and {patch.directory}") seen[patch.identifier] = patch.directory return sorted(patches, key=lambda item: item.identifier) def apply(text: str, patch: GuiPatch, endpoint: str) -> str: """`text` with every edit of `patch` applied; raises ValueError when an edit does not match once.""" newline = "\r\n" if "\r\n" in text else "\n" for number, edit in enumerate(patch.edits, start=1): replace = edit.replace.replace("\n", newline).replace(ENDPOINT_PLACEHOLDER, endpoint) text = _replace_unique(text, edit.find, replace, f"{patch.identifier} edit {number} in {patch.file}") return text def _replace_unique(text: str, find: str, replace: str, label: str) -> str: """Replace the single occurrence of `find` (written with "\\n" line endings), treating "\\r\\n" and "\\n" in the script as the same line break; stock scripts mix both. Only the matched span changes, every other character of the script is kept.""" # For every normalized character, where its original sequence starts ("\r\n" maps to its "\r"). original: list[int] = [] kept: list[str] = [] index = 0 while index < len(text): original.append(index) if text[index] == "\r" and text[index + 1:index + 2] == "\n": kept.append("\n") index += 2 else: kept.append(text[index]) index += 1 original.append(len(text)) normalized = "".join(kept) first = normalized.find(find) if first == -1: raise ValueError(f"{label}: stock text not found") if normalized.find(find, first + len(find)) != -1: raise ValueError(f"{label}: stock text appears more than once") return text[:original[first]] + replace + text[original[first + len(find)]:] def read_fragment(directory: Path, name: str) -> str: if "/" in name or "\\" in name: raise ValueError(f"{directory}: fragment {name!r} must be a file in the patch folder") text = (directory / name).read_text("utf-8-sig").replace("\r\n", "\n") return text[:-1] if text.endswith("\n") else text def _read(directory: Path) -> GuiPatch: where = directory / PATCH_FILE raw = jsonc.load_object(where) unknown = sorted(set(raw) - ALLOWED_KEYS) if unknown: raise ValueError(f"{where}: unknown key(s) {', '.join(unknown)}; explanations belong in comments or the patch notes") for key in ("id", "title", "file"): if not isinstance(raw.get(key), str) or not raw[key]: raise ValueError(f"{where}: {key!r} must be a non-empty string") verified_on = tuple(str(item) for item in raw.get("verified_on", ())) if not verified_on: raise ValueError(f"{where}: 'verified_on' must name at least one game version") edits_raw = raw.get("edits") if not isinstance(edits_raw, list) or not edits_raw: raise ValueError(f"{where}: 'edits' must be a non-empty list") edits = [] for number, item in enumerate(edits_raw, start=1): if not isinstance(item, dict) or not isinstance(item.get("find"), str) or not isinstance(item.get("replace"), str): raise ValueError(f"{where}: edit {number} needs fragment file names 'find' and 'replace'") find = read_fragment(directory, item["find"]) if not find: raise ValueError(f"{where}: edit {number} has an empty 'find' fragment") edits.append(GuiEdit(find=find, replace=read_fragment(directory, item["replace"]))) return GuiPatch( identifier=raw["id"], title=raw["title"], file=raw["file"], features=tuple(str(item) for item in raw.get("features", ())), verified_on=verified_on, edits=tuple(edits), directory=directory, )