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.
This commit is contained in:
1 parent
b260d2899e
commit
db981ab834
185 files changed
+2676
-1487
No files matched your search
@@ -2,10 +2,12 @@
|
||||
|
||||
One directory per change to the program's behaviour, under exe-patches/<domain>/<name>/:
|
||||
|
||||
patch.json what the program does now, what it does after the patch, why the
|
||||
executable has to change at all, which features depend on it, and the
|
||||
bytes to write
|
||||
locate.json how to find the site, and how that was established
|
||||
patch.jsonc id, title, features, required patches, the game versions it was verified
|
||||
on, and the bytes to write; comments explain the change and why the local
|
||||
service cannot provide it
|
||||
locate.jsonc how to find the site
|
||||
|
||||
Unknown keys are rejected so that explanations stay in comments and in the patch notes.
|
||||
|
||||
The engine reads these; it holds no knowledge about any particular patch. Keeping the
|
||||
definitions as data is what lets the installer report exactly which changes did not apply
|
||||
@@ -13,14 +15,17 @@ and which features are affected.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .. import jsonc
|
||||
from .errors import DefinitionError
|
||||
|
||||
PATCH_FILE = "patch.json"
|
||||
LOCATE_FILE = "locate.json"
|
||||
PATCH_FILE = "patch.jsonc"
|
||||
LOCATE_FILE = "locate.jsonc"
|
||||
PATCH_KEYS = frozenset({"id", "title", "features", "requires", "verified_on", "edit"})
|
||||
EDIT_KEYS = frozenset({"offset", "asm", "data", "bytes", "expect_original"})
|
||||
LOCATE_KEYS = frozenset({"method", "section", "pattern"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -47,10 +52,10 @@ class PatchDefinition:
|
||||
title: str
|
||||
features: tuple[str, ...]
|
||||
requires: tuple[str, ...]
|
||||
verified_on: tuple[str, ...]
|
||||
edit: PatchEdit
|
||||
locate: dict
|
||||
directory: Path | None = None
|
||||
notes: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def locate_method(self) -> str:
|
||||
@@ -68,27 +73,39 @@ def load_patches(root: Path) -> list[PatchDefinition]:
|
||||
def _read(directory: Path) -> PatchDefinition:
|
||||
patch = _read_json(directory / PATCH_FILE)
|
||||
locate = _read_json(directory / LOCATE_FILE)
|
||||
_reject_unknown_keys(patch, PATCH_KEYS, directory / PATCH_FILE)
|
||||
_reject_unknown_keys(locate, LOCATE_KEYS, directory / LOCATE_FILE)
|
||||
for key in ("id", "title", "edit"):
|
||||
if key not in patch:
|
||||
raise DefinitionError(f"{directory / PATCH_FILE}: missing key {key!r}")
|
||||
if "method" not in locate:
|
||||
raise DefinitionError(f"{directory / LOCATE_FILE}: missing key 'method'")
|
||||
verified_on = tuple(str(item) for item in patch.get("verified_on", ()))
|
||||
if not verified_on:
|
||||
raise DefinitionError(f"{directory / PATCH_FILE}: 'verified_on' must name at least one game version")
|
||||
return PatchDefinition(
|
||||
identifier=str(patch["id"]),
|
||||
title=str(patch["title"]),
|
||||
features=tuple(str(item) for item in patch.get("features", ())),
|
||||
requires=tuple(str(item) for item in patch.get("requires", ())),
|
||||
verified_on=verified_on,
|
||||
edit=_read_edit(directory, patch["edit"]),
|
||||
locate=locate,
|
||||
directory=directory,
|
||||
notes={key: value for key, value in patch.items()
|
||||
if key not in ("id", "title", "features", "requires", "edit")},
|
||||
)
|
||||
|
||||
|
||||
def _reject_unknown_keys(data: dict, allowed: frozenset[str], where: Path) -> None:
|
||||
unknown = sorted(set(data) - allowed)
|
||||
if unknown:
|
||||
raise DefinitionError(f"{where}: unknown key(s) {', '.join(unknown)}; "
|
||||
"explanations belong in comments or the patch notes")
|
||||
|
||||
|
||||
def _read_edit(directory: Path, raw: object) -> PatchEdit:
|
||||
if not isinstance(raw, dict):
|
||||
raise DefinitionError(f"{directory / PATCH_FILE}: 'edit' must be an object")
|
||||
_reject_unknown_keys(raw, EDIT_KEYS, directory / PATCH_FILE)
|
||||
for key in ("bytes", "expect_original"):
|
||||
if not isinstance(raw.get(key), str):
|
||||
raise DefinitionError(f"{directory / PATCH_FILE}: edit needs a hex string {key!r}")
|
||||
@@ -109,15 +126,10 @@ def _hex(directory: Path, key: str, text: str) -> bytes:
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict:
|
||||
if not path.is_file():
|
||||
raise DefinitionError(f"{path}: file not found")
|
||||
try:
|
||||
data = json.loads(path.read_text("utf-8"))
|
||||
except json.JSONDecodeError as error:
|
||||
raise DefinitionError(f"{path}: invalid JSON: {error}") from error
|
||||
if not isinstance(data, dict):
|
||||
raise DefinitionError(f"{path}: expected a JSON object")
|
||||
return data
|
||||
return jsonc.load_object(path)
|
||||
except ValueError as error:
|
||||
raise DefinitionError(str(error)) from error
|
||||
|
||||
|
||||
def _reject_duplicate_ids(definitions: list[PatchDefinition]) -> None:
|
||||
|
||||
@@ -8,13 +8,13 @@ with the target script's real `gui.vromfs.bin` imports runs the full `SQParser`
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .guipatch import apply, load_gui_patches
|
||||
from .vromfs import Archive, read_archive
|
||||
|
||||
MOUNT_PREFIXES: tuple[tuple[str, str], ...] = (
|
||||
@@ -112,54 +112,48 @@ def verify_gui_patches(
|
||||
endpoint: str = "127.0.0.1:47115",
|
||||
) -> GuiCheckReport:
|
||||
archive = read_archive(gui_pack_path.read_bytes())
|
||||
patch_files = sorted(patches_dir.rglob("patch.json"))
|
||||
patches = load_gui_patches(patches_dir)
|
||||
touched_files: list[str] = []
|
||||
errors: list[str] = []
|
||||
|
||||
for patch_path in patch_files:
|
||||
raw = json.loads(patch_path.read_text(encoding="utf-8"))
|
||||
target = raw["file"].lower()
|
||||
for patch in patches:
|
||||
target = patch.file.lower()
|
||||
if target not in archive.files:
|
||||
errors.append(f"{raw['id']}: missing file {target} in gui.vromfs.bin")
|
||||
errors.append(f"{patch.identifier}: missing file {target} in gui.vromfs.bin")
|
||||
continue
|
||||
current = archive.files[target].decode("utf-8")
|
||||
find_text = raw["edit"]["find"]
|
||||
first = current.find(find_text)
|
||||
if first == -1:
|
||||
errors.append(f"{raw['id']}: target snippet not found in {target}")
|
||||
if any("`" in edit.replace for edit in patch.edits):
|
||||
errors.append(f"{patch.identifier}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +")
|
||||
continue
|
||||
if current.find(find_text, first + len(find_text)) != -1:
|
||||
errors.append(f"{raw['id']}: target snippet appears more than once in {target}")
|
||||
try:
|
||||
updated = apply(archive.files[target].decode("utf-8"), patch, endpoint)
|
||||
except ValueError as error:
|
||||
errors.append(str(error))
|
||||
continue
|
||||
replace_text = raw["edit"]["replace"].replace("{{LOCAL_ENDPOINT}}", endpoint)
|
||||
if "`" in replace_text:
|
||||
errors.append(f"{raw['id']}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +")
|
||||
continue
|
||||
updated = current[:first] + replace_text + current[first + len(find_text):]
|
||||
archive.put(target, updated.encode("utf-8"))
|
||||
if target not in touched_files:
|
||||
touched_files.append(target)
|
||||
|
||||
if errors:
|
||||
return GuiCheckReport(len(patch_files), 0, tuple(errors))
|
||||
return GuiCheckReport(len(patches), 0, tuple(errors))
|
||||
|
||||
export_cache: dict[str, set[str]] = {}
|
||||
native_syms = _collect_all_named_imports(archive)
|
||||
stock_archive = read_archive(gui_pack_path.read_bytes())
|
||||
|
||||
for patch_path in patch_files:
|
||||
raw = json.loads(patch_path.read_text(encoding="utf-8"))
|
||||
target = raw["file"].lower()
|
||||
for patch in patches:
|
||||
target = patch.file.lower()
|
||||
stock_src = stock_archive.files[target].decode("utf-8")
|
||||
imp_names, imp_classes = _resolve_file_bindings(stock_src, stock_archive, export_cache, native_syms)
|
||||
reserved = (imp_names | imp_classes) - set(MODULE_BUILTINS)
|
||||
new_locals = _declared_locals(raw["edit"]["replace"]) - _declared_locals(raw["edit"]["find"])
|
||||
new_locals: set[str] = set()
|
||||
for edit in patch.edits:
|
||||
new_locals |= _declared_locals(edit.replace) - _declared_locals(edit.find)
|
||||
collisions = sorted(new_locals & reserved)
|
||||
if collisions:
|
||||
errors.append(f"{raw['id']}: local binding(s) {collisions} conflict with module imports in {target}")
|
||||
errors.append(f"{patch.identifier}: local binding(s) {collisions} conflict with module imports in {target}")
|
||||
|
||||
if errors:
|
||||
return GuiCheckReport(len(patch_files), 0, tuple(errors))
|
||||
return GuiCheckReport(len(patches), 0, tuple(errors))
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="wto-gui-check-") as tmp:
|
||||
tmp_dir = Path(tmp)
|
||||
@@ -191,7 +185,7 @@ def verify_gui_patches(
|
||||
if line.strip():
|
||||
errors.append(line.strip())
|
||||
|
||||
return GuiCheckReport(len(patch_files), len(touched_files), tuple(errors))
|
||||
return GuiCheckReport(len(patches), len(touched_files), tuple(errors))
|
||||
|
||||
|
||||
def _resolve_vromfs_path(spec: str) -> str | None:
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""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,
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""JSON with comments: the format of the patch definitions and the local service's tuning files.
|
||||
|
||||
Line comments (//) and block comments are blanked out, outside string literals only; the rest
|
||||
goes to json.loads, so error positions still match the file. Same rules as the TypeScript
|
||||
reader in packages/jsonc.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def loads(text: str):
|
||||
return json.loads(_strip_comments(text))
|
||||
|
||||
|
||||
def load_object(path: Path) -> dict:
|
||||
"""The object stored in `path`; raises ValueError naming the file when it is not one."""
|
||||
if not path.is_file():
|
||||
raise ValueError(f"{path}: file not found")
|
||||
try:
|
||||
data = loads(path.read_text("utf-8-sig"))
|
||||
except json.JSONDecodeError as error:
|
||||
raise ValueError(f"{path}: invalid JSON: {error}") from error
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"{path}: expected a JSON object")
|
||||
return data
|
||||
|
||||
|
||||
def _strip_comments(text: str) -> str:
|
||||
out: list[str] = []
|
||||
index = 0
|
||||
length = len(text)
|
||||
while index < length:
|
||||
ch = text[index]
|
||||
nxt = text[index + 1] if index + 1 < length else ""
|
||||
if ch == '"':
|
||||
end = _string_end(text, index)
|
||||
out.append(text[index:end])
|
||||
index = end
|
||||
elif ch == "/" and nxt == "/":
|
||||
while index < length and text[index] != "\n":
|
||||
index += 1
|
||||
elif ch == "/" and nxt == "*":
|
||||
end = text.find("*/", index + 2)
|
||||
stop = length if end < 0 else end + 2
|
||||
out.append("".join("\n" if c == "\n" else " " for c in text[index:stop]))
|
||||
index = stop
|
||||
else:
|
||||
out.append(ch)
|
||||
index += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _string_end(text: str, start: int) -> int:
|
||||
index = start + 1
|
||||
while index < len(text):
|
||||
if text[index] == "\\":
|
||||
index += 2
|
||||
elif text[index] == '"':
|
||||
return index + 1
|
||||
else:
|
||||
index += 1
|
||||
return len(text)
|
||||
Reference in new issue
Block a user