Files
WT-Offline/tools/src/wtotools/guipatch.py
T
N0VAN0M4LY db981ab834 refactor(patches)!: migrate definitions to JSONC and script fragments
Patch definitions under exe-patches/ and gui-patches/ move from
patch.json/locate.json to patch.jsonc/locate.jsonc. Each file now holds
only the data needed to apply the patch plus a short English comment
stating what it changes, why the local service cannot provide it, and
what happens without it. Every definition records the game versions it
was verified on (verified_on, required).

GUI patches keep their stock text and replacement in find.nut and
replace.nut next to patch.jsonc instead of escaped JSON strings, so the
script edits are readable, diffable and can carry Quirrel comments.
Matching treats CRLF and LF as the same line break because stock
scripts mix both; only the matched span is rewritten.

Loaders on both sides (packages/build, packages/exepatch, wtotools)
reject unknown keys so analysis text cannot creep back into the data.
JSONC parsing moves into a shared @wto/jsonc package; the build now
parses tuning/store.jsonc instead of scanning it with a regex.

Verified: npm run typecheck; check-patches (10/10 ready on 2.61.0.37);
check-gui (33 patches, 24 scripts compile); the TypeScript and Python
appliers produce identical scripts, byte-identical to the previous
definitions except one stock script with mixed line endings.

The 15 battle patches are migrated mechanically and still carry the
pending-review comment; they are rewritten by the LocalMP review.

BREAKING CHANGE: Patch loaders require JSONC definitions. Migrate patch.json and locate.json and move embedded GUI edits to separate Quirrel files.
2026-11-28 03:24:12 +08:00

125 lines
5.2 KiB
Python

"""GUI script patch definitions, one folder per change under gui-patches/<domain>/<name>/.
patch.jsonc id, title, target script, features, game versions verified on, and the edits;
comments explain the change and why the local service cannot provide it
<name>.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/build/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,
)