refactor: type and split dat importers

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:39:30 +01:00
1 parent 4fdc100197
commit 7905729c18
3 files changed
+220 -152

No files matched your search

+129 -91
View File
@@ -37,8 +37,8 @@ from __future__ import annotations
import argparse
import ast
import functools
import hashlib
import io
import json
import re
import sys
@@ -48,6 +48,7 @@ from collections import Counter
from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO
from ..artifacts import write_if_changed
from ..common import load_emulator_profiles, run_cli
@@ -137,7 +138,7 @@ def _attrs(raw: bytes) -> dict[str, str]:
return {k.decode(): v.decode() for k, v in _ATTR.findall(raw)}
def iter_sets(stream: io.BufferedIOBase) -> Iterator[SetEntry]:
def iter_sets(stream: IO[bytes]) -> Iterator[SetEntry]:
"""Every machine or game element of a DAT or -listxml, streamed.
Attributes come in any order (mame2003 writes ``<game runnable="no"
@@ -309,7 +310,7 @@ def _fbneo_driver_names(entries: list[SetEntry], names: dict[str, set[str]]) ->
def fbneo_sets(
openers: list[Callable[[], io.BufferedIOBase]], names: dict[str, set[str]]
openers: list[Callable[[], IO[bytes]]], names: dict[str, set[str]]
) -> tuple[dict[str, SetEntry], dict[str, str]]:
"""Every set of FBNeo's DATs keyed by its driver, and the archive of each
set whose driver name is not its archive name.
@@ -634,55 +635,72 @@ class _Preprocessor:
out.append(line)
continue
word, rest = directive.groups()
if word in ("if", "ifdef", "ifndef"):
if not active:
stack.append((False, True, False))
continue
if word == "if":
value = bool(_condition_value(rest, defines))
else:
value = (rest.split()[0] in defines) == (word == "ifdef")
stack.append((True, value, value))
active = value
elif word in ("elif", "else"):
if not stack:
raise DriverSourceError(f"{path}: #{word} without #if")
outer, taken, _ = stack[-1]
value = (
outer and not taken
and (word == "else" or bool(_condition_value(rest, defines)))
)
stack[-1] = (outer, taken or value, value)
active = value
elif word == "endif":
if not stack:
raise DriverSourceError(f"{path}: #endif without #if")
stack.pop()
active = stack[-1][2] if stack else True
elif not active:
continue
elif word == "define":
head = _MACRO_HEAD.match(rest)
if head:
defines[head.group(1)] = head.group(3)
if local is not None:
params = head.group(2)
local[head.group(1)] = (
[a.strip() for a in params[1:-1].split(",")] if params else None,
head.group(3),
)
elif word == "undef":
defines.pop(rest.strip(), None)
elif word == "include":
target = _INCLUDE.match(rest)
header = self._resolve(target.group(1), path) if target else None
if header and header not in seen:
seen.add(header)
self.run(header, self.headers[header], defines, None, seen)
if word in _CONDITIONALS:
active = _branch(path, word, rest, defines, stack, active)
elif active:
self._define(path, word, rest, defines, local, seen)
if stack:
raise DriverSourceError(f"{path}: #if without #endif")
return "\n".join(out)
def _define(
self, path: str, word: str, rest: str, defines: dict[str, str],
local: dict[str, tuple[list[str] | None, str]] | None, seen: set[str],
) -> None:
"""#define, #undef and #include in an active region."""
if word == "define":
head = _MACRO_HEAD.match(rest)
if head:
defines[head.group(1)] = head.group(3)
if local is not None:
params = head.group(2)
local[head.group(1)] = (
[a.strip() for a in params[1:-1].split(",")] if params else None,
head.group(3),
)
elif word == "undef":
defines.pop(rest.strip(), None)
elif word == "include":
target = _INCLUDE.match(rest)
header = self._resolve(target.group(1), path) if target else None
if header and header not in seen:
seen.add(header)
self.run(header, self.headers[header], defines, None, seen)
_CONDITIONALS = frozenset({"if", "ifdef", "ifndef", "elif", "else", "endif"})
def _branch(
path: str, word: str, rest: str, defines: dict[str, str],
stack: list[tuple[bool, bool, bool]], active: bool,
) -> bool:
"""Apply one conditional directive to *stack*. Returns the new active state."""
if word in ("if", "ifdef", "ifndef"):
if not active:
stack.append((False, True, False))
return active
if word == "if":
value = bool(_condition_value(rest, defines))
else:
value = (rest.split()[0] in defines) == (word == "ifdef")
stack.append((True, value, value))
return value
if word in ("elif", "else"):
if not stack:
raise DriverSourceError(f"{path}: #{word} without #if")
outer, taken, _ = stack[-1]
value = (
outer and not taken
and (word == "else" or bool(_condition_value(rest, defines)))
)
stack[-1] = (outer, taken or value, value)
return value
if not stack:
raise DriverSourceError(f"{path}: #endif without #if")
stack.pop()
return stack[-1][2] if stack else True
def _dumped(args: list[str]) -> bool:
"""A ROM_LOAD whose ROM was dumped: 0.78 writes ``NO_DUMP`` in the hash
@@ -693,6 +711,10 @@ def _dumped(args: list[str]) -> bool:
return not re.fullmatch(r"0[xX]0+|0", crc.strip())
def _argument(values: dict[str, str], match: re.Match[str]) -> str:
return values.get(match.group(0), match.group(0))
def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str]]) -> str:
"""Calls of a file's own function-like macros that write a ROM_START or a
GAME line, expanded (pgm.c builds every DoDonPachi II set through
@@ -716,7 +738,7 @@ def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str
raise DriverSourceError(f"{match.group(1)} called with {len(args)} arguments")
values = dict(zip(params, args))
out.append(text[position : match.start()])
out.append(_IDENTIFIER.sub(lambda m: values.get(m.group(0), m.group(0)), body))
out.append(_IDENTIFIER.sub(functools.partial(_argument, values), body))
position = end
out.append(text[position:])
return "".join(out)
@@ -732,6 +754,50 @@ def compiled_drivers(driver_c: str, preprocessor: _Preprocessor) -> list[str]:
return [n for n in _DRIVER_ENTRY.findall(text) if n != "NAME"]
def _holds_roms(
body: str, local: dict[str, tuple[list[str] | None, str]], known: dict[str, bool],
seen: frozenset[str] = frozenset(),
) -> bool:
for match in _ROM_LOAD.finditer(body):
if _dumped(_call_args(body, match.end())):
return True
# A ROM list shared through a macro of the same file (a BIOS
# block every game of the board pulls in).
for word in set(_IDENTIFIER.findall(body)) - seen:
if word in local:
if word not in known:
known[word] = _holds_roms(local[word][1], local, known, seen | {word})
if known[word]:
return True
return False
def _read_driver(
path: str, source: str, preprocessor: _Preprocessor,
declared: dict[str, tuple[str | None, bool]], roms: dict[str, tuple[bool, bool]],
) -> None:
"""The ROM_START blocks and GAME declarations of one driver file."""
local: dict[str, tuple[list[str] | None, str]] = {}
text = _expand_declarations(preprocessor.run(path, source, {}, local, set()), local)
known: dict[str, bool] = {}
for match in _ROM_START.finditer(text):
body = match.group(2)
roms.setdefault(
match.group(1), (_holds_roms(body, local, known), bool(_DISK_IMAGE.search(body)))
)
for match in _GAME_MACRO.finditer(text):
args = _call_args(text, match.end())
if len(args) < 9:
raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments")
name, parent = args[1], args[2]
if name in declared:
raise DriverSourceError(f"{path}: {name} declared twice")
declared[name] = (
None if parent == "0" else parent,
any("NOT_A_DRIVER" in a for a in args[3:]),
)
def driver_source_sets(
driver_c: str, drivers: dict[str, str], headers: dict[str, str]
) -> dict[str, SetEntry]:
@@ -746,38 +812,7 @@ def driver_source_sets(
declared: dict[str, tuple[str | None, bool]] = {}
roms: dict[str, tuple[bool, bool]] = {}
for path, source in sorted(drivers.items()):
local: dict[str, tuple[list[str] | None, str]] = {}
text = _expand_declarations(preprocessor.run(path, source, {}, local, set()), local)
known: dict[str, bool] = {}
def holds_roms(body: str, seen: frozenset[str] = frozenset()) -> bool:
for match in _ROM_LOAD.finditer(body):
if _dumped(_call_args(body, match.end())):
return True
# A ROM list shared through a macro of the same file (a BIOS
# block every game of the board pulls in).
for word in set(_IDENTIFIER.findall(body)) - seen:
if word in local:
if word not in known:
known[word] = holds_roms(local[word][1], seen | {word})
if known[word]:
return True
return False
for match in _ROM_START.finditer(text):
body = match.group(2)
roms.setdefault(match.group(1), (holds_roms(body), bool(_DISK_IMAGE.search(body))))
for match in _GAME_MACRO.finditer(text):
args = _call_args(text, match.end())
if len(args) < 9:
raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments")
name, parent = args[1], args[2]
if name in declared:
raise DriverSourceError(f"{path}: {name} declared twice")
declared[name] = (
None if parent == "0" else parent,
any("NOT_A_DRIVER" in a for a in args[3:]),
)
_read_driver(path, source, preprocessor, declared, roms)
compiled = compiled_drivers(driver_c, preprocessor)
undeclared = [n for n in compiled if n not in declared]
if undeclared:
@@ -973,7 +1008,11 @@ def _cached_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tup
return destination, git_blob_sha(destination.read_bytes())
def _xml_streams(path: Path) -> Iterator[Callable[[], io.BufferedIOBase]]:
def _file_opener(path: Path) -> Callable[[], IO[bytes]]:
return lambda: path.open("rb")
def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]:
"""Openers for the XML documents a file holds: itself, or each XML or
DAT member of a ZIP."""
if path.suffix.lower() != ".zip":
@@ -984,16 +1023,15 @@ def _xml_streams(path: Path) -> Iterator[Callable[[], io.BufferedIOBase]]:
n for n in archive.namelist() if n.lower().endswith((".xml", ".dat"))
)
for member in names:
def opener(member: str = member) -> io.BufferedIOBase:
archive = zipfile.ZipFile(path)
stream = archive.open(member)
stream.close_archive = archive # keep the archive alive
return stream
def opener(member: str = member) -> IO[bytes]:
# The member keeps the archive alive: its shared file closes
# through the archive's own _fpclose.
return zipfile.ZipFile(path).open(member)
yield opener
def read_sets(openers: list[Callable[[], io.BufferedIOBase]]) -> dict[str, SetEntry]:
def read_sets(openers: list[Callable[[], IO[bytes]]]) -> dict[str, SetEntry]:
"""Every set of several documents. A set read twice keeps its first
reading: FBNeo's Arcade and Neogeo DATs both carry the neogeo BIOS."""
sets: dict[str, SetEntry] = {}
@@ -1024,6 +1062,8 @@ def import_profile(
commit = str(data.get("source_commit") or "")
source_url = str(data.get("source") or "")
kind = spec["kind"]
source: dict[str, object]
openers: list[Callable[[], IO[bytes]]]
if kind == "listxml":
tag = "mame" + str(data["core_version"]).replace(".", "").zfill(4)
if offline:
@@ -1060,9 +1100,7 @@ def import_profile(
FBNEO_DRIVERLIST: listing_sha,
},
}
openers = [
(lambda p=folder / name: p.open("rb")) for name in sorted(blobs)
]
openers = [_file_opener(folder / name) for name in sorted(blobs)]
sets, archives = fbneo_sets(openers, fbneo_drivers(listing.read_text(encoding="utf-8")))
index = build_index(sets, spec["marker"], archives)
elif kind == "source":
+4 -5
View File
@@ -19,14 +19,13 @@ files hash/<list>.xml (attribute_softlists) and the floppy sound samples
from __future__ import annotations
import html
import io
import re
import zipfile
from collections.abc import Callable, Collection, Iterable, Iterator
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from pathlib import Path
from typing import NamedTuple
from typing import IO, NamedTuple
from common import yaml_load
@@ -96,7 +95,7 @@ def _device_roms(body: bytes) -> list[dict]:
@contextmanager
def open_listxml(path: Path) -> Iterator[io.BufferedIOBase]:
def open_listxml(path: Path) -> Iterator[IO[bytes]]:
"""Byte stream over a -listxml document, plain or as MAME's release zip."""
if path.suffix.lower() != ".zip":
with path.open("rb") as stream:
@@ -133,7 +132,7 @@ class Release(NamedTuple):
machines: dict[str, MachineLinks]
def scan_release(stream: io.BufferedIOBase) -> Release:
def scan_release(stream: IO[bytes]) -> Release:
"""Release tag, device sets with dumped ROMs and every element's links.
The document is read through a sliding window, never whole: the 0.289
@@ -192,7 +191,7 @@ def scan_release(stream: io.BufferedIOBase) -> Release:
return Release(tag, devices, machines)
def scan_device_sets(stream: io.BufferedIOBase) -> tuple[str, dict[str, dict]]:
def scan_device_sets(stream: IO[bytes]) -> tuple[str, dict[str, dict]]:
"""Release tag of a -listxml document and its device sets with dumped ROMs."""
release = scan_release(stream)
return release.tag, release.devices
+87 -56
View File
@@ -31,7 +31,6 @@ from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import re
@@ -41,8 +40,10 @@ import urllib.parse
import urllib.request
import zipfile
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import IO
from ..common import (
list_registered_platforms,
@@ -62,9 +63,9 @@ DEFAULT_OUTPUT = "recipes/{source}.json"
def relevant_archives(emulators_dir: str, platforms_dir: str) -> set[str]:
"""Archive names any profile or platform refers to."""
names: set[str] = set()
for _profile_name, profile in load_emulator_profiles(
for profile in load_emulator_profiles(
emulators_dir, skip_aliases=False
).items():
).values():
for entry in profile.get("files", []) or []:
name = entry.get("name", "")
if name.endswith(".zip"):
@@ -283,7 +284,7 @@ def _machine_roms(blob: bytes) -> list[dict]:
def _scan_listxml(
stream: io.BufferedIOBase,
stream: IO[bytes],
selector: Callable[[str], bool],
targets: Targets | None = None,
) -> dict[str, tuple[str | None, list[dict]]]:
@@ -326,7 +327,7 @@ def _scan_listxml(
def listxml_entries(
open_stream: Callable[[], io.BufferedIOBase],
open_stream: Callable[[], IO[bytes]],
label: str,
keep: set[str] | None,
targets: Targets | None = None,
@@ -575,6 +576,8 @@ def fetch_pack(
if not sha:
raise BlobMismatchError(f"libretro/FBNeo has no revision {tag}")
listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}")
if not isinstance(listing, list):
raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}")
target = cache_dir / "fbneo-dats"
target.mkdir(parents=True, exist_ok=True)
blobs: dict[str, str] = {}
@@ -616,21 +619,21 @@ def _is_listxml(pack: Path) -> bool:
return b"<!ELEMENT mame" in handle.read(4096)
def _listxml_opener(pack: Path) -> Callable[[], io.BufferedIOBase]:
def _listxml_opener(pack: Path) -> Callable[[], IO[bytes]]:
"""A callable giving a fresh byte stream over the listxml document."""
if pack.suffix.lower() == ".zip":
def opener() -> zipfile.ZipExtFile:
def opener() -> IO[bytes]:
archive = zipfile.ZipFile(pack)
name = next(n for n in archive.namelist() if n.lower().endswith(".xml"))
stream = archive.open(name)
stream.close_archive = archive # keep the archive alive
return stream
# The member keeps the archive alive: its shared file closes
# through the archive's own _fpclose.
return archive.open(name)
return opener
return lambda: pack.open("rb")
def main() -> int:
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__)
parser.add_argument(
"--source", choices=SOURCES, required=True,
@@ -677,6 +680,76 @@ def main() -> int:
"--dry-run", action="store_true",
help="print what would change and write nothing",
)
return parser
@dataclass(frozen=True)
class _Selection:
"""Which sets a snapshot keeps: None everywhere keeps every set."""
keep: set[str] | None = None
targets: Targets | None = None
by_members: ByMembers | None = None
def _selection(args: argparse.Namespace) -> _Selection:
if args.all:
return _Selection()
held, by_members = collection_archives(args.db)
keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held
targets = catalog_targets(args.provenance_dir, args.db)
return _Selection(keep, targets, by_members)
def _import_listxml(pack: Path, args: argparse.Namespace, output: str, chosen: _Selection) -> int:
label = f"MAME {pack.stem.replace('lx', '')}"
entries = listxml_entries(
_listxml_opener(pack), label, chosen.keep, chosen.targets, chosen.by_members
)
dats = {label: pack.stem}
print(f" {label}: {len(entries)} sets retenus")
members = sum(len(entry["members"]) for entry in entries)
print(f"{len(entries)} recettes, {members} membres, depuis 1 listxml")
if args.dry_run:
return 0
changed = merge_snapshot(output, args.source, dats, entries)
print(f"{'Wrote' if changed else 'Unchanged'} {output}")
return 0
def _dat_recipes(
pack: Path, revision: str, chosen: _Selection
) -> tuple[dict[str, str], list[dict]]:
"""Recipes of every Logiqx DAT a pack holds, and each DAT's version."""
dats: dict[str, str] = {}
entries: list[dict] = []
skipped = 0
for member, content in _iter_dat_contents(pack):
try:
dat = parse_logiqx(content)
except (ValueError, SyntaxError) as exc:
print(f" Skipped {member}: {exc}", file=sys.stderr)
skipped += 1
continue
if not dat.roms:
skipped += 1
continue
if revision:
dat.name = f"{dat.name or member} @ {revision}"
found = recipe_entries(dat, chosen.keep, chosen.targets, chosen.by_members)
if not found:
continue
dats[dat.name or member] = dat.version
entries.extend(found)
print(f" {dat.name or member}: {len(found)} sets retenus")
if skipped:
print(f" {skipped} fichier(s) ignore(s) (non-Logiqx ou vides)")
return dats, entries
def main() -> int:
parser = _parser()
args = parser.parse_args()
blobs: dict[str, str] = {}
@@ -708,54 +781,12 @@ def main() -> int:
output = args.output or DEFAULT_OUTPUT.format(source=args.source)
Path(output).parent.mkdir(parents=True, exist_ok=True)
keep: set[str] | None = None
targets = None
by_members: ByMembers | None = None
if not args.all:
held, by_members = collection_archives(args.db)
keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held
targets = catalog_targets(args.provenance_dir, args.db)
dats: dict[str, str] = {}
entries: list[dict] = []
skipped = 0
chosen = _selection(args)
if _is_listxml(pack):
label = f"MAME {pack.stem.replace('lx', '')}"
entries = listxml_entries(
_listxml_opener(pack), label, keep, targets, by_members
)
dats[label] = pack.stem
print(f" {label}: {len(entries)} sets retenus")
members = sum(len(entry["members"]) for entry in entries)
print(f"{len(entries)} recettes, {members} membres, depuis 1 listxml")
if args.dry_run:
return 0
changed = merge_snapshot(output, args.source, dats, entries)
print(f"{'Wrote' if changed else 'Unchanged'} {output}")
return 0
return _import_listxml(pack, args, output, chosen)
for member, content in _iter_dat_contents(pack):
try:
dat = parse_logiqx(content)
except (ValueError, SyntaxError) as exc:
print(f" Skipped {member}: {exc}", file=sys.stderr)
skipped += 1
continue
if not dat.roms:
skipped += 1
continue
if revision:
dat.name = f"{dat.name or member} @ {revision}"
found = recipe_entries(dat, keep, targets, by_members)
if not found:
continue
dats[dat.name or member] = dat.version
entries.extend(found)
print(f" {dat.name or member}: {len(found)} sets retenus")
if skipped:
print(f" {skipped} fichier(s) ignore(s) (non-Logiqx ou vides)")
dats, entries = _dat_recipes(pack, revision, chosen)
members = sum(len(entry["members"]) for entry in entries)
print(f"{len(entries)} recettes, {members} membres, depuis {len(dats)} DAT")