A game update used to fail a patch whenever any byte it compared moved, even when only an address in the instruction changed. Patch definitions now say what a change needs and read the rest from the code: - patch.jsonc holds a list of variants, each written for one game build (written_for) with its own locate block and edit; locate.jsonc is merged into it. Exactly one variant must apply, otherwise the patch is left out. GUI script patches use the same variants rule. - expect_original and the bytes to write use the signature syntax, so addresses that differ between builds can be wildcards. - A locate block can capture values at the site (rel32 targets, immediates, displacements); a rel32 fixup fills a hole in the written bytes from a capture. allow-local-host-bot-spawns now jumps to the target of the conditional jump it replaces instead of a stored distance, which makes it apply to 2.61.0.43 as well. - verified_on is gone from the definitions. patches/versions/<version>.jsonc records, per checked game build, which variant of every patch applies and where; scripts/record-game-version.ts writes it and the launcher reads the recorded versions from there. The Python tools (check-patches, patch-exe, check-gui) read the same format; check-patches assembles a variant whose assembly names captures at the site it was located at. Checked: root and launcher type checks; check-patches and check-gui on 2.61.0.37 and 2.61.0.43 (12 exe and 35 GUI patches each); check-patches and check-gui report a deliberately broken patch with a non-zero exit; build-game-copy from 2.61.0.43 into a temporary folder. The computed bytes of allow-local-host-bot-spawns on 2.61.0.37 equal the bytes it stored before. BREAKING CHANGE: Each patch needs a variants list. Move executable locators into patch.jsonc and regenerate game version records with record-game-version.ts.
158 lines
6.6 KiB
Python
158 lines
6.6 KiB
Python
"""GUI script patch definitions, one folder per change under patches/gui/<domain>/<name>/.
|
|
|
|
patch.jsonc id, title, features, and the variants; comments explain the change and why the
|
|
local server cannot provide it
|
|
<name>.nut edit fragments a variant names: the stock text to find and its replacement
|
|
|
|
A variant is the change written for one game build: the target script and its edits. Exactly one
|
|
variant must apply (`select`), the same rule as exe patches.
|
|
|
|
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
|
|
from .exepatch.definition import reject_unknown_keys, variant_objects
|
|
from .exepatch.errors import PatchError
|
|
from .exepatch.variants import choose_variant
|
|
|
|
PATCH_FILE = "patch.jsonc"
|
|
PATCH_KEYS = frozenset({"id", "title", "features", "variants"})
|
|
VARIANT_KEYS = frozenset({"written_for", "file", "edits"})
|
|
ENDPOINT_PLACEHOLDER = "{{LOCAL_ENDPOINT}}"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GuiEdit:
|
|
find: str
|
|
replace: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GuiVariant:
|
|
written_for: str
|
|
file: str
|
|
edits: tuple[GuiEdit, ...]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GuiPatch:
|
|
identifier: str
|
|
title: str
|
|
features: tuple[str, ...]
|
|
variants: tuple[GuiVariant, ...]
|
|
directory: Path
|
|
|
|
|
|
class GuiPatchMismatch(PatchError):
|
|
"""The stock text of an edit was not found exactly once, or the target script is missing."""
|
|
|
|
|
|
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 select(files: dict[str, bytes], patch: GuiPatch, endpoint: str) -> tuple[GuiVariant, str]:
|
|
"""The variant of `patch` that applies to the scripts in `files` (lower-case paths) and its
|
|
target script with the edits made; raises PatchError when none or more than one applies."""
|
|
def attempt(variant: GuiVariant) -> str:
|
|
target = variant.file.lower()
|
|
if target not in files:
|
|
raise GuiPatchMismatch(f"the data pack has no script {target}")
|
|
return apply(files[target].decode("utf-8"), variant, endpoint)
|
|
|
|
try:
|
|
return choose_variant(patch.variants, attempt)
|
|
except PatchError as error:
|
|
raise PatchError(f"{patch.identifier}: {error}") from error
|
|
|
|
|
|
def apply(text: str, variant: GuiVariant, endpoint: str) -> str:
|
|
"""`text` with every edit of `variant` applied; raises GuiPatchMismatch when an edit does not match once."""
|
|
newline = "\r\n" if "\r\n" in text else "\n"
|
|
for number, edit in enumerate(variant.edits, start=1):
|
|
replace = edit.replace.replace("\n", newline).replace(ENDPOINT_PLACEHOLDER, endpoint)
|
|
text = _replace_unique(text, edit.find, replace, f"edit {number} in {variant.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 GuiPatchMismatch(f"{label}: stock text not found")
|
|
if normalized.find(find, first + len(find)) != -1:
|
|
raise GuiPatchMismatch(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)
|
|
reject_unknown_keys(raw, PATCH_KEYS, where)
|
|
for key in ("id", "title"):
|
|
if not isinstance(raw.get(key), str) or not raw[key]:
|
|
raise ValueError(f"{where}: {key!r} must be a non-empty string")
|
|
variants = tuple(_read_variant(directory, item, f"{where} variant {item['written_for']}")
|
|
for item in variant_objects(raw.get("variants"), where))
|
|
return GuiPatch(
|
|
identifier=raw["id"],
|
|
title=raw["title"],
|
|
features=tuple(str(item) for item in raw.get("features", ())),
|
|
variants=variants,
|
|
directory=directory,
|
|
)
|
|
|
|
|
|
def _read_variant(directory: Path, raw: dict, where: str) -> GuiVariant:
|
|
reject_unknown_keys(raw, VARIANT_KEYS, where)
|
|
if not isinstance(raw.get("file"), str) or not raw["file"]:
|
|
raise ValueError(f"{where}: 'file' must be a non-empty string")
|
|
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 set(item) != {"find", "replace"} or not all(isinstance(v, str) for v in item.values()):
|
|
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 GuiVariant(written_for=raw["written_for"], file=raw["file"], edits=tuple(edits))
|