Let each patch carry variants written for different game builds
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.
This commit is contained in:
1 parent
3f366651bd
commit
b819912733
94 files changed
+1884
-933
No files matched your search
@@ -1,8 +1,11 @@
|
||||
"""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
|
||||
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
|
||||
@@ -15,9 +18,13 @@ 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"
|
||||
ALLOWED_KEYS = frozenset({"id", "title", "file", "features", "verified_on", "edits"})
|
||||
PATCH_KEYS = frozenset({"id", "title", "features", "variants"})
|
||||
VARIANT_KEYS = frozenset({"written_for", "file", "edits"})
|
||||
ENDPOINT_PLACEHOLDER = "{{LOCAL_ENDPOINT}}"
|
||||
|
||||
|
||||
@@ -27,17 +34,26 @@ class GuiEdit:
|
||||
replace: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GuiVariant:
|
||||
written_for: str
|
||||
file: str
|
||||
edits: tuple[GuiEdit, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GuiPatch:
|
||||
identifier: str
|
||||
title: str
|
||||
file: str
|
||||
features: tuple[str, ...]
|
||||
verified_on: tuple[str, ...]
|
||||
edits: tuple[GuiEdit, ...]
|
||||
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] = {}
|
||||
@@ -48,12 +64,27 @@ def load_gui_patches(root: Path) -> list[GuiPatch]:
|
||||
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."""
|
||||
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(patch.edits, start=1):
|
||||
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"{patch.identifier} edit {number} in {patch.file}")
|
||||
text = _replace_unique(text, edit.find, replace, f"edit {number} in {variant.file}")
|
||||
return text
|
||||
|
||||
|
||||
@@ -77,9 +108,9 @@ def _replace_unique(text: str, find: str, replace: str, label: str) -> str:
|
||||
normalized = "".join(kept)
|
||||
first = normalized.find(find)
|
||||
if first == -1:
|
||||
raise ValueError(f"{label}: stock text not found")
|
||||
raise GuiPatchMismatch(f"{label}: stock text not found")
|
||||
if normalized.find(find, first + len(find)) != -1:
|
||||
raise ValueError(f"{label}: stock text appears more than once")
|
||||
raise GuiPatchMismatch(f"{label}: stock text appears more than once")
|
||||
return text[:original[first]] + replace + text[original[first + len(find)]:]
|
||||
|
||||
|
||||
@@ -93,32 +124,34 @@ def read_fragment(directory: Path, name: str) -> str:
|
||||
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"):
|
||||
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")
|
||||
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")
|
||||
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 not isinstance(item.get("find"), str) or not isinstance(item.get("replace"), str):
|
||||
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 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,
|
||||
)
|
||||
return GuiVariant(written_for=raw["written_for"], file=raw["file"], edits=tuple(edits))
|
||||
Reference in new issue
Block a user