"""Patch definitions as they are stored on disk. One directory per change to the program's behaviour, under exe-patches///: 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 and which features are affected. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path from .. import jsonc from .errors import DefinitionError 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) class PatchEdit: """Bytes to write, and the bytes that must already be there.""" offset: int payload: bytes expect_original: bytes asm: tuple[str, ...] # For edits to constant data (strings) instead of code: {"encoding": ..., "text": ...}. # The text, encoded and padded with zero bytes to the edit's length, must equal the payload. data: dict | None = None def __post_init__(self) -> None: if len(self.payload) != len(self.expect_original): raise DefinitionError( f"payload is {len(self.payload)} bytes but expect_original is " f"{len(self.expect_original)}; they must cover the same bytes") @dataclass(frozen=True) class PatchDefinition: identifier: str title: str features: tuple[str, ...] requires: tuple[str, ...] verified_on: tuple[str, ...] edit: PatchEdit locate: dict directory: Path | None = None @property def locate_method(self) -> str: return str(self.locate.get("method", "")) def load_patches(root: Path) -> list[PatchDefinition]: """Read every patch definition under `root`, sorted by identifier.""" definitions = [_read(path.parent) for path in sorted(root.rglob(PATCH_FILE))] _reject_duplicate_ids(definitions) _reject_unknown_requirements(definitions) return sorted(definitions, key=lambda item: item.identifier) 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, ) 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}") return PatchEdit( offset=int(raw.get("offset", 0)), payload=_hex(directory, "bytes", raw["bytes"]), expect_original=_hex(directory, "expect_original", raw["expect_original"]), asm=tuple(str(line) for line in raw.get("asm", ())), data=raw.get("data") if isinstance(raw.get("data"), dict) else None, ) def _hex(directory: Path, key: str, text: str) -> bytes: try: return bytes.fromhex(text) except ValueError as error: raise DefinitionError(f"{directory / PATCH_FILE}: {key} is not valid hex: {text!r}") from error def _read_json(path: Path) -> dict: try: return jsonc.load_object(path) except ValueError as error: raise DefinitionError(str(error)) from error def _reject_duplicate_ids(definitions: list[PatchDefinition]) -> None: seen: dict[str, Path | None] = {} for definition in definitions: if definition.identifier in seen: raise DefinitionError(f"two definitions use id {definition.identifier!r}: " f"{seen[definition.identifier]} and {definition.directory}") seen[definition.identifier] = definition.directory def _reject_unknown_requirements(definitions: list[PatchDefinition]) -> None: known = {definition.identifier for definition in definitions} for definition in definitions: unknown = [item for item in definition.requires if item not in known] if unknown: raise DefinitionError(f"{definition.identifier} requires unknown patch(es): {', '.join(unknown)}")