diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 19a76cb54..cbfb6ba81 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -112,6 +112,21 @@ on: - "scripts/romrecipes/__init__.py" - "scripts/romrecipes/ledger.py" - "scripts/romrecipes/romsets.py" + - "scripts/schemas/citations.py" + - "scripts/schemas/documents.py" + - "scripts/schemas/events.py" + - "scripts/schemas/games.py" + - "scripts/schemas/installs.py" + - "scripts/schemas/measurements.py" + - "scripts/schemas/packmanifests.py" + - "scripts/schemas/platformchecks.py" + - "scripts/schemas/profilechecks.py" + - "scripts/schemas/registry.py" + - "scripts/schemas/romfolders.py" + - "scripts/schemas/run.py" + - "scripts/schemas/sources.py" + - "scripts/schemas/sourcetree.py" + - "scripts/schemas/validators.py" - "scripts/site_markdown.py" - "scripts/sitegen/__init__.py" - "scripts/sitegen/agents.py" diff --git a/scripts/schemas/__init__.py b/scripts/schemas/__init__.py index 3b7915328..c999cb100 100644 --- a/scripts/schemas/__init__.py +++ b/scripts/schemas/__init__.py @@ -1 +1 @@ -"""Data contracts: JSON schemas and the semantic checks beside them.""" +"""The data contracts: JSON schemas and the semantic invariants they cannot express.""" diff --git a/scripts/schemas/citations.py b/scripts/schemas/citations.py new file mode 100644 index 000000000..8e545c4d8 --- /dev/null +++ b/scripts/schemas/citations.py @@ -0,0 +1,135 @@ +"""Source citations that name no code, or a place no repository holds.""" + +from __future__ import annotations + +import re +from pathlib import Path + +import core.paths +from model.sourceref import split_source_ref + + +_CODE_SUFFIXES = frozenset( + ["c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "inc", "inl", "ipp", "m", "mm", "mjs", "cjs", "js", "jsx", "ts", "tsx", "py", "cs", "java", "kt", "go", "rs", "lua", "pas", "pp", "asm", "s", "sh", "bash", "zsh", "ps1", "bat", "cmd", "vbs", "swift", "d", "zig", "nim", "qml", "qc", "rb", "pl", "php", "scala", "ml", "hs", "dart", "vue", "ino", "z80", "smali"] +) + + +_CODE_FILE = re.compile(r"(?<=[\w+-])\.([A-Za-z0-9+]+)\b") + + +# A compiled image: a part that names one has to say where in it the file +# is read, an address, a decompiled function or an IL method. +# A name under a directory is a file of the tree it sits in, and a further +# extension (.dll.map) makes it another file. +_BINARY_FILE = re.compile( + r"(? bool: + """A source_ref cites a source file or a place in a compiled image. + + A part naming a binary without an address, a decompiled function or an + IL method says only that the binary exists: "import directory", + "string table" and "readelf -d" are not the code that reads a file. + """ + cited = False + for part in split_source_ref(ref): + located = bool(_BINARY_EVIDENCE.search(part.raw)) or any( + suffix.lower() in _CODE_SUFFIXES for suffix in _CODE_FILE.findall(part.raw) + ) + if _BINARY_FILE.search(part.raw) and not located: + return False + cited = cited or located + return cited + + +def data_only_source_refs(path: Path, document: object) -> list[str]: + """A files[] source_ref that cites only data or build files. + + A data file is evidence that the emulator reads a file only once the + code that ships and parses it is cited too: iwadinfo.txt names the + IWADs, d_iwad.cpp is what reads it. 655 entries in 27 profiles cited + the table alone, and six of them named a file no code opens. + """ + if not isinstance(document, dict) or path.stem in DATA_ONLY_REF_EXCEPTIONS: + return [] + out: list[str] = [] + for index, entry in enumerate(document.get("files") or []): + if not isinstance(entry, dict) or not entry.get("source_ref"): + continue + refs = entry["source_ref"] + out.extend( + f"{path.relative_to(core.paths.REPO_ROOT)}: files[{index}] ({entry.get('name')}) " + f"source_ref cites no code that reads the file: {ref}" + for ref in (refs.values() if isinstance(refs, dict) else [refs]) + if ref and not _ref_cites_code(str(ref)) + ) + return out + + +UNREACHABLE_REF = re.compile( + r"(?:^|[\s,;(])(?:tmp/|/|[A-Za-z]:[\\/]|\.{1,2}/)[\w.\\/+-]*[\w+-]:\d+(?:-\d+)?" +) + + +def unreachable_citations(path: Path, document: object) -> list[str]: + """Refs naming a place no repository can hold. + + A citation is read against a revision of a declared repository, so a + scratch directory, an absolute path or one climbing out of the tree can + never resolve and never will. kenji-nx carried tmp/es-de/ANDROID.md:470, + a path from whoever profiled it, which profile_sync could only report + missing forever. + """ + out: list[str] = [] + stack: list[object] = [document] + while stack: + node = stack.pop() + if isinstance(node, dict): + stack.extend(node.values()) + elif isinstance(node, list): + stack.extend(node) + elif isinstance(node, str): + out.extend( + f"{path.relative_to(core.paths.REPO_ROOT)}: citation names a path outside " + f"any repository: {match.group().strip(' ,;(')}" + for match in UNREACHABLE_REF.finditer(node) + ) + return out + + +DOUBLED_PATH = re.compile(r"((?:[\w.-]+/){2,})\1") + + +def doubled_paths(path: Path) -> list[str]: + """A citation whose directory is written twice in a row. + + Read from the raw text, comments included: primehack's note on the + Realtek loader cited Source/Core/Core/IOS/USB/Bluetooth/ twice over, a + path no revision holds, in a comment the parsed document never shows. + """ + out: list[str] = [] + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + match = DOUBLED_PATH.search(line) + if match: + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}:{number}: citation repeats its " + f"directory: {match.group(1)}" + ) + return out diff --git a/scripts/schemas/documents.py b/scripts/schemas/documents.py new file mode 100644 index 000000000..3b71d67dd --- /dev/null +++ b/scripts/schemas/documents.py @@ -0,0 +1,61 @@ +"""Generated JSON documents against their schemas: the database and the site API.""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from pathlib import Path + +import core.paths +from schemas.validators import load_json, schema_errors, schema_validator + + +def validate_json_files( + paths: list[Path], + schema_name: str, + semantic_check: Callable[[Path, dict], list[str]] | None = None, +) -> list[str]: + validator = schema_validator(schema_name) + out: list[str] = [] + for path in paths: + try: + data = load_json(path) + except (OSError, json.JSONDecodeError) as exc: + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: {exc}") + continue + validation_errors = schema_errors(validator, data, str(path.relative_to(core.paths.REPO_ROOT))) + out.extend(validation_errors) + # Every schema a semantic check follows describes an object. + if not validation_errors and semantic_check is not None and isinstance(data, dict): + out.extend(semantic_check(path, data)) + return out + + +def semantic_envelope_checks(path: Path, document: dict) -> list[str]: + if document.get("count") != len(document.get("items", [])): + return [f"{path.relative_to(core.paths.REPO_ROOT)}: count does not equal len(items)"] + return [] + + +def semantic_database_checks(database: dict) -> list[str]: + out: list[str] = [] + files = database.get("files", {}) + if database.get("total_files") != len(files): + out.append("database.json: total_files does not equal len(files)") + if database.get("total_size") != sum(entry.get("size", 0) for entry in files.values()): + out.append("database.json: total_size does not equal the file-size sum") + # One path holds one content. Two entries naming the same path means one + # of them declares a hash the file at that path does not have. + owners: dict[str, str] = {} + for sha1, entry in files.items(): + if entry.get("sha1") != sha1: + out.append(f"database.json: files/{sha1}: key and sha1 differ") + path = entry.get("path", "") + if not path: + continue + first = owners.setdefault(path, sha1) + if first != sha1: + out.append( + f"database.json: {path} is claimed by {first} and {sha1}" + ) + return out diff --git a/scripts/schemas/events.py b/scripts/schemas/events.py new file mode 100644 index 000000000..c415f3a52 --- /dev/null +++ b/scripts/schemas/events.py @@ -0,0 +1,24 @@ +"""The installer event schema against EVENT_KEYS.""" + +from __future__ import annotations + +from jsonschema import Draft202012Validator + +import core.paths +from installer_build import eventschema +from schemas.validators import load_json + + +def event_schema_errors() -> list[str]: + """install-events.schema.json is EVENT_KEYS written out, and a valid schema.""" + path = core.paths.REPO_ROOT / "schemas" / eventschema.OUTPUT.name + label = path.relative_to(core.paths.REPO_ROOT).as_posix() + if not path.is_file(): + return [f"{label}: missing, run python scripts/generate_event_schema.py"] + if path.read_text(encoding="utf-8") != eventschema.render( + eventschema.build_schema() + ): + return [f"{label}: differs from EVENT_KEYS in install.py, run " + "python scripts/generate_event_schema.py"] + Draft202012Validator.check_schema(load_json(path)) + return [] diff --git a/scripts/schemas/games.py b/scripts/schemas/games.py new file mode 100644 index 000000000..365926b5a --- /dev/null +++ b/scripts/schemas/games.py @@ -0,0 +1,100 @@ +"""The games-on-card sources, the arcade pins and the published games index.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import core.paths +from core.paths import EMULATORS_DIR +from model.safeparse import yaml_load +from schemas.sources import source_mapping +from schemas.validators import defs_validator, json_object, schema_errors, schema_validator + + +# Source data of the games-on-card mode: file pattern -> schema. +_GAMES_SOURCES = ( + ("games/catalogs/*/*.json", "game-catalog.schema.json"), + ("games/arcade/*.json", "arcade-parents.schema.json"), + ("games/headers.yml", "game-headers.schema.json"), + ("games/regions.yml", "game-regions.schema.json"), + ("games/extras.yml", "game-extras.schema.json"), +) + + +def games_source_errors() -> list[str]: + out: list[str] = [] + for pattern, schema in _GAMES_SOURCES: + paths = sorted(core.paths.REPO_ROOT.glob(pattern)) + if not paths: + continue + validator = schema_validator(schema) + for path in paths: + with path.open(encoding="utf-8") as handle: + data = json.load(handle) if path.suffix == ".json" else yaml_load(handle) + out.extend(schema_errors(validator, data, str(path.relative_to(core.paths.REPO_ROOT)))) + return out + + +def arcade_pin_errors() -> list[str]: + """games/arcade/.json read at the revision and version its + profile pins. A bump of the profile left the game-to-BIOS map of the old + code in place, and the installer kept serving it.""" + out: list[str] = [] + for path in sorted((core.paths.REPO_ROOT / "games" / "arcade").glob("*.json")): + doc = json_object(path) + profile_path = core.paths.REPO_ROOT / EMULATORS_DIR / f"{doc.get('profile')}.yml" + label = str(path.relative_to(core.paths.REPO_ROOT)) + if not profile_path.is_file(): + out.append(f"{label}: no profile emulators/{profile_path.name}") + continue + profile = source_mapping(profile_path) + pinned = profile.get("source_commit") + pins = set(pinned.values()) if isinstance(pinned, dict) else {pinned} + commit = (doc.get("source") or {}).get("commit") + drifted = [] + if commit and commit not in pins: + drifted.append(f"read at {commit[:12]}, the profile pins {pinned}") + if doc.get("core_version") != profile.get("core_version"): + drifted.append(f"core_version {doc.get('core_version')!r}, " + f"the profile says {profile.get('core_version')!r}") + if drifted: + out.append(f"{label}: {'; '.join(drifted)} " + f"(python -m scripts.scraper.arcade_parent_importer --profile {doc.get('profile')})") + return out + + +def games_index_errors() -> list[str]: + """install/games/: each document against its kind, and the index + against the files it lists (size and sha256).""" + base = core.paths.REPO_ROOT / "install" / "games" + index_path = base / "index.json" + if not index_path.exists(): + return [] + out: list[str] = [] + index = json_object(index_path) + out.extend(schema_errors(defs_validator("games-index.schema.json", "index"), index, + str(index_path.relative_to(core.paths.REPO_ROOT)))) + kinds = { + "setups": defs_validator("games-index.schema.json", "setup"), + "fallback": defs_validator("games-index.schema.json", "fallback"), + "systems": defs_validator("games-index.schema.json", "system"), + "arcade": schema_validator("arcade-parents.schema.json"), + } + listed: set[Path] = set() + for kind, validator in kinds.items(): + for entry in (index.get(kind) or {}).values(): + path = base / entry["file"] + listed.add(path) + label = str(path.relative_to(core.paths.REPO_ROOT)) + if not path.exists(): + out.append(f"{label}: listed in index.json, absent") + continue + data = path.read_bytes() + if len(data) != entry["size"] or hashlib.sha256(data).hexdigest() != entry["sha256"]: + out.append(f"{label}: size or sha256 differs from index.json") + out.extend(schema_errors(validator, json.loads(data), label)) + out.extend(f"{path.relative_to(core.paths.REPO_ROOT)}: not listed in index.json" + for path in sorted(base.rglob("*.json")) if path != index_path and path not in listed) + return out diff --git a/scripts/schemas/installs.py b/scripts/schemas/installs.py new file mode 100644 index 000000000..ddc2abef2 --- /dev/null +++ b/scripts/schemas/installs.py @@ -0,0 +1,98 @@ +"""Install manifest invariants: counts, destinations and the standalone layouts.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import core.paths + + +def semantic_install_checks(path: Path, manifest: dict) -> list[str]: + out: list[str] = [] + files = manifest.get("files", []) + if manifest.get("total_files") != len(files): + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: total_files does not equal len(files)") + if manifest.get("total_size") != sum(entry.get("size", 0) for entry in files): + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: total_size does not equal the file-size sum") + omitted = manifest.get("omitted_files", []) + if manifest.get("total_omitted") != len(omitted): + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: total_omitted does not equal " + "len(omitted_files)" + ) + # One dest below the BIOS folder and one below the save directory are + # two places. + destinations = [(entry.get("root"), entry.get("dest")) for entry in files] + if len(destinations) != len(set(destinations)): + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: duplicate destinations") + # root: emulator is each core's own folder: mame2015 and mame2016 read + # 3dobios.zip in two places, one omission each, named by its cores. + omitted_destinations = [ + (entry.get("root"), entry.get("dest"), + tuple(entry.get("cores") or ()) if entry.get("root") == "emulator" else ()) + for entry in omitted + ] + if len(omitted_destinations) != len(set(omitted_destinations)): + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: duplicate omitted destinations") + overlap = set(destinations) & set(omitted_destinations) + if overlap: + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: destinations are both downloadable and omitted" + ) + saved = [ + entry for entry in [*files, *manifest.get("case_variants", [])] + if entry.get("root") == "save" + ] + layout = manifest.get("save_directory") + if saved and not layout: + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: entries read below the save directory " + "and no save_directory" + ) + builds = core.paths.REPO_ROOT / "install" / "standalone" / path.name + if manifest.get("standalone_builds") and path.parent == core.paths.REPO_ROOT / "install" \ + and not builds.is_file(): + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: standalone_builds and no " + f"install/standalone/{path.name}") + stray = sorted( + entry["dest"] for entry in [*files, *omitted] + if entry.get("core_folder") and entry.get("root") != "save" + ) + if stray: + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: core_folder outside root: save ({stray[0]})" + ) + return out + + +def semantic_standalone_checks(path: Path, layouts: object) -> list[str]: + """A standalone layout file goes with its platform's list: the list + names the same builds, and each [dest, sha1] item takes its download + from a copy of that list.""" + where = path.relative_to(core.paths.REPO_ROOT) + if not isinstance(layouts, dict): + return [f"{where}: not an object"] + plat = layouts.get("platform") + if path.stem != plat: + return [f"{where}: platform {plat} in a file named {path.stem}"] + listed = core.paths.REPO_ROOT / "install" / f"{plat}.json" + if not listed.is_file(): + return [f"{where}: no install/{plat}.json beside it"] + manifest = json.loads(listed.read_text(encoding="utf-8")) + out: list[str] = [] + if sorted(layouts.get("standalone_layouts", {})) != manifest.get("standalone_builds"): + out.append(f"{where}: its builds differ from standalone_builds in {listed.name}") + held = { + copy.get("sha1") + for entry in [*manifest.get("files", []), *(manifest.get("truth_files") or [])] + for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] + } + missing = sorted({ + item[1] for items in layouts.get("standalone_layouts", {}).values() + for item in items if isinstance(item, list) and item[1] not in held + }) + if missing: + out.append(f"{where}: {len(missing)} sha1 no copy of {listed.name} carries " + f"({missing[0]})") + return out diff --git a/scripts/schemas/measurements.py b/scripts/schemas/measurements.py new file mode 100644 index 000000000..583aa470a --- /dev/null +++ b/scripts/schemas/measurements.py @@ -0,0 +1,38 @@ +"""The record lines under measurements/ against their schemas.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import core.paths +from model import measurements as mr +from schemas.validators import schema_errors, schema_validator + + +def measurement_errors(root: Path | None = None) -> list[str]: + """Every record line under measurements/, against its schema and the + rules model.measurements.read_records applies.""" + root = root or core.paths.REPO_ROOT + validator = schema_validator("core-probe-record.schema.json") + out: list[str] = [] + campaign = {mr.records_path(name): schema_validator(schema) + for name, (_, schema) in mr.CAMPAIGN_FILES.items()} + for path, file in sorted(mr.tree_files(root).items()): + if not path.endswith(".jsonl"): + continue + for number, line in enumerate(file.read_text(encoding="utf-8").splitlines(), 1): + try: + record = json.loads(line) + except json.JSONDecodeError as exc: + out.append(f"{path}:{number}: {exc}") + continue + out.extend(schema_errors(campaign.get(path, validator), record, f"{path}:{number}")) + if not out: + try: + mr.read_records(root) + for name in mr.CAMPAIGN_FILES: + mr.read_campaign(root, name) + except mr.MeasurementsError as exc: + out.append(str(exc)) + return out diff --git a/scripts/schemas/packmanifests.py b/scripts/schemas/packmanifests.py new file mode 100644 index 000000000..e8680a85c --- /dev/null +++ b/scripts/schemas/packmanifests.py @@ -0,0 +1,79 @@ +"""The manifest.json each generated pack carries, read inside the archive.""" + +from __future__ import annotations + +import json +import sys +import zipfile +from pathlib import Path, PurePosixPath + +import core.paths +from core.artifacts import ArtifactLockBusy, artifact_lock +from schemas.validators import schema_errors, schema_validator + + +def validate_pack_manifests(dist: Path) -> list[str]: + """Validate the integrity manifest each generated pack carries. + + generate_pack.py writes manifest.json inside the archive, not beside it, + so a filesystem glob over dist/ matches nothing and silently validates + zero documents. + + Reading a pack while a build is writing it reports "File is not a zip + file" about an archive that is merely half-written, so this takes the same + shared lock --verify-packs does. A build holding the exclusive lock means + the packs on disk are mid-flight and there is nothing stable to validate. + """ + if not dist.is_dir(): + return [] + + try: + with artifact_lock(str(dist), exclusive=False): + return _scan_pack_manifests(dist) + except ArtifactLockBusy: + print( + f"note: {dist.name} is being written, skipping pack manifests", + file=sys.stderr, + ) + return [] + + +def _scan_pack_manifests(dist: Path) -> list[str]: + validator = schema_validator("pack-manifest.schema.json") + # The lists a pack carries for the installer, each under its own + # contract: the schemas name no other file, so they are checked here. + carried = { + "install_list": schema_validator("install-manifest.schema.json"), + "targets": schema_validator("target-manifest.schema.json"), + } + + def _label(path: Path) -> str: + resolved = path.resolve() + try: + return str(resolved.relative_to(core.paths.REPO_ROOT)) + except ValueError: + return str(resolved) + + out: list[str] = [] + for archive in sorted(dist.glob("*.zip")): + try: + with zipfile.ZipFile(archive) as handle: + members = [ + name + for name in handle.namelist() + if PurePosixPath(name).name == "manifest.json" + ] + for member in members: + label = f"{_label(archive)}:{member}" + try: + document = json.loads(handle.read(member).decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + out.append(f"{label}: {exc}") + continue + out.extend(schema_errors(validator, document, label)) + for key, inner in carried.items(): + if isinstance(document, dict) and key in document: + out.extend(schema_errors(inner, document[key], f"{label}:{key}")) + except (OSError, zipfile.BadZipFile) as exc: + out.append(f"{_label(archive)}: {exc}") + return out diff --git a/scripts/schemas/platformchecks.py b/scripts/schemas/platformchecks.py new file mode 100644 index 000000000..3bdc54a7e --- /dev/null +++ b/scripts/schemas/platformchecks.py @@ -0,0 +1,35 @@ +"""Platform file invariants: launcher records and the config evidence they cite.""" + +from __future__ import annotations + +from pathlib import Path + +import core.paths +from resolve.launcherrefs import config_ref, is_feature_ref + + +def config_records_without_evidence(path: Path, document: object) -> list[str]: + """A launcher record citing a config without the links its extractor reads. + + A config file is proof only when the code installing it and the code + reading it are shown (launchers.config_evidence). The platform's half + is the extractor's to write: a record citing a shipped config carries + installs and overrides, and a feature or option file is never a + record's source, only its choices_from. + """ + if not isinstance(document, dict): + return [] + out: list[str] = [] + for index, record in enumerate(document.get("launchers") or []): + if not isinstance(record, dict): + continue + cited = config_ref(str(record.get("source_ref") or "")) + where = f"{path.relative_to(core.paths.REPO_ROOT)}: launchers[{index}] ({record.get('emulator')})" + features = [part for part in cited if is_feature_ref(part)] + if features: + out.append(f"{where} cites {features[0]} as source, choices_from holds it") + if [part for part in cited if not is_feature_ref(part)] and not ( + record.get("installs") and "overrides" in record + ): + out.append(f"{where} cites a config without installs and overrides") + return out diff --git a/scripts/schemas/profilechecks.py b/scripts/schemas/profilechecks.py new file mode 100644 index 000000000..5d56436a2 --- /dev/null +++ b/scripts/schemas/profilechecks.py @@ -0,0 +1,164 @@ +"""Emulator profile invariants the schema cannot express.""" + +from __future__ import annotations + +from pathlib import Path + +import core.paths +from model.alternatives import groups_of +from resolve.validation import read_from_save_dir + + +CHECK_FIELDS = { + "crc32": ("crc32",), + "md5": ("md5",), + "sha1": ("sha1",), + "sha256": ("sha256",), + "size": ("size", "min_size", "max_size", "size_multiple"), + "romdir": ("romdir",), + "masked_sha1": ("masked_sha1",), +} + + +def config_reads_without_build(path: Path, document: object) -> list[str]: + """A config_reads entry naming a platform the profile gives no pin_build. + + Such an entry is read at the build that platform ships, and pin_build is + where that build is named. + """ + if not isinstance(document, dict): + return [] + builds = {str(b.get("platform")) for b in document.get("pin_build") or []} + out: list[str] = [] + for index, read in enumerate(document.get("config_reads") or []): + if not isinstance(read, dict): + continue + if read.get("revision") or read.get("binary_sha256"): + continue + out.extend( + f"{path.relative_to(core.paths.REPO_ROOT)}: config_reads[{index}] ({read.get('file')}) " + f"names {platform}, which has no pin_build" + for platform in read.get("platforms") or [] if str(platform) not in builds + ) + return out + + +def systems_outside_profile(path: Path, document: object) -> list[str]: + """An entry's system: or systems: naming a system its profile does not list. + + A --system pick selects the profile by its systems: and then the entry + by its own, so a name the profile lacks is one no pick ever reaches. + """ + if not isinstance(document, dict): + return [] + listed = {str(s) for s in document.get("systems") or []} + out: list[str] = [] + for index, entry in enumerate(document.get("files") or []): + if not isinstance(entry, dict): + continue + named = [entry["system"]] if entry.get("system") else [] + named += list(entry.get("systems") or []) + unknown = [str(s) for s in named if str(s) not in listed] + if unknown: + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: files[{index}] ({entry.get('name')}) " + f"system {', '.join(unknown)} not in the profile's systems" + ) + return out + + +def group_requirement_split(path: Path, document: object) -> list[str]: + """A set named by a member and not declared, declared and never used, + or a member that writes a required of its own. + + The requirement belongs to the set, in the profile's groups map, and a + member's is derived from it. A value on the member is a second source + that can contradict the first: a true on the first name only wrote the + search order into required, and the other names read as optional. + """ + if not isinstance(document, dict): + return [] + label = path.relative_to(core.paths.REPO_ROOT) + declared = set((document.get("groups") or {}).keys()) + used: set[str] = set() + out: list[str] = [] + for index, entry in enumerate(document.get("files") or []): + if not isinstance(entry, dict): + continue + names = groups_of(entry) + used.update(names) + if names and "required" in entry: + out.append(f"{label}: files[{index}] ({entry.get('name')}) is in a group " + "and writes required: the set's requirement is in groups") + out.extend(f"{label}: group {g} has no entry in groups" for g in sorted(used - declared)) + out.extend(f"{label}: groups declares {g}, which no entry names" for g in sorted(declared - used)) + return out + + +def checks_without_values(path: Path, document: object) -> list[str]: + """A check an entry declares with nothing to compare against. + + validation: [crc32] with no crc32 runs nothing: the file passes whatever + it holds, and the report reads as checked. Fourteen profiles carried + one, the code they describe either refusing or warning on a value the + entry never wrote down. + """ + out: list[str] = [] + files = document.get("files") if isinstance(document, dict) else None + for index, entry in enumerate(files or []): + if not isinstance(entry, dict): + continue + declared = entry.get("validation") or [] + if isinstance(declared, dict): + declared = [check for checks in declared.values() for check in checks or []] + for check in declared: + fields = CHECK_FIELDS.get(check) + if fields and not any(entry.get(field) not in (None, "", []) for field in fields): + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: files[{index}] ({entry.get('name')}) " + f"declares a {check} check with no {'/'.join(fields)} value" + ) + return out + + +def save_dir_without_library_name(path: Path, document: object) -> list[str]: + """A file the libretro build reads below the save directory, in a profile + naming no library_name. + + RetroArch hands each core / by default + (sort_savefiles_enable): without the name, packs and the installer + cannot say where the file goes, and leave it out. + """ + if not isinstance(document, dict): + return [] + if "library_name" in document: + return _save_folder_once_paths(path, document) + return [ + f"{path.relative_to(core.paths.REPO_ROOT)}: files[{index}] ({entry.get('name')}) is read " + "below the save directory and the profile declares no library_name" + for index, entry in enumerate(document.get("files") or []) + if isinstance(entry, dict) + and read_from_save_dir(entry) + and not ("path" in entry and entry["path"] is None) + ] + + +def _save_folder_once_paths(path: Path, document: dict) -> list[str]: + """A core adding its own folder once: each save path starts with it. + + The pack places such a file at / whether the + frontend sorts saves by core or not, which holds only when the path + already names the folder the core reads below. + """ + if not document.get("save_folder_once"): + return [] + folder = f"{document.get('library_name') or ''}/" + return [ + f"{path.relative_to(core.paths.REPO_ROOT)}: files[{index}] ({entry.get('name')}) does not " + f"start with {folder}, the folder save_folder_once says the core adds" + for index, entry in enumerate(document.get("files") or []) + if isinstance(entry, dict) + and read_from_save_dir(entry) + and entry.get("path") + and not str(entry["path"]).startswith(folder) + ] diff --git a/scripts/schemas/registry.py b/scripts/schemas/registry.py new file mode 100644 index 000000000..82f7fa255 --- /dev/null +++ b/scripts/schemas/registry.py @@ -0,0 +1,116 @@ +"""platforms/_registry.yml: its schema, the release packs and the save directory blocks.""" + +from __future__ import annotations + +import core.paths +from core.paths import PLATFORMS_DIR +from model.platforms import load_platform_config +from model.registry import load_platform_registry +from model.safeparse import yaml_load +from schemas.validators import schema_errors, schema_validator + + +def registry_contract() -> list[str]: + """The registry against its schema, and a release that still ships a pack. + + `release_pack` is the only list of the ZIPs a release publishes: a + registry where no platform carries it would cut a release with no pack + at all, and every download link would lead to the command. + """ + registry_path = core.paths.REPO_ROOT / PLATFORMS_DIR / "_registry.yml" + if not registry_path.is_file(): + return [] + with registry_path.open(encoding="utf-8") as handle: + registry = yaml_load(handle) or {} + label = str(registry_path.relative_to(core.paths.REPO_ROOT)) + out = schema_errors(schema_validator("registry.schema.json"), registry, label) + platforms = registry.get("platforms") or {} + if isinstance(platforms, dict) and not any( + isinstance(entry, dict) and entry.get("release_pack") is True + for entry in platforms.values() + ): + out.append(f"{label}: no platform has release_pack: true") + return out + + +def save_directory_blocks() -> list[str]: + """Each registry save_directory is null or a folder and a by_core flag. + + The folder names the pack folder and the save directory's default place + beside the BIOS directory: a relative path that never climbs. ``by_system`` (a save + folder per launched system) needs the platform file's libretro_systems, + and ``by_core_for`` names the cores a launcher sorts by core. + """ + platforms = load_platform_registry(core.paths.REPO_ROOT / PLATFORMS_DIR) + out: list[str] = [] + for name, entry in sorted(platforms.items()): + if not isinstance(entry, dict) or "save_directory" not in entry: + continue + block = entry["save_directory"] + if block is None: + continue + folder = block.get("folder") if isinstance(block, dict) else None + sorted_cores = block.get("by_core_for", []) if isinstance(block, dict) else None + if ( + not isinstance(block, dict) + or not {"folder", "by_core"} <= set(block) <= { + "folder", "by_core", "by_system", "by_core_for", "pack_folder", + } + or not isinstance(block.get("pack_folder", "x"), str) + or "/" in str(block.get("pack_folder", "")) + or not isinstance(folder, str) + or not folder + or "\\" in folder + or any(part in ("", ".", "..") for part in folder.split("/")) + or not isinstance(block.get("by_core"), bool) + or not isinstance(block.get("by_system", False), bool) + or not isinstance(sorted_cores, list) + or not all(isinstance(core, str) and core for core in sorted_cores) + ): + out.append( + f"platforms/_registry.yml: {name}.save_directory must be null or " + "{folder: , by_core: , by_system: , " + "by_core_for: []}" + ) + continue + if block.get("by_system") and not _libretro_systems(name): + out.append( + f"platforms/_registry.yml: {name}.save_directory.by_system and " + f"platforms/{name}.yml lists no libretro_systems" + ) + in_pack = block.get("pack_folder") or folder + taken = bios_tree_below(name, in_pack) + if taken: + out.append( + f"platforms/_registry.yml: {name}.save_directory puts the save " + f"files in {in_pack}/, which the BIOS tree uses ({taken}): " + "name another pack_folder" + ) + return out + + +def bios_tree_below(platform: str, folder: str) -> str: + """A destination the platform declares below ``folder``, or empty.""" + try: + config = load_platform_config(platform, str(core.paths.REPO_ROOT / PLATFORMS_DIR)) + except FileNotFoundError: + return "" + prefix = f"{folder}/".lower() + return next( + ( + str(entry["destination"]) + for system in (config.get("systems") or {}).values() + for entry in system.get("files") or [] + if str(entry.get("destination") or "").lower().startswith(prefix) + ), + "", + ) + + +def _libretro_systems(platform: str) -> dict: + """The platform file's core -> systems table, inheritance included.""" + try: + config = load_platform_config(platform, str(core.paths.REPO_ROOT / PLATFORMS_DIR)) + except FileNotFoundError: + return {} + return config.get("libretro_systems") or {} diff --git a/scripts/schemas/romfolders.py b/scripts/schemas/romfolders.py new file mode 100644 index 000000000..ce49e391b --- /dev/null +++ b/scripts/schemas/romfolders.py @@ -0,0 +1,40 @@ +"""The scraped rom folder setups and the sources their refs name.""" + +from __future__ import annotations + +import core.paths +from core.paths import PLATFORMS_DIR +from model.romfolders import source_refs, split_refs +from model.safeparse import yaml_load +from schemas.validators import schema_errors, schema_validator + + +def romfolder_errors() -> list[str]: + """Every scraped setup against its schema, and every source_ref against + the sources the file declares: a ref naming no declared repository can + never be read back at a pin.""" + directory = core.paths.REPO_ROOT / PLATFORMS_DIR / "romfolders" + if not directory.is_dir(): + return [] + validator = schema_validator("romfolders.schema.json") + out: list[str] = [] + for path in sorted(directory.glob("*.yml")): + label = str(path.relative_to(core.paths.REPO_ROOT)) + with path.open(encoding="utf-8") as handle: + data = yaml_load(handle) + errors = schema_errors(validator, data, label) + out.extend(errors) + if errors: + continue + declared = set(data["sources"]) + for ref in source_refs(data): + try: + parts = split_refs(ref) + except ValueError as exc: + out.append(f"{label}: {exc}") + continue + for key, path, lines in parts: + if key not in declared: + part = f"{key} {path}" + (f":{lines}" if lines else "") + out.append(f"{label}: source_ref {part!r} names undeclared source {key!r}") + return out diff --git a/scripts/schemas/run.py b/scripts/schemas/run.py new file mode 100644 index 000000000..598a02e9a --- /dev/null +++ b/scripts/schemas/run.py @@ -0,0 +1,129 @@ +"""Every check of a validation run, in the order the command reports them.""" + +from __future__ import annotations + +import core.paths +from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR +from schemas.documents import ( + semantic_database_checks, + semantic_envelope_checks, + validate_json_files, +) +from schemas.events import event_schema_errors +from schemas.games import arcade_pin_errors, games_index_errors, games_source_errors +from schemas.installs import semantic_install_checks, semantic_standalone_checks +from schemas.measurements import measurement_errors +from schemas.packmanifests import validate_pack_manifests +from schemas.registry import registry_contract, save_directory_blocks +from schemas.romfolders import romfolder_errors +from schemas.sourcetree import ( + repository_layout_in_profiles, + unknown_data_dir_refs, + validate_yaml_directory, +) +from schemas.validators import format_errors + + +def source_errors() -> list[str]: + """The emulator and platform sources and the data committed beside them.""" + root = core.paths.REPO_ROOT + errors: list[str] = format_errors() + errors.extend( + validate_yaml_directory(root / EMULATORS_DIR, "emulator.schema.json") + ) + errors.extend( + validate_yaml_directory( + root / PLATFORMS_DIR, "platform.schema.json", skip_private=True + ) + ) + errors.extend(unknown_data_dir_refs()) + errors.extend(repository_layout_in_profiles()) + errors.extend(save_directory_blocks()) + errors.extend(registry_contract()) + errors.extend(event_schema_errors()) + errors.extend(measurement_errors()) + errors.extend(romfolder_errors()) + errors.extend(games_source_errors()) + errors.extend(arcade_pin_errors()) + return errors + + +def generated_errors() -> list[str]: + """The generated artifacts: database, install lists, site data and packs.""" + root = core.paths.REPO_ROOT + errors = validate_json_files( + [root / DB_FILE], + "database.schema.json", + lambda _path, database: semantic_database_checks(database), + ) + + install_paths = sorted((root / "install").glob("*.json")) + errors.extend( + validate_json_files( + install_paths, "install-manifest.schema.json", semantic_install_checks + ) + ) + + standalone_paths = sorted((root / "install" / "standalone").glob("*.json")) + errors.extend( + validate_json_files( + standalone_paths, "install-standalone.schema.json", + semantic_standalone_checks, + ) + ) + + target_paths = sorted((root / "install" / "targets").glob("*.json")) + errors.extend( + validate_json_files(target_paths, "target-manifest.schema.json") + ) + + release_path = root / "release.json" + if release_path.exists(): + errors.extend(validate_json_files([release_path], "release.schema.json")) + + stats_path = root / "website" / "public" / "stats.json" + if stats_path.exists(): + errors.extend(validate_json_files([stats_path], "stats.schema.json")) + + errors.extend(_site_api_errors()) + errors.extend(games_index_errors()) + errors.extend(validate_pack_manifests(root / "dist")) + return errors + + +def _site_api_errors() -> list[str]: + """The documents the site publishes under api/v1/.""" + api_dir = core.paths.REPO_ROOT / "website" / "public" / "api" / "v1" + errors: list[str] = [] + api_database = api_dir / "database.json" + if api_database.exists(): + errors.extend( + validate_json_files([api_database], "database.schema.json") + ) + api_stats = api_dir / "stats.json" + if api_stats.exists(): + errors.extend(validate_json_files([api_stats], "stats.schema.json")) + envelope_paths = [ + api_dir / name + for name in ("catalog.json", "platforms.json", "emulators.json", "gaps.json") + if (api_dir / name).exists() + ] + sorted((api_dir / "platforms").glob("*.json")) + sorted( + (api_dir / "systems").glob("*.json") + ) + sorted((api_dir / "lookup").glob("*.json")) + errors.extend( + validate_json_files( + envelope_paths, + "site-api-envelope.schema.json", + semantic_envelope_checks, + ) + ) + return errors + + +def validation_errors(source_only: bool) -> list[str]: + """Every error of a run: the sources, then the generated artifacts unless + ``source_only``.""" + errors = source_errors() + if not source_only: + errors.extend(generated_errors()) + return errors diff --git a/scripts/schemas/sources.py b/scripts/schemas/sources.py new file mode 100644 index 000000000..7ea45c688 --- /dev/null +++ b/scripts/schemas/sources.py @@ -0,0 +1,33 @@ +"""The source YAML files, parsed once per run whichever check reads them.""" + +from __future__ import annotations + +from pathlib import Path + +from model.safeparse import yaml_load + + +_SOURCES: dict[tuple[Path, int, int], object] = {} + + +def load_source(path: Path) -> object: + """A source YAML, parsed once per run whichever check reads it: the + schema pass, the data directory refs and the layout check each parsed + all 649 profiles again. Keyed by size and mtime too, so a file written + again in the same process is read again.""" + stat = path.stat() + key = (path, stat.st_mtime_ns, stat.st_size) + if key not in _SOURCES: + with path.open(encoding="utf-8") as handle: + _SOURCES[key] = yaml_load(handle) + return _SOURCES[key] + + +def source_mapping(path: Path) -> dict: + """A source YAML that holds a mapping, empty when the file is.""" + document = load_source(path) + if not document: + return {} + if not isinstance(document, dict): + raise ValueError(f"{path}: not a mapping") + return document diff --git a/scripts/schemas/sourcetree.py b/scripts/schemas/sourcetree.py new file mode 100644 index 000000000..49b24b84e --- /dev/null +++ b/scripts/schemas/sourcetree.py @@ -0,0 +1,106 @@ +"""The emulators/ and platforms/ trees against their schemas and invariants.""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +import core.paths +from core.paths import EMULATORS_DIR, PLATFORMS_DIR +from model.profiles import source_yaml_paths +from model.registry import load_data_dir_registry +from schemas.citations import data_only_source_refs, doubled_paths, unreachable_citations +from schemas.platformchecks import config_records_without_evidence +from schemas.profilechecks import ( + checks_without_values, + config_reads_without_build, + group_requirement_split, + save_dir_without_library_name, + systems_outside_profile, +) +from schemas.sources import load_source, source_mapping +from schemas.validators import schema_errors, schema_validator + + +def validate_yaml_directory( + directory: Path, + schema_name: str, + *, + skip_private: bool = False, +) -> list[str]: + validator = schema_validator(schema_name) + out: list[str] = [] + for path in source_yaml_paths(directory): + if skip_private and path.name.startswith("_"): + continue + try: + data = load_source(path) + except (OSError, yaml.YAMLError) as exc: + out.append(f"{path.relative_to(core.paths.REPO_ROOT)}: {exc}") + continue + out.extend(schema_errors(validator, data, str(path.relative_to(core.paths.REPO_ROOT)))) + out.extend(unreachable_citations(path, data)) + if schema_name == "platform.schema.json": + out.extend(config_records_without_evidence(path, data)) + if schema_name == "emulator.schema.json": + out.extend(config_reads_without_build(path, data)) + out.extend(checks_without_values(path, data)) + out.extend(save_dir_without_library_name(path, data)) + out.extend(systems_outside_profile(path, data)) + out.extend(doubled_paths(path)) + out.extend(group_requirement_split(path, data)) + out.extend(data_only_source_refs(path, data)) + return out + + +def unknown_data_dir_refs() -> list[str]: + """data_directories refs the registry does not define. + + A ref nobody registers is never fetched: yaps2 named yaps2-resources and + every run printed "not cached" while refresh_data_dirs had nothing to + refresh. + """ + registered = set(load_data_dir_registry(core.paths.REPO_ROOT / PLATFORMS_DIR, required=True)) + out: list[str] = [] + for directory in (core.paths.REPO_ROOT / EMULATORS_DIR, core.paths.REPO_ROOT / PLATFORMS_DIR): + for path in source_yaml_paths(directory): + if path.name.startswith("_"): + continue + document = source_mapping(path) + systems = document.get("systems") + holders = [document, *(systems.values() if isinstance(systems, dict) else [])] + for holder in holders: + if not isinstance(holder, dict): + continue + for entry in holder.get("data_directories") or []: + ref = entry.get("ref") if isinstance(entry, dict) else None + if ref and ref not in registered: + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: data directory {ref!r} " + f"is not in platforms/_data_dirs.yml" + ) + return out + + +def repository_layout_in_profiles() -> list[str]: + """Profile destinations that name this repository's storage. + + `path:` is where the emulator's code reads the file, never where we keep + it: a profile written from a clone filed its variants under + `.variants/...`, and the pack then wrote them where no emulator looks. + """ + out: list[str] = [] + for path in source_yaml_paths(core.paths.REPO_ROOT / EMULATORS_DIR): + document = source_mapping(path) + for entry in document.get("files") or []: + if not isinstance(entry, dict): + continue + for key in ("path", "standalone_path"): + value = str(entry.get(key) or "") + if ".variants" in value.replace("\\", "/").split("/"): + out.append( + f"{path.relative_to(core.paths.REPO_ROOT)}: {entry.get('name')} {key} " + f"names the repository's .variants/ storage: {value}" + ) + return out diff --git a/scripts/schemas/validators.py b/scripts/schemas/validators.py new file mode 100644 index 000000000..3c6a7b6d7 --- /dev/null +++ b/scripts/schemas/validators.py @@ -0,0 +1,71 @@ +"""The schema files under schemas/, their validators and the error lines they give.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +from jsonschema import Draft202012Validator, FormatChecker + +import core.paths + + +SCHEMAS = core.paths.REPO_ROOT / "schemas" + + +def load_json(path: Path) -> object: + with path.open(encoding="utf-8") as handle: + return json.load(handle) + + +def json_object(path: Path) -> dict: + data = load_json(path) + if not isinstance(data, dict): + raise ValueError(f"{path}: not a JSON object") + return data + + +def schema_validator(name: str) -> Draft202012Validator: + schema = load_json(SCHEMAS / name) + Draft202012Validator.check_schema(schema) + return Draft202012Validator(schema, format_checker=FormatChecker()) + + +def defs_validator(name: str, definition: str) -> Draft202012Validator: + """A validator for one $defs entry of a schema file.""" + schema = json_object(SCHEMAS / name) + Draft202012Validator.check_schema(schema) + return Draft202012Validator( + {**schema, "$ref": f"#/$defs/{definition}"}, format_checker=FormatChecker() + ) + + +def schema_errors(validator: Draft202012Validator, data: object, label: str) -> list[str]: + out: list[str] = [] + for error in sorted(validator.iter_errors(data), key=lambda item: list(item.path)): + location = "/".join(str(part) for part in error.absolute_path) or "" + out.append(f"{label}:{location}: {error.message}") + return out + + +def unchecked_formats() -> list[str]: + """Formats the schemas declare that this jsonschema install cannot check. + + date-time and uri need the format extras. Without them the ten format + constraints of the published schemas were accepted unread. + """ + used = { + match + for path in SCHEMAS.glob("*.json") + for match in re.findall(r'"format"\s*:\s*"([^"]+)"', path.read_text(encoding="utf-8")) + } + return sorted(used - set(FormatChecker().checkers)) + + +def format_errors() -> list[str]: + """jsonschema skips a format it has no checker for: say so, and fail.""" + return [ + f"no checker for format {name}: install \"jsonschema[format-nongpl]\"" + for name in unchecked_formats() + ] diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index 1bcbcc562..24885a6be 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -4,23 +4,11 @@ from __future__ import annotations import argparse -import json -import re import sys -import zipfile -from collections.abc import Callable -from pathlib import Path, PurePosixPath - -import yaml - -from core.artifacts import ArtifactLockBusy, artifact_lock -from model.registry import load_data_dir_registry, load_platform_registry -from model.profiles import source_yaml_paths -from model.safeparse import yaml_load -from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT +from importlib import import_module try: - from jsonschema import Draft202012Validator, FormatChecker + import_module("jsonschema") except ImportError: # Tests import this module and skip on the ImportError, the command # names the install pipeline.py names for the same step. @@ -28,971 +16,7 @@ except ImportError: raise sys.exit('Error: jsonschema required (pip install "jsonschema[format-nongpl]")') -SCHEMAS = REPO_ROOT / "schemas" - - -def _load_json(path: Path) -> object: - with path.open(encoding="utf-8") as handle: - return json.load(handle) - - -def _json_object(path: Path) -> dict: - data = _load_json(path) - if not isinstance(data, dict): - raise ValueError(f"{path}: not a JSON object") - return data - - -def _validator(name: str) -> Draft202012Validator: - schema = _load_json(SCHEMAS / name) - Draft202012Validator.check_schema(schema) - return Draft202012Validator(schema, format_checker=FormatChecker()) - - -def _errors(validator: Draft202012Validator, data: object, label: str) -> list[str]: - out: list[str] = [] - for error in sorted(validator.iter_errors(data), key=lambda item: list(item.path)): - location = "/".join(str(part) for part in error.absolute_path) or "" - out.append(f"{label}:{location}: {error.message}") - return out - - -_SOURCES: dict[tuple[Path, int, int], object] = {} - - -def _load_source(path: Path) -> object: - """A source YAML, parsed once per run whichever check reads it: the - schema pass, the data directory refs and the layout check each parsed - all 649 profiles again. Keyed by size and mtime too, so a file written - again in the same process is read again.""" - stat = path.stat() - key = (path, stat.st_mtime_ns, stat.st_size) - if key not in _SOURCES: - with path.open(encoding="utf-8") as handle: - _SOURCES[key] = yaml_load(handle) - return _SOURCES[key] - - -def _source_mapping(path: Path) -> dict: - """A source YAML that holds a mapping, empty when the file is.""" - document = _load_source(path) - if not document: - return {} - if not isinstance(document, dict): - raise ValueError(f"{path}: not a mapping") - return document - - -def _validate_yaml_directory( - directory: Path, - schema_name: str, - *, - skip_private: bool = False, -) -> list[str]: - validator = _validator(schema_name) - out: list[str] = [] - for path in source_yaml_paths(directory): - if skip_private and path.name.startswith("_"): - continue - try: - data = _load_source(path) - except (OSError, yaml.YAMLError) as exc: - out.append(f"{path.relative_to(REPO_ROOT)}: {exc}") - continue - out.extend(_errors(validator, data, str(path.relative_to(REPO_ROOT)))) - out.extend(_unreachable_citations(path, data)) - if schema_name == "platform.schema.json": - out.extend(_config_records_without_evidence(path, data)) - if schema_name == "emulator.schema.json": - out.extend(_config_reads_without_build(path, data)) - out.extend(_checks_without_values(path, data)) - out.extend(_save_dir_without_library_name(path, data)) - out.extend(_systems_outside_profile(path, data)) - out.extend(_doubled_paths(path)) - out.extend(_group_requirement_split(path, data)) - out.extend(_data_only_source_refs(path, data)) - return out - - -_CHECK_FIELDS = { - "crc32": ("crc32",), - "md5": ("md5",), - "sha1": ("sha1",), - "sha256": ("sha256",), - "size": ("size", "min_size", "max_size", "size_multiple"), - "romdir": ("romdir",), - "masked_sha1": ("masked_sha1",), -} - - -def _config_records_without_evidence(path: Path, document: object) -> list[str]: - """A launcher record citing a config without the links its extractor reads. - - A config file is proof only when the code installing it and the code - reading it are shown (launchers.config_evidence). The platform's half - is the extractor's to write: a record citing a shipped config carries - installs and overrides, and a feature or option file is never a - record's source, only its choices_from. - """ - if not isinstance(document, dict): - return [] - from resolve.launcherrefs import config_ref, is_feature_ref - - out: list[str] = [] - for index, record in enumerate(document.get("launchers") or []): - if not isinstance(record, dict): - continue - cited = config_ref(str(record.get("source_ref") or "")) - where = f"{path.relative_to(REPO_ROOT)}: launchers[{index}] ({record.get('emulator')})" - features = [part for part in cited if is_feature_ref(part)] - if features: - out.append(f"{where} cites {features[0]} as source, choices_from holds it") - if [part for part in cited if not is_feature_ref(part)] and not ( - record.get("installs") and "overrides" in record - ): - out.append(f"{where} cites a config without installs and overrides") - return out - - -def _config_reads_without_build(path: Path, document: object) -> list[str]: - """A config_reads entry naming a platform the profile gives no pin_build. - - Such an entry is read at the build that platform ships, and pin_build is - where that build is named. - """ - if not isinstance(document, dict): - return [] - builds = {str(b.get("platform")) for b in document.get("pin_build") or []} - out: list[str] = [] - for index, read in enumerate(document.get("config_reads") or []): - if not isinstance(read, dict): - continue - if read.get("revision") or read.get("binary_sha256"): - continue - out.extend( - f"{path.relative_to(REPO_ROOT)}: config_reads[{index}] ({read.get('file')}) " - f"names {platform}, which has no pin_build" - for platform in read.get("platforms") or [] if str(platform) not in builds - ) - return out - - -def _systems_outside_profile(path: Path, document: object) -> list[str]: - """An entry's system: or systems: naming a system its profile does not list. - - A --system pick selects the profile by its systems: and then the entry - by its own, so a name the profile lacks is one no pick ever reaches. - """ - if not isinstance(document, dict): - return [] - listed = {str(s) for s in document.get("systems") or []} - out: list[str] = [] - for index, entry in enumerate(document.get("files") or []): - if not isinstance(entry, dict): - continue - named = [entry["system"]] if entry.get("system") else [] - named += list(entry.get("systems") or []) - unknown = [str(s) for s in named if str(s) not in listed] - if unknown: - out.append( - f"{path.relative_to(REPO_ROOT)}: files[{index}] ({entry.get('name')}) " - f"system {', '.join(unknown)} not in the profile's systems" - ) - return out - - -def _group_requirement_split(path: Path, document: object) -> list[str]: - """A set named by a member and not declared, declared and never used, - or a member that writes a required of its own. - - The requirement belongs to the set, in the profile's groups map, and a - member's is derived from it. A value on the member is a second source - that can contradict the first: a true on the first name only wrote the - search order into required, and the other names read as optional. - """ - from model.alternatives import groups_of - - if not isinstance(document, dict): - return [] - label = path.relative_to(REPO_ROOT) - declared = set((document.get("groups") or {}).keys()) - used: set[str] = set() - out: list[str] = [] - for index, entry in enumerate(document.get("files") or []): - if not isinstance(entry, dict): - continue - names = groups_of(entry) - used.update(names) - if names and "required" in entry: - out.append(f"{label}: files[{index}] ({entry.get('name')}) is in a group " - "and writes required: the set's requirement is in groups") - out.extend(f"{label}: group {g} has no entry in groups" for g in sorted(used - declared)) - out.extend(f"{label}: groups declares {g}, which no entry names" for g in sorted(declared - used)) - return out - - -_CODE_SUFFIXES = frozenset( - ["c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "inc", "inl", "ipp", "m", "mm", "mjs", "cjs", "js", "jsx", "ts", "tsx", "py", "cs", "java", "kt", "go", "rs", "lua", "pas", "pp", "asm", "s", "sh", "bash", "zsh", "ps1", "bat", "cmd", "vbs", "swift", "d", "zig", "nim", "qml", "qc", "rb", "pl", "php", "scala", "ml", "hs", "dart", "vue", "ino", "z80", "smali"] -) -_CODE_FILE = re.compile(r"(?<=[\w+-])\.([A-Za-z0-9+]+)\b") -# A compiled image: a part that names one has to say where in it the file -# is read, an address, a decompiled function or an IL method. -# A name under a directory is a file of the tree it sits in, and a further -# extension (.dll.map) makes it another file. -_BINARY_FILE = re.compile( - r"(? bool: - """A source_ref cites a source file or a place in a compiled image. - - A part naming a binary without an address, a decompiled function or an - IL method says only that the binary exists: "import directory", - "string table" and "readelf -d" are not the code that reads a file. - """ - from model.sourceref import split_source_ref - - cited = False - for part in split_source_ref(ref): - located = bool(_BINARY_EVIDENCE.search(part.raw)) or any( - suffix.lower() in _CODE_SUFFIXES for suffix in _CODE_FILE.findall(part.raw) - ) - if _BINARY_FILE.search(part.raw) and not located: - return False - cited = cited or located - return cited - - -def _data_only_source_refs(path: Path, document: object) -> list[str]: - """A files[] source_ref that cites only data or build files. - - A data file is evidence that the emulator reads a file only once the - code that ships and parses it is cited too: iwadinfo.txt names the - IWADs, d_iwad.cpp is what reads it. 655 entries in 27 profiles cited - the table alone, and six of them named a file no code opens. - """ - if not isinstance(document, dict) or path.stem in DATA_ONLY_REF_EXCEPTIONS: - return [] - out: list[str] = [] - for index, entry in enumerate(document.get("files") or []): - if not isinstance(entry, dict) or not entry.get("source_ref"): - continue - refs = entry["source_ref"] - out.extend( - f"{path.relative_to(REPO_ROOT)}: files[{index}] ({entry.get('name')}) " - f"source_ref cites no code that reads the file: {ref}" - for ref in (refs.values() if isinstance(refs, dict) else [refs]) - if ref and not _ref_cites_code(str(ref)) - ) - return out - - -def _checks_without_values(path: Path, document: object) -> list[str]: - """A check an entry declares with nothing to compare against. - - validation: [crc32] with no crc32 runs nothing: the file passes whatever - it holds, and the report reads as checked. Fourteen profiles carried - one, the code they describe either refusing or warning on a value the - entry never wrote down. - """ - out: list[str] = [] - files = document.get("files") if isinstance(document, dict) else None - for index, entry in enumerate(files or []): - if not isinstance(entry, dict): - continue - declared = entry.get("validation") or [] - if isinstance(declared, dict): - declared = [check for checks in declared.values() for check in checks or []] - for check in declared: - fields = _CHECK_FIELDS.get(check) - if fields and not any(entry.get(field) not in (None, "", []) for field in fields): - out.append( - f"{path.relative_to(REPO_ROOT)}: files[{index}] ({entry.get('name')}) " - f"declares a {check} check with no {'/'.join(fields)} value" - ) - return out - - -def _validate_json_files( - paths: list[Path], - schema_name: str, - semantic_check: Callable[[Path, dict], list[str]] | None = None, -) -> list[str]: - validator = _validator(schema_name) - out: list[str] = [] - for path in paths: - try: - data = _load_json(path) - except (OSError, json.JSONDecodeError) as exc: - out.append(f"{path.relative_to(REPO_ROOT)}: {exc}") - continue - validation_errors = _errors(validator, data, str(path.relative_to(REPO_ROOT))) - out.extend(validation_errors) - # Every schema a semantic check follows describes an object. - if not validation_errors and semantic_check is not None and isinstance(data, dict): - out.extend(semantic_check(path, data)) - return out - - -def _validate_pack_manifests(dist: Path) -> list[str]: - """Validate the integrity manifest each generated pack carries. - - generate_pack.py writes manifest.json inside the archive, not beside it, - so a filesystem glob over dist/ matches nothing and silently validates - zero documents. - - Reading a pack while a build is writing it reports "File is not a zip - file" about an archive that is merely half-written, so this takes the same - shared lock --verify-packs does. A build holding the exclusive lock means - the packs on disk are mid-flight and there is nothing stable to validate. - """ - if not dist.is_dir(): - return [] - - try: - with artifact_lock(str(dist), exclusive=False): - return _scan_pack_manifests(dist) - except ArtifactLockBusy: - print( - f"note: {dist.name} is being written, skipping pack manifests", - file=sys.stderr, - ) - return [] - - -def _scan_pack_manifests(dist: Path) -> list[str]: - validator = _validator("pack-manifest.schema.json") - # The lists a pack carries for the installer, each under its own - # contract: the schemas name no other file, so they are checked here. - carried = { - "install_list": _validator("install-manifest.schema.json"), - "targets": _validator("target-manifest.schema.json"), - } - - def _label(path: Path) -> str: - resolved = path.resolve() - try: - return str(resolved.relative_to(REPO_ROOT)) - except ValueError: - return str(resolved) - - out: list[str] = [] - for archive in sorted(dist.glob("*.zip")): - try: - with zipfile.ZipFile(archive) as handle: - members = [ - name - for name in handle.namelist() - if PurePosixPath(name).name == "manifest.json" - ] - for member in members: - label = f"{_label(archive)}:{member}" - try: - document = json.loads(handle.read(member).decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - out.append(f"{label}: {exc}") - continue - out.extend(_errors(validator, document, label)) - for key, inner in carried.items(): - if isinstance(document, dict) and key in document: - out.extend(_errors(inner, document[key], f"{label}:{key}")) - except (OSError, zipfile.BadZipFile) as exc: - out.append(f"{_label(archive)}: {exc}") - return out - - -_UNREACHABLE_REF = re.compile( - r"(?:^|[\s,;(])(?:tmp/|/|[A-Za-z]:[\\/]|\.{1,2}/)[\w.\\/+-]*[\w+-]:\d+(?:-\d+)?" -) - - -def _unreachable_citations(path: Path, document: object) -> list[str]: - """Refs naming a place no repository can hold. - - A citation is read against a revision of a declared repository, so a - scratch directory, an absolute path or one climbing out of the tree can - never resolve and never will. kenji-nx carried tmp/es-de/ANDROID.md:470, - a path from whoever profiled it, which profile_sync could only report - missing forever. - """ - out: list[str] = [] - stack: list[object] = [document] - while stack: - node = stack.pop() - if isinstance(node, dict): - stack.extend(node.values()) - elif isinstance(node, list): - stack.extend(node) - elif isinstance(node, str): - out.extend( - f"{path.relative_to(REPO_ROOT)}: citation names a path outside " - f"any repository: {match.group().strip(' ,;(')}" - for match in _UNREACHABLE_REF.finditer(node) - ) - return out - - -_DOUBLED_PATH = re.compile(r"((?:[\w.-]+/){2,})\1") - - -def _doubled_paths(path: Path) -> list[str]: - """A citation whose directory is written twice in a row. - - Read from the raw text, comments included: primehack's note on the - Realtek loader cited Source/Core/Core/IOS/USB/Bluetooth/ twice over, a - path no revision holds, in a comment the parsed document never shows. - """ - out: list[str] = [] - for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): - match = _DOUBLED_PATH.search(line) - if match: - out.append( - f"{path.relative_to(REPO_ROOT)}:{number}: citation repeats its " - f"directory: {match.group(1)}" - ) - return out - - -def _unknown_data_dir_refs() -> list[str]: - """data_directories refs the registry does not define. - - A ref nobody registers is never fetched: yaps2 named yaps2-resources and - every run printed "not cached" while refresh_data_dirs had nothing to - refresh. - """ - registered = set(load_data_dir_registry(REPO_ROOT / PLATFORMS_DIR, required=True)) - out: list[str] = [] - for directory in (REPO_ROOT / EMULATORS_DIR, REPO_ROOT / PLATFORMS_DIR): - for path in source_yaml_paths(directory): - if path.name.startswith("_"): - continue - document = _source_mapping(path) - systems = document.get("systems") - holders = [document, *(systems.values() if isinstance(systems, dict) else [])] - for holder in holders: - if not isinstance(holder, dict): - continue - for entry in holder.get("data_directories") or []: - ref = entry.get("ref") if isinstance(entry, dict) else None - if ref and ref not in registered: - out.append( - f"{path.relative_to(REPO_ROOT)}: data directory {ref!r} " - f"is not in platforms/_data_dirs.yml" - ) - return out - - -def _repository_layout_in_profiles() -> list[str]: - """Profile destinations that name this repository's storage. - - `path:` is where the emulator's code reads the file, never where we keep - it: a profile written from a clone filed its variants under - `.variants/...`, and the pack then wrote them where no emulator looks. - """ - out: list[str] = [] - for path in source_yaml_paths(REPO_ROOT / EMULATORS_DIR): - document = _source_mapping(path) - for entry in document.get("files") or []: - if not isinstance(entry, dict): - continue - for key in ("path", "standalone_path"): - value = str(entry.get(key) or "") - if ".variants" in value.replace("\\", "/").split("/"): - out.append( - f"{path.relative_to(REPO_ROOT)}: {entry.get('name')} {key} " - f"names the repository's .variants/ storage: {value}" - ) - return out - - -def _semantic_envelope_checks(path: Path, document: dict) -> list[str]: - if document.get("count") != len(document.get("items", [])): - return [f"{path.relative_to(REPO_ROOT)}: count does not equal len(items)"] - return [] - - -def _semantic_database_checks(database: dict) -> list[str]: - out: list[str] = [] - files = database.get("files", {}) - if database.get("total_files") != len(files): - out.append("database.json: total_files does not equal len(files)") - if database.get("total_size") != sum(entry.get("size", 0) for entry in files.values()): - out.append("database.json: total_size does not equal the file-size sum") - # One path holds one content. Two entries naming the same path means one - # of them declares a hash the file at that path does not have. - owners: dict[str, str] = {} - for sha1, entry in files.items(): - if entry.get("sha1") != sha1: - out.append(f"database.json: files/{sha1}: key and sha1 differ") - path = entry.get("path", "") - if not path: - continue - first = owners.setdefault(path, sha1) - if first != sha1: - out.append( - f"database.json: {path} is claimed by {first} and {sha1}" - ) - return out - - -def _save_dir_without_library_name(path: Path, document: object) -> list[str]: - """A file the libretro build reads below the save directory, in a profile - naming no library_name. - - RetroArch hands each core / by default - (sort_savefiles_enable): without the name, packs and the installer - cannot say where the file goes, and leave it out. - """ - from resolve.validation import read_from_save_dir - - if not isinstance(document, dict): - return [] - if "library_name" in document: - return _save_folder_once_paths(path, document) - return [ - f"{path.relative_to(REPO_ROOT)}: files[{index}] ({entry.get('name')}) is read " - "below the save directory and the profile declares no library_name" - for index, entry in enumerate(document.get("files") or []) - if isinstance(entry, dict) - and read_from_save_dir(entry) - and not ("path" in entry and entry["path"] is None) - ] - - -def _save_folder_once_paths(path: Path, document: dict) -> list[str]: - """A core adding its own folder once: each save path starts with it. - - The pack places such a file at / whether the - frontend sorts saves by core or not, which holds only when the path - already names the folder the core reads below. - """ - from resolve.validation import read_from_save_dir - - if not document.get("save_folder_once"): - return [] - folder = f"{document.get('library_name') or ''}/" - return [ - f"{path.relative_to(REPO_ROOT)}: files[{index}] ({entry.get('name')}) does not " - f"start with {folder}, the folder save_folder_once says the core adds" - for index, entry in enumerate(document.get("files") or []) - if isinstance(entry, dict) - and read_from_save_dir(entry) - and entry.get("path") - and not str(entry["path"]).startswith(folder) - ] - - -def _registry_contract() -> list[str]: - """The registry against its schema, and a release that still ships a pack. - - `release_pack` is the only list of the ZIPs a release publishes: a - registry where no platform carries it would cut a release with no pack - at all, and every download link would lead to the command. - """ - registry_path = REPO_ROOT / PLATFORMS_DIR / "_registry.yml" - if not registry_path.is_file(): - return [] - with registry_path.open(encoding="utf-8") as handle: - registry = yaml_load(handle) or {} - label = str(registry_path.relative_to(REPO_ROOT)) - out = _errors(_validator("registry.schema.json"), registry, label) - platforms = registry.get("platforms") or {} - if isinstance(platforms, dict) and not any( - isinstance(entry, dict) and entry.get("release_pack") is True - for entry in platforms.values() - ): - out.append(f"{label}: no platform has release_pack: true") - return out - - -def _save_directory_blocks() -> list[str]: - """Each registry save_directory is null or a folder and a by_core flag. - - The folder names the pack folder and the save directory's default place - beside the BIOS directory: a relative path that never climbs. ``by_system`` (a save - folder per launched system) needs the platform file's libretro_systems, - and ``by_core_for`` names the cores a launcher sorts by core. - """ - platforms = load_platform_registry(REPO_ROOT / PLATFORMS_DIR) - out: list[str] = [] - for name, entry in sorted(platforms.items()): - if not isinstance(entry, dict) or "save_directory" not in entry: - continue - block = entry["save_directory"] - if block is None: - continue - folder = block.get("folder") if isinstance(block, dict) else None - sorted_cores = block.get("by_core_for", []) if isinstance(block, dict) else None - if ( - not isinstance(block, dict) - or not {"folder", "by_core"} <= set(block) <= { - "folder", "by_core", "by_system", "by_core_for", "pack_folder", - } - or not isinstance(block.get("pack_folder", "x"), str) - or "/" in str(block.get("pack_folder", "")) - or not isinstance(folder, str) - or not folder - or "\\" in folder - or any(part in ("", ".", "..") for part in folder.split("/")) - or not isinstance(block.get("by_core"), bool) - or not isinstance(block.get("by_system", False), bool) - or not isinstance(sorted_cores, list) - or not all(isinstance(core, str) and core for core in sorted_cores) - ): - out.append( - f"platforms/_registry.yml: {name}.save_directory must be null or " - "{folder: , by_core: , by_system: , " - "by_core_for: []}" - ) - continue - if block.get("by_system") and not _libretro_systems(name): - out.append( - f"platforms/_registry.yml: {name}.save_directory.by_system and " - f"platforms/{name}.yml lists no libretro_systems" - ) - in_pack = block.get("pack_folder") or folder - taken = _bios_tree_below(name, in_pack) - if taken: - out.append( - f"platforms/_registry.yml: {name}.save_directory puts the save " - f"files in {in_pack}/, which the BIOS tree uses ({taken}): " - "name another pack_folder" - ) - return out - - -def _bios_tree_below(platform: str, folder: str) -> str: - """A destination the platform declares below ``folder``, or empty.""" - from model.platforms import load_platform_config - - try: - config = load_platform_config(platform, str(REPO_ROOT / PLATFORMS_DIR)) - except FileNotFoundError: - return "" - prefix = f"{folder}/".lower() - return next( - ( - str(entry["destination"]) - for system in (config.get("systems") or {}).values() - for entry in system.get("files") or [] - if str(entry.get("destination") or "").lower().startswith(prefix) - ), - "", - ) - - -def _libretro_systems(platform: str) -> dict: - """The platform file's core -> systems table, inheritance included.""" - from model.platforms import load_platform_config - - try: - config = load_platform_config(platform, str(REPO_ROOT / PLATFORMS_DIR)) - except FileNotFoundError: - return {} - return config.get("libretro_systems") or {} - - -def _semantic_install_checks(path: Path, manifest: dict) -> list[str]: - out: list[str] = [] - files = manifest.get("files", []) - if manifest.get("total_files") != len(files): - out.append(f"{path.relative_to(REPO_ROOT)}: total_files does not equal len(files)") - if manifest.get("total_size") != sum(entry.get("size", 0) for entry in files): - out.append(f"{path.relative_to(REPO_ROOT)}: total_size does not equal the file-size sum") - omitted = manifest.get("omitted_files", []) - if manifest.get("total_omitted") != len(omitted): - out.append( - f"{path.relative_to(REPO_ROOT)}: total_omitted does not equal " - "len(omitted_files)" - ) - # One dest below the BIOS folder and one below the save directory are - # two places. - destinations = [(entry.get("root"), entry.get("dest")) for entry in files] - if len(destinations) != len(set(destinations)): - out.append(f"{path.relative_to(REPO_ROOT)}: duplicate destinations") - # root: emulator is each core's own folder: mame2015 and mame2016 read - # 3dobios.zip in two places, one omission each, named by its cores. - omitted_destinations = [ - (entry.get("root"), entry.get("dest"), - tuple(entry.get("cores") or ()) if entry.get("root") == "emulator" else ()) - for entry in omitted - ] - if len(omitted_destinations) != len(set(omitted_destinations)): - out.append(f"{path.relative_to(REPO_ROOT)}: duplicate omitted destinations") - overlap = set(destinations) & set(omitted_destinations) - if overlap: - out.append( - f"{path.relative_to(REPO_ROOT)}: destinations are both downloadable and omitted" - ) - saved = [ - entry for entry in [*files, *manifest.get("case_variants", [])] - if entry.get("root") == "save" - ] - layout = manifest.get("save_directory") - if saved and not layout: - out.append( - f"{path.relative_to(REPO_ROOT)}: entries read below the save directory " - "and no save_directory" - ) - builds = REPO_ROOT / "install" / "standalone" / path.name - if manifest.get("standalone_builds") and path.parent == REPO_ROOT / "install" \ - and not builds.is_file(): - out.append(f"{path.relative_to(REPO_ROOT)}: standalone_builds and no " - f"install/standalone/{path.name}") - stray = sorted( - entry["dest"] for entry in [*files, *omitted] - if entry.get("core_folder") and entry.get("root") != "save" - ) - if stray: - out.append( - f"{path.relative_to(REPO_ROOT)}: core_folder outside root: save ({stray[0]})" - ) - return out - - -def _semantic_standalone_checks(path: Path, layouts: object) -> list[str]: - """A standalone layout file goes with its platform's list: the list - names the same builds, and each [dest, sha1] item takes its download - from a copy of that list.""" - where = path.relative_to(REPO_ROOT) - if not isinstance(layouts, dict): - return [f"{where}: not an object"] - plat = layouts.get("platform") - if path.stem != plat: - return [f"{where}: platform {plat} in a file named {path.stem}"] - listed = REPO_ROOT / "install" / f"{plat}.json" - if not listed.is_file(): - return [f"{where}: no install/{plat}.json beside it"] - manifest = json.loads(listed.read_text(encoding="utf-8")) - out: list[str] = [] - if sorted(layouts.get("standalone_layouts", {})) != manifest.get("standalone_builds"): - out.append(f"{where}: its builds differ from standalone_builds in {listed.name}") - held = { - copy.get("sha1") - for entry in [*manifest.get("files", []), *(manifest.get("truth_files") or [])] - for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] - } - missing = sorted({ - item[1] for items in layouts.get("standalone_layouts", {}).values() - for item in items if isinstance(item, list) and item[1] not in held - }) - if missing: - out.append(f"{where}: {len(missing)} sha1 no copy of {listed.name} carries " - f"({missing[0]})") - return out - - -def _event_schema_errors() -> list[str]: - """install-events.schema.json is EVENT_KEYS written out, and a valid schema.""" - from installer_build import eventschema - - path = REPO_ROOT / "schemas" / eventschema.OUTPUT.name - label = path.relative_to(REPO_ROOT).as_posix() - if not path.is_file(): - return [f"{label}: missing, run python scripts/generate_event_schema.py"] - if path.read_text(encoding="utf-8") != eventschema.render( - eventschema.build_schema() - ): - return [f"{label}: differs from EVENT_KEYS in install.py, run " - "python scripts/generate_event_schema.py"] - Draft202012Validator.check_schema(_load_json(path)) - return [] - - -def unchecked_formats() -> list[str]: - """Formats the schemas declare that this jsonschema install cannot check. - - date-time and uri need the format extras. Without them the ten format - constraints of the published schemas were accepted unread. - """ - used = { - match - for path in SCHEMAS.glob("*.json") - for match in re.findall(r'"format"\s*:\s*"([^"]+)"', path.read_text(encoding="utf-8")) - } - return sorted(used - set(FormatChecker().checkers)) - - -def _format_errors() -> list[str]: - """jsonschema skips a format it has no checker for: say so, and fail.""" - return [ - f"no checker for format {name}: install \"jsonschema[format-nongpl]\"" - for name in unchecked_formats() - ] - - -def _measurement_errors(root: Path | None = None) -> list[str]: - """Every record line under measurements/, against its schema and the - rules model.measurements.read_records applies.""" - from model import measurements as mr - - root = root or REPO_ROOT - validator = _validator("core-probe-record.schema.json") - out: list[str] = [] - campaign = {mr.records_path(name): _validator(schema) - for name, (_, schema) in mr.CAMPAIGN_FILES.items()} - for path, file in sorted(mr.tree_files(root).items()): - if not path.endswith(".jsonl"): - continue - for number, line in enumerate(file.read_text(encoding="utf-8").splitlines(), 1): - try: - record = json.loads(line) - except json.JSONDecodeError as exc: - out.append(f"{path}:{number}: {exc}") - continue - out.extend(_errors(campaign.get(path, validator), record, f"{path}:{number}")) - if not out: - try: - mr.read_records(root) - for name in mr.CAMPAIGN_FILES: - mr.read_campaign(root, name) - except mr.MeasurementsError as exc: - out.append(str(exc)) - return out - - -def _defs_validator(name: str, definition: str) -> Draft202012Validator: - """A validator for one $defs entry of a schema file.""" - schema = _json_object(SCHEMAS / name) - Draft202012Validator.check_schema(schema) - return Draft202012Validator( - {**schema, "$ref": f"#/$defs/{definition}"}, format_checker=FormatChecker() - ) - - -def _romfolder_errors() -> list[str]: - """Every scraped setup against its schema, and every source_ref against - the sources the file declares: a ref naming no declared repository can - never be read back at a pin.""" - from model.romfolders import source_refs, split_refs - - directory = REPO_ROOT / PLATFORMS_DIR / "romfolders" - if not directory.is_dir(): - return [] - validator = _validator("romfolders.schema.json") - out: list[str] = [] - for path in sorted(directory.glob("*.yml")): - label = str(path.relative_to(REPO_ROOT)) - with path.open(encoding="utf-8") as handle: - data = yaml_load(handle) - errors = _errors(validator, data, label) - out.extend(errors) - if errors: - continue - declared = set(data["sources"]) - for ref in source_refs(data): - try: - parts = split_refs(ref) - except ValueError as exc: - out.append(f"{label}: {exc}") - continue - for key, path, lines in parts: - if key not in declared: - part = f"{key} {path}" + (f":{lines}" if lines else "") - out.append(f"{label}: source_ref {part!r} names undeclared source {key!r}") - return out - - -# Source data of the games-on-card mode: file pattern -> schema. -_GAMES_SOURCES = ( - ("games/catalogs/*/*.json", "game-catalog.schema.json"), - ("games/arcade/*.json", "arcade-parents.schema.json"), - ("games/headers.yml", "game-headers.schema.json"), - ("games/regions.yml", "game-regions.schema.json"), - ("games/extras.yml", "game-extras.schema.json"), -) - - -def _games_source_errors() -> list[str]: - out: list[str] = [] - for pattern, schema in _GAMES_SOURCES: - paths = sorted(REPO_ROOT.glob(pattern)) - if not paths: - continue - validator = _validator(schema) - for path in paths: - with path.open(encoding="utf-8") as handle: - data = json.load(handle) if path.suffix == ".json" else yaml_load(handle) - out.extend(_errors(validator, data, str(path.relative_to(REPO_ROOT)))) - return out - - -def _arcade_pin_errors() -> list[str]: - """games/arcade/.json read at the revision and version its - profile pins. A bump of the profile left the game-to-BIOS map of the old - code in place, and the installer kept serving it.""" - out: list[str] = [] - for path in sorted((REPO_ROOT / "games" / "arcade").glob("*.json")): - doc = _json_object(path) - profile_path = REPO_ROOT / EMULATORS_DIR / f"{doc.get('profile')}.yml" - label = str(path.relative_to(REPO_ROOT)) - if not profile_path.is_file(): - out.append(f"{label}: no profile emulators/{profile_path.name}") - continue - profile = _source_mapping(profile_path) - pinned = profile.get("source_commit") - pins = set(pinned.values()) if isinstance(pinned, dict) else {pinned} - commit = (doc.get("source") or {}).get("commit") - drifted = [] - if commit and commit not in pins: - drifted.append(f"read at {commit[:12]}, the profile pins {pinned}") - if doc.get("core_version") != profile.get("core_version"): - drifted.append(f"core_version {doc.get('core_version')!r}, " - f"the profile says {profile.get('core_version')!r}") - if drifted: - out.append(f"{label}: {'; '.join(drifted)} " - f"(python -m scripts.scraper.arcade_parent_importer --profile {doc.get('profile')})") - return out - - -def _games_index_errors() -> list[str]: - """install/games/: each document against its kind, and the index - against the files it lists (size and sha256).""" - import hashlib - - base = REPO_ROOT / "install" / "games" - index_path = base / "index.json" - if not index_path.exists(): - return [] - out: list[str] = [] - index = _json_object(index_path) - out.extend(_errors(_defs_validator("games-index.schema.json", "index"), index, - str(index_path.relative_to(REPO_ROOT)))) - kinds = { - "setups": _defs_validator("games-index.schema.json", "setup"), - "fallback": _defs_validator("games-index.schema.json", "fallback"), - "systems": _defs_validator("games-index.schema.json", "system"), - "arcade": _validator("arcade-parents.schema.json"), - } - listed: set[Path] = set() - for kind, validator in kinds.items(): - for entry in (index.get(kind) or {}).values(): - path = base / entry["file"] - listed.add(path) - label = str(path.relative_to(REPO_ROOT)) - if not path.exists(): - out.append(f"{label}: listed in index.json, absent") - continue - data = path.read_bytes() - if len(data) != entry["size"] or hashlib.sha256(data).hexdigest() != entry["sha256"]: - out.append(f"{label}: size or sha256 differs from index.json") - out.extend(_errors(validator, json.loads(data), label)) - out.extend(f"{path.relative_to(REPO_ROOT)}: not listed in index.json" - for path in sorted(base.rglob("*.json")) if path != index_path and path not in listed) - return out +from schemas.run import validation_errors def main() -> int: @@ -1004,90 +28,7 @@ def main() -> int: ) args = parser.parse_args() - errors: list[str] = _format_errors() - errors.extend( - _validate_yaml_directory(REPO_ROOT / EMULATORS_DIR, "emulator.schema.json") - ) - errors.extend( - _validate_yaml_directory( - REPO_ROOT / PLATFORMS_DIR, "platform.schema.json", skip_private=True - ) - ) - errors.extend(_unknown_data_dir_refs()) - errors.extend(_repository_layout_in_profiles()) - errors.extend(_save_directory_blocks()) - errors.extend(_registry_contract()) - errors.extend(_event_schema_errors()) - errors.extend(_measurement_errors()) - errors.extend(_romfolder_errors()) - errors.extend(_games_source_errors()) - errors.extend(_arcade_pin_errors()) - - if not args.source_only: - database_path = REPO_ROOT / DB_FILE - errors.extend( - _validate_json_files( - [database_path], - "database.schema.json", - lambda _path, database: _semantic_database_checks(database), - ) - ) - - install_paths = sorted((REPO_ROOT / "install").glob("*.json")) - errors.extend( - _validate_json_files( - install_paths, "install-manifest.schema.json", _semantic_install_checks - ) - ) - - standalone_paths = sorted((REPO_ROOT / "install" / "standalone").glob("*.json")) - errors.extend( - _validate_json_files( - standalone_paths, "install-standalone.schema.json", - _semantic_standalone_checks, - ) - ) - - target_paths = sorted((REPO_ROOT / "install" / "targets").glob("*.json")) - errors.extend( - _validate_json_files(target_paths, "target-manifest.schema.json") - ) - - release_path = REPO_ROOT / "release.json" - if release_path.exists(): - errors.extend(_validate_json_files([release_path], "release.schema.json")) - - stats_path = REPO_ROOT / "website" / "public" / "stats.json" - if stats_path.exists(): - errors.extend(_validate_json_files([stats_path], "stats.schema.json")) - - api_dir = REPO_ROOT / "website" / "public" / "api" / "v1" - api_database = api_dir / "database.json" - if api_database.exists(): - errors.extend( - _validate_json_files([api_database], "database.schema.json") - ) - api_stats = api_dir / "stats.json" - if api_stats.exists(): - errors.extend(_validate_json_files([api_stats], "stats.schema.json")) - envelope_paths = [ - api_dir / name - for name in ("catalog.json", "platforms.json", "emulators.json", "gaps.json") - if (api_dir / name).exists() - ] + sorted((api_dir / "platforms").glob("*.json")) + sorted( - (api_dir / "systems").glob("*.json") - ) + sorted((api_dir / "lookup").glob("*.json")) - errors.extend( - _validate_json_files( - envelope_paths, - "site-api-envelope.schema.json", - _semantic_envelope_checks, - ) - ) - - errors.extend(_games_index_errors()) - errors.extend(_validate_pack_manifests(REPO_ROOT / "dist")) - + errors = validation_errors(args.source_only) if errors: for error in errors: print(f"ERROR {error}") diff --git a/tests/sources.py b/tests/sources.py index 252784e35..07be4ac79 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -88,6 +88,13 @@ COMMANDS = { "sitesources.py": ("sitegen/sources.py",), "site_markdown.py": ("sitegen/pagemarkdown.py",), "validate_site.py": ("sitegen/validate.py",), + "validate_schemas.py": ( + "schemas/validators.py", "schemas/sources.py", "schemas/profilechecks.py", + "schemas/citations.py", "schemas/platformchecks.py", "schemas/sourcetree.py", + "schemas/registry.py", "schemas/documents.py", "schemas/installs.py", + "schemas/packmanifests.py", "schemas/events.py", "schemas/measurements.py", + "schemas/romfolders.py", "schemas/games.py", "schemas/run.py", + ), "site_insights.py": ("sitegen/insights.py",), "generate_readme.py": ("sitegen/readme.py",), "romset_recipes.py": ( diff --git a/tests/test_arcade_parents.py b/tests/test_arcade_parents.py index 457798210..194f2b2d3 100644 --- a/tests/test_arcade_parents.py +++ b/tests/test_arcade_parents.py @@ -412,9 +412,9 @@ class CommittedIndex(unittest.TestCase): """A bumped profile kept the game-to-BIOS map of the old code.""" from unittest import mock - import validate_schemas + from schemas import games - self.assertEqual(validate_schemas._arcade_pin_errors(), []) + self.assertEqual(games.arcade_pin_errors(), []) with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) (root / "games" / "arcade").mkdir(parents=True) @@ -423,8 +423,8 @@ class CommittedIndex(unittest.TestCase): f"source_commit: {'b' * 40}\ncore_version: '0.2'\n") (root / "games" / "arcade" / "core.json").write_text(json.dumps( {"profile": "core", "core_version": "0.1", "source": {"commit": COMMIT}})) - with mock.patch.object(validate_schemas, "REPO_ROOT", root): - (error,) = validate_schemas._arcade_pin_errors() + with mock.patch("core.paths.REPO_ROOT", root): + (error,) = games.arcade_pin_errors() self.assertIn("read at aaaaaaaaaaaa", error) self.assertIn("core_version '0.1'", error) self.assertIn("arcade_parent_importer --profile core", error) diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index d9eab78b8..1ba3ac55b 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -472,9 +472,9 @@ class UnreachableCitationRegressions(unittest.TestCase): @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") def _hits(self, text: str) -> bool: - import validate_schemas + from schemas import citations - return bool(validate_schemas._UNREACHABLE_REF.search(" " + text)) + return bool(citations.UNREACHABLE_REF.search(" " + text)) def test_a_scratch_directory_is_rejected(self): self.assertTrue(self._hits("tmp/es-de/ANDROID.md:470-474")) @@ -499,13 +499,13 @@ class UnreachableCitationRegressions(unittest.TestCase): @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") def test_the_corpus_carries_none(self): - import validate_schemas + from schemas import citations errors = [] for path in sorted((ROOT / "emulators").glob("*.yml")): with path.open(encoding="utf-8") as handle: errors.extend( - validate_schemas._unreachable_citations(path, yaml.safe_load(handle)) + citations.unreachable_citations(path, yaml.safe_load(handle)) ) self.assertEqual(errors, []) @@ -517,9 +517,9 @@ class DoubledCitationPaths(unittest.TestCase): showed it to the citation checks.""" def _hits(self, text: str) -> bool: - import validate_schemas + from schemas import citations - return bool(validate_schemas._DOUBLED_PATH.search(text)) + return bool(citations.DOUBLED_PATH.search(text)) def test_a_repeated_directory_is_rejected(self): self.assertTrue(self._hits( @@ -537,11 +537,11 @@ class DoubledCitationPaths(unittest.TestCase): self.assertFalse(self._hits(good)) def test_the_corpus_carries_none(self): - import validate_schemas + from schemas import citations errors = [] for path in sorted((ROOT / "emulators").glob("*.yml")): - errors.extend(validate_schemas._doubled_paths(path)) + errors.extend(citations.doubled_paths(path)) self.assertEqual(errors, []) @@ -1377,11 +1377,11 @@ class SchemaFormatsAreChecked(unittest.TestCase): @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") def test_a_missing_checker_is_named(self): - import validate_schemas + from schemas import validators empty = mock.Mock(checkers={}) - with mock.patch.object(validate_schemas, "FormatChecker", return_value=empty): - self.assertEqual(validate_schemas.unchecked_formats(), ["date-time", "uri"]) + with mock.patch.object(validators, "FormatChecker", return_value=empty): + self.assertEqual(validators.unchecked_formats(), ["date-time", "uri"]) def test_every_install_asks_for_the_extras(self): for path in (".github/workflows/validate.yml", ".github/workflows/deploy-site.yml", @@ -2162,7 +2162,7 @@ class InstallerBoundaryRegressions(unittest.TestCase): A filesystem glob over dist/ matches nothing and reports success without validating a single document. """ - import validate_schemas + from schemas import packmanifests with tempfile.TemporaryDirectory() as directory: dist = Path(directory) @@ -2180,7 +2180,7 @@ class InstallerBoundaryRegressions(unittest.TestCase): with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: archive.writestr("manifest.json", json.dumps(broken)) - errors = validate_schemas._validate_pack_manifests(dist) + errors = packmanifests.validate_pack_manifests(dist) self.assertTrue(errors, "an invalid in-archive manifest must be reported") self.assertTrue(any("sha1" in message for message in errors), errors) @@ -2191,7 +2191,7 @@ class InstallerBoundaryRegressions(unittest.TestCase): alone. The pack schema refused both keys, and each is checked under its own contract.""" from packs import scope - import validate_schemas + from schemas import packmanifests install_list = json.loads((ROOT / "install" / "romm.json").read_text(encoding="utf-8")) targets = {"browser": None, "rpi4": {"cores": ["mgba"], "images": ["rpi4"]}} @@ -2210,13 +2210,13 @@ class InstallerBoundaryRegressions(unittest.TestCase): dist = Path(directory) with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: archive.writestr("manifest.json", json.dumps(document)) - self.assertEqual(validate_schemas._validate_pack_manifests(dist), []) + self.assertEqual(packmanifests.validate_pack_manifests(dist), []) broken = {**document, "targets": {"rpi4": [1]}, "install_list": {**install_list, "files": "none"}} with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: archive.writestr("manifest.json", json.dumps(broken)) - errors = validate_schemas._validate_pack_manifests(dist) + errors = packmanifests.validate_pack_manifests(dist) self.assertTrue(any(":targets:" in message for message in errors), errors) self.assertTrue(any(":install_list:" in message for message in errors), errors) @@ -3905,8 +3905,8 @@ class ModuleConstantsDeclaredOnce(unittest.TestCase): class OnlyTheSchemaValidatorNeedsJsonschema(unittest.TestCase): """Build scripts and install.py run on stdlib plus pyyaml, and jsonschema is - tooling for validate_schemas and CI. An import anywhere else turns a - contributor's pipeline run into an ImportError.""" + tooling for the schemas package behind validate_schemas and CI. An import + anywhere else turns a contributor's pipeline run into an ImportError.""" @staticmethod def _imports_jsonschema(source: str) -> bool: @@ -3925,7 +3925,7 @@ class OnlyTheSchemaValidatorNeedsJsonschema(unittest.TestCase): offenders = [ str(path.relative_to(ROOT)) for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"] - if path.name != "validate_schemas.py" + if path.parent != ROOT / "scripts" / "schemas" and self._imports_jsonschema(path.read_text()) ] self.assertEqual(offenders, []) @@ -3945,14 +3945,14 @@ class HashMergeBackupsAreNotSources(unittest.TestCase): def test_the_validator_skips_a_backup(self): try: - from validate_schemas import _validate_yaml_directory + from schemas.sourcetree import validate_yaml_directory except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") with tempfile.TemporaryDirectory() as directory: (Path(directory) / "mame.old.yml").write_text("emulator: [\n") self.assertEqual( - _validate_yaml_directory(Path(directory), "emulator.schema.json"), [] + validate_yaml_directory(Path(directory), "emulator.schema.json"), [] ) def test_the_backup_suffix_is_written_once(self): @@ -6161,7 +6161,7 @@ class AProfilePathIsTheEmulatorsNotOurs(unittest.TestCase): from unittest import mock try: - from scripts import validate_schemas + from schemas import sourcetree except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") @@ -6172,8 +6172,8 @@ class AProfilePathIsTheEmulatorsNotOurs(unittest.TestCase): "emulator: X\nfiles:\n - name: scph1001.bin\n" " path: .variants/scph1001.bin.abc12345\n" ) - with mock.patch.object(validate_schemas, "REPO_ROOT", Path(directory)): - errors = validate_schemas._repository_layout_in_profiles() + with mock.patch("core.paths.REPO_ROOT", Path(directory)): + errors = sourcetree.repository_layout_in_profiles() self.assertEqual(len(errors), 1) self.assertIn(".variants/", errors[0]) diff --git a/tests/test_checks_have_values.py b/tests/test_checks_have_values.py index 27a55f829..1ba4019db 100644 --- a/tests/test_checks_have_values.py +++ b/tests/test_checks_have_values.py @@ -20,10 +20,10 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class ChecksHaveValues(unittest.TestCase): def setUp(self): try: - import validate_schemas + from schemas import profilechecks except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") - self.check = validate_schemas._checks_without_values + self.check = profilechecks.checks_without_values def test_a_valueless_check_is_named(self): path = REPO_ROOT / "emulators" / "x.yml" diff --git a/tests/test_data_dir_refs.py b/tests/test_data_dir_refs.py index 32b01ec6b..21f3f0a1e 100644 --- a/tests/test_data_dir_refs.py +++ b/tests/test_data_dir_refs.py @@ -17,10 +17,10 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class DataDirRefsAreRegistered(unittest.TestCase): def test_no_unknown_ref(self): try: - import validate_schemas + from schemas import sourcetree except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") - self.assertEqual(validate_schemas._unknown_data_dir_refs(), []) + self.assertEqual(sourcetree.unknown_data_dir_refs(), []) @@ -33,7 +33,7 @@ class EachSourceIsParsedOnce(unittest.TestCase): from unittest import mock try: - import validate_schemas + from schemas import sources, sourcetree except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") with tempfile.TemporaryDirectory() as tmp: @@ -44,15 +44,15 @@ class EachSourceIsParsedOnce(unittest.TestCase): (root / "emulators" / "core.yml").write_text( "emulator: Core\nfiles:\n- name: a.bin\n path: .variants/a.bin\n") loaded = [] - real = validate_schemas.yaml_load - with mock.patch.object(validate_schemas, "REPO_ROOT", root), \ - mock.patch.object(validate_schemas, "yaml_load", + real = sources.yaml_load + with mock.patch("core.paths.REPO_ROOT", root), \ + mock.patch.object(sources, "yaml_load", side_effect=lambda h: loaded.append(h.name) or real(h)): - validate_schemas._validate_yaml_directory(root / "emulators", "emulator.schema.json") - validate_schemas._unknown_data_dir_refs() - layout = validate_schemas._repository_layout_in_profiles() + sourcetree.validate_yaml_directory(root / "emulators", "emulator.schema.json") + sourcetree.unknown_data_dir_refs() + layout = sourcetree.repository_layout_in_profiles() # _data_dirs.yml is read by model.registry.load_data_dir_registry, so - # only the profile passes through validate_schemas' own loader. + # only the profile passes through the schema checks' own loader. self.assertEqual(sorted(Path(n).name for n in loaded), ["core.yml"]) self.assertEqual(len(layout), 1) diff --git a/tests/test_data_only_refs.py b/tests/test_data_only_refs.py index dcce22884..048b47833 100644 --- a/tests/test_data_only_refs.py +++ b/tests/test_data_only_refs.py @@ -10,9 +10,9 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] try: - import validate_schemas + from schemas import citations, sources except ImportError as exc: - validate_schemas = None + citations = sources = None IMPORT_ERROR = str(exc) else: IMPORT_ERROR = "" @@ -22,12 +22,12 @@ def _profile(ref: object) -> dict: return {"files": [{"name": "doom.wad", "source_ref": ref}]} -@unittest.skipIf(validate_schemas is None, f"validate_schemas unavailable: {IMPORT_ERROR}") +@unittest.skipIf(citations is None, f"the schema checks are unavailable: {IMPORT_ERROR}") class DataOnlySourceRefs(unittest.TestCase): path = REPO_ROOT / "emulators" / "synthetic.yml" def errors(self, ref: object) -> list[str]: - return validate_schemas._data_only_source_refs(self.path, _profile(ref)) + return citations.data_only_source_refs(self.path, _profile(ref)) def test_a_data_table_alone_is_refused(self): self.assertEqual(len(self.errors("wadsrc_extra/static/iwadinfo.txt:420, 437")), 1) @@ -78,15 +78,15 @@ class DataOnlySourceRefs(unittest.TestCase): def test_an_excepted_profile_is_not_judged(self): path = REPO_ROOT / "emulators" / "synthetic.yml" - exceptions = validate_schemas.DATA_ONLY_REF_EXCEPTIONS + exceptions = citations.DATA_ONLY_REF_EXCEPTIONS exceptions["synthetic"] = "binary found nowhere" try: - self.assertEqual(validate_schemas._data_only_source_refs(path, _profile("history.txt:38")), []) + self.assertEqual(citations.data_only_source_refs(path, _profile("history.txt:38")), []) finally: del exceptions["synthetic"] def test_every_exception_names_a_profile_and_a_reason(self): - for name, reason in validate_schemas.DATA_ONLY_REF_EXCEPTIONS.items(): + for name, reason in citations.DATA_ONLY_REF_EXCEPTIONS.items(): with self.subTest(profile=name): self.assertTrue((REPO_ROOT / "emulators" / f"{name}.yml").is_file()) self.assertTrue(reason.strip()) @@ -94,8 +94,8 @@ class DataOnlySourceRefs(unittest.TestCase): def test_the_profiles_cite_their_readers(self): errors: list[str] = [] for path in sorted((REPO_ROOT / "emulators").glob("*.yml")): - errors.extend(validate_schemas._data_only_source_refs( - path, validate_schemas._load_source(path))) + errors.extend(citations.data_only_source_refs( + path, sources.load_source(path))) self.assertEqual(errors, []) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index c2822f4ce..b45dcd80b 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -7018,19 +7018,19 @@ class OneOfASearchList(unittest.TestCase): @unittest.skipUnless(HAS_JSONSCHEMA, "validate_schemas needs jsonschema") def test_schema_refuses_a_set_split_on_required(self): - from validate_schemas import _group_requirement_split + from schemas.profilechecks import group_requirement_split from core.paths import REPO_ROOT path = REPO_ROOT / "emulators" / "seq.yml" own_value = {"groups": {"g": {"required": True}}, "files": [{"name": "a", "group": "g", "required": False}, {"name": "b", "group": "g"}]} - self.assertEqual(len(_group_requirement_split(path, own_value)), 1) + self.assertEqual(len(group_requirement_split(path, own_value)), 1) undeclared_set = {"files": [{"name": "a", "group": "g"}]} - self.assertEqual(len(_group_requirement_split(path, undeclared_set)), 1) + self.assertEqual(len(group_requirement_split(path, undeclared_set)), 1) unused = {"groups": {"g": {"required": True}}, "files": [{"name": "a"}]} - self.assertEqual(len(_group_requirement_split(path, unused)), 1) - self.assertEqual(_group_requirement_split(path, self.raw), []) + self.assertEqual(len(group_requirement_split(path, unused)), 1) + self.assertEqual(group_requirement_split(path, self.raw), []) def test_a_shared_fallback_takes_its_requirement_from_its_sets(self): """pom2 falls back on apple2e.rom for the //e it boots by default diff --git a/tests/test_install_expert.py b/tests/test_install_expert.py index 1f5edf527..8cfc1bef5 100644 --- a/tests/test_install_expert.py +++ b/tests/test_install_expert.py @@ -593,7 +593,7 @@ class ExpertRuns(Lists): from unittest import mock try: - import validate_schemas + from schemas import installs except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") @@ -603,8 +603,8 @@ class ExpertRuns(Lists): json.dumps({**LIST, "truth_files": None}), encoding="utf-8") path = Path(root) / "install" / "standalone" / "retroarch.json" path.write_text(json.dumps(LAYOUTS), encoding="utf-8") - with mock.patch.object(validate_schemas, "REPO_ROOT", Path(root)): - self.assertEqual(validate_schemas._semantic_standalone_checks(path, LAYOUTS), + with mock.patch("core.paths.REPO_ROOT", Path(root)): + self.assertEqual(installs.semantic_standalone_checks(path, LAYOUTS), []) def test_a_layout_file_missing_or_unreachable_refuses_on_one_line(self): diff --git a/tests/test_launcher_evidence.py b/tests/test_launcher_evidence.py index a2c4c4b88..803870b75 100644 --- a/tests/test_launcher_evidence.py +++ b/tests/test_launcher_evidence.py @@ -11,6 +11,7 @@ import tests import unittest from pathlib import Path +from types import SimpleNamespace import yaml @@ -31,13 +32,17 @@ from resolve.launcherrefs import config_ref, is_feature_ref REPO_ROOT = Path(__file__).resolve().parents[1] -def schema_checks(test: unittest.TestCase): - """validate_schemas, or a skip: it needs jsonschema, the build does not.""" +def schema_checks(test: unittest.TestCase) -> SimpleNamespace: + """The launcher and config_reads checks, or a skip: they need jsonschema, + the build does not.""" try: - import validate_schemas + from schemas import platformchecks, profilechecks except ImportError as exc: test.skipTest(f"validate_schemas needs jsonschema: {exc}") - return validate_schemas + return SimpleNamespace( + config_records_without_evidence=platformchecks.config_records_without_evidence, + config_reads_without_build=profilechecks.config_reads_without_build, + ) def record(**fields: object) -> dict: @@ -241,27 +246,27 @@ class StartScripts(unittest.TestCase): class Invariants(unittest.TestCase): def test_a_config_record_without_its_platform_links_is_an_error(self) -> None: - _config_records_without_evidence = schema_checks(self)._config_records_without_evidence + config_records_without_evidence = schema_checks(self).config_records_without_evidence path = REPO_ROOT / "platforms" / "x.yml" bare = {k: v for k, v in record().items() if k not in ("installs", "overrides")} listed = record(source_ref="gen.cs:3, es_features.yml:9") - errors = _config_records_without_evidence(path, {"launchers": [record(), bare, listed]}) + errors = config_records_without_evidence(path, {"launchers": [record(), bare, listed]}) self.assertEqual(len(errors), 2) self.assertIn("without installs and overrides", errors[0]) self.assertIn("choices_from holds it", errors[1]) def test_reads_naming_a_platform_need_its_build(self) -> None: - _config_reads_without_build = schema_checks(self)._config_reads_without_build + config_reads_without_build = schema_checks(self).config_reads_without_build path = REPO_ROOT / "emulators" / "x.yml" reads = [{"file": "a.ini", "platforms": ["rocknix"], "source_ref": "a:1", "keys": []}] - self.assertEqual(len(_config_reads_without_build(path, {"config_reads": reads})), 1) - self.assertEqual(_config_reads_without_build( + self.assertEqual(len(config_reads_without_build(path, {"config_reads": reads})), 1) + self.assertEqual(config_reads_without_build( path, {"config_reads": reads, "pin_build": [{"platform": "rocknix"}]} ), []) pinned = [{**reads[0], "revision": "c" * 40, "revision_from": "the exe"}] - self.assertEqual(_config_reads_without_build(path, {"config_reads": pinned}), []) + self.assertEqual(config_reads_without_build(path, {"config_reads": pinned}), []) closed = [{**reads[0], "binary_sha256": "d" * 64, "revision_from": "the archive"}] - self.assertEqual(_config_reads_without_build(path, {"config_reads": closed}), []) + self.assertEqual(config_reads_without_build(path, {"config_reads": closed}), []) class ShippedBuild(unittest.TestCase): @@ -395,13 +400,13 @@ class RepositoryRecords(unittest.TestCase): ) def test_every_config_record_carries_its_platform_links(self) -> None: - _config_records_without_evidence = schema_checks(self)._config_records_without_evidence + config_records_without_evidence = schema_checks(self).config_records_without_evidence for path in sorted((REPO_ROOT / "platforms").glob("*.yml")): if path.name.startswith("_"): continue with self.subTest(platform=path.stem): document = yaml.safe_load(path.read_text(encoding="utf-8")) - self.assertEqual(_config_records_without_evidence(path, document), []) + self.assertEqual(config_records_without_evidence(path, document), []) if __name__ == "__main__": diff --git a/tests/test_layers.py b/tests/test_layers.py index e19dd342b..a26780ad4 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -43,13 +43,10 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { # The launcher archives are written by the pack member writer. "installer_build": frozenset({"packs"}), "devtools": frozenset(), - "freshness": frozenset(), - "orchestrate": frozenset(), - "schemas": frozenset(), - "collection": frozenset(), - "games": frozenset(), # A job's commit subjects are checked against the repository's commit rules. "unattended": frozenset({"devtools"}), + # The installer event schema is checked against the one the build writes. + "schemas": frozenset({"installer_build"}), } # Top-level files that stay whole at their path although packages import them: diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index 29b5036eb..658ff3706 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -650,10 +650,10 @@ class APickReadsTheEntrySystems(unittest.TestCase): def test_the_schema_and_the_profile_list(self): try: - from scripts import validate_schemas + from schemas import profilechecks, validators except ImportError as exc: self.skipTest(f"validate_schemas needs jsonschema: {exc}") - validator = validate_schemas._validator("emulator.schema.json") + validator = validators.schema_validator("emulator.schema.json") root = Path(__file__).resolve().parents[1] base = {"emulator": "x", "type": "libretro", "systems": ["a", "b"]} both = {**base, "files": [{"name": "x.zip", "system": "a", "systems": ["a", "b"]}]} @@ -663,16 +663,16 @@ class APickReadsTheEntrySystems(unittest.TestCase): fine = {**base, "files": [{"name": "x.zip", "systems": ["a", "b"]}]} self.assertEqual(list(validator.iter_errors(fine)), []) outside = {**base, "files": [{"name": "x.zip", "systems": ["a", "c"]}]} - found = validate_schemas._systems_outside_profile(root / "emulators" / "x.yml", outside) + found = profilechecks.systems_outside_profile(root / "emulators" / "x.yml", outside) self.assertEqual(len(found), 1) self.assertIn("system c", found[0]) single = {**base, "files": [{"name": "x.zip", "system": "c"}]} - found = validate_schemas._systems_outside_profile(root / "emulators" / "x.yml", single) + found = profilechecks.systems_outside_profile(root / "emulators" / "x.yml", single) self.assertEqual(len(found), 1) self.assertIn("system c", found[0]) listed = {**base, "files": [{"name": "x.zip", "system": "a"}]} self.assertEqual( - validate_schemas._systems_outside_profile(root / "emulators" / "x.yml", listed), [] + profilechecks.systems_outside_profile(root / "emulators" / "x.yml", listed), [] ) diff --git a/tests/test_measurements.py b/tests/test_measurements.py index d317c8c90..e5b571ecc 100644 --- a/tests/test_measurements.py +++ b/tests/test_measurements.py @@ -343,14 +343,14 @@ class ReadAndIndex(Workspace): from jsonschema import Draft202012Validator except ImportError: self.skipTest("jsonschema is not installed") - import validate_schemas + from schemas import measurements - self.assertEqual(validate_schemas._measurement_errors(self.tree), []) + self.assertEqual(measurements.measurement_errors(self.tree), []) lines = self.tree / mr.records_path("beta") record = json.loads(lines.read_text()) record["kind"] = "guess" lines.write_text(mr.line_text(record) + "\n") - errors = validate_schemas._measurement_errors(self.tree) + errors = measurements.measurement_errors(self.tree) self.assertTrue(any("measurements/beta.jsonl:1" in e and "kind" in e for e in errors), errors) self.assertIsNotNone(Draft202012Validator) @@ -375,20 +375,20 @@ class ReadAndIndex(Workspace): def test_a_version_4_record_needs_its_verdicts(self) -> None: if importlib.util.find_spec("jsonschema") is None: self.skipTest("jsonschema is not installed") - import validate_schemas + from schemas import measurements lines = self.tree / mr.records_path("beta") record = json.loads(lines.read_text()) del record["variants"][0]["verdict"] del record["variants"][0]["repetitions"][0]["verdict_evidence"] lines.write_text(mr.line_text(record) + "\n") - errors = validate_schemas._measurement_errors(self.tree) + errors = measurements.measurement_errors(self.tree) self.assertTrue(any("'verdict' is a required property" in e for e in errors), errors) self.assertTrue(any("'verdict_evidence' is a required property" in e for e in errors), errors) old = {**record, "record_version": 3} lines.write_text(mr.line_text(old) + "\n") self.assertFalse(any("required property" in e - for e in validate_schemas._measurement_errors(self.tree))) + for e in measurements.measurement_errors(self.tree))) class AppendOnly(Workspace): diff --git a/tests/test_optional_dependencies.py b/tests/test_optional_dependencies.py index dd94b94ec..43dfcef62 100644 --- a/tests/test_optional_dependencies.py +++ b/tests/test_optional_dependencies.py @@ -35,7 +35,7 @@ sys.exit(0 if result.wasSuccessful() else 1) """ -IMPORTS_SCHEMA_CODE = re.compile(r"^\s*(?:import|from)\s+(?:jsonschema|validate_schemas)\b", re.M) +IMPORTS_SCHEMA_CODE = re.compile(r"^\s*(?:import|from)\s+(?:jsonschema|validate_schemas|schemas)\b", re.M) class SuiteWithoutJsonschema(unittest.TestCase): @@ -91,7 +91,8 @@ def _runtime_nodes(node: ast.AST) -> Iterator[ast.AST]: def _foreign_imports(source: str, file_name: str, local: set[str]) -> list[str]: """The top-level packages a script imports at run time beyond the - standard library, pyyaml and the repository's own modules.""" + standard library, pyyaml and the repository's own modules. ``file_name`` + is the path under scripts/.""" allowed = {"yaml"} found = [] for node in _runtime_nodes(ast.parse(source)): @@ -104,7 +105,7 @@ def _foreign_imports(source: str, file_name: str, local: set[str]) -> list[str]: for name in names: if name in sys.stdlib_module_names or name in local or name in allowed: continue - if name == "jsonschema" and file_name == "validate_schemas.py": + if name == "jsonschema" and file_name.startswith("schemas/"): continue if MAINTENANCE_TOOLS.get(file_name) == name: continue @@ -114,9 +115,10 @@ def _foreign_imports(source: str, file_name: str, local: set[str]) -> list[str]: class ScriptsNeedOnlyPyyaml(unittest.TestCase): """The build scripts need the standard library and pyyaml. jsonschema is - validate_schemas.py's alone. CI installs jsonschema with its whole tree - (attrs, referencing, rpds-py), so an import of any of them would pass - there and fail for a contributor following the documented setup.""" + the schemas package's alone, behind validate_schemas.py. CI installs + jsonschema with its whole tree (attrs, referencing, rpds-py), so an + import of any of them would pass there and fail for a contributor + following the documented setup.""" def test_no_script_imports_another_package(self): scripts = Path(__file__).resolve().parents[1] / "scripts" @@ -129,7 +131,8 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase): found = [ f"{path.relative_to(scripts)}: {name}" for path in sorted(scripts.rglob("*.py")) - for name in _foreign_imports(path.read_text(encoding="utf-8"), path.name, local) + for name in _foreign_imports(path.read_text(encoding="utf-8"), + path.relative_to(scripts).as_posix(), local) ] self.assertEqual(found, []) diff --git a/tests/test_save_root.py b/tests/test_save_root.py index 74b3fcf47..71dd6c8ae 100644 --- a/tests/test_save_root.py +++ b/tests/test_save_root.py @@ -180,12 +180,12 @@ class ThePlatformNamesItsSaveDirectory(unittest.TestCase): "userdata-saves/atari2600/stella/KVS1.WAV") self.assertEqual(SaveLayout("saves", True).in_pack, "saves") try: - from validate_schemas import _bios_tree_below + from schemas.registry import bios_tree_below except ImportError: self.skipTest("validate_schemas needs jsonschema") - self.assertEqual(_bios_tree_below("batocera", "saves"), + self.assertEqual(bios_tree_below("batocera", "saves"), "saves/dolphin-emu/Triforce/segaboot.gcm") - self.assertEqual(_bios_tree_below("batocera", "userdata-saves"), "") + self.assertEqual(bios_tree_below("batocera", "userdata-saves"), "") def test_the_systems_a_core_runs_for(self): from packs.paths import libretro_systems @@ -750,14 +750,14 @@ class TheInstallerWritesThem(unittest.TestCase): class TheProfilesFollowTheContract(unittest.TestCase): def test_every_save_dir_entry_has_a_library_name(self): try: - from validate_schemas import _save_dir_without_library_name + from schemas.profilechecks import save_dir_without_library_name except ImportError: self.skipTest("validate_schemas needs jsonschema") for path in sorted((REPO_ROOT / "emulators").glob("*.yml")): document = yaml.safe_load(path.read_text(encoding="utf-8")) with self.subTest(profile=path.name): - self.assertEqual(_save_dir_without_library_name(path, document), []) + self.assertEqual(save_dir_without_library_name(path, document), []) def test_azahar_reads_its_user_folder_below_the_save_directory(self): profile = yaml.safe_load((REPO_ROOT / "emulators" / "azahar.yml").read_text()) @@ -769,11 +769,11 @@ class TheProfilesFollowTheContract(unittest.TestCase): def test_the_registry_blocks(self): try: - from validate_schemas import _save_directory_blocks + from schemas.registry import save_directory_blocks except ImportError: self.skipTest("validate_schemas needs jsonschema") - self.assertEqual(_save_directory_blocks(), []) + self.assertEqual(save_directory_blocks(), []) def test_the_published_retroarch_list_places_azahar(self): manifest = json.loads((REPO_ROOT / "install" / "retroarch.json").read_text()) diff --git a/tests/test_schema_semantic_gate.py b/tests/test_schema_semantic_gate.py index dd02a985a..38ad8045c 100644 --- a/tests/test_schema_semantic_gate.py +++ b/tests/test_schema_semantic_gate.py @@ -17,6 +17,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] try: import validate_schemas + from schemas import documents, installs except ImportError as exc: validate_schemas = None IMPORT_ERROR = str(exc) @@ -50,7 +51,7 @@ class SemanticManifestValidation(unittest.TestCase): ) output = io.StringIO() - with mock.patch.object(validate_schemas, "REPO_ROOT", root), mock.patch.object( + with mock.patch("core.paths.REPO_ROOT", root), mock.patch.object( sys, "argv", ["validate_schemas.py"] ), redirect_stdout(output): result = validate_schemas.main() @@ -85,10 +86,10 @@ class SemanticManifestValidation(unittest.TestCase): with tempfile.TemporaryDirectory(dir=REPO_ROOT) as directory: path = Path(directory) / "synthetic.json" path.write_text(json.dumps(manifest), encoding="utf-8") - errors = validate_schemas._validate_json_files( + errors = documents.validate_json_files( [path], "install-manifest.schema.json", - validate_schemas._semantic_install_checks, + installs.semantic_install_checks, ) self.assertEqual(len(errors), 1) @@ -105,7 +106,7 @@ class SemanticManifestValidation(unittest.TestCase): def errors(omitted: list[dict]) -> list[str]: manifest = {"files": [], "total_files": 0, "total_size": 0, "omitted_files": omitted, "total_omitted": len(omitted)} - return [e for e in validate_schemas._semantic_install_checks(path, manifest) + return [e for e in installs.semantic_install_checks(path, manifest) if "omitted destinations" in e] self.assertEqual(errors([omission("mame2015"), omission("mame2016")]), []) diff --git a/wiki/architecture.md b/wiki/architecture.md index 696d708f5..8e217d3ef 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -50,6 +50,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c release/ the release record, its notes and the checks of its assets installer_build/ install.py from installer/, its pins, launchers and PyPI package devtools/ the commit message rules and the checks of a pull request + schemas/ the data contracts behind validate_schemas.py: schemas and semantic invariants unattended/ the job registry, worktree, CI breaker and units behind autorun.py install/ JSON install manifests per platform targets/ JSON target manifests per platform (cores per architecture)