Files
WT-Offline/tools/src/wtotools/guipatch.py
T
N0VAN0M4LY 27fc535301 Split the repository into apps, packages and patches
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
2026-11-29 03:20:54 +08:00

125 lines
5.2 KiB
Python

"""GUI script patch definitions, one folder per change under patches/gui/<domain>/<name>/.
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
<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/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,
)