mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-02 14:28:54 -06:00
refactor: group scraper modules by subject
scraper/ held the platform scrapers next to three other subjects. The launcher readers move to scraper/launchers/ (their _launchers suffix dropped), the MAME and FBNeo hash scrapers and romset importers to scraper/arcade/, the DAT readers and dump catalog importers to scraper/dats/. The buildbot check is a freshness check and moves to freshness/buildbot.py. Every -m command, workflow job, schema description and page follows. The scraper discovery in scraper/__init__.py had no caller: the registry's scraper: field names the module, and the pages now say so.
This commit is contained in:
1 parent
4e01cff854
commit
e1bad01b82
130 files changed
+445
-414
No files matched your search
@@ -0,0 +1,4 @@
|
||||
"""MAME and FBNeo: the BIOS set hashes read from their source, merged into the
|
||||
emulator profiles, the romset recipes read from their DATs, and the BIOS set
|
||||
each arcade game loads.
|
||||
"""
|
||||
@@ -0,0 +1,416 @@
|
||||
"""Merge fetched hash data into emulator YAML profiles.
|
||||
|
||||
Supports two strategies:
|
||||
- MAME: bios_zip entries with contents lists
|
||||
- FBNeo: individual ROM entries grouped by archive field
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
from model.sources import source_yaml_file
|
||||
|
||||
|
||||
_MAME_RELEASE_RE = re.compile(r"^0\.\d+")
|
||||
_MAMEDEV = "https://github.com/mamedev/mame"
|
||||
|
||||
|
||||
def mame_ref_role(profile: dict[str, Any]) -> str:
|
||||
"""Role word a ref read from mamedev/mame carries in this profile.
|
||||
|
||||
A profile that builds from another tree (libretro/mame) cites lines of
|
||||
mamedev/mame as "upstream <path>:<line>". Written bare, the ref was read
|
||||
against the libretro port, and every refresh rewrote the 171 prefixed refs
|
||||
of mame.yml into that form.
|
||||
"""
|
||||
upstream = str(profile.get("upstream") or "").rstrip("/")
|
||||
source = str(profile.get("source") or "").rstrip("/")
|
||||
if upstream.startswith(_MAMEDEV) and source and source != upstream:
|
||||
return "upstream "
|
||||
return ""
|
||||
|
||||
|
||||
def settled_required(entry: dict, set_data: dict) -> bool:
|
||||
"""The required flag a bios_zip entry carries after a refresh.
|
||||
|
||||
set_data["required"] is what romload.cpp does with the set missing: False
|
||||
when every ROM is NO_DUMP or ROM_OPTIONAL, so the machine runs without
|
||||
it, and nothing outranks that. True only says the machine itself stops;
|
||||
whether the core needs that machine is the profile's call, so a curated
|
||||
false is kept. The exception is a false over no contents, which is
|
||||
what an undumped set leaves: once a ROM is dumped, the set is required.
|
||||
"""
|
||||
current = entry.get("required", True)
|
||||
code = set_data.get("required")
|
||||
if code is False:
|
||||
return False
|
||||
if code is True and current is False and not entry.get("contents"):
|
||||
return True
|
||||
return current
|
||||
|
||||
|
||||
def mame_pin(profile: dict[str, Any], hashes: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The core_version and upstream_commit a refresh gives a MAME profile."""
|
||||
# The version follows the refs only for profiles already labelled with a
|
||||
# MAME release. A derivative pins its own line: same_cdi ("Git") and a7800
|
||||
# ("5.2") would otherwise be relabelled with a MAME version they were
|
||||
# never built from.
|
||||
if not _MAME_RELEASE_RE.match(str(profile.get("core_version") or "")):
|
||||
return {}
|
||||
pin = {"core_version": hashes.get("version", profile.get("core_version"))}
|
||||
# The refs about to be written are line numbers of that release's
|
||||
# mamedev/mame tree: the pin moves with them, or the profile cites lines
|
||||
# its declared revision does not hold.
|
||||
if profile.get("upstream") == _MAMEDEV and hashes.get("commit"):
|
||||
pin["upstream_commit"] = hashes["commit"]
|
||||
return pin
|
||||
|
||||
|
||||
def merge_mame_profile(
|
||||
profile: dict[str, Any],
|
||||
hashes: dict[str, Any],
|
||||
add_new: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Merge MAME bios_zip entries from upstream hash data.
|
||||
|
||||
Preserves system and note per entry. Updates contents and source_ref
|
||||
from the hashes JSON, and required where the source settles it (see
|
||||
settled_required). New sets are only added when add_new=True (main
|
||||
profile). Entries not in the hash data are left untouched (the scraper
|
||||
only covers MACHINE_IS_BIOS_ROOT sets, not all machine ROM sets).
|
||||
|
||||
Returns the merged profile and leaves the input dict as it was. Writing
|
||||
is write_mame_profile's.
|
||||
"""
|
||||
profile = dict(profile)
|
||||
profile.update(mame_pin(profile, hashes))
|
||||
|
||||
files = profile.get("files", [])
|
||||
bios_zip, non_bios = _split_files(files, lambda f: f.get("category") == "bios_zip")
|
||||
|
||||
existing_by_name: dict[str, dict] = {}
|
||||
for entry in bios_zip:
|
||||
key = _zip_name_to_set(entry["name"])
|
||||
existing_by_name[key] = entry
|
||||
|
||||
updated_bios: list[dict] = []
|
||||
matched_names: set[str] = set()
|
||||
|
||||
role = mame_ref_role(profile)
|
||||
for set_name, set_data in hashes.get("bios_sets", {}).items():
|
||||
contents = _build_contents(set_data.get("roms", []))
|
||||
source_ref = _build_source_ref(set_data, role)
|
||||
|
||||
if set_name in existing_by_name:
|
||||
# Update existing entry: preserve manual fields, update contents
|
||||
entry = existing_by_name[set_name].copy()
|
||||
entry["contents"] = contents
|
||||
if source_ref:
|
||||
entry["source_ref"] = source_ref
|
||||
entry["required"] = settled_required(existing_by_name[set_name], set_data)
|
||||
updated_bios.append(entry)
|
||||
matched_names.add(set_name)
|
||||
elif add_new:
|
||||
# New BIOS set, only added to the main profile
|
||||
entry = {
|
||||
"name": f"{set_name}.zip",
|
||||
"required": settled_required({}, set_data),
|
||||
"category": "bios_zip",
|
||||
"system": None,
|
||||
"source_ref": source_ref,
|
||||
"contents": contents,
|
||||
}
|
||||
updated_bios.append(entry)
|
||||
|
||||
# Entries not matched by the scraper stay untouched
|
||||
# (computer ROMs, device ROMs, etc., outside BIOS root set scope)
|
||||
for set_name, entry in existing_by_name.items():
|
||||
if set_name not in matched_names:
|
||||
updated_bios.append(entry)
|
||||
|
||||
profile["files"] = non_bios + updated_bios
|
||||
return profile
|
||||
|
||||
|
||||
def merge_fbneo_profile(
|
||||
profile: dict[str, Any],
|
||||
hashes: dict[str, Any],
|
||||
add_new: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Merge FBNeo individual ROM entries from upstream hash data.
|
||||
|
||||
Preserves system, required per entry. Updates crc32, size, and
|
||||
source_ref. New ROMs are only added when add_new=True (main profile).
|
||||
Entries not in the hash data are left untouched.
|
||||
|
||||
Returns the merged profile and leaves the input dict as it was. Writing
|
||||
is write_fbneo_profile's.
|
||||
"""
|
||||
profile = dict(profile)
|
||||
|
||||
# core_version stays as written: it is the version of the code at the
|
||||
# profile's own pin, read through version_basis (profile_sync
|
||||
# --set-version). The hashes come from finalburnneo/FBNeo's tip, a
|
||||
# revision the libretro/FBNeo pin does not name: writing its version
|
||||
# left fbneo, fbneo_cps12 and fbneo_neogeo on a release their pin
|
||||
# never was.
|
||||
|
||||
files = profile.get("files", [])
|
||||
archive_files, non_archive = _split_files(files, lambda f: "archive" in f)
|
||||
|
||||
existing_by_key: dict[tuple[str, str], dict] = {}
|
||||
for entry in archive_files:
|
||||
key = (entry["archive"], entry["name"])
|
||||
existing_by_key[key] = entry
|
||||
|
||||
merged: list[dict] = []
|
||||
matched_keys: set[tuple[str, str]] = set()
|
||||
|
||||
for set_name, set_data in hashes.get("bios_sets", {}).items():
|
||||
archive_name = f"{set_name}.zip"
|
||||
source_ref = _build_source_ref(set_data)
|
||||
|
||||
for rom in set_data.get("roms", []):
|
||||
rom_name = rom["name"]
|
||||
key = (archive_name, rom_name)
|
||||
|
||||
if key in existing_by_key:
|
||||
entry = existing_by_key[key].copy()
|
||||
entry["size"] = rom["size"]
|
||||
entry["crc32"] = rom["crc32"]
|
||||
if rom.get("sha1"):
|
||||
entry["sha1"] = rom["sha1"]
|
||||
if source_ref:
|
||||
entry["source_ref"] = source_ref
|
||||
merged.append(entry)
|
||||
matched_keys.add(key)
|
||||
elif add_new:
|
||||
entry = {
|
||||
"name": rom_name,
|
||||
"archive": archive_name,
|
||||
"required": True,
|
||||
"size": rom["size"],
|
||||
"crc32": rom["crc32"],
|
||||
}
|
||||
if rom.get("sha1"):
|
||||
entry["sha1"] = rom["sha1"]
|
||||
if source_ref:
|
||||
entry["source_ref"] = source_ref
|
||||
merged.append(entry)
|
||||
|
||||
# Entries not matched stay untouched
|
||||
for key, entry in existing_by_key.items():
|
||||
if key not in matched_keys:
|
||||
merged.append(entry)
|
||||
|
||||
profile["files"] = non_archive + merged
|
||||
return profile
|
||||
|
||||
|
||||
def compute_diff(
|
||||
profile: dict[str, Any],
|
||||
hashes: dict[str, Any],
|
||||
mode: str = "mame",
|
||||
) -> dict[str, Any]:
|
||||
"""Compute diff between profile and hashes without writing.
|
||||
|
||||
Returns counts of added, updated, removed, and unchanged entries.
|
||||
"""
|
||||
if mode == "mame":
|
||||
return diff_mame(profile, hashes)
|
||||
return diff_fbneo(profile, hashes)
|
||||
|
||||
|
||||
def diff_mame(
|
||||
profile: dict[str, Any],
|
||||
hashes: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Sets the hash data adds to or changes in a MAME profile."""
|
||||
files = profile.get("files", [])
|
||||
bios_zip, _ = _split_files(files, lambda f: f.get("category") == "bios_zip")
|
||||
|
||||
existing_by_name: dict[str, dict] = {}
|
||||
for entry in bios_zip:
|
||||
existing_by_name[_zip_name_to_set(entry["name"])] = entry
|
||||
|
||||
added: list[str] = []
|
||||
updated: list[str] = []
|
||||
unchanged = 0
|
||||
|
||||
role = mame_ref_role(profile)
|
||||
bios_sets = hashes.get("bios_sets", {})
|
||||
for set_name, set_data in bios_sets.items():
|
||||
if set_name not in existing_by_name:
|
||||
added.append(set_name)
|
||||
continue
|
||||
|
||||
old_entry = existing_by_name[set_name]
|
||||
new_contents = _build_contents(set_data.get("roms", []))
|
||||
old_contents = old_entry.get("contents", [])
|
||||
new_ref = _build_source_ref(set_data, role)
|
||||
|
||||
# A driver keeping the same ROMs still moves inside its file between
|
||||
# releases. Without this the hashes stay current while the source_ref
|
||||
# rots, which is exactly what profile_sync then reports as drift.
|
||||
ref_moved = bool(new_ref) and old_entry.get("source_ref") != new_ref
|
||||
|
||||
required_moved = old_entry.get("required", True) != settled_required(old_entry, set_data)
|
||||
|
||||
if contents_differ(old_contents, new_contents) or ref_moved or required_moved:
|
||||
updated.append(set_name)
|
||||
else:
|
||||
unchanged += 1
|
||||
|
||||
# Items in profile but not in scraper output = out of scope (not removed)
|
||||
out_of_scope = len(existing_by_name) - sum(
|
||||
1 for s in existing_by_name if s in bios_sets
|
||||
)
|
||||
|
||||
# A release that leaves every BIOS root set as it was still moves the pin.
|
||||
# merge_mame_profile writes it, so the write gate has to see it.
|
||||
pin = {
|
||||
field: (profile.get(field), value)
|
||||
for field, value in mame_pin(profile, hashes).items()
|
||||
if profile.get(field) != value
|
||||
}
|
||||
|
||||
return {
|
||||
"added": added,
|
||||
"updated": updated,
|
||||
"removed": [],
|
||||
"unchanged": unchanged,
|
||||
"out_of_scope": out_of_scope,
|
||||
"pin": pin,
|
||||
}
|
||||
|
||||
|
||||
def diff_fbneo(
|
||||
profile: dict[str, Any],
|
||||
hashes: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""ROMs the hash data adds to or changes in an FBNeo profile."""
|
||||
files = profile.get("files", [])
|
||||
archive_files, _ = _split_files(files, lambda f: "archive" in f)
|
||||
|
||||
existing_by_key: dict[tuple[str, str], dict] = {}
|
||||
for entry in archive_files:
|
||||
existing_by_key[(entry["archive"], entry["name"])] = entry
|
||||
|
||||
added: list[str] = []
|
||||
updated: list[str] = []
|
||||
unchanged = 0
|
||||
|
||||
seen_keys: set[tuple[str, str]] = set()
|
||||
bios_sets = hashes.get("bios_sets", {})
|
||||
|
||||
for set_name, set_data in bios_sets.items():
|
||||
archive_name = f"{set_name}.zip"
|
||||
for rom in set_data.get("roms", []):
|
||||
key = (archive_name, rom["name"])
|
||||
seen_keys.add(key)
|
||||
label = f"{archive_name}:{rom['name']}"
|
||||
|
||||
if key not in existing_by_key:
|
||||
added.append(label)
|
||||
continue
|
||||
|
||||
old = existing_by_key[key]
|
||||
# source_ref is deliberately not compared here. The scraper knows
|
||||
# one line per driver, the struct, while a curated entry cites the
|
||||
# RomDesc line of its own ROM. Treating the difference as drift
|
||||
# would replace per-ROM precision with a single driver line, which
|
||||
# the profiling rules call the signature of a faulty entry.
|
||||
if old.get("crc32") != rom.get("crc32") or old.get("size") != rom.get(
|
||||
"size"
|
||||
):
|
||||
updated.append(label)
|
||||
else:
|
||||
unchanged += 1
|
||||
|
||||
out_of_scope = sum(1 for k in existing_by_key if k not in seen_keys)
|
||||
|
||||
return {
|
||||
"added": added,
|
||||
"updated": updated,
|
||||
"removed": [],
|
||||
"unchanged": unchanged,
|
||||
"out_of_scope": out_of_scope,
|
||||
}
|
||||
|
||||
|
||||
# Helpers
|
||||
|
||||
|
||||
def load_profile(path: str | Path) -> dict[str, Any]:
|
||||
"""The profile at path as the merge reads it, empty when the file is."""
|
||||
return source_yaml_file(path) or {}
|
||||
|
||||
|
||||
def _split_files(
|
||||
files: list[dict],
|
||||
predicate: Any,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
matching: list[dict] = []
|
||||
rest: list[dict] = []
|
||||
for f in files:
|
||||
if predicate(f):
|
||||
matching.append(f)
|
||||
else:
|
||||
rest.append(f)
|
||||
return matching, rest
|
||||
|
||||
|
||||
def _zip_name_to_set(name: str) -> str:
|
||||
if name.endswith(".zip"):
|
||||
return name[:-4]
|
||||
return name
|
||||
|
||||
|
||||
def _build_contents(roms: list[dict]) -> list[dict]:
|
||||
contents: list[dict] = []
|
||||
for rom in roms:
|
||||
entry: dict[str, Any] = {
|
||||
"name": rom["name"],
|
||||
"size": rom["size"],
|
||||
"crc32": rom["crc32"],
|
||||
}
|
||||
if rom.get("sha1"):
|
||||
entry["sha1"] = rom["sha1"]
|
||||
desc = rom.get("bios_description") or rom.get("bios_label") or ""
|
||||
if desc:
|
||||
entry["description"] = desc
|
||||
if rom.get("bad_dump"):
|
||||
entry["bad_dump"] = True
|
||||
contents.append(entry)
|
||||
return contents
|
||||
|
||||
|
||||
def _build_source_ref(set_data: dict, role: str = "") -> str:
|
||||
source_file = set_data.get("source_file", "")
|
||||
source_line = set_data.get("source_line")
|
||||
if not source_file:
|
||||
return ""
|
||||
if source_line is not None:
|
||||
return f"{role}{source_file}:{source_line}"
|
||||
return f"{role}{source_file}"
|
||||
|
||||
|
||||
def contents_differ(old: list[dict], new: list[dict]) -> bool:
|
||||
if len(old) != len(new):
|
||||
return True
|
||||
old_by_name = {c["name"]: c for c in old}
|
||||
for entry in new:
|
||||
prev = old_by_name.get(entry["name"])
|
||||
if prev is None:
|
||||
return True
|
||||
if prev.get("crc32") != entry.get("crc32"):
|
||||
return True
|
||||
if prev.get("size") != entry.get("size"):
|
||||
return True
|
||||
if prev.get("sha1") != entry.get("sha1"):
|
||||
return True
|
||||
return False
|
||||
@@ -0,0 +1,412 @@
|
||||
"""Text patches that write merged hashes into a profile and keep its formatting."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import write_text_atomic
|
||||
from model.profiles import PROFILE_BACKUP_SUFFIX
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
|
||||
DEVICE_SECTION = " # --- Device ROM sets (generated from MAME -listxml) ---"
|
||||
SOFTLIST_SECTION = " # --- Software lists (generated from MAME -listxml) ---"
|
||||
|
||||
|
||||
def write_mame_profile(path: str | Path, data: dict) -> None:
|
||||
"""Write merged profile using text-based patching to preserve formatting.
|
||||
|
||||
Instead of yaml.dump (which destroys comments, quoting, indentation),
|
||||
this reads the original file as text, patches specific fields
|
||||
(core_version, contents, source_ref), and appends new entries.
|
||||
"""
|
||||
p = Path(path)
|
||||
backup = p.with_suffix(PROFILE_BACKUP_SUFFIX)
|
||||
shutil.copy2(p, backup)
|
||||
|
||||
original = p.read_text(encoding="utf-8")
|
||||
patched = _patch_core_version(original, data.get("core_version", ""))
|
||||
patched = _set_scalar(
|
||||
patched, "upstream_commit", data.get("upstream_commit", ""),
|
||||
after=("source_commit", "upstream"),
|
||||
)
|
||||
patched = patch_bios_entries(patched, data.get("files", []))
|
||||
patched = _append_new_entries(patched, data.get("files", []), original)
|
||||
|
||||
write_text_atomic(str(p), patched)
|
||||
|
||||
|
||||
def _patch_core_version(text: str, version: str) -> str:
|
||||
"""Replace core_version value in-place."""
|
||||
return _patch_scalar(text, "core_version", version)
|
||||
|
||||
|
||||
def _patch_scalar(text: str, key: str, value: str) -> str:
|
||||
"""Replace a top-level scalar in-place, quoted. An absent value changes nothing."""
|
||||
if not value:
|
||||
return text
|
||||
return re.sub(
|
||||
rf"^({re.escape(key)}:\s*).*$",
|
||||
rf'\g<1>"{value}"',
|
||||
text,
|
||||
count=1,
|
||||
flags=re.MULTILINE,
|
||||
)
|
||||
|
||||
|
||||
def _set_scalar(text: str, key: str, value: str, after: tuple[str, ...]) -> str:
|
||||
"""Write a top-level scalar, adding its line after the first key of *after* found.
|
||||
|
||||
The merge sets the value whether or not the profile carries the key: a
|
||||
patch that only rewrites an existing line would report the change and
|
||||
leave the file without it.
|
||||
"""
|
||||
if not value or re.search(rf"^{re.escape(key)}:", text, re.MULTILINE):
|
||||
return _patch_scalar(text, key, value)
|
||||
for anchor in after:
|
||||
match = re.search(rf"^{re.escape(anchor)}:[^\n]*$", text, re.MULTILINE)
|
||||
if match:
|
||||
return f'{text[: match.end()]}\n{key}: "{value}"{text[match.end():]}'
|
||||
raise ValueError(f"no {' or '.join(after)} line to place {key} after")
|
||||
|
||||
|
||||
def _owned_end(lines: list[str], start_line: int) -> int:
|
||||
"""The last "owned" line of the entry starting at start_line.
|
||||
|
||||
Owned = indented with 4+ spaces (field lines of this entry).
|
||||
"""
|
||||
last_owned = start_line
|
||||
for j in range(start_line + 1, len(lines)):
|
||||
stripped = lines[j].strip()
|
||||
if not stripped:
|
||||
break # blank line = end of entry
|
||||
if stripped.startswith("#"):
|
||||
break # comment = belongs to next entry
|
||||
if re.match(r"^ - ", lines[j]):
|
||||
break # next list item
|
||||
if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]):
|
||||
last_owned = j
|
||||
else:
|
||||
break
|
||||
return last_owned
|
||||
|
||||
|
||||
def _patch_source_ref(lines: list[str], start_line: int, last_owned: int, source_ref: str) -> int:
|
||||
"""Patch source_ref in-place, or add it. Returns the new last owned line."""
|
||||
for j in range(start_line + 1, last_owned + 1):
|
||||
if re.match(r"^ source_ref:", lines[j]):
|
||||
lines[j] = f' source_ref: "{source_ref}"'
|
||||
return last_owned
|
||||
lines.insert(last_owned + 1, f' source_ref: "{source_ref}"')
|
||||
return last_owned + 1
|
||||
|
||||
|
||||
def _patch_required(lines: list[str], start_line: int, last_owned: int, required: bool) -> int:
|
||||
"""Rewrite required in-place, or add it before category when it is false.
|
||||
|
||||
An absent line reads as true, so only a false needs a line of its own.
|
||||
Returns the new last owned line.
|
||||
"""
|
||||
value = f" required: {str(required).lower()}"
|
||||
for j in range(start_line + 1, last_owned + 1):
|
||||
if re.match(r"^ required:", lines[j]):
|
||||
lines[j] = value
|
||||
return last_owned
|
||||
if required:
|
||||
return last_owned
|
||||
at = next(
|
||||
(j for j in range(start_line + 1, last_owned + 1) if re.match(r"^ category:", lines[j])),
|
||||
last_owned + 1,
|
||||
)
|
||||
lines.insert(at, value)
|
||||
return last_owned + 1
|
||||
|
||||
|
||||
def _drop_contents(lines: list[str], start_line: int, last_owned: int) -> int:
|
||||
"""Remove an existing contents block. Returns the new last owned line."""
|
||||
contents_start = None
|
||||
contents_end = None
|
||||
for j in range(start_line + 1, last_owned + 1):
|
||||
if re.match(r"^ contents:", lines[j]):
|
||||
contents_start = j
|
||||
elif contents_start is not None:
|
||||
if re.match(r"^ ", lines[j]):
|
||||
contents_end = j
|
||||
else:
|
||||
break
|
||||
if contents_start is None:
|
||||
return last_owned
|
||||
if contents_end is None:
|
||||
contents_end = contents_start
|
||||
del lines[contents_start : contents_end + 1]
|
||||
return last_owned - (contents_end - contents_start + 1)
|
||||
|
||||
|
||||
def _patch_entry(lines: list[str], start_line: int, fe: dict) -> None:
|
||||
contents = fe.get("contents", [])
|
||||
source_ref = fe.get("source_ref", "")
|
||||
|
||||
last_owned = _owned_end(lines, start_line)
|
||||
|
||||
if source_ref:
|
||||
last_owned = _patch_source_ref(lines, start_line, last_owned, source_ref)
|
||||
|
||||
# The source settles required for a set the machine runs without
|
||||
if "required" in fe:
|
||||
last_owned = _patch_required(lines, start_line, last_owned, fe["required"])
|
||||
|
||||
last_owned = _drop_contents(lines, start_line, last_owned)
|
||||
|
||||
# Insert new contents after last owned line
|
||||
if contents:
|
||||
new_lines = format_contents(contents).split("\n")
|
||||
for k, cl in enumerate(new_lines):
|
||||
lines.insert(last_owned + 1 + k, cl)
|
||||
|
||||
|
||||
def patch_bios_entries(text: str, files: list[dict]) -> str:
|
||||
"""Patch contents, source_ref and required of bios_zip entries in-place.
|
||||
|
||||
Processes entries in reverse order to preserve line offsets.
|
||||
Each entry's "owned" lines are: the `- name:` line plus all indented
|
||||
lines that follow (4+ spaces), stopping at blank lines, comments,
|
||||
or the next `- name:`.
|
||||
"""
|
||||
patches: dict[str, dict] = {}
|
||||
for fe in files:
|
||||
if fe.get("category") != "bios_zip":
|
||||
continue
|
||||
patches[fe["name"]] = fe
|
||||
|
||||
if not patches:
|
||||
return text
|
||||
|
||||
lines = text.split("\n")
|
||||
# Find all entry start positions (line indices)
|
||||
entry_starts: list[tuple[int, str]] = []
|
||||
for i, line in enumerate(lines):
|
||||
m = re.match(r"^ - name:\s*(.+?)\s*$", line)
|
||||
if m:
|
||||
entry_starts.append((i, m.group(1).strip('"').strip("'")))
|
||||
|
||||
# Process in reverse so line insertions don't shift indices
|
||||
for idx in range(len(entry_starts) - 1, -1, -1):
|
||||
start_line, entry_name = entry_starts[idx]
|
||||
if entry_name in patches:
|
||||
_patch_entry(lines, start_line, patches[entry_name])
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _append_new_entries(text: str, files: list[dict], original: str) -> str:
|
||||
"""Append new bios_zip entries (system=None) that aren't in the original."""
|
||||
# Parse original to get existing entry names (more reliable than text search)
|
||||
existing_data = yaml_load(original) or {}
|
||||
existing_names = {f["name"] for f in existing_data.get("files", [])}
|
||||
|
||||
new_entries = []
|
||||
for fe in files:
|
||||
if fe.get("category") != "bios_zip" or fe.get("system") is not None:
|
||||
continue
|
||||
if fe["name"] in existing_names:
|
||||
continue
|
||||
new_entries.append(fe)
|
||||
|
||||
if not new_entries:
|
||||
return text
|
||||
|
||||
lines = []
|
||||
profile_type = str(existing_data.get("type") or "")
|
||||
for fe in new_entries:
|
||||
lines.append(f"\n - name: {yaml_scalar(fe['name'])}")
|
||||
lines.extend(set_path_lines(profile_type, fe["name"]))
|
||||
lines.append(f" required: {str(fe['required']).lower()}")
|
||||
lines.append(" category: bios_zip")
|
||||
if fe.get("source_ref"):
|
||||
lines.append(f' source_ref: "{fe["source_ref"]}"')
|
||||
if fe.get("contents"):
|
||||
lines.append(format_contents(fe["contents"]))
|
||||
|
||||
if lines:
|
||||
# New BIOS root sets go before the generated sections, which run to
|
||||
# the end of the files list.
|
||||
at = generated_start(text)
|
||||
if at is None:
|
||||
text = text.rstrip("\n") + "\n" + "\n".join(lines) + "\n"
|
||||
else:
|
||||
text = text[:at].rstrip("\n") + "\n" + "\n".join(lines) + "\n\n" + text[at:]
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def device_section_start(text: str) -> int | None:
|
||||
"""Offset of the generated device section header, if the profile has one."""
|
||||
match = re.search(rf"^{re.escape(DEVICE_SECTION)}$", text, re.M)
|
||||
return match.start() if match else None
|
||||
|
||||
|
||||
def softlist_section_start(text: str) -> int | None:
|
||||
"""Offset of the generated software list section header, if any."""
|
||||
match = re.search(rf"^{re.escape(SOFTLIST_SECTION)}$", text, re.M)
|
||||
return match.start() if match else None
|
||||
|
||||
|
||||
def generated_start(text: str) -> int | None:
|
||||
"""Offset of the first generated section: what a reader wrote ends there."""
|
||||
found = [at for at in (softlist_section_start(text), device_section_start(text)) if at is not None]
|
||||
return min(found) if found else None
|
||||
|
||||
|
||||
def set_path_lines(profile_type: str, name: str) -> list[str]:
|
||||
"""Where each build of a MAME profile reads a set it lists.
|
||||
|
||||
The libretro build searches the content folder, then <system>/mame/bios
|
||||
and <system>/mame/roms (libretro-internal/retro_init.cpp,
|
||||
Set_Path_Option), never the system folder itself. The standalone build
|
||||
reads the top of its rompath.
|
||||
"""
|
||||
if "libretro" not in profile_type:
|
||||
return []
|
||||
lines = [f' path: "mame/bios/{name}"']
|
||||
if "standalone" in profile_type:
|
||||
lines.append(f' standalone_path: "{name}"')
|
||||
return lines
|
||||
|
||||
|
||||
def yaml_scalar(value: object) -> str:
|
||||
"""Quote a scalar so YAML reads back exactly what the source said.
|
||||
|
||||
A MAME ROM named ``01`` written bare re-parses as the integer 1, and the
|
||||
set stops naming the file the driver loads. Quoting is not cosmetic here.
|
||||
"""
|
||||
return json.dumps(str(value), ensure_ascii=False)
|
||||
|
||||
|
||||
def format_contents(contents: list[dict]) -> str:
|
||||
"""Format a contents list as YAML text."""
|
||||
lines = [" contents:"]
|
||||
for rom in contents:
|
||||
lines.append(f" - name: {yaml_scalar(rom['name'])}")
|
||||
if rom.get("description"):
|
||||
lines.append(f" description: {yaml_scalar(rom['description'])}")
|
||||
if rom.get("size"):
|
||||
lines.append(f" size: {rom['size']}")
|
||||
if rom.get("crc32"):
|
||||
lines.append(f' crc32: "{rom["crc32"]}"')
|
||||
if rom.get("sha1"):
|
||||
lines.append(f' sha1: "{rom["sha1"]}"')
|
||||
if rom.get("bad_dump"):
|
||||
lines.append(" bad_dump: true")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# Content values an FBNeo entry carries, in the order a new one is written.
|
||||
_FBNEO_VALUES = ("size", "crc32", "sha1")
|
||||
_ENTRY_START = re.compile(r"^ - name: ", re.M)
|
||||
_FIELD_LINE = re.compile(r"^ (?P<key>[a-z0-9_]+):\s*(?P<value>[^#\n]*?)\s*(?P<comment>#.*)?$")
|
||||
|
||||
|
||||
def _patch_fbneo_values(text: str, changed: dict[tuple[str, str], dict]) -> str:
|
||||
"""Rewrite size/crc32/sha1 inside the blocks of the changed entries."""
|
||||
starts = [m.start() for m in _ENTRY_START.finditer(text)] + [len(text)]
|
||||
out = [text[: starts[0]]]
|
||||
for begin, end in zip(starts, starts[1:]):
|
||||
block = text[begin:end]
|
||||
fields = {}
|
||||
for line in block.splitlines()[1:]:
|
||||
match = _FIELD_LINE.match(line)
|
||||
if match:
|
||||
fields[match["key"]] = match["value"].strip().strip('"')
|
||||
name = block.splitlines()[0].removeprefix(" - name:").strip().strip('"')
|
||||
entry = changed.get((fields.get("archive", ""), name))
|
||||
if entry is not None:
|
||||
block = _patch_block_values(block, entry)
|
||||
out.append(block)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _patch_block_values(block: str, entry: dict) -> str:
|
||||
lines = block.split("\n")
|
||||
for key in _FBNEO_VALUES:
|
||||
value = entry.get(key)
|
||||
if not value:
|
||||
continue
|
||||
rendered = str(value) if key == "size" else f'"{value}"'
|
||||
for i, line in enumerate(lines):
|
||||
match = _FIELD_LINE.match(line)
|
||||
if match and match["key"] == key:
|
||||
if match["value"].strip().strip('"') != str(value):
|
||||
# A size comment spells the old value, so it goes with it.
|
||||
lines[i] = f" {key}: {rendered}"
|
||||
break
|
||||
else:
|
||||
anchor = max(
|
||||
(i for i, line in enumerate(lines)
|
||||
if (m := _FIELD_LINE.match(line)) and m["key"] in ("archive", *_FBNEO_VALUES)),
|
||||
default=0,
|
||||
)
|
||||
lines.insert(anchor + 1, f" {key}: {rendered}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def write_fbneo_profile(path: str | Path, data: dict) -> None:
|
||||
"""Write merged FBNeo profile using text-based patching.
|
||||
|
||||
FBNeo profiles have individual ROM entries with archive: field.
|
||||
Patches the content values of existing entries that changed and
|
||||
appends new ROM entries. core_version is the pin's, never written here.
|
||||
Comments and curated source_refs stay as written.
|
||||
"""
|
||||
p = Path(path)
|
||||
backup = p.with_suffix(PROFILE_BACKUP_SUFFIX)
|
||||
shutil.copy2(p, backup)
|
||||
|
||||
original = p.read_text(encoding="utf-8")
|
||||
patched = original
|
||||
|
||||
# Identify new ROM entries by comparing parsed data keys, not text search
|
||||
existing_data = yaml_load(original) or {}
|
||||
existing_by_key = {
|
||||
(f["archive"], f["name"]): f
|
||||
for f in existing_data.get("files", [])
|
||||
if f.get("archive")
|
||||
}
|
||||
existing_keys = set(existing_by_key)
|
||||
changed = {
|
||||
(f["archive"], f["name"]): f
|
||||
for f in data.get("files", [])
|
||||
if f.get("archive")
|
||||
and (f["archive"], f["name"]) in existing_by_key
|
||||
and any(
|
||||
str(f.get(k) or "") != str(existing_by_key[(f["archive"], f["name"])].get(k) or "")
|
||||
for k in _FBNEO_VALUES
|
||||
if f.get(k)
|
||||
)
|
||||
}
|
||||
if changed:
|
||||
patched = _patch_fbneo_values(patched, changed)
|
||||
new_roms = [
|
||||
f
|
||||
for f in data.get("files", [])
|
||||
if f.get("archive") and (f["archive"], f["name"]) not in existing_keys
|
||||
]
|
||||
|
||||
if new_roms:
|
||||
lines = []
|
||||
for fe in new_roms:
|
||||
lines.append(f" - name: {yaml_scalar(fe['name'])}")
|
||||
lines.append(f" archive: {yaml_scalar(fe['archive'])}")
|
||||
lines.append(f" required: {str(fe.get('required', True)).lower()}")
|
||||
if fe.get("size"):
|
||||
lines.append(f" size: {fe['size']}")
|
||||
if fe.get("crc32"):
|
||||
lines.append(f' crc32: "{fe["crc32"]}"')
|
||||
if fe.get("source_ref"):
|
||||
lines.append(f' source_ref: "{fe["source_ref"]}"')
|
||||
lines.append("")
|
||||
patched = patched.rstrip("\n") + "\n\n" + "\n".join(lines)
|
||||
|
||||
write_text_atomic(str(p), patched)
|
||||
@@ -0,0 +1,398 @@
|
||||
"""The generated device and software list sections of a MAME profile."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import write_text_atomic
|
||||
from model.profiles import PROFILE_BACKUP_SUFFIX
|
||||
from model.safeparse import yaml_load
|
||||
from ._hash_merge import _build_contents, _build_source_ref, contents_differ, mame_ref_role
|
||||
from ._hash_write import (
|
||||
DEVICE_SECTION,
|
||||
SOFTLIST_SECTION,
|
||||
device_section_start,
|
||||
format_contents,
|
||||
patch_bios_entries,
|
||||
softlist_section_start,
|
||||
yaml_scalar,
|
||||
generated_start,
|
||||
set_path_lines,
|
||||
)
|
||||
|
||||
|
||||
_FILES_END = re.compile(r"^\S", re.M)
|
||||
|
||||
|
||||
def _device_contents(roms: list[dict], old: list[dict]) -> list[dict]:
|
||||
"""Contents of a device set, keeping the member descriptions a reader wrote."""
|
||||
written = {str(c.get("name")): c.get("description") for c in old or []}
|
||||
contents = _build_contents(roms)
|
||||
for member in contents:
|
||||
if written.get(member["name"]):
|
||||
member["description"] = written[member["name"]]
|
||||
elif member.get("description"):
|
||||
# A biosset description is MAME's text, quoted as written.
|
||||
member["description"] = f"`{member['description']}`"
|
||||
return contents
|
||||
|
||||
|
||||
def _device_note(description: str) -> str:
|
||||
"""The note of a generated entry. The device name is MAME's own text,
|
||||
quoted verbatim in backticks: `Sun-1 Workstation Monitor; PROM 1&3: Rev AJ`
|
||||
is a name, not a sentence."""
|
||||
return f"Device ROM set, loaded when a machine instantiates `{description}`."
|
||||
|
||||
|
||||
def _zip_scalar(name: str) -> str:
|
||||
"""An archive name as the written entries spell it: bare when YAML keeps it."""
|
||||
return name if re.fullmatch(r"[a-z0-9_]+\.zip", name) else yaml_scalar(name)
|
||||
|
||||
|
||||
_PLAIN_SYSTEM = re.compile(r"^[a-z][a-z0-9-]*$")
|
||||
|
||||
|
||||
def _system_lines(systems: list[str]) -> list[str]:
|
||||
"""`system:` for one system, `systems:` for several, nothing for none."""
|
||||
def scalar(value: str) -> str:
|
||||
return value if _PLAIN_SYSTEM.match(value) else yaml_scalar(value)
|
||||
|
||||
if not systems:
|
||||
return []
|
||||
if len(systems) == 1:
|
||||
return [f" system: {scalar(systems[0])}"]
|
||||
return [" systems:", *(f" - {scalar(s)}" for s in systems)]
|
||||
|
||||
|
||||
def _entry_systems(entry: dict) -> list[str]:
|
||||
"""The systems an entry states, in the shape _system_lines writes."""
|
||||
if entry.get("system"):
|
||||
return [str(entry["system"])]
|
||||
return [str(s) for s in entry.get("systems") or []]
|
||||
|
||||
|
||||
def _section_names(text: str) -> set[str]:
|
||||
"""Entry names inside the generated device section."""
|
||||
start = device_section_start(text)
|
||||
if start is None:
|
||||
return set()
|
||||
end = _FILES_END.search(text, text.index("\n", start) + 1)
|
||||
section = text[start : end.start() if end else len(text)]
|
||||
return {
|
||||
m.group(1).strip('"').strip("'")
|
||||
for m in re.finditer(r"^ - name:\s*(.+?)\s*$", section, re.M)
|
||||
}
|
||||
|
||||
|
||||
def _set_section_systems(text: str, systems: dict[str, list[str]]) -> str:
|
||||
"""Rewrite the system fields of the named entries of the device section.
|
||||
|
||||
Any `system:` or `systems:` the entry holds is dropped and the new one
|
||||
written right after its category, where a written entry keeps it.
|
||||
"""
|
||||
if not systems:
|
||||
return text
|
||||
start = device_section_start(text)
|
||||
if start is None:
|
||||
return text
|
||||
return text[:start] + _rewrite_systems(text[start:], systems)
|
||||
|
||||
|
||||
def _rewrite_systems(section: str, systems: dict[str, list[str]]) -> str:
|
||||
"""Rewrite the system fields of the named entries of one stretch of text."""
|
||||
out: list[str] = []
|
||||
current = ""
|
||||
in_list = False
|
||||
for line in section.split("\n"):
|
||||
entry_head = re.match(r"^ - name:\s*(.+?)\s*$", line)
|
||||
if entry_head:
|
||||
current = entry_head.group(1).strip('"').strip("'")
|
||||
if current in systems:
|
||||
if in_list and line.startswith(" - "):
|
||||
continue
|
||||
in_list = False
|
||||
if re.match(r"^ system:", line):
|
||||
continue
|
||||
if re.match(r"^ systems:\s*$", line):
|
||||
in_list = True
|
||||
continue
|
||||
out.append(line)
|
||||
if current in systems and re.match(r"^ category:", line):
|
||||
out.extend(_system_lines(systems[current]))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _format_device_entry(name: str, device: dict, role: str, profile_type: str = "") -> str:
|
||||
"""One generated device entry, in the field order of the written ones."""
|
||||
lines = [
|
||||
f" - name: {_zip_scalar(name)}",
|
||||
*set_path_lines(profile_type, name),
|
||||
" required: false",
|
||||
" category: bios_zip",
|
||||
*_system_lines(device.get("systems") or []),
|
||||
]
|
||||
if device.get("source_line"):
|
||||
lines.append(f' source_ref: "{_build_source_ref(device, role)}"')
|
||||
lines.append(" note: >-")
|
||||
lines.extend(
|
||||
textwrap.wrap(
|
||||
_device_note(device.get("description") or name[:-4]),
|
||||
width=78,
|
||||
initial_indent=" ",
|
||||
subsequent_indent=" ",
|
||||
break_on_hyphens=False,
|
||||
)
|
||||
)
|
||||
lines.append(format_contents(_device_contents(device["roms"], [])))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def merge_mame_devices(
|
||||
profile_path: str,
|
||||
devices: dict[str, dict],
|
||||
write: bool = False,
|
||||
) -> dict[str, list[str]]:
|
||||
"""Merge MAME device ROM sets into a profile.
|
||||
|
||||
*devices* maps a device shortname to its listxml description, its dumped
|
||||
ROMs and, when found, source_file and source_line. A set the profile
|
||||
already lists keeps every field a reader wrote: its contents are refreshed
|
||||
with the member descriptions kept, and a source_ref is added only where it
|
||||
has none. A set it lacks is written under the generated section, in name
|
||||
order, with required false. An entry of another category under a device
|
||||
name is reported, never touched.
|
||||
|
||||
A device carrying `systems` (attribute_systems) has them written on its
|
||||
entry when the entry is in the generated section: `system:` for one,
|
||||
`systems:` for several, neither for none. An entry above the section
|
||||
keeps the system a reader gave it.
|
||||
"""
|
||||
path = Path(profile_path)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
profile = yaml_load(text) or {}
|
||||
role = mame_ref_role(profile)
|
||||
entries: dict[str, list[dict]] = {}
|
||||
for entry in profile.get("files") or []:
|
||||
entries.setdefault(str(entry.get("name")), []).append(entry)
|
||||
|
||||
report: dict[str, list[str]] = {
|
||||
"added": [], "updated": [], "unchanged": [], "conflict": [],
|
||||
}
|
||||
contents_patches: list[dict] = []
|
||||
ref_patches: dict[str, str] = {}
|
||||
system_patches: dict[str, list[str]] = {}
|
||||
new_blocks: dict[str, str] = {}
|
||||
generated = _section_names(text)
|
||||
for set_name, device in sorted(devices.items()):
|
||||
name = f"{set_name}.zip"
|
||||
existing = entries.get(name)
|
||||
if not existing:
|
||||
new_blocks[name] = _format_device_entry(
|
||||
name, device, role, str(profile.get("type") or "")
|
||||
)
|
||||
report["added"].append(set_name)
|
||||
continue
|
||||
if any(e.get("category") != "bios_zip" for e in existing):
|
||||
report["conflict"].append(set_name)
|
||||
continue
|
||||
old = existing[0]
|
||||
contents = _device_contents(device["roms"], old.get("contents") or [])
|
||||
changed = False
|
||||
if contents_differ(old.get("contents") or [], contents):
|
||||
contents_patches.append({"name": name, "category": "bios_zip", "contents": contents})
|
||||
changed = True
|
||||
if not old.get("source_ref") and device.get("source_line"):
|
||||
ref_patches[name] = _build_source_ref(device, role)
|
||||
changed = True
|
||||
if (
|
||||
"systems" in device
|
||||
and name in generated
|
||||
and _entry_systems(old) != list(device["systems"])
|
||||
):
|
||||
system_patches[name] = list(device["systems"])
|
||||
changed = True
|
||||
report["updated" if changed else "unchanged"].append(set_name)
|
||||
|
||||
if write and (contents_patches or ref_patches or system_patches or new_blocks):
|
||||
patched = _add_source_refs(text, ref_patches)
|
||||
patched = _set_section_systems(patched, system_patches)
|
||||
patched = patch_bios_entries(patched, contents_patches)
|
||||
patched = _insert_device_entries(patched, new_blocks)
|
||||
shutil.copy2(path, path.with_suffix(PROFILE_BACKUP_SUFFIX))
|
||||
write_text_atomic(str(path), patched)
|
||||
return report
|
||||
|
||||
|
||||
def _softlist_section(profile: dict, lists: dict[str, list[str]], role: str) -> str:
|
||||
"""The generated software list section, one entry per list and tree.
|
||||
|
||||
A list takes the fields of each hash/ tree the profile delivers (a
|
||||
bundled tree ships with the emulator, not in a pack) and the path of
|
||||
that tree. Members the section names leave the tree's own entry.
|
||||
"""
|
||||
trees = [
|
||||
entry for entry in profile.get("files") or []
|
||||
if entry.get("type") == "directory"
|
||||
and str(entry.get("name")) == "hash/"
|
||||
and not entry.get("bundled")
|
||||
]
|
||||
blocks: list[str] = []
|
||||
for tree in trees:
|
||||
base = str(tree.get("path") or tree["name"])
|
||||
for name, systems in sorted(lists.items()):
|
||||
lines = [
|
||||
f" - name: {yaml_scalar(name + '.xml')}",
|
||||
f" path: {yaml_scalar(base + name + '.xml')}",
|
||||
]
|
||||
if tree.get("mode"):
|
||||
lines.append(f" mode: {tree['mode']}")
|
||||
lines += [
|
||||
" category: game_data",
|
||||
" required: false",
|
||||
*_system_lines(systems),
|
||||
]
|
||||
blocks.append("\n".join(lines))
|
||||
if not blocks:
|
||||
return ""
|
||||
lead = [
|
||||
SOFTLIST_SECTION,
|
||||
" # software_list_device::parse opens <list>.xml for each software list a",
|
||||
" # machine declares. Each list below is filed under the systems whose",
|
||||
" # machines declare it, a list no such machine declares stays with its",
|
||||
" # hash/ tree.",
|
||||
f" # ref: {role}src/emu/softlist_dev.cpp:281-313,",
|
||||
f" # {role}src/frontend/mame/infoxml.cpp:2184-2198",
|
||||
]
|
||||
return "\n".join(lead) + "\n\n" + "\n\n".join(blocks) + "\n"
|
||||
|
||||
|
||||
def merge_mame_support(
|
||||
profile_path: str,
|
||||
lists: dict[str, list[str]],
|
||||
samples: dict[str, list[str]],
|
||||
write: bool = False,
|
||||
) -> dict[str, list[str]]:
|
||||
"""File the software lists and the floppy samples of a MAME profile.
|
||||
|
||||
*lists* maps a software list to the systems whose machines declare it,
|
||||
for the lists the release ships. They are written as the generated
|
||||
software list section, ahead of the device section, and a refresh
|
||||
rewrites the whole section. *samples* maps a floppy sample name to the
|
||||
systems whose drives load it: each written entry named <sample>.wav
|
||||
under a samples/floppy/ path gets them, and one no system loads gets
|
||||
none.
|
||||
"""
|
||||
path = Path(profile_path)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
profile = yaml_load(text) or {}
|
||||
role = mame_ref_role(profile)
|
||||
|
||||
original = text
|
||||
start = softlist_section_start(text)
|
||||
if start is not None:
|
||||
device = device_section_start(text)
|
||||
if device is not None and device > start:
|
||||
end = device
|
||||
else:
|
||||
end_match = _FILES_END.search(text, text.index("\n", start) + 1)
|
||||
end = end_match.start() if end_match else len(text)
|
||||
text = text[:start] + text[end:]
|
||||
section = _softlist_section(profile, lists, role)
|
||||
|
||||
head_end = generated_start(text)
|
||||
head = text if head_end is None else text[:head_end]
|
||||
written = yaml_load(head) or {}
|
||||
sample_systems: dict[str, list[str]] = {}
|
||||
for entry in written.get("files") or []:
|
||||
name = str(entry.get("name") or "")
|
||||
if "samples/floppy/" not in str(entry.get("path") or "") or not name.endswith(".wav"):
|
||||
continue
|
||||
wanted = samples.get(name[:-4], [])
|
||||
if _entry_systems(entry) != wanted:
|
||||
sample_systems[name] = wanted
|
||||
head = _rewrite_systems(head, sample_systems) if sample_systems else head
|
||||
rest = "" if head_end is None else text[head_end:]
|
||||
|
||||
if section and not rest:
|
||||
files_at = re.search(r"^files:[ \t]*$", head, re.M)
|
||||
if files_at is None or _FILES_END.search(head, files_at.end()):
|
||||
raise ValueError(
|
||||
"files: must be the last top-level key to hold a software list section"
|
||||
)
|
||||
patched = head.rstrip("\n") + "\n"
|
||||
if section:
|
||||
patched += "\n" + section
|
||||
if rest:
|
||||
patched += "\n" + rest
|
||||
|
||||
if write and patched != original:
|
||||
shutil.copy2(path, path.with_suffix(PROFILE_BACKUP_SUFFIX))
|
||||
write_text_atomic(str(path), patched)
|
||||
return {
|
||||
"lists": sorted(lists),
|
||||
"samples": sorted(sample_systems),
|
||||
"changed": [str(path)] if patched != original else [],
|
||||
}
|
||||
|
||||
|
||||
def _add_source_refs(text: str, refs: dict[str, str]) -> str:
|
||||
"""Give each named entry a source_ref line, right after its category."""
|
||||
if not refs:
|
||||
return text
|
||||
lines = text.split("\n")
|
||||
current = ""
|
||||
out: list[str] = []
|
||||
for line in lines:
|
||||
head = re.match(r"^ - name:\s*(.+?)\s*$", line)
|
||||
if head:
|
||||
current = head.group(1).strip('"').strip("'")
|
||||
out.append(line)
|
||||
if current in refs and re.match(r"^ category:", line):
|
||||
out.append(f' source_ref: "{refs[current]}"')
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _insert_device_entries(text: str, blocks: dict[str, str]) -> str:
|
||||
"""Place new device entries in name order inside the generated section.
|
||||
|
||||
The section opens at its header and runs to the end of the files list.
|
||||
Entries already there stay in the order they are written, each new one
|
||||
goes before the first whose name sorts after it.
|
||||
"""
|
||||
if not blocks:
|
||||
return text
|
||||
start = device_section_start(text)
|
||||
if start is None:
|
||||
files_at = re.search(r"^files:[ \t]*$", text, re.M)
|
||||
if files_at is None or _FILES_END.search(text, files_at.end()):
|
||||
raise ValueError(
|
||||
"files: must be the last top-level key to hold a device section"
|
||||
)
|
||||
text = text.rstrip("\n") + "\n\n" + DEVICE_SECTION + "\n"
|
||||
start = device_section_start(text)
|
||||
body_at = text.index("\n", start) + 1
|
||||
end_match = _FILES_END.search(text, body_at)
|
||||
end = end_match.start() if end_match else len(text)
|
||||
section = text[body_at:end]
|
||||
starts = [m.start() for m in re.finditer(r"^ - name:", section, re.M)]
|
||||
lead = (section[: starts[0]] if starts else section).strip("\n")
|
||||
present = [
|
||||
section[a:b].rstrip("\n") for a, b in zip(starts, starts[1:] + [len(section)])
|
||||
]
|
||||
|
||||
def block_name(block: str) -> str:
|
||||
return block.split("\n", 1)[0].split(":", 1)[1].strip().strip('"')
|
||||
|
||||
merged: list[str] = []
|
||||
pending = sorted(blocks)
|
||||
for block in present:
|
||||
while pending and pending[0] < block_name(block):
|
||||
merged.append(blocks[pending.pop(0)])
|
||||
merged.append(block)
|
||||
merged.extend(blocks[name] for name in pending)
|
||||
body = (lead + "\n" if lead else "") + "\n\n".join(merged) + "\n"
|
||||
rest = text[end:]
|
||||
return text[:body_at] + body + ("\n" + rest if rest else "")
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Game sets read from the driver code of the MAME versions whose DAT the code moved past."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import functools
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .arcade_sets import SetEntry
|
||||
from ..base_scraper import BlobMismatchError, download
|
||||
from .clex import DriverSourceError, blank_comments, call_args, call_span
|
||||
from .dat_fetch import api_json
|
||||
from core.hashing import git_blob_sha
|
||||
|
||||
|
||||
# --- MAME 0.37 and 0.78 driver source (mame2000, mame2003, mame2003-plus) ----
|
||||
|
||||
# driver.h at each pin: NAME is argument 1 and PARENT argument 2 in every
|
||||
# form, and a BIOS set carries NOT_A_DRIVER in its flags.
|
||||
_GAME_MACRO = re.compile(r"\b(GAME|GAMEX|GAMEC|GAMECX|GAMEB|GAMEBX)\s*\(")
|
||||
_DRIVER_ENTRY = re.compile(r"\bDRIVER\s*\(\s*(\w+)\s*\)")
|
||||
_ROM_START = re.compile(r"\bROM_START\s*\(\s*(\w+)\s*\)(.*?)\bROM_END\b", re.S)
|
||||
_ROM_LOAD = re.compile(r"\bROMX?_LOAD\w*\s*\(")
|
||||
_DISK_IMAGE = re.compile(r"\bDISK_IMAGE\w*\s*\(")
|
||||
_ROM_START_HEAD = re.compile(r"\bROM_START\s*\(")
|
||||
_DIRECTIVE = re.compile(r"^[ \t]*#[ \t]*(\w+)[ \t]*(.*)$")
|
||||
_MACRO_HEAD = re.compile(r"(\w+)(\([^)]*\))?[ \t]*(.*)")
|
||||
_CONDITION_TOKEN = re.compile(
|
||||
r"\s*(?:(0[xX][0-9a-fA-F]+|\d+)[uUlL]*|(defined)|([A-Za-z_]\w*)"
|
||||
r"|(&&|\|\||==|!=|<=|>=|<<|>>|[!<>()+\-*/%~&|^]))"
|
||||
)
|
||||
_IDENTIFIER = re.compile(r"\b[A-Za-z_]\w*\b")
|
||||
_INCLUDE = re.compile(r'"([^"]+)"')
|
||||
|
||||
|
||||
def _condition_value(expr: str, defines: dict[str, str], depth: int = 0) -> int:
|
||||
"""An ``#if`` expression the way the C preprocessor reads it: a name not
|
||||
defined is 0, a defined name is its value."""
|
||||
python: list[str] = []
|
||||
position = 0
|
||||
expr = expr.strip()
|
||||
while position < len(expr):
|
||||
match = _CONDITION_TOKEN.match(expr, position)
|
||||
if not match:
|
||||
raise DriverSourceError(f"#if {expr}: cannot read")
|
||||
number, defined, name, operator = match.groups()
|
||||
position = match.end()
|
||||
if number:
|
||||
python.append(str(int(number, 0)))
|
||||
elif defined:
|
||||
target = re.match(r"\s*\(?\s*(\w+)\s*\)?", expr[position:])
|
||||
if not target:
|
||||
raise DriverSourceError(f"#if {expr}: defined without a name")
|
||||
python.append("1" if target.group(1) in defines else "0")
|
||||
position += target.end()
|
||||
elif name:
|
||||
value = defines.get(name, "0").strip() or "1"
|
||||
if depth > 8:
|
||||
raise DriverSourceError(f"#if {expr}: {name} does not resolve")
|
||||
python.append(str(_condition_value(value, defines, depth + 1)))
|
||||
else:
|
||||
python.append(
|
||||
{"&&": " and ", "||": " or ", "!": " not ", "/": "//"}.get(operator, operator)
|
||||
)
|
||||
try:
|
||||
return int(_arithmetic(ast.parse("".join(python).strip(), mode="eval").body))
|
||||
except (SyntaxError, ZeroDivisionError, TypeError) as exc:
|
||||
raise DriverSourceError(f"#if {expr}: {exc}") from exc
|
||||
|
||||
|
||||
_BINARY = {
|
||||
ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b,
|
||||
ast.Mult: lambda a, b: a * b, ast.FloorDiv: lambda a, b: a // b,
|
||||
ast.Mod: lambda a, b: a % b, ast.LShift: lambda a, b: a << b,
|
||||
ast.RShift: lambda a, b: a >> b, ast.BitAnd: lambda a, b: a & b,
|
||||
ast.BitOr: lambda a, b: a | b, ast.BitXor: lambda a, b: a ^ b,
|
||||
}
|
||||
_COMPARE = {
|
||||
ast.Eq: lambda a, b: a == b, ast.NotEq: lambda a, b: a != b,
|
||||
ast.Lt: lambda a, b: a < b, ast.LtE: lambda a, b: a <= b,
|
||||
ast.Gt: lambda a, b: a > b, ast.GtE: lambda a, b: a >= b,
|
||||
}
|
||||
|
||||
|
||||
def _arithmetic(node: ast.AST) -> int:
|
||||
"""Integer arithmetic of an ``#if``, nothing else evaluated."""
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, int):
|
||||
return node.value
|
||||
if isinstance(node, ast.UnaryOp):
|
||||
value = _arithmetic(node.operand)
|
||||
if isinstance(node.op, ast.Not):
|
||||
return int(not value)
|
||||
if isinstance(node.op, ast.USub):
|
||||
return -value
|
||||
if isinstance(node.op, ast.UAdd):
|
||||
return value
|
||||
if isinstance(node.op, ast.Invert):
|
||||
return ~value
|
||||
if isinstance(node, ast.BoolOp):
|
||||
values = [_arithmetic(v) for v in node.values]
|
||||
return int(all(values) if isinstance(node.op, ast.And) else any(values))
|
||||
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
|
||||
return _BINARY[type(node.op)](_arithmetic(node.left), _arithmetic(node.right))
|
||||
if isinstance(node, ast.Compare):
|
||||
left = _arithmetic(node.left)
|
||||
for op, right_node in zip(node.ops, node.comparators):
|
||||
right = _arithmetic(right_node)
|
||||
if type(op) not in _COMPARE or not _COMPARE[type(op)](left, right):
|
||||
return 0
|
||||
left = right
|
||||
return 1
|
||||
raise TypeError(f"{type(node).__name__} in a condition")
|
||||
|
||||
|
||||
class _Preprocessor:
|
||||
"""Conditional compilation over src/, enough to tell which GAME and
|
||||
ROM_START a build compiles. Headers are read for their definitions."""
|
||||
|
||||
def __init__(self, headers: dict[str, str]) -> None:
|
||||
self.headers = headers
|
||||
self._by_basename: dict[str, list[str]] = {}
|
||||
for path in headers:
|
||||
self._by_basename.setdefault(path.rsplit("/", 1)[-1], []).append(path)
|
||||
|
||||
def _resolve(self, name: str, including: str) -> str | None:
|
||||
folder = including.rsplit("/", 1)[0]
|
||||
for candidate in (f"{folder}/{name}", f"src/{name}", f"src/includes/{name}"):
|
||||
if candidate in self.headers:
|
||||
return candidate
|
||||
found = self._by_basename.get(name.rsplit("/", 1)[-1], [])
|
||||
return found[0] if len(found) == 1 else None
|
||||
|
||||
def run(
|
||||
self, path: str, text: str, defines: dict[str, str],
|
||||
local: dict[str, tuple[list[str] | None, str]] | None, seen: set[str],
|
||||
) -> str:
|
||||
text = blank_comments(text, keep_lines=False).replace("\\\r\n", " ").replace("\\\n", " ")
|
||||
out: list[str] = []
|
||||
# Each level: (enclosing level active, a branch already taken, this branch active).
|
||||
stack: list[tuple[bool, bool, bool]] = []
|
||||
active = True
|
||||
for line in text.splitlines():
|
||||
directive = _DIRECTIVE.match(line)
|
||||
if not directive:
|
||||
if active:
|
||||
out.append(line)
|
||||
continue
|
||||
word, rest = directive.groups()
|
||||
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
|
||||
argument, 0.37 a zero CRC."""
|
||||
if any("NO_DUMP" in a for a in args):
|
||||
return False
|
||||
crc = args[3] if len(args) > 3 else ""
|
||||
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
|
||||
``DDP2_SET(name, program, asic)``)."""
|
||||
writers = {
|
||||
name: (params, body)
|
||||
for name, (params, body) in local.items()
|
||||
if params is not None and (_ROM_START_HEAD.search(body) or _GAME_MACRO.search(body))
|
||||
}
|
||||
if not writers:
|
||||
return text
|
||||
call = re.compile(r"\b(" + "|".join(map(re.escape, writers)) + r")\s*\(")
|
||||
out: list[str] = []
|
||||
position = 0
|
||||
for match in call.finditer(text):
|
||||
if match.start() < position:
|
||||
continue
|
||||
params, body = writers[match.group(1)]
|
||||
args, end = call_span(text, match.end())
|
||||
if len(args) != len(params):
|
||||
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(functools.partial(_argument, values), body))
|
||||
position = end
|
||||
out.append(text[position:])
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def compiled_drivers(driver_c: str, preprocessor: _Preprocessor) -> list[str]:
|
||||
"""The DRIVER() entries driver.c compiles into the driver list."""
|
||||
# driver.c is read twice by the build, the second time with
|
||||
# DRIVER_RECURSIVE defined: that pass is the list.
|
||||
text = preprocessor.run(
|
||||
"src/driver.c", driver_c, {"DRIVER_RECURSIVE": "", "DRIVER": ""}, None, set()
|
||||
)
|
||||
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]:
|
||||
"""Every compiled set and every set on its parent chain, from the source.
|
||||
|
||||
*drivers* maps each path under src/drivers/ to its text and *headers*
|
||||
every header under src/. A set is declared by a GAME-family macro whose
|
||||
ROMs are ``ROM_START(name)``, and a set flagged ``NOT_A_DRIVER`` is a BIOS
|
||||
set, the flag the 0.37 and 0.78 info.c use to tell a resource from a game.
|
||||
"""
|
||||
preprocessor = _Preprocessor(headers)
|
||||
declared: dict[str, tuple[str | None, bool]] = {}
|
||||
roms: dict[str, tuple[bool, bool]] = {}
|
||||
for path, source in sorted(drivers.items()):
|
||||
_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:
|
||||
raise DriverSourceError(f"driver.c lists undeclared sets: {', '.join(undeclared[:10])}")
|
||||
sets: dict[str, SetEntry] = {}
|
||||
pending = list(compiled)
|
||||
while pending:
|
||||
name = pending.pop()
|
||||
if name in sets or name not in declared:
|
||||
continue
|
||||
parent, bios = declared[name]
|
||||
has_roms, disks = roms.get(name, (False, False))
|
||||
sets[name] = SetEntry(
|
||||
name=name, romof=parent, isbios=bios, runnable=not bios,
|
||||
has_roms=has_roms, disks=disks,
|
||||
)
|
||||
if parent:
|
||||
pending.append(parent)
|
||||
return sets
|
||||
|
||||
|
||||
def git_tree_sha(entries: dict[str, tuple[str, str]]) -> str:
|
||||
"""The sha git gives a directory, from ``{path: (mode, blob sha)}`` of
|
||||
every file under it, paths relative to it."""
|
||||
children: dict[str, dict[str, tuple[str, str]]] = {}
|
||||
rows: list[tuple[str, str, str]] = []
|
||||
for path, (mode, sha) in entries.items():
|
||||
head, sep, tail = path.partition("/")
|
||||
if sep:
|
||||
children.setdefault(head, {})[tail] = (mode, sha)
|
||||
else:
|
||||
rows.append((head, mode, sha))
|
||||
rows += [(name, "40000", git_tree_sha(sub)) for name, sub in children.items()]
|
||||
# git orders a tree by name, a directory compared as if it ended in "/".
|
||||
rows.sort(key=lambda row: row[0].encode() + (b"/" if row[1] == "40000" else b""))
|
||||
body = b"".join(
|
||||
mode.encode() + b" " + name.encode() + b"\0" + bytes.fromhex(sha)
|
||||
for name, mode, sha in rows
|
||||
)
|
||||
return hashlib.sha1(f"tree {len(body)}\0".encode() + body).hexdigest()
|
||||
|
||||
|
||||
@dataclass
|
||||
class DriverSource:
|
||||
"""What the reader needs from src/ at one commit, and the tree sha of
|
||||
src/ computed from every file of it."""
|
||||
|
||||
driver_c: str
|
||||
drivers: dict[str, str]
|
||||
headers: dict[str, str]
|
||||
tree: str
|
||||
|
||||
|
||||
def read_driver_source(tarball: Path) -> DriverSource:
|
||||
"""src/ of a GitHub tarball: the texts the reader needs, and the git
|
||||
tree sha of the whole directory."""
|
||||
import tarfile
|
||||
|
||||
entries: dict[str, tuple[str, str]] = {}
|
||||
texts: dict[str, str] = {}
|
||||
with tarfile.open(tarball, "r:gz") as archive:
|
||||
for member in archive:
|
||||
parts = member.name.split("/", 1)
|
||||
if len(parts) < 2 or not parts[1].startswith("src/"):
|
||||
continue
|
||||
path = parts[1]
|
||||
if member.issym():
|
||||
entries[path[4:]] = ("120000", git_blob_sha(member.linkname.encode()))
|
||||
elif member.isfile():
|
||||
handle = archive.extractfile(member)
|
||||
data = handle.read() if handle else b""
|
||||
mode = "100755" if member.mode & 0o111 else "100644"
|
||||
entries[path[4:]] = (mode, git_blob_sha(data))
|
||||
if path == "src/driver.c" or path.endswith(".h") or (
|
||||
path.startswith("src/drivers/") and path.endswith(".c")
|
||||
):
|
||||
texts[path] = data.decode("latin-1")
|
||||
if "src/driver.c" not in texts:
|
||||
raise FileNotFoundError(f"{tarball} has no src/driver.c")
|
||||
return DriverSource(
|
||||
driver_c=texts["src/driver.c"],
|
||||
drivers={p: t for p, t in texts.items() if p.startswith("src/drivers/") and p.endswith(".c")},
|
||||
headers={p: t for p, t in texts.items() if p.endswith(".h")},
|
||||
tree=git_tree_sha(entries),
|
||||
)
|
||||
|
||||
|
||||
def fetch_driver_source(
|
||||
slug: str, commit: str, cache_dir: Path, offline: bool = False
|
||||
) -> DriverSource:
|
||||
"""src/ at a commit, its tree sha checked against the repository's own
|
||||
when online."""
|
||||
tarball = cache_dir / "src" / slug / f"{commit}.tar.gz"
|
||||
if offline:
|
||||
if not tarball.is_file():
|
||||
raise FileNotFoundError(f"{tarball} is not cached")
|
||||
else:
|
||||
download(f"https://codeload.github.com/{slug}/tar.gz/{commit}", tarball,
|
||||
skip_existing=True)
|
||||
source = read_driver_source(tarball)
|
||||
if not offline:
|
||||
listing = api_json(f"https://api.github.com/repos/{slug}/git/trees/{commit}")
|
||||
listed = next(
|
||||
(
|
||||
item.get("sha")
|
||||
for item in (listing.get("tree", []) if isinstance(listing, dict) else [])
|
||||
if item.get("path") == "src"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if listed != source.tree:
|
||||
tarball.unlink()
|
||||
raise BlobMismatchError(f"{slug}@{commit[:8]}:src is tree {listed}, not {source.tree}")
|
||||
return source
|
||||
@@ -0,0 +1,477 @@
|
||||
"""Import, per arcade core version, which BIOS set each game set loads.
|
||||
|
||||
A game set names its parent through ``romof``: a clone reads its parent game,
|
||||
and the chain ends at a BIOS set (``neogeo``, ``naomi``, ``pgm``). The archive
|
||||
the installer has to provide for a game on the card is every BIOS set on that
|
||||
chain, plus, for the MAME family, the device sets with ROMs the machine
|
||||
instantiates (``device_ref``), which a split or merged romset reads from their
|
||||
own archive. The answer is read at the revision the profile pins, from the
|
||||
DAT of the core version that runs the game where that DAT is the code's own
|
||||
output, and from the driver code where it is not:
|
||||
|
||||
python -m scripts.scraper.arcade.arcade_parent_importer --all
|
||||
python -m scripts.scraper.arcade.arcade_parent_importer --profile mame2003_plus
|
||||
python -m scripts.scraper.arcade.arcade_parent_importer --all --offline
|
||||
|
||||
A BIOS set is ``isbios="yes"`` (MAME 0.139 and later, FBNeo). mame2000,
|
||||
mame2003 and mame2003-plus carry a DAT in metadata/ that their code has
|
||||
moved past (mame2003-plus: 186 compiled sets absent, nbajamex under a BIOS
|
||||
set the code no longer declares), so they are read from src/driver.c and
|
||||
src/drivers/: the parent is the GAME macro's PARENT argument and a BIOS set
|
||||
is flagged NOT_A_DRIVER. Their DAT is still read, to report where it
|
||||
disagrees. FBNeo's DATs are read one at a time, a console set keyed by its
|
||||
driver (``msx_1942``): the Arcade, MSX and NES DATs each carry a ``1942``.
|
||||
flycast keeps its NAOMI and Atomiswave table in code: ``Games[].bios`` names
|
||||
the BIOS, ``naomi`` when it is null (core/hw/naomi/naomi_cart.cpp:195-197),
|
||||
and ``BIOS[].filename`` the archive when it differs from the name
|
||||
(naomi_cart.cpp:75).
|
||||
|
||||
Output: games/arcade/<profile>.json. CHD games are listed, not resolved: a
|
||||
CHD is game content. A ``romof`` pointing outside the sets read is listed
|
||||
with its target, never guessed. The games that load no BIOS set
|
||||
(``no_bios``) and every BIOS set (``bios_sets``) are listed too: a set name
|
||||
on a card that none of the lists holds is one the core does not know.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import zipfile
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from typing import IO
|
||||
|
||||
from model.database import load_database
|
||||
from core.artifacts import write_if_changed
|
||||
from model.profiles import load_emulator_profiles
|
||||
from core.cli import add_repo_inputs, run_cli
|
||||
from core.hashing import compute_hashes, git_blob_sha
|
||||
from core.upstream import parse_repo
|
||||
from ..base_scraper import fetch_verified_blob
|
||||
from ..dats.listxml import Opener, open_listxml
|
||||
from model.mamerelease import mame_tag
|
||||
from .dat_fetch import MAME_LISTXML_URL, api_json, cached_pack, fetch_pack
|
||||
from .arcade_drivers import driver_source_sets, fetch_driver_source
|
||||
from .arcade_sets import (
|
||||
FBNEO_DRIVERLIST,
|
||||
SetEntry,
|
||||
fbneo_drivers,
|
||||
fbneo_sets,
|
||||
flycast_index,
|
||||
is_bios,
|
||||
iter_sets,
|
||||
)
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
DEFAULT_OUTPUT = Path("games") / "arcade"
|
||||
DEFAULT_CACHE = Path(".cache") / "dats"
|
||||
|
||||
# How each profile's DAT is found. "listxml": the -listxml release asset of
|
||||
# the MAME version core_version names. "fbneo": every DAT of libretro/FBNeo's
|
||||
# dats/ at source_commit. "repo": files of the profile's source repository at
|
||||
# source_commit (a ZIP member when the file is an archive). "source": the
|
||||
# driver code itself at source_commit (src/driver.c and src/drivers/), for the
|
||||
# cores whose committed DAT contradicts their code; "paths" then names that
|
||||
# DAT, read only to report where it disagrees. "flycast": the BIOS and Games
|
||||
# tables of naomi_roms.cpp at source_commit.
|
||||
PROFILES: dict[str, dict] = {
|
||||
"mame": {"kind": "listxml", "marker": "isbios"},
|
||||
"mame0258": {"kind": "listxml", "marker": "isbios"},
|
||||
"mame0278": {"kind": "listxml", "marker": "isbios"},
|
||||
"fbneo": {"kind": "fbneo", "marker": "isbios"},
|
||||
"mame2016": {
|
||||
"kind": "repo",
|
||||
"marker": "isbios",
|
||||
"paths": ["metadata/MAME 0.174 Arcade XML DAT.zip", "metadata/MAME 0.174 Home XML DAT.zip"],
|
||||
},
|
||||
"mame2015": {"kind": "repo", "marker": "isbios", "paths": ["metadata/mame2014-xml.zip"]},
|
||||
"mame2010": {"kind": "repo", "marker": "isbios", "paths": ["metadata/mame2010.xml"]},
|
||||
"mame2003_plus": {"kind": "source", "marker": "runnable", "paths": ["metadata/mame2003-plus.xml"]},
|
||||
"mame2003": {"kind": "source", "marker": "runnable", "paths": ["metadata/mame2003.xml"]},
|
||||
"mame2000": {"kind": "source", "marker": "isbios", "paths": ["metadata/MAME 0.37b5 XML.dat"]},
|
||||
"flycast": {"kind": "flycast", "paths": ["core/hw/naomi/naomi_roms.cpp"]},
|
||||
}
|
||||
|
||||
# About 95 % of what the pinned DATs gave on 2026-11-03: a build that
|
||||
# resolves fewer games to a BIOS set has read a DAT of another shape.
|
||||
FLOORS: dict[str, int] = {
|
||||
"mame": 2600,
|
||||
"mame0258": 2490,
|
||||
"mame0278": 2580,
|
||||
"fbneo": 9800,
|
||||
"mame2016": 1840,
|
||||
"mame2015": 1470,
|
||||
"mame2010": 1060,
|
||||
"mame2003_plus": 650,
|
||||
"mame2003": 420,
|
||||
"mame2000": 120,
|
||||
"flycast": 330,
|
||||
}
|
||||
|
||||
|
||||
def build_index(
|
||||
sets: dict[str, SetEntry], marker: str, archives: dict[str, str] | None = None
|
||||
) -> dict:
|
||||
"""BIOS sets per game, device sets per game, CHD games, broken chains.
|
||||
|
||||
A BIOS set none of whose ROMs was dumped is passed over: its archive holds
|
||||
nothing, and the loader only warns about a ROM without a dump. *archives*
|
||||
names the archive of a set whose name is not its archive's (an FBNeo
|
||||
console driver)."""
|
||||
archive = (archives or {}).get
|
||||
bios_names = {n for n, e in sets.items() if is_bios(e, marker)}
|
||||
device_roms = {n for n, e in sets.items() if e.isdevice and e.has_roms}
|
||||
games = {
|
||||
n: e for n, e in sets.items()
|
||||
if n not in bios_names and not e.isdevice and e.runnable and (e.has_roms or e.disks)
|
||||
}
|
||||
bios: dict[str, set[str]] = {}
|
||||
parents: dict[str, set[str]] = {}
|
||||
devices: dict[str, set[str]] = {}
|
||||
missing: dict[str, str] = {}
|
||||
for name, entry in games.items():
|
||||
seen = {name}
|
||||
current = entry.romof
|
||||
while current and current not in seen:
|
||||
seen.add(current)
|
||||
parent = sets.get(current)
|
||||
if parent is None:
|
||||
missing[name] = archive(current, current)
|
||||
break
|
||||
if current in bios_names and parent.has_roms:
|
||||
bios.setdefault(archive(current, current), set()).add(name)
|
||||
elif current not in bios_names and parent.has_roms:
|
||||
# A clone's ROM shared with its parent is looked up in the
|
||||
# parent's archive too: MAME's search path is the set and
|
||||
# every ancestor (src/emu/driver.cpp:31-38,
|
||||
# src/emu/romload.cpp:67-84 at mame0289).
|
||||
parents.setdefault(archive(current, current), set()).add(name)
|
||||
current = parent.romof
|
||||
for device in set(entry.devices) & device_roms:
|
||||
devices.setdefault(device, set()).add(name)
|
||||
with_bios = {g for members in bios.values() for g in members}
|
||||
# The source file of each game and device set: what a launcher that
|
||||
# starts whatever set a folder holds selects a folder's machines by
|
||||
# (ES-DE runs MAME on any CPS-2 set of roms/cps2).
|
||||
sources: dict[str, set[str]] = {}
|
||||
for name, entry in sets.items():
|
||||
if entry.source and (name in games or name in device_roms):
|
||||
sources.setdefault(entry.source, set()).add(archive(name, name))
|
||||
return {
|
||||
"bios": {k: sorted(v) for k, v in sorted(bios.items())},
|
||||
"parents": {k: sorted(v) for k, v in sorted(parents.items())},
|
||||
"devices": {k: sorted(v) for k, v in sorted(devices.items())},
|
||||
"chd": sorted(n for n, e in games.items() if e.disks),
|
||||
"missing_parents": dict(sorted(missing.items())),
|
||||
"no_bios": sorted(set(games) - with_bios - set(missing)),
|
||||
"bios_sets": sorted(bios_names),
|
||||
**({"sources": {k: sorted(v) for k, v in sorted(sources.items())}} if sources else {}),
|
||||
"counts": {
|
||||
"sets": len(sets),
|
||||
"games": len(games),
|
||||
"games_with_bios": len(with_bios),
|
||||
"bios_sets": len(bios_names),
|
||||
"bios_roots_used": len(bios),
|
||||
"games_with_devices": len({g for v in devices.values() for g in v}),
|
||||
"chd_games": sum(1 for e in games.values() if e.disks),
|
||||
"missing_parents": len(missing),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def dat_gaps(code: dict[str, SetEntry], dat: dict[str, SetEntry], marker: str) -> dict:
|
||||
"""Where the DAT a repository carries contradicts its own code."""
|
||||
both = code.keys() & dat.keys()
|
||||
return {
|
||||
"code_only": sorted(code.keys() - dat.keys()),
|
||||
"dat_only": sorted(dat.keys() - code.keys()),
|
||||
"romof": sorted(n for n in both if code[n].romof != dat[n].romof),
|
||||
"bios": sorted(n for n in both if is_bios(code[n], marker) != is_bios(dat[n], marker)),
|
||||
}
|
||||
|
||||
|
||||
def _dat_cross_check(
|
||||
spec: dict, slug: str, commit: str, cache_dir: Path, offline: bool,
|
||||
code: dict[str, SetEntry],
|
||||
) -> dict | None:
|
||||
"""dat_gaps against the DAT the repository carries, None when the DAT
|
||||
is not cached and the run is offline."""
|
||||
paths: list[Path] = []
|
||||
for path in spec.get("paths", []):
|
||||
try:
|
||||
local, _ = (
|
||||
_cached_repo_file(slug, commit, path, cache_dir)
|
||||
if offline
|
||||
else fetch_repo_file(slug, commit, path, cache_dir)
|
||||
)
|
||||
except FileNotFoundError:
|
||||
if offline:
|
||||
return None
|
||||
raise
|
||||
paths.append(local)
|
||||
if not paths:
|
||||
return None
|
||||
dat = read_sets([opener for p in paths for opener in _xml_streams(p)])
|
||||
return dat_gaps(code, dat, spec["marker"])
|
||||
|
||||
|
||||
# --- Fetching ----------------------------------------------------------------
|
||||
|
||||
|
||||
def _repo_slug(url: str) -> str:
|
||||
"""owner/name of the GitHub repository a profile's source names."""
|
||||
repo = parse_repo(url)
|
||||
if repo is None or repo.family != "github":
|
||||
raise ValueError(f"not a GitHub repository URL: {url}")
|
||||
return repo.slug
|
||||
|
||||
|
||||
def fetch_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple[Path, str]:
|
||||
"""One file of a GitHub repository at a commit, checked against the blob
|
||||
sha the repository lists for it, and that sha."""
|
||||
folder, _, name = path.rpartition("/")
|
||||
listing = api_json(
|
||||
f"https://api.github.com/repos/{slug}/contents/{urllib.parse.quote(folder)}?ref={commit}"
|
||||
)
|
||||
item = next(
|
||||
(i for i in listing if isinstance(i, dict) and i.get("name") == name), None
|
||||
) if isinstance(listing, list) else None
|
||||
if item is None:
|
||||
raise FileNotFoundError(f"{slug}@{commit[:8]} has no {path}")
|
||||
url = (
|
||||
f"https://raw.githubusercontent.com/{slug}/{commit}/"
|
||||
f"{urllib.parse.quote(path)}"
|
||||
)
|
||||
destination = fetch_verified_blob(url, cache_dir / "repo" / slug / commit / path, item["sha"])
|
||||
return destination, item["sha"]
|
||||
|
||||
|
||||
def _cached_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple[Path, str]:
|
||||
"""The cached copy, offline. Its blob sha is recomputed from the bytes."""
|
||||
destination = cache_dir / "repo" / slug / commit / path
|
||||
if not destination.is_file():
|
||||
raise FileNotFoundError(f"{slug}@{commit[:8]}:{path} is not in {cache_dir}")
|
||||
return destination, git_blob_sha(destination.read_bytes())
|
||||
|
||||
|
||||
def _file_opener(path: Path) -> Opener:
|
||||
return lambda: path.open("rb")
|
||||
|
||||
|
||||
def _xml_streams(path: Path) -> Iterator[Opener]:
|
||||
"""Openers for the XML documents a file holds: itself, or each XML or
|
||||
DAT member of a ZIP."""
|
||||
if path.suffix.lower() != ".zip":
|
||||
yield lambda: path.open("rb")
|
||||
return
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
names = sorted(
|
||||
n for n in archive.namelist() if n.lower().endswith((".xml", ".dat"))
|
||||
)
|
||||
for member in names:
|
||||
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[Opener]) -> 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] = {}
|
||||
for opener in openers:
|
||||
with opener() as stream:
|
||||
for entry in iter_sets(stream):
|
||||
if entry.name:
|
||||
sets.setdefault(entry.name, entry)
|
||||
return sets
|
||||
|
||||
|
||||
def import_profile(
|
||||
profile: str, data: dict, cache_dir: Path, offline: bool = False,
|
||||
report: dict | None = None,
|
||||
) -> dict:
|
||||
"""The index document for one profile, from the DAT or the code its pin
|
||||
names. *report* receives, for a profile read from its code, where the DAT
|
||||
the repository carries disagrees with that code."""
|
||||
spec = PROFILES[profile]
|
||||
commit = str(data.get("source_commit") or "")
|
||||
source_url = str(data.get("source") or "")
|
||||
kind = spec["kind"]
|
||||
source: dict[str, object]
|
||||
openers: list[Opener]
|
||||
if kind == "listxml":
|
||||
tag = mame_tag(str(data["core_version"]))
|
||||
pack, _ = (cached_pack if offline else fetch_pack)("mame", tag, cache_dir)
|
||||
source = {
|
||||
"release": f"mamedev/mame {tag}",
|
||||
"url": MAME_LISTXML_URL.format(tag=tag),
|
||||
"sha256": compute_hashes(pack, frozenset({"sha256"}), cache=False)["sha256"],
|
||||
}
|
||||
index = build_index(read_sets([lambda: open_listxml(pack)]), spec["marker"])
|
||||
elif kind == "fbneo":
|
||||
folder, blobs = (cached_pack if offline else fetch_pack)("fbneo", commit, cache_dir)
|
||||
slug = _repo_slug(source_url)
|
||||
listing, listing_sha = (
|
||||
_cached_repo_file(slug, commit, FBNEO_DRIVERLIST, cache_dir)
|
||||
if offline
|
||||
else fetch_repo_file(slug, commit, FBNEO_DRIVERLIST, cache_dir)
|
||||
)
|
||||
source = {
|
||||
"repo": source_url,
|
||||
"commit": commit,
|
||||
"files": {
|
||||
**{f"dats/{name}": sha for name, sha in sorted(blobs.items())},
|
||||
FBNEO_DRIVERLIST: listing_sha,
|
||||
},
|
||||
}
|
||||
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":
|
||||
slug = _repo_slug(source_url)
|
||||
tree = fetch_driver_source(slug, commit, cache_dir, offline)
|
||||
sets = driver_source_sets(tree.driver_c, tree.drivers, tree.headers)
|
||||
source = {"repo": source_url, "commit": commit, "files": {"src": tree.tree}}
|
||||
index = build_index(sets, spec["marker"])
|
||||
if report is not None:
|
||||
report["dat_gaps"] = _dat_cross_check(spec, slug, commit, cache_dir, offline, sets)
|
||||
else:
|
||||
slug = _repo_slug(source_url)
|
||||
files: dict[str, str] = {}
|
||||
paths: list[Path] = []
|
||||
for path in spec["paths"]:
|
||||
local, sha = (
|
||||
_cached_repo_file(slug, commit, path, cache_dir)
|
||||
if offline
|
||||
else fetch_repo_file(slug, commit, path, cache_dir)
|
||||
)
|
||||
files[path] = sha
|
||||
paths.append(local)
|
||||
source = {"repo": source_url, "commit": commit, "files": files}
|
||||
if kind == "flycast":
|
||||
index = flycast_index(paths[0].read_text(encoding="utf-8"))
|
||||
else:
|
||||
openers = [opener for p in paths for opener in _xml_streams(p)]
|
||||
index = build_index(read_sets(openers), spec["marker"])
|
||||
return {
|
||||
"schema": SCHEMA_VERSION,
|
||||
"profile": profile,
|
||||
"core_version": data.get("core_version"),
|
||||
"source": source,
|
||||
**index,
|
||||
}
|
||||
|
||||
|
||||
# --- Checks against the collection -------------------------------------------
|
||||
|
||||
|
||||
def declared_archives(profile: dict) -> set[str]:
|
||||
"""Archive names a profile declares, lowercased: file names, aliases and
|
||||
the archive a member lives in."""
|
||||
names: set[str] = set()
|
||||
for entry in profile.get("files") or []:
|
||||
for value in [entry.get("name"), entry.get("archive"), *(entry.get("aliases") or [])]:
|
||||
if isinstance(value, str) and value:
|
||||
names.add(value.rsplit("/", 1)[-1].lower())
|
||||
return names
|
||||
|
||||
|
||||
def collection_names(database: str) -> set[str]:
|
||||
db = load_database(database)
|
||||
return {n.lower() for n in db.get("indexes", {}).get("by_name", {})}
|
||||
|
||||
|
||||
def bios_roots(doc: dict) -> list[str]:
|
||||
return sorted(doc["bios"])
|
||||
|
||||
|
||||
def dump(doc: dict) -> str:
|
||||
return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.splitlines()[0])
|
||||
which = parser.add_mutually_exclusive_group(required=True)
|
||||
which.add_argument("--profile", action="append", choices=sorted(PROFILES),
|
||||
help="profile to import (repeatable)")
|
||||
which.add_argument("--all", action="store_true", help="every profile with an arcade source")
|
||||
add_repo_inputs(parser, "emulators", "db")
|
||||
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT,
|
||||
help=f"where the parent maps are written (default {DEFAULT_OUTPUT})")
|
||||
parser.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE,
|
||||
help=f"downloaded DATs and sources (default {DEFAULT_CACHE})")
|
||||
parser.add_argument("--offline", action="store_true", help="read the download cache only")
|
||||
parser.add_argument("--dry-run", action="store_true", help="print coverage, write nothing")
|
||||
args = parser.parse_args()
|
||||
|
||||
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
|
||||
names = collection_names(args.db)
|
||||
failed = False
|
||||
for profile in sorted(PROFILES) if args.all else args.profile:
|
||||
if profile not in profiles:
|
||||
print(f"FAIL {profile}: no emulators/{profile}.yml", file=sys.stderr)
|
||||
failed = True
|
||||
continue
|
||||
try:
|
||||
report: dict = {}
|
||||
doc = import_profile(
|
||||
profile, profiles[profile], args.cache_dir, args.offline, report
|
||||
)
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
print(f"FAIL {profile}: {exc}", file=sys.stderr)
|
||||
failed = True
|
||||
continue
|
||||
counts = doc["counts"]
|
||||
roots = bios_roots(doc)
|
||||
declared = declared_archives(profiles[profile])
|
||||
undeclared = [r for r in roots if f"{r}.zip" not in declared]
|
||||
absent = [r for r in roots if f"{r}.zip" not in names]
|
||||
print(
|
||||
f"{profile}: {counts['games']} games, {counts['games_with_bios']} with a BIOS set, "
|
||||
f"{counts['bios_roots_used']} BIOS sets used, "
|
||||
f"{counts['games_with_devices']} with device sets, {counts['chd_games']} CHD, "
|
||||
f"{counts['missing_parents']} parents absent"
|
||||
)
|
||||
if PROFILES[profile]["kind"] == "source":
|
||||
gaps = report.get("dat_gaps")
|
||||
if gaps is None:
|
||||
print(" read from the code, the committed DAT is not cached for the cross-check")
|
||||
else:
|
||||
print(
|
||||
f" read from the code, the committed DAT disagrees: "
|
||||
f"{len(gaps['code_only'])} sets only in the code, "
|
||||
f"{len(gaps['dat_only'])} only in the DAT, "
|
||||
f"{len(gaps['romof'])} parents and {len(gaps['bios'])} BIOS flags differ"
|
||||
)
|
||||
for key in ("dat_only", "romof", "bios"):
|
||||
if gaps[key]:
|
||||
print(f" {key}: {', '.join(gaps[key][:20])}")
|
||||
if absent:
|
||||
print(f" BIOS sets absent from the collection: {', '.join(absent)}")
|
||||
if undeclared:
|
||||
print(f" BIOS sets the profile does not declare: {', '.join(undeclared)}")
|
||||
floor = FLOORS.get(profile, 0)
|
||||
if counts["games_with_bios"] < floor:
|
||||
print(
|
||||
f"FAIL {profile}: {counts['games_with_bios']} games with a BIOS set, "
|
||||
f"floor {floor}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
failed = True
|
||||
continue
|
||||
if not args.dry_run:
|
||||
target = args.output_dir / f"{profile}.json"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if write_if_changed(str(target), dump(doc)):
|
||||
print(f" wrote {target}")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_cli(main)
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Game sets and their BIOS parents as a DAT, FBNeo's driver list and flycast's table declare them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from typing import IO
|
||||
|
||||
from .clex import blank_comments
|
||||
from .fbneo_parser import zip_name
|
||||
from ..dats.listxml import Opener, attrs, iter_elements, rom_members
|
||||
|
||||
|
||||
@dataclass
|
||||
class SetEntry:
|
||||
"""What the index needs from one machine or game element."""
|
||||
|
||||
name: str
|
||||
romof: str | None = None
|
||||
isbios: bool = False
|
||||
isdevice: bool = False
|
||||
runnable: bool = True
|
||||
has_roms: bool = False
|
||||
disks: bool = False
|
||||
devices: list[str] = field(default_factory=list)
|
||||
source: str | None = None
|
||||
|
||||
|
||||
_DEVICE_REF = re.compile(rb'<device_ref\b[^>]*\bname="([^"]+)"')
|
||||
_DISK = re.compile(rb"<disk\b([^>]*)>")
|
||||
|
||||
|
||||
def iter_sets(stream: IO[bytes]) -> Iterator[SetEntry]:
|
||||
"""Every machine or game element of a DAT or -listxml, streamed."""
|
||||
for element in iter_elements(stream, ("machine", "game")):
|
||||
found, body = element.attrs, element.body
|
||||
disks = [attrs(d) for d in _DISK.findall(body)]
|
||||
yield SetEntry(
|
||||
name=found.get("name", ""),
|
||||
romof=found.get("romof") or None,
|
||||
isbios=found.get("isbios") == "yes",
|
||||
isdevice=found.get("isdevice") == "yes",
|
||||
runnable=found.get("runnable", "yes") != "no",
|
||||
has_roms=bool(rom_members(body)),
|
||||
disks=any(d.get("status") != "nodump" for d in disks),
|
||||
devices=[d.decode() for d in _DEVICE_REF.findall(body)],
|
||||
source=found.get("sourcefile"),
|
||||
)
|
||||
|
||||
|
||||
def is_bios(entry: SetEntry, marker: str) -> bool:
|
||||
if entry.isbios:
|
||||
return True
|
||||
return marker == "runnable" and not entry.runnable and not entry.isdevice
|
||||
|
||||
|
||||
# --- FBNeo: one namespace per DAT ---------------------------------------------
|
||||
|
||||
# Generated at build time from every driver and committed: the set name and the
|
||||
# source file of each driver.
|
||||
FBNEO_DRIVERLIST = "src/dep/generated/driverlist.h"
|
||||
_FBNEO_DRIVER = re.compile(r'\{\s*"([^"]+)",\s*"([^"]+\.cpp)"\s*\}')
|
||||
|
||||
|
||||
def fbneo_drivers(listing: str) -> dict[str, set[str]]:
|
||||
"""Driver names per source file, from driverlist.h."""
|
||||
names: dict[str, set[str]] = {}
|
||||
for name, path in _FBNEO_DRIVER.findall(listing):
|
||||
names.setdefault(path, set()).add(name)
|
||||
if not names:
|
||||
raise ValueError(f"{FBNEO_DRIVERLIST} lists no driver")
|
||||
return names
|
||||
|
||||
|
||||
def _fbneo_candidates(entry: SetEntry, names: dict[str, set[str]]) -> list[str]:
|
||||
"""The drivers a DAT set can be. A console DAT writes the archive name,
|
||||
which the driver's GetZipName() takes by cutting the system prefix:
|
||||
``1942`` in the MSX DAT is the driver ``msx_1942``."""
|
||||
drivers = names.get(entry.source or "", set())
|
||||
if entry.name in drivers:
|
||||
return [entry.name]
|
||||
return sorted(n for n in drivers if "_" in n and zip_name(n) == entry.name)
|
||||
|
||||
|
||||
def _fbneo_driver_names(entries: list[SetEntry], names: dict[str, set[str]]) -> dict[str, str]:
|
||||
"""Driver name per set of one DAT. Where a source file holds two systems
|
||||
(d_nes.cpp builds the NES and the FDS drivers), the prefix the rest of
|
||||
the DAT carries decides."""
|
||||
candidates = {e.name: _fbneo_candidates(e, names) for e in entries}
|
||||
prefixes = Counter(
|
||||
found[0].split("_", 1)[0]
|
||||
for name, found in candidates.items()
|
||||
if len(found) == 1 and found[0] != name
|
||||
)
|
||||
driver: dict[str, str] = {}
|
||||
for entry in entries:
|
||||
found = candidates[entry.name]
|
||||
if len(found) > 1 and prefixes:
|
||||
dominant = prefixes.most_common(1)[0][0]
|
||||
found = [n for n in found if n.split("_", 1)[0] == dominant]
|
||||
if len(found) != 1:
|
||||
raise ValueError(f"{entry.source}: {entry.name} matches drivers {found}")
|
||||
driver[entry.name] = found[0]
|
||||
return driver
|
||||
|
||||
|
||||
def fbneo_sets(
|
||||
openers: list[Opener], 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.
|
||||
|
||||
Each DAT is its own namespace: the Arcade, MSX, NES and ZX Spectrum DATs
|
||||
all carry a ``1942``, and a ``romof`` inside a DAT names a set of that DAT.
|
||||
Merged by archive name, the MSX ``1942`` that needs msx.zip was the
|
||||
arcade one, which needs nothing. The Arcade and Neo Geo DATs both carry
|
||||
the Neo Geo drivers: a driver read twice keeps its first reading.
|
||||
"""
|
||||
sets: dict[str, SetEntry] = {}
|
||||
archives: dict[str, str] = {}
|
||||
for opener in openers:
|
||||
with opener() as stream:
|
||||
entries = [e for e in iter_sets(stream) if e.name]
|
||||
driver = _fbneo_driver_names(entries, names)
|
||||
for entry in entries:
|
||||
name = driver[entry.name]
|
||||
if name in sets:
|
||||
continue
|
||||
if name != entry.name:
|
||||
archives[name] = entry.name
|
||||
if entry.romof:
|
||||
entry.romof = driver.get(entry.romof, entry.romof)
|
||||
entry.name = name
|
||||
sets[name] = entry
|
||||
return sets, archives
|
||||
|
||||
|
||||
# --- C table reader (flycast naomi_roms.cpp) ---------------------------------
|
||||
|
||||
_TOKEN = re.compile(r'"(?:\\.|[^"\\])*"|[{},]|[^\s{},"]+')
|
||||
|
||||
|
||||
def _initializer(text: str, array: str) -> list:
|
||||
"""The brace initializer of ``const <type> <array>[] = {...}`` as nested
|
||||
lists of tokens, each element split on its top-level commas."""
|
||||
match = re.search(rf"\b{re.escape(array)}\s*\[\s*\]\s*=\s*\{{", text)
|
||||
if not match:
|
||||
raise ValueError(f"no initializer for {array}[]")
|
||||
tokens = _TOKEN.findall(text[match.end() - 1 :])
|
||||
stack: list[list] = []
|
||||
item: list = []
|
||||
for token in tokens:
|
||||
if token == "{":
|
||||
stack.append(item)
|
||||
item = []
|
||||
stack.append([])
|
||||
elif token == "}":
|
||||
elements = stack.pop()
|
||||
if item:
|
||||
elements.append(item if len(item) > 1 else item[0])
|
||||
item = stack.pop()
|
||||
item.append(elements)
|
||||
if not stack:
|
||||
return item[0]
|
||||
elif token == ",":
|
||||
elements = stack[-1]
|
||||
if item:
|
||||
elements.append(item if len(item) > 1 else item[0])
|
||||
item = []
|
||||
else:
|
||||
item.append(token)
|
||||
raise ValueError(f"unterminated initializer for {array}[]")
|
||||
|
||||
|
||||
def _string(token: object) -> str | None:
|
||||
if isinstance(token, str) and token.startswith('"'):
|
||||
return token[1:-1]
|
||||
return None
|
||||
|
||||
|
||||
def flycast_index(source: str) -> dict:
|
||||
"""BIOS archive per NAOMI/Atomiswave game from naomi_roms.cpp."""
|
||||
text = blank_comments(source)
|
||||
archive_of: dict[str, str] = {}
|
||||
for element in _initializer(text, "BIOS"):
|
||||
if not isinstance(element, list) or not element:
|
||||
continue
|
||||
name = _string(element[0])
|
||||
if name is None:
|
||||
continue
|
||||
# BIOS_t: name, blobs[], filename (naomi_roms.h:53-66).
|
||||
filename = _string(element[2]) if len(element) > 2 else None
|
||||
archive_of[name] = filename or name
|
||||
bios: dict[str, set[str]] = {}
|
||||
chd: list[str] = []
|
||||
unknown: dict[str, str] = {}
|
||||
games: set[str] = set()
|
||||
for element in _initializer(text, "Games"):
|
||||
if not isinstance(element, list) or not element:
|
||||
continue
|
||||
name = _string(element[0])
|
||||
if name is None:
|
||||
continue
|
||||
# shors2k2 is declared twice at e88b0ced: a name counts once.
|
||||
games.add(name)
|
||||
# Game: name, parent_name, description, size, key, bios, cart_type,
|
||||
# rotation, blobs[], gdrom_name, ... (naomi_roms.h:71-94).
|
||||
named = _string(element[5]) if len(element) > 5 else None
|
||||
if named is not None and named not in archive_of:
|
||||
unknown[name] = named
|
||||
continue
|
||||
bios.setdefault(archive_of[named or "naomi"], set()).add(name)
|
||||
if len(element) > 9 and _string(element[9]):
|
||||
chd.append(name)
|
||||
return {
|
||||
"bios": {k: sorted(v) for k, v in sorted(bios.items())},
|
||||
"devices": {},
|
||||
"chd": sorted(chd),
|
||||
"missing_parents": dict(sorted(unknown.items())),
|
||||
"no_bios": [],
|
||||
"bios_sets": sorted(set(archive_of.values())),
|
||||
"counts": {
|
||||
"sets": len(games) + len(archive_of),
|
||||
"games": len(games),
|
||||
"games_with_bios": len({g for v in bios.values() for g in v}),
|
||||
"bios_sets": len(archive_of),
|
||||
"bios_roots_used": len(bios),
|
||||
"games_with_devices": 0,
|
||||
"chd_games": len(chd),
|
||||
"missing_parents": len(unknown),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"""C and C++ source read the way the compiler reads it: comments apart from
|
||||
code, string and character literals kept whole, macro calls split into their
|
||||
arguments (MAME, FBNeo and flycast drivers)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_COMMENT_OR_LITERAL = re.compile(
|
||||
r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S
|
||||
)
|
||||
|
||||
|
||||
class DriverSourceError(ValueError):
|
||||
"""The driver source does not have the shape the reader knows."""
|
||||
|
||||
|
||||
def blank_comments(text: str, keep_lines: bool = True) -> str:
|
||||
"""Text with every comment blanked, literals untouched.
|
||||
|
||||
By default a comment becomes as many spaces as it has characters, its
|
||||
newlines kept: offsets and line numbers survive, so a block found in the
|
||||
result is cited at its line in the file, and a ROM_START written inside
|
||||
a comment is not a block. With `keep_lines` false a comment becomes one
|
||||
space, as translation phase 3 does: a directive a comment spans several
|
||||
lines of stays one line.
|
||||
"""
|
||||
|
||||
def blank(match: re.Match[str]) -> str:
|
||||
found = match.group(0)
|
||||
if found[0] in "\"'":
|
||||
return found
|
||||
return re.sub(r"[^\n]", " ", found) if keep_lines else " "
|
||||
|
||||
return _COMMENT_OR_LITERAL.sub(blank, text)
|
||||
|
||||
|
||||
def call_span(text: str, start: int) -> tuple[list[str], int]:
|
||||
"""The top-level arguments of the call whose opening parenthesis ends at
|
||||
*start*, literals kept whole, and the offset just past its parenthesis."""
|
||||
args: list[str] = []
|
||||
current: list[str] = []
|
||||
depth, i, n = 1, start, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c in "\"'":
|
||||
j = i + 1
|
||||
while j < n and text[j] != c:
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
current.append(text[i : j + 1])
|
||||
i = j + 1
|
||||
continue
|
||||
if c == "(":
|
||||
depth += 1
|
||||
elif c == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
args.append("".join(current).strip())
|
||||
return args, i + 1
|
||||
elif c == "," and depth == 1:
|
||||
args.append("".join(current).strip())
|
||||
current = []
|
||||
i += 1
|
||||
continue
|
||||
current.append(c)
|
||||
i += 1
|
||||
raise DriverSourceError("unterminated macro call")
|
||||
|
||||
|
||||
def call_args(text: str, start: int) -> list[str]:
|
||||
"""The top-level arguments of the call whose opening parenthesis ends at
|
||||
*start*, literals kept whole."""
|
||||
return call_span(text, start)[0]
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Upstream MAME and FBNeo DATs, downloaded once into a cache read offline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.hashing import git_blob_sha
|
||||
from ..base_scraper import (
|
||||
BlobMismatchError,
|
||||
download,
|
||||
fetch_branch_head,
|
||||
fetch_verified_blob,
|
||||
github_json,
|
||||
)
|
||||
|
||||
MAME_LISTXML_URL = (
|
||||
"https://github.com/mamedev/mame/releases/download/{tag}/{tag}lx.zip"
|
||||
)
|
||||
FBNEO_REPO = "libretro/FBNeo"
|
||||
FBNEO_API = f"https://api.github.com/repos/{FBNEO_REPO}"
|
||||
|
||||
|
||||
def api_json(url: str) -> object:
|
||||
"""An api.github.com answer, ConnectionError when it cannot be read."""
|
||||
return github_json(url, f"cannot read {url}", timeout=60, error=ConnectionError)
|
||||
|
||||
|
||||
def is_tracked_dat(item: object) -> bool:
|
||||
"""Whether an entry of the FBNeo ``dats`` listing is a DAT the import reads."""
|
||||
return (
|
||||
isinstance(item, dict)
|
||||
and item.get("type") == "file"
|
||||
and str(item.get("name", "")).lower().endswith(".dat")
|
||||
)
|
||||
|
||||
|
||||
def mame_label(pack_stem: str) -> str:
|
||||
"""The snapshot label of a MAME listxml pack (``mame0289lx`` gives ``MAME mame0289``)."""
|
||||
return f"MAME {pack_stem.replace('lx', '')}"
|
||||
|
||||
|
||||
def label_version(label: str) -> str | None:
|
||||
"""The MAME tag a snapshot label names, None for a label without one."""
|
||||
match = re.search(r"\b(mame\d{4})\b", label)
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
class NotCached(FileNotFoundError):
|
||||
"""The cache holds no pack for the revision asked."""
|
||||
|
||||
|
||||
def _listxml_path(tag: str, cache_dir: Path) -> Path:
|
||||
return cache_dir / f"{tag}lx.zip"
|
||||
|
||||
|
||||
def _fbneo_folder(commit: str, cache_dir: Path) -> Path:
|
||||
# One folder per commit: a folder refilled for whatever revision was
|
||||
# last asked gave an offline read the DATs of another pin.
|
||||
return cache_dir / "fbneo-dats" / commit
|
||||
|
||||
|
||||
def fetch_pack(
|
||||
source: str, tag: str, cache_dir: Path
|
||||
) -> tuple[Path, dict[str, str]]:
|
||||
"""Download the upstream DAT for *source*.
|
||||
|
||||
MAME ships its ``-listxml`` output as a release asset, and FBNeo keeps its
|
||||
DATs in the repository, so neither needs a browser. The second value
|
||||
names the upstream state fetched: empty for a release asset, whose tag
|
||||
already says which version it is, and the git blob sha of every DAT for
|
||||
FBNeo, whose files change under a constant header version.
|
||||
"""
|
||||
if source == "mame":
|
||||
listxml = _listxml_path(tag, cache_dir)
|
||||
download(MAME_LISTXML_URL.format(tag=tag), listxml, skip_existing=True)
|
||||
return listxml, {}
|
||||
|
||||
# The revision is resolved to a commit first and everything is read at
|
||||
# that commit: a branch URL is served through a CDN cache, so the bytes
|
||||
# could predate the listing that named their blob.
|
||||
sha = fetch_branch_head(FBNEO_REPO, None if tag == "latest" else 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 = _fbneo_folder(sha, cache_dir)
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
blobs: dict[str, str] = {}
|
||||
for item in listing:
|
||||
if not is_tracked_dat(item):
|
||||
continue
|
||||
fetch_verified_blob(
|
||||
item["download_url"], target / item["name"], item["sha"],
|
||||
f" of libretro/FBNeo {sha}",
|
||||
)
|
||||
blobs[item["name"]] = item["sha"]
|
||||
# A DAT the revision does not carry is not read from an older fetch.
|
||||
for stale in target.glob("*"):
|
||||
if stale.is_file() and stale.name not in blobs:
|
||||
stale.unlink()
|
||||
return target, blobs
|
||||
|
||||
|
||||
def cached_pack(
|
||||
source: str, revision: str, cache_dir: Path
|
||||
) -> tuple[Path, dict[str, str]]:
|
||||
"""What fetch_pack wrote for *revision* (a MAME tag, a full FBNeo commit),
|
||||
read offline. The FBNeo blobs are recomputed from the bytes."""
|
||||
if source == "mame":
|
||||
listxml = _listxml_path(revision, cache_dir)
|
||||
if not listxml.is_file():
|
||||
raise NotCached(f"{listxml} is not cached")
|
||||
return listxml, {}
|
||||
folder = _fbneo_folder(revision, cache_dir)
|
||||
blobs = {
|
||||
p.name: git_blob_sha(p.read_bytes())
|
||||
for p in (sorted(folder.iterdir()) if folder.is_dir() else ())
|
||||
if is_tracked_dat({"type": "file" if p.is_file() else "dir", "name": p.name})
|
||||
}
|
||||
if not blobs:
|
||||
raise NotCached(f"{folder} is not cached")
|
||||
return folder, blobs
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Scrape FBNeo BIOS set hashes from upstream source via sparse clone.
|
||||
|
||||
Does NOT inherit BaseScraper (uses git sparse clone, not URL fetch).
|
||||
Parses BDF_BOARDROM drivers from src/burn/drv/ to extract CRC32/size
|
||||
for all BIOS ROM sets, then optionally merges into emulator profiles.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from core import paths
|
||||
from core.paths import REPO_ROOT
|
||||
from model.profiles import source_yaml_paths
|
||||
from core.artifacts import write_text_atomic
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
from ._hash_merge import compute_diff, load_profile, merge_fbneo_profile
|
||||
from ._hash_write import write_fbneo_profile
|
||||
from .fbneo_parser import parse_fbneo_source_tree
|
||||
from .sparse_clone import fresh_cache, remove_clone, sparse_clone
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
REPO_URL = "https://github.com/finalburnneo/FBNeo.git"
|
||||
# One clone per process, for the reason mame_hash_scraper gives.
|
||||
CLONE_DIR = REPO_ROOT / "tmp" / f"fbneo-{os.getpid()}"
|
||||
CACHE_PATH = REPO_ROOT / "data" / "fbneo-hashes.json"
|
||||
EMULATORS_DIR = REPO_ROOT / paths.EMULATORS_DIR
|
||||
STALE_HOURS = 24
|
||||
|
||||
|
||||
# src/burn/version.h, as the libretro core prints it: "v%x.%x.%x.%02x" of
|
||||
# the BCD BURN_VERSION, so VER_ALPHA 3 reads 1.0.0.03. FBNeo bumps this file
|
||||
# without tagging: the last tag (v1.0.0.02) was 9 337 commits behind it.
|
||||
_VERSION_H = re.compile(
|
||||
r"#define\s+VER_MAJOR\s+(\d+)\s+#define\s+VER_MINOR\s+(\d+)\s+"
|
||||
r"#define\s+VER_BETA\s+(\d+)\s+#define\s+VER_ALPHA\s+(\d+)"
|
||||
)
|
||||
|
||||
|
||||
def version_from_header(text: str) -> str:
|
||||
"""The version src/burn/version.h states."""
|
||||
found = _VERSION_H.search(text)
|
||||
if not found:
|
||||
raise RuntimeError("src/burn/version.h states no VER_MAJOR..VER_ALPHA")
|
||||
major, minor, beta, alpha = (int(group) for group in found.groups())
|
||||
return f"v{major}.{minor}.{beta}.{alpha:02d}"
|
||||
|
||||
|
||||
def _extract_version() -> str:
|
||||
"""The version the cloned source states."""
|
||||
header = CLONE_DIR / "src" / "burn" / "version.h"
|
||||
return version_from_header(header.read_text(encoding="utf-8", errors="replace"))
|
||||
|
||||
|
||||
def fetch_and_cache(force: bool = False) -> dict[str, Any]:
|
||||
"""Clone, parse, and write JSON cache. Returns the cache dict."""
|
||||
fresh = None if force else fresh_cache(CACHE_PATH, STALE_HOURS)
|
||||
if fresh is not None:
|
||||
log.info("cache fresh, skipping clone (use --force to override)")
|
||||
return fresh
|
||||
|
||||
try:
|
||||
# src/burn/drv, and in cone mode src/burn/version.h.
|
||||
commit = sparse_clone(REPO_URL, CLONE_DIR, ["src/burn/drv"])
|
||||
|
||||
log.info("extracting version")
|
||||
version = _extract_version()
|
||||
|
||||
log.info("parsing source tree")
|
||||
bios_sets = parse_fbneo_source_tree(str(CLONE_DIR))
|
||||
if not bios_sets:
|
||||
# An empty read was cached for a day and merged nothing, and
|
||||
# the pipeline step reported OK.
|
||||
raise RuntimeError(f"no BIOS set read at FBNeo {version} ({commit[:12]})")
|
||||
|
||||
cache: dict[str, Any] = {
|
||||
"source": "finalburnneo/FBNeo",
|
||||
"version": version,
|
||||
"commit": commit,
|
||||
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
||||
"bios_sets": bios_sets,
|
||||
}
|
||||
|
||||
CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_text_atomic(
|
||||
str(CACHE_PATH), json.dumps(cache, indent=2, ensure_ascii=False) + "\n"
|
||||
)
|
||||
log.info("wrote %d BIOS sets to %s", len(bios_sets), CACHE_PATH)
|
||||
|
||||
return cache
|
||||
finally:
|
||||
remove_clone(CLONE_DIR)
|
||||
|
||||
|
||||
def _find_fbneo_profiles() -> list[Path]:
|
||||
"""Find emulator profiles whose upstream references finalburnneo/FBNeo."""
|
||||
profiles: list[Path] = []
|
||||
for path in source_yaml_paths(EMULATORS_DIR):
|
||||
try:
|
||||
data = yaml_load(path.read_text(encoding="utf-8"))
|
||||
except (yaml.YAMLError, OSError) as exc:
|
||||
# Skipped, a broken fbneo.yml left the list and the refresh
|
||||
# reported "no matching emulator profiles found" with exit 0.
|
||||
raise RuntimeError(f"cannot read {path}: {exc}") from exc
|
||||
if not data or not isinstance(data, dict):
|
||||
continue
|
||||
upstream = data.get("upstream", "")
|
||||
if isinstance(upstream, str) and "finalburnneo/fbneo" in upstream.lower():
|
||||
profiles.append(path)
|
||||
return profiles
|
||||
|
||||
|
||||
def _format_diff(
|
||||
profile_name: str, diff: dict[str, Any], show_added: bool = True
|
||||
) -> str:
|
||||
"""Format diff for a single profile."""
|
||||
lines: list[str] = []
|
||||
lines.append(f" {profile_name}:")
|
||||
|
||||
added = diff.get("added", [])
|
||||
updated = diff.get("updated", [])
|
||||
oos = diff.get("out_of_scope", 0)
|
||||
|
||||
if not added and not updated:
|
||||
lines.append(" no changes")
|
||||
if oos:
|
||||
lines.append(f" . {oos} out of scope")
|
||||
return "\n".join(lines)
|
||||
|
||||
if show_added:
|
||||
lines.extend(f" + {label}" for label in added)
|
||||
elif added:
|
||||
lines.append(f" + {len(added)} new ROMs available (main profile only)")
|
||||
lines.extend(f" ~ {label}" for label in updated)
|
||||
lines.append(f" = {diff['unchanged']} unchanged")
|
||||
if oos:
|
||||
lines.append(f" . {oos} out of scope")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def run(
|
||||
dry_run: bool = False,
|
||||
force: bool = False,
|
||||
json_output: bool = False,
|
||||
) -> int:
|
||||
"""Main entry point for the scraper."""
|
||||
cache = fetch_and_cache(force=force)
|
||||
|
||||
version = cache.get("version", "unknown")
|
||||
commit = cache.get("commit", "?")[:12]
|
||||
bios_sets = cache.get("bios_sets", {})
|
||||
profiles = _find_fbneo_profiles()
|
||||
|
||||
if json_output:
|
||||
result: dict[str, Any] = {
|
||||
"source": cache.get("source"),
|
||||
"version": version,
|
||||
"commit": cache.get("commit"),
|
||||
"bios_set_count": len(bios_sets),
|
||||
"profiles": {},
|
||||
}
|
||||
for path in profiles:
|
||||
diff = compute_diff(load_profile(path), cache, mode="fbneo")
|
||||
result["profiles"][path.stem] = diff
|
||||
print(json.dumps(result, indent=2))
|
||||
return 0
|
||||
|
||||
header = (
|
||||
f"fbneo-hashes: {len(bios_sets)} BIOS sets "
|
||||
f"from finalburnneo/FBNeo @ {version} ({commit})"
|
||||
)
|
||||
print(header)
|
||||
print()
|
||||
|
||||
if not profiles:
|
||||
print(" no matching emulator profiles found")
|
||||
return 0
|
||||
|
||||
for path in profiles:
|
||||
is_main = path.name == "fbneo.yml"
|
||||
profile = load_profile(path)
|
||||
diff = compute_diff(profile, cache, mode="fbneo")
|
||||
print(_format_diff(path.stem, diff, show_added=is_main))
|
||||
|
||||
# New entries are never written: the parser knows one line per
|
||||
# driver, the struct, while a curated entry cites the RomDesc line of
|
||||
# its own ROM. Existing entries, console archives included (the
|
||||
# parser keys each board ROM set by the archive GetZipName opens),
|
||||
# are refreshed in place.
|
||||
if not dry_run and diff["updated"]:
|
||||
write_fbneo_profile(path, merge_fbneo_profile(profile, cache, add_new=False))
|
||||
log.info("merged changes into %s", path.name)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
allow_abbrev=False,
|
||||
description="Scrape FBNeo BIOS set hashes from upstream source",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="show diff without writing changes",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="force re-clone even if cache is fresh",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
dest="json_output",
|
||||
help="output diff as JSON",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(name)s: %(message)s",
|
||||
)
|
||||
|
||||
sys.exit(
|
||||
run(
|
||||
dry_run=args.dry_run,
|
||||
force=args.force,
|
||||
json_output=args.json_output,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Parser for FBNeo source files to extract BIOS sets and ROM definitions.
|
||||
|
||||
Parses BurnRomInfo structs (static ROM arrays) and BurnDriver structs
|
||||
(driver registration) from FBNeo C source files. BIOS sets are identified
|
||||
by the BDF_BOARDROM flag in BurnDriver definitions, and keyed by the
|
||||
archive the driver opens.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.lines import LineIndex
|
||||
|
||||
# Sizes are written in hex or decimal (d_snes.cpp: ``{ "dsp1.bin", 10240, ...``).
|
||||
_ROM_ENTRY_RE = re.compile(
|
||||
r'\{\s*"([^"]+)"\s*,\s*(0x[\da-fA-F]+|\d+)\s*,\s*(0x[\da-fA-F]+)\s*,\s*([^}]+)\}',
|
||||
)
|
||||
|
||||
_BURN_DRIVER_RE = re.compile(
|
||||
r"struct\s+BurnDriver\s+BurnDrv(\w+)\s*=\s*\{(.*?)\};",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
# The first three fields of a BurnDriver: name, parent, board ROM.
|
||||
_DRIVER_HEAD_RE = re.compile(r'\s*("[^"]*"|NULL)\s*,\s*("[^"]*"|NULL)\s*,\s*("[^"]*"|NULL)')
|
||||
|
||||
# The GetZipName field of a BurnDriver and its RomInfo, which names the
|
||||
# RomDesc array (BurnDrvngpc_ngp is "ngp_ngp" and reads ngpc_ngpRomDesc).
|
||||
_ZIP_AND_ROMS_RE = re.compile(r"(\w+)\s*,\s*(\w+)RomInfo\s*,")
|
||||
|
||||
|
||||
def zip_name(driver: str) -> str:
|
||||
"""The archive a driver opens through a system GetZipName.
|
||||
|
||||
Every non-arcade GetZipName cuts the system prefix up to its underscore
|
||||
(MSXGetZipName in d_msx.cpp: ``msx_msx`` opens msx.zip, ``msx_1942``
|
||||
opens 1942.zip). The arcade drivers have none and open their own name.
|
||||
"""
|
||||
return driver.split("_", 1)[1] if "_" in driver else driver
|
||||
|
||||
|
||||
def _quoted(field: str) -> str:
|
||||
return field.strip('"') if field != "NULL" else ""
|
||||
|
||||
|
||||
def find_bios_sets(source: str, filename: str) -> dict[str, dict]:
|
||||
"""Find BDF_BOARDROM drivers in source code.
|
||||
|
||||
A board ROM set is keyed by the archive the games open it under: their
|
||||
GetZipName reads the board ROM name too (``i == 1``), so ``ngp_ngp``,
|
||||
whose own field is NULL, is looked up as ngp.zip by every NGP game.
|
||||
|
||||
Returns a dict mapping that archive to metadata:
|
||||
{archive: {"source_file": str, "source_line": int, "rom_desc": str}}
|
||||
"""
|
||||
lines = LineIndex(source)
|
||||
boards: list[tuple[str, int, bool, str]] = []
|
||||
zipped_boards: set[str] = set()
|
||||
|
||||
for match in _BURN_DRIVER_RE.finditer(source):
|
||||
body = match.group(2)
|
||||
head = _DRIVER_HEAD_RE.match(body)
|
||||
fields = _ZIP_AND_ROMS_RE.search(body)
|
||||
own_zip = fields is not None and fields.group(1) != "NULL"
|
||||
if head and own_zip and _quoted(head.group(3)):
|
||||
zipped_boards.add(_quoted(head.group(3)))
|
||||
if "BDF_BOARDROM" not in body:
|
||||
continue
|
||||
# Set name is the first quoted string in the struct body
|
||||
name_match = re.search(r'"([^"]+)"', body)
|
||||
if not name_match:
|
||||
continue
|
||||
driver = name_match.group(1)
|
||||
rom_desc = fields.group(2) if fields else driver
|
||||
boards.append((driver, lines.line(match.start()), own_zip, rom_desc))
|
||||
|
||||
return {
|
||||
(zip_name(driver) if own_zip or driver in zipped_boards else driver): {
|
||||
"source_file": filename,
|
||||
"source_line": line,
|
||||
"rom_desc": rom_desc,
|
||||
}
|
||||
for driver, line, own_zip, rom_desc in boards
|
||||
}
|
||||
|
||||
|
||||
def parse_rom_info(source: str, set_name: str) -> list[dict]:
|
||||
"""Parse a BurnRomInfo array for the given set name.
|
||||
|
||||
Returns a list of dicts with keys: name, size, crc32.
|
||||
Sentinel entries (empty name) are skipped.
|
||||
"""
|
||||
pattern = re.compile(
|
||||
r"static\s+struct\s+BurnRomInfo\s+"
|
||||
+ re.escape(set_name)
|
||||
+ r"RomDesc\s*\[\s*\]\s*=\s*\{(.*?)\};",
|
||||
re.DOTALL,
|
||||
)
|
||||
match = pattern.search(source)
|
||||
if not match:
|
||||
return []
|
||||
|
||||
body = match.group(1)
|
||||
roms: list[dict] = []
|
||||
|
||||
for entry in _ROM_ENTRY_RE.finditer(body):
|
||||
name = entry.group(1)
|
||||
if not name:
|
||||
continue
|
||||
size = int(entry.group(2), 0)
|
||||
crc32 = format(int(entry.group(3), 16), "08x")
|
||||
|
||||
roms.append(
|
||||
{
|
||||
"name": name,
|
||||
"size": size,
|
||||
"crc32": crc32,
|
||||
}
|
||||
)
|
||||
|
||||
return roms
|
||||
|
||||
|
||||
def parse_fbneo_source_tree(base_path: str) -> dict[str, dict]:
|
||||
"""Walk the FBNeo driver source tree and extract all BIOS sets.
|
||||
|
||||
Scans .cpp files under src/burn/drv/ for BDF_BOARDROM drivers,
|
||||
then parses their associated BurnRomInfo arrays.
|
||||
|
||||
Returns a dict mapping the archive each driver opens to:
|
||||
{source_file, source_line, roms: [{name, size, crc32}, ...]}
|
||||
"""
|
||||
drv_path = Path(base_path) / "src" / "burn" / "drv"
|
||||
if not drv_path.is_dir():
|
||||
return {}
|
||||
|
||||
results: dict[str, dict] = {}
|
||||
|
||||
for root, _dirs, files in os.walk(drv_path):
|
||||
for fname in files:
|
||||
if not fname.endswith(".cpp"):
|
||||
continue
|
||||
|
||||
filepath = Path(root) / fname
|
||||
source = filepath.read_text(encoding="utf-8", errors="replace")
|
||||
rel_path = str(filepath.relative_to(base_path))
|
||||
|
||||
bios_sets = find_bios_sets(source, rel_path)
|
||||
for archive, meta in bios_sets.items():
|
||||
roms = parse_rom_info(source, meta["rom_desc"])
|
||||
results[archive] = {
|
||||
"source_file": meta["source_file"],
|
||||
"source_line": meta["source_line"],
|
||||
"roms": roms,
|
||||
}
|
||||
|
||||
return results
|
||||
@@ -0,0 +1,526 @@
|
||||
"""Device ROM sets of one MAME release, read from its -listxml.
|
||||
|
||||
A machine that instantiates a device loads the device's ROMs from
|
||||
<device shortname>.zip (src/emu/device.cpp:140-152, searchpath), and a missing
|
||||
ROM that is neither optional nor undumped stops that machine
|
||||
(src/emu/romload.cpp:529-570, 667-671). The listxml names every such set with
|
||||
isdevice="yes", its ROMs and the source file defining the device. The lines
|
||||
cited for a set are the ROM_START block of that file declaring those ROMs, read
|
||||
at the release tag. A set whose block cannot be told apart is left without
|
||||
lines and reported.
|
||||
|
||||
The same document says which machines load each set, so a set is filed under
|
||||
the systems of those machines (attribute_systems). It also names the software
|
||||
lists each machine declares and the floppy drives it can instantiate, which
|
||||
files hash/<list>.xml (attribute_softlists) and the floppy sound samples
|
||||
(floppy_sample_systems) the same way.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from collections.abc import Callable, Collection, Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import IO, NamedTuple
|
||||
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
from ._hash_write import generated_start
|
||||
from .clex import blank_comments
|
||||
from ..dats.listxml import LISTXML_CHUNK, attrs, iter_elements, rom_members
|
||||
from .mame_parser import _collect_rom_macros, _expand_macros, _parse_rom_entries
|
||||
|
||||
_BUILD = re.compile(rb'<mame build="[^"]*\((mame\d+)\)"')
|
||||
_DESCRIPTION = re.compile(rb"<description>(.*?)</description>", re.S)
|
||||
_BIOSSET = re.compile(rb"<biosset\b([^>]*)>")
|
||||
_DEVICE_REF = re.compile(rb'<device_ref\b[^>]*\bname="([^"]+)"')
|
||||
_SLOT_OPTION = re.compile(rb'<slotoption\b[^>]*\bdevname="([^"]+)"')
|
||||
_SOFTWARE_LIST = re.compile(rb'<softwarelist\b[^>]*\bname="([^"]+)"')
|
||||
|
||||
_ROM_START = re.compile(r"ROM_START\s*\(\s*(\w+)\s*\)")
|
||||
_ROM_END = re.compile(r"\bROM_END\b")
|
||||
_CRC = re.compile(r"CRC\s*\(\s*([0-9a-fA-F]+)\s*\)")
|
||||
_ROM_NAME = re.compile(r"\bROM_NAME\s*\(\s*(\w+)\s*\)")
|
||||
_CLASS_END = re.compile(r"^\};", re.M)
|
||||
|
||||
# Why a set carries no line: no block of the file holds its first ROM,
|
||||
# several remain after every narrowing, or the release lacks the file.
|
||||
ABSENT = "absent"
|
||||
AMBIGUOUS = "ambiguous"
|
||||
NO_FILE = "no file"
|
||||
|
||||
|
||||
def _device_roms(body: bytes) -> list[dict]:
|
||||
"""Dumped ROMs of one machine element, first of each name kept."""
|
||||
bios_names = {
|
||||
found.get("name", ""): found.get("description", "")
|
||||
for found in map(attrs, _BIOSSET.findall(body))
|
||||
}
|
||||
roms: list[dict] = []
|
||||
for rom in rom_members(body, dedupe=True, extra=("status", "bios")):
|
||||
if rom.pop("status", "") == "baddump":
|
||||
rom["bad_dump"] = True
|
||||
description = bios_names.get(rom.pop("bios", ""), "")
|
||||
if description:
|
||||
rom["bios_description"] = description
|
||||
roms.append(rom)
|
||||
return roms
|
||||
|
||||
|
||||
class MachineLinks(NamedTuple):
|
||||
"""What one listxml element says about the sets it loads.
|
||||
|
||||
*romof* is the parent the element names. *uses* are the devices it can
|
||||
instantiate: every subdevice of its default configuration, each device a
|
||||
selectable slot option adds, and for a device its parent ROM device,
|
||||
whose set the device's ROMs are also searched in. *softlists* are the
|
||||
software lists the element declares, *sourcefile* the file defining it.
|
||||
"""
|
||||
|
||||
romof: str
|
||||
isdevice: bool
|
||||
uses: tuple[str, ...]
|
||||
softlists: tuple[str, ...] = ()
|
||||
sourcefile: str = ""
|
||||
|
||||
|
||||
class Release(NamedTuple):
|
||||
tag: str
|
||||
devices: dict[str, dict]
|
||||
machines: dict[str, MachineLinks]
|
||||
|
||||
|
||||
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
|
||||
listxml is 311 MB. The links are what infoxml.cpp writes: romof is the
|
||||
driver's parent (src/frontend/mame/infoxml.cpp:761-765) or a device's
|
||||
parent ROM device (856-858), device_ref every subdevice of the default
|
||||
configuration (786, 1010-1015), slotoption each selectable card of a
|
||||
slot (2129-2172), softwarelist each software list device of the
|
||||
configuration (2184-2198). device_t::searchpath puts the parent ROM
|
||||
device after the device itself (src/emu/device.cpp:140-152).
|
||||
"""
|
||||
head = stream.read(LISTXML_CHUNK)
|
||||
build = _BUILD.search(head)
|
||||
tag = build.group(1).decode() if build else ""
|
||||
devices: dict[str, dict] = {}
|
||||
machines: dict[str, MachineLinks] = {}
|
||||
for element in iter_elements(stream, head=head):
|
||||
name, found, body = element.attrs.get("name", ""), element.attrs, element.body
|
||||
isdevice = found.get("isdevice") == "yes"
|
||||
romof = found.get("romof", "")
|
||||
uses = {
|
||||
ref.decode()
|
||||
for ref in (*_DEVICE_REF.findall(body), *_SLOT_OPTION.findall(body))
|
||||
}
|
||||
if isdevice and romof:
|
||||
uses.add(romof)
|
||||
uses.discard(name)
|
||||
softlists = {item.decode() for item in _SOFTWARE_LIST.findall(body)}
|
||||
machines[name] = MachineLinks(
|
||||
romof, isdevice, tuple(sorted(uses)), tuple(sorted(softlists)),
|
||||
found.get("sourcefile", ""),
|
||||
)
|
||||
if isdevice:
|
||||
roms = _device_roms(body)
|
||||
if roms:
|
||||
description = _DESCRIPTION.search(body)
|
||||
devices[name] = {
|
||||
"description": html.unescape(description.group(1).decode())
|
||||
if description else "",
|
||||
"sourcefile": found.get("sourcefile", ""),
|
||||
"roms": roms,
|
||||
}
|
||||
if not tag:
|
||||
raise ValueError("no <mame build=...> header: not a MAME -listxml document")
|
||||
return Release(tag, devices, machines)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def profile_seeds(text: str) -> dict[str, str]:
|
||||
"""Set name to system, for the bios_zip entries before the generated ones.
|
||||
|
||||
These are the entries a reader wrote, the seeds attribute_systems starts
|
||||
from. The generated sections are left out: their systems derive from
|
||||
these, and reading them back would carry a previous release's answer
|
||||
forward.
|
||||
"""
|
||||
start = generated_start(text)
|
||||
written = yaml_load(text if start is None else text[:start]) or {}
|
||||
seeds: dict[str, str] = {}
|
||||
for entry in written.get("files") or []:
|
||||
name = str(entry.get("name") or "")
|
||||
if entry.get("category") == "bios_zip" and name.endswith(".zip") and entry.get("system"):
|
||||
seeds[name[:-4]] = str(entry["system"])
|
||||
return seeds
|
||||
|
||||
|
||||
def _seed_system(
|
||||
name: str, machines: dict[str, MachineLinks], seeds: dict[str, str]
|
||||
) -> str:
|
||||
"""System a profile entry gives this element, through its romof chain.
|
||||
|
||||
A clone names its parent and a parent its BIOS root set, so a Neo Geo
|
||||
game reaches neogeo and takes its system. A device is never walked: its
|
||||
romof is a parent ROM device, not the machine it belongs to. The driver
|
||||
file decides nothing: one file holds machines of several systems
|
||||
(neogeo.cpp declares the MVS and the AES, atari400.cpp the 800 and the
|
||||
5200), and filing a machine under the wrong one would take its devices
|
||||
away from its own system.
|
||||
"""
|
||||
seen: set[str] = set()
|
||||
while name and name not in seen:
|
||||
seen.add(name)
|
||||
if name in seeds:
|
||||
return seeds[name]
|
||||
links = machines.get(name)
|
||||
if links is None or links.isdevice:
|
||||
return ""
|
||||
name = links.romof
|
||||
return ""
|
||||
|
||||
|
||||
def attribute_systems(
|
||||
machines: dict[str, MachineLinks], seeds: dict[str, str]
|
||||
) -> dict[str, list[str]]:
|
||||
"""Systems whose machines can load each set.
|
||||
|
||||
*seeds* maps a set name to the system a profile entry states for it.
|
||||
Each element _seed_system places passes its system to every device it
|
||||
can instantiate, followed through those devices' own links. One walk per
|
||||
system, so the cost is the size of the graph times the number of
|
||||
systems.
|
||||
"""
|
||||
starts: dict[str, list[str]] = {}
|
||||
for name in machines:
|
||||
system = _seed_system(name, machines, seeds)
|
||||
if system:
|
||||
starts.setdefault(system, []).append(name)
|
||||
systems: dict[str, set[str]] = {}
|
||||
for system, nodes in starts.items():
|
||||
seen = set(nodes)
|
||||
stack = list(nodes)
|
||||
while stack:
|
||||
links = machines.get(stack.pop())
|
||||
for used in links.uses if links else ():
|
||||
if used not in seen:
|
||||
seen.add(used)
|
||||
stack.append(used)
|
||||
for name in seen:
|
||||
systems.setdefault(name, set()).add(system)
|
||||
return {name: sorted(found) for name, found in systems.items()}
|
||||
|
||||
|
||||
def device_systems(
|
||||
machines: dict[str, MachineLinks],
|
||||
seeds: dict[str, str],
|
||||
fallback: str,
|
||||
) -> dict[str, list[str]]:
|
||||
"""Systems whose machines can load each set, unplaced machines under *fallback*.
|
||||
|
||||
attribute_systems files a set under the systems of the machines a seed
|
||||
places. A machine no seed places (a computer no platform runs through
|
||||
this profile, a game outside every BIOS family) still loads its devices,
|
||||
and MAME starts it from its set name, the way an arcade folder passes a
|
||||
game: it counts as a machine of *fallback*. A set only such machines
|
||||
load (an Amiga keyboard, an ISA card) then goes under *fallback* alone,
|
||||
and a set both kinds load (ym2413, for the CoCo and for arcade games)
|
||||
under both. A set no runnable machine of the release instantiates keeps
|
||||
no system: the document never names its machine.
|
||||
"""
|
||||
if not fallback:
|
||||
return attribute_systems(machines, seeds)
|
||||
unplaced = {
|
||||
name: fallback
|
||||
for name, links in machines.items()
|
||||
if not links.isdevice and not _seed_system(name, machines, seeds)
|
||||
}
|
||||
return attribute_systems(machines, {**seeds, **unplaced})
|
||||
|
||||
|
||||
def platform_seeds(
|
||||
stated: Iterable[tuple[str, str]],
|
||||
machines: dict[str, MachineLinks],
|
||||
systems: Collection[str],
|
||||
written: dict[str, str],
|
||||
) -> tuple[dict[str, str], dict[str, list[str]]]:
|
||||
"""Seeds a platform file states, and the sets it states two ways.
|
||||
|
||||
*stated* are (archive name, system) pairs a platform declares. A pair
|
||||
seeds a set when the archive is a machine of the release, not a device,
|
||||
the system is one the profile lists, and the profile has not written
|
||||
the set itself. A set stated under two of the profile's systems seeds
|
||||
nothing and is returned with them.
|
||||
"""
|
||||
found: dict[str, set[str]] = {}
|
||||
listed = set(systems)
|
||||
for archive, system in stated:
|
||||
if not archive.endswith(".zip") or system not in listed:
|
||||
continue
|
||||
name = archive[:-4]
|
||||
links = machines.get(name)
|
||||
if name in written or links is None or links.isdevice:
|
||||
continue
|
||||
found.setdefault(name, set()).add(system)
|
||||
seeds = {name: next(iter(s)) for name, s in found.items() if len(s) == 1}
|
||||
conflicts = {name: sorted(s) for name, s in found.items() if len(s) > 1}
|
||||
return seeds, conflicts
|
||||
|
||||
|
||||
def attribute_softlists(
|
||||
machines: dict[str, MachineLinks], placed: dict[str, list[str]]
|
||||
) -> dict[str, list[str]]:
|
||||
"""Systems whose machines declare each software list.
|
||||
|
||||
*placed* is what attribute_systems returns. A list goes to the systems
|
||||
of every element declaring it: a machine writes the lists of its whole
|
||||
configuration and a slot card its own (infoxml.cpp:2184-2198).
|
||||
software_list_device::parse opens <list>.xml from the hash path
|
||||
(src/emu/softlist_dev.cpp:281-313).
|
||||
"""
|
||||
lists: dict[str, set[str]] = {}
|
||||
for name, systems in placed.items():
|
||||
links = machines.get(name)
|
||||
for listed in links.softlists if links else ():
|
||||
lists.setdefault(listed, set()).update(systems)
|
||||
return {name: sorted(found) for name, found in lists.items()}
|
||||
|
||||
|
||||
# floppy_image_device adds its sound device under this shortname
|
||||
# (src/devices/imagedev/floppy.cpp:50, 2076-2082).
|
||||
FLOPPY_SOUND = "flopsnd"
|
||||
|
||||
_FORM_FACTOR = re.compile(r"\bm_form_factor\s*=\s*floppy_image::(FF_\w+)")
|
||||
_SAMPLE_FORM_FACTOR = re.compile(
|
||||
r"\bm_default_samples\.set_form_factor\s*\(\s*floppy_image::(FF_\w+)"
|
||||
r"|\bm_default_samples\.add_\w+_sample\s*\(\s*\"([^\"]+)\""
|
||||
)
|
||||
|
||||
|
||||
def default_floppy_samples(text: str) -> dict[str, str]:
|
||||
"""Each sample of floppy_sound_device's default list, to its form factor.
|
||||
|
||||
The constructor sets a form factor, then adds the samples recorded for
|
||||
it (src/devices/imagedev/floppy.cpp:1656-1686).
|
||||
"""
|
||||
body = re.search(
|
||||
r"floppy_sound_device::floppy_sound_device\s*\([^)]*\)[^{]*\{(.*?)\n\}",
|
||||
blank_comments(text),
|
||||
re.S,
|
||||
)
|
||||
samples: dict[str, str] = {}
|
||||
current = ""
|
||||
for match in _SAMPLE_FORM_FACTOR.finditer(body.group(1) if body else ""):
|
||||
if match.group(1):
|
||||
current = match.group(1)
|
||||
elif current:
|
||||
samples[match.group(2)] = current
|
||||
return samples
|
||||
|
||||
|
||||
def drive_form_factor(text: str, shortname: str) -> str:
|
||||
"""Form factor a floppy drive type sets in setup_characteristics, or ""."""
|
||||
text = blank_comments(text)
|
||||
declaration = re.search(
|
||||
r"DEFINE_DEVICE_TYPE\w*\s*\(\s*\w+\s*,\s*(\w+)\s*,\s*\"" + re.escape(shortname) + '"',
|
||||
text,
|
||||
)
|
||||
if declaration is None:
|
||||
return ""
|
||||
body = re.search(
|
||||
rf"\b{re.escape(declaration.group(1))}::setup_characteristics\s*\(\s*\)\s*\{{(.*?)\n\}}",
|
||||
text,
|
||||
re.S,
|
||||
)
|
||||
found = _FORM_FACTOR.search(body.group(1)) if body else None
|
||||
return found.group(1) if found else ""
|
||||
|
||||
|
||||
def selected_form_factor(form_factor: str, available: Collection[str]) -> str:
|
||||
"""The list floppy_sound_samples::select takes for a drive's form factor.
|
||||
|
||||
3" falls back to 3.5", anything else to 5.25", and a form factor no list
|
||||
answers takes none (src/devices/imagedev/floppy.cpp:1428-1473).
|
||||
"""
|
||||
while form_factor not in available:
|
||||
if form_factor == "FF_3":
|
||||
form_factor = "FF_35"
|
||||
elif form_factor != "FF_525":
|
||||
form_factor = "FF_525"
|
||||
else:
|
||||
return ""
|
||||
return form_factor
|
||||
|
||||
|
||||
def floppy_drives(machines: dict[str, MachineLinks]) -> list[str]:
|
||||
"""Device types that instantiate the floppy sound device."""
|
||||
return sorted(
|
||||
name for name, links in machines.items()
|
||||
if links.isdevice and FLOPPY_SOUND in links.uses
|
||||
)
|
||||
|
||||
|
||||
def floppy_sample_systems(
|
||||
machines: dict[str, MachineLinks],
|
||||
placed: dict[str, list[str]],
|
||||
samples: dict[str, str],
|
||||
form_factors: dict[str, str],
|
||||
) -> dict[str, list[str]]:
|
||||
"""Systems whose machines load each floppy sound sample.
|
||||
|
||||
Every drive starts a floppy sound device, which loads the default list
|
||||
of the form factor its drive selects (floppy.cpp:1709-1738,
|
||||
1759-1767). *samples* maps a sample to its form factor
|
||||
(default_floppy_samples), *form_factors* a drive to its own
|
||||
(drive_form_factor). A drive whose form factor is unknown is taken to
|
||||
load every list.
|
||||
"""
|
||||
available = set(samples.values())
|
||||
found: dict[str, set[str]] = {}
|
||||
for drive in floppy_drives(machines):
|
||||
systems = placed.get(drive)
|
||||
if not systems:
|
||||
continue
|
||||
own = form_factors.get(drive, "")
|
||||
chosen = {selected_form_factor(own, available)} if own else available
|
||||
for sample, form_factor in samples.items():
|
||||
if form_factor in chosen:
|
||||
found.setdefault(sample, set()).update(systems)
|
||||
return {name: sorted(s) for name, s in found.items()}
|
||||
|
||||
|
||||
def source_path(sourcefile: str) -> str:
|
||||
"""Repository path of a listxml sourcefile.
|
||||
|
||||
The listxml writes device files relative to src/ and driver files
|
||||
relative to src/mame/.
|
||||
"""
|
||||
if sourcefile.startswith(("devices/", "emu/", "lib/")):
|
||||
return f"src/{sourcefile}"
|
||||
return f"src/mame/{sourcefile}"
|
||||
|
||||
|
||||
def rom_region_label(text: str, set_name: str) -> str:
|
||||
"""ROM_START label the device class of *set_name* returns, or "".
|
||||
|
||||
DEFINE_DEVICE_TYPE names the class right before the quoted shortname, and
|
||||
the class's device_rom_region returns ROM_NAME(label), written out of line
|
||||
or inside the class body. A class inheriting the method gives nothing.
|
||||
"""
|
||||
declaration = re.search(
|
||||
r"DEFINE_DEVICE_TYPE\w*\s*\((?:[^;]*?,)?\s*(\w+)\s*,\s*\"" + re.escape(set_name) + '"',
|
||||
text,
|
||||
)
|
||||
if declaration is None:
|
||||
return ""
|
||||
cls = re.escape(declaration.group(1))
|
||||
method = re.search(rf"\b{cls}::device_rom_region\b[^{{]*\{{([^}}]*)\}}", text)
|
||||
if method is None:
|
||||
body = re.search(rf"\bclass\s+{cls}\b", text)
|
||||
if body is None:
|
||||
return ""
|
||||
end = _CLASS_END.search(text, body.end())
|
||||
scope = text[body.end() : end.start() if end else len(text)]
|
||||
method = re.search(r"\bdevice_rom_region\b[^{;]*\{([^}]*)\}", scope)
|
||||
if method is None:
|
||||
return ""
|
||||
label = _ROM_NAME.search(method.group(1))
|
||||
return label.group(1) if label else ""
|
||||
|
||||
|
||||
def find_rom_block(
|
||||
lines: list[str], set_name: str, roms: list[tuple[str, str]]
|
||||
) -> tuple[str | None, str]:
|
||||
"""Lines of the ROM_START block declaring these ROMs, or why there are none.
|
||||
|
||||
The span runs from ROM_START to ROM_END: its label is often not the set
|
||||
name, and the ROM_START line alone spells neither the name nor a CRC.
|
||||
|
||||
*roms* are (name, crc32) pairs. A block qualifies when it holds the first
|
||||
ROM's CRC, after comments are blanked and the file's ROM macros expanded.
|
||||
Several qualifying, the narrowest test that leaves one wins: every ROM by
|
||||
name and CRC, then every CRC, then the block named after the set, then the
|
||||
block the device class returns from device_rom_region. Two blocks of one
|
||||
file can load the same dump under different names, as the Amiga keyboards
|
||||
do with their old and new MCU programs.
|
||||
"""
|
||||
text = blank_comments("\n".join(lines))
|
||||
macros = _collect_rom_macros(text)
|
||||
wanted = {(name, int(crc, 16)) for name, crc in roms}
|
||||
crcs = {crc for _name, crc in wanted}
|
||||
first = int(roms[0][1], 16)
|
||||
blocks: list[tuple[str, str, set[tuple[str, int]], set[int]]] = []
|
||||
for start in _ROM_START.finditer(text):
|
||||
end = _ROM_END.search(text, start.end())
|
||||
if end is None:
|
||||
continue
|
||||
body = _expand_macros(text[start.end() : end.start()], macros)
|
||||
held = {int(crc, 16) for crc in _CRC.findall(body)}
|
||||
if first not in held:
|
||||
continue
|
||||
pairs = {
|
||||
(rom["name"], int(rom["crc32"], 16))
|
||||
for rom in _parse_rom_entries(body) if rom["crc32"]
|
||||
}
|
||||
first_line = text.count("\n", 0, start.start()) + 1
|
||||
last_line = text.count("\n", 0, end.start()) + 1
|
||||
blocks.append((f"{first_line}-{last_line}", start.group(1), pairs, held))
|
||||
if not blocks:
|
||||
return None, ABSENT
|
||||
for narrowed in (
|
||||
[b for b in blocks if wanted <= b[2]],
|
||||
[b for b in blocks if crcs <= b[3]],
|
||||
blocks,
|
||||
):
|
||||
if len(narrowed) == 1:
|
||||
return narrowed[0][0], ""
|
||||
named = [b for b in narrowed if b[1] == set_name]
|
||||
if len(named) == 1:
|
||||
return named[0][0], ""
|
||||
if narrowed:
|
||||
label = rom_region_label(text, set_name)
|
||||
returned = [b for b in narrowed if label and b[1] == label]
|
||||
if len(returned) == 1:
|
||||
return returned[0][0], ""
|
||||
break
|
||||
return None, AMBIGUOUS
|
||||
|
||||
|
||||
def locate_sources(
|
||||
devices: dict[str, dict],
|
||||
fetch: Callable[[str], list[str] | None],
|
||||
workers: int = 8,
|
||||
) -> dict[str, str]:
|
||||
"""Write source_file and source_line into each set, return the unplaced.
|
||||
|
||||
*fetch* returns the lines of one repository path at the release, or None
|
||||
when the path does not exist there. The result maps each set left without
|
||||
a line to the reason.
|
||||
"""
|
||||
paths = sorted({source_path(d["sourcefile"]) for d in devices.values()})
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
texts = dict(zip(paths, pool.map(fetch, paths)))
|
||||
unplaced: dict[str, str] = {}
|
||||
for name, device in sorted(devices.items()):
|
||||
path = source_path(device["sourcefile"])
|
||||
device["source_file"] = path
|
||||
lines = texts[path]
|
||||
if lines is None:
|
||||
unplaced[name] = NO_FILE
|
||||
continue
|
||||
line, reason = find_rom_block(
|
||||
lines, name, [(rom["name"], rom["crc32"]) for rom in device["roms"]]
|
||||
)
|
||||
if line is None:
|
||||
unplaced[name] = reason
|
||||
else:
|
||||
device["source_line"] = line
|
||||
return unplaced
|
||||
@@ -0,0 +1,620 @@
|
||||
"""Fetch MAME BIOS hashes from mamedev/mame source and merge into profiles.
|
||||
|
||||
Sparse clones the MAME repo, parses the source tree for BIOS root sets,
|
||||
caches results to data/mame-hashes.json, and optionally merges into
|
||||
emulator profiles that reference mamedev/mame upstream.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from model.registry import list_registered_platforms
|
||||
from model.platforms import load_platform_config
|
||||
from model.profiles import source_yaml_paths
|
||||
from core.artifacts import write_text_atomic
|
||||
from model.safeparse import yaml_load
|
||||
from model.sources import source_yaml_file
|
||||
from core.cli import SourceUnreadable
|
||||
|
||||
from core import upstream
|
||||
from core import upstreamtree
|
||||
|
||||
from ..base_scraper import fetch_github_latest_version
|
||||
from ._hash_merge import (
|
||||
_build_contents,
|
||||
_build_source_ref,
|
||||
compute_diff,
|
||||
load_profile,
|
||||
merge_mame_profile,
|
||||
settled_required,
|
||||
)
|
||||
from ._mame_sections import merge_mame_devices, merge_mame_support
|
||||
from ._hash_write import write_mame_profile
|
||||
from .mame_devices import (
|
||||
attribute_softlists,
|
||||
attribute_systems,
|
||||
default_floppy_samples,
|
||||
device_systems,
|
||||
drive_form_factor,
|
||||
floppy_drives,
|
||||
floppy_sample_systems,
|
||||
locate_sources,
|
||||
platform_seeds,
|
||||
profile_seeds,
|
||||
scan_release,
|
||||
source_path,
|
||||
)
|
||||
from ..dats.listxml import open_listxml
|
||||
from model.mamerelease import mame_tag, mame_version
|
||||
from .dat_fetch import fetch_pack
|
||||
from .sparse_clone import fresh_cache, remove_clone, sparse_clone
|
||||
from .mame_parser import parse_mame_source_tree
|
||||
from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_CACHE_PATH = REPO_ROOT / "data" / "mame-hashes.json"
|
||||
# One clone per process: a fixed tmp/mame was removed and recloned at another
|
||||
# release by a second run while the first was still parsing it.
|
||||
_CLONE_DIR = REPO_ROOT / "tmp" / f"mame-{os.getpid()}"
|
||||
_EMULATORS_DIR = REPO_ROOT / EMULATORS_DIR
|
||||
_PLATFORMS_DIR = REPO_ROOT / PLATFORMS_DIR
|
||||
_FLOPPY_SOURCE = "src/devices/imagedev/floppy.cpp"
|
||||
# Where a device set goes when only machines no seed places load it: MAME
|
||||
# starts such a machine from its set name, as an arcade folder passes one.
|
||||
UNPLACED_SYSTEM = "arcade"
|
||||
MAME_REPO = "mamedev/mame"
|
||||
_REPO_URL = f"https://github.com/{MAME_REPO}.git"
|
||||
_STALE_HOURS = 24
|
||||
|
||||
|
||||
# Cache
|
||||
|
||||
|
||||
def _write_cache(data: dict[str, Any]) -> None:
|
||||
_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_text_atomic(
|
||||
str(_CACHE_PATH), json.dumps(data, indent=2, ensure_ascii=False)
|
||||
)
|
||||
log.info("cache written to %s", _CACHE_PATH)
|
||||
|
||||
|
||||
# Git operations
|
||||
|
||||
|
||||
def _sparse_clone(tag: str) -> str:
|
||||
"""Clone the release the data will be labelled with, not master, and
|
||||
return its commit.
|
||||
|
||||
The version comes from the latest release. Cloning master gave line
|
||||
numbers and hashes of a later revision under that release's label, and
|
||||
the profiles cited lines no declared revision holds.
|
||||
"""
|
||||
return sparse_clone(_REPO_URL, _CLONE_DIR, ["src/mame", "src/devices"], tag)
|
||||
|
||||
|
||||
def _get_version() -> str:
|
||||
"""The latest MAME release version, such as 0.289.
|
||||
|
||||
version.cpp is generated at build time, not in the repo. A failed lookup
|
||||
raises: "unknown" was cached for a day and written as core_version.
|
||||
"""
|
||||
return mame_version(fetch_github_latest_version(MAME_REPO))
|
||||
|
||||
|
||||
# Profile discovery
|
||||
|
||||
|
||||
_MAME_TREES = frozenset({
|
||||
"https://github.com/mamedev/mame",
|
||||
"https://github.com/libretro/mame",
|
||||
})
|
||||
|
||||
|
||||
def _find_mame_profiles() -> list[Path]:
|
||||
profiles: list[Path] = []
|
||||
for path in source_yaml_paths(_EMULATORS_DIR):
|
||||
try:
|
||||
data = source_yaml_file(path)
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
upstream = data.get("upstream", "")
|
||||
source = data.get("source", "")
|
||||
# Only match profiles tracking current MAME (not frozen snapshots
|
||||
# which have upstream like "mamedev/mame/tree/mame0139"), and only
|
||||
# those whose own tree is MAME's. GroovyMAME, A7800 and SAME CDi
|
||||
# declare mamedev/mame upstream but build from their own fork at
|
||||
# another release: refreshing their refs from current MAME moves
|
||||
# them onto paths their tree does not have, such as the 0.289 move
|
||||
# of neogeo.cpp from src/mame/neogeo/ to src/mame/snk/. A profile
|
||||
# that builds mamedev/mame itself at a pinned commit, as pSxMAME
|
||||
# does at 0.133, is a snapshot of that tree just the same.
|
||||
if (
|
||||
isinstance(upstream, str)
|
||||
and upstream.rstrip("/") == "https://github.com/mamedev/mame"
|
||||
and isinstance(source, str)
|
||||
and source.rstrip("/") in _MAME_TREES
|
||||
and not (
|
||||
source.rstrip("/") == "https://github.com/mamedev/mame"
|
||||
and data.get("source_commit")
|
||||
)
|
||||
):
|
||||
profiles.append(path)
|
||||
except (SourceUnreadable, OSError) as exc:
|
||||
# Skipped, a broken mame.yml left the list and the refresh
|
||||
# reported success without touching it.
|
||||
raise RuntimeError(f"cannot read {path}: {exc}") from exc
|
||||
return profiles
|
||||
|
||||
|
||||
# Diff formatting
|
||||
|
||||
|
||||
def _format_diff(
|
||||
profile_path: Path,
|
||||
diff: dict[str, Any],
|
||||
hashes: dict[str, Any],
|
||||
show_added: bool = True,
|
||||
) -> list[str]:
|
||||
lines: list[str] = []
|
||||
name = profile_path.stem
|
||||
|
||||
added = diff.get("added", [])
|
||||
updated = diff.get("updated", [])
|
||||
removed = diff.get("removed", [])
|
||||
unchanged = diff.get("unchanged", 0)
|
||||
|
||||
pin = diff.get("pin", {})
|
||||
|
||||
if not added and not updated and not removed and not pin:
|
||||
lines.append(f" {name}:")
|
||||
lines.append(" no changes")
|
||||
return lines
|
||||
|
||||
lines.append(f" {name}:")
|
||||
lines.extend(f" ^ {field} moves from {old} to {new}" for field, (old, new) in pin.items())
|
||||
|
||||
if show_added:
|
||||
bios_sets = hashes.get("bios_sets", {})
|
||||
for set_name in added:
|
||||
rom_count = len(bios_sets.get(set_name, {}).get("roms", []))
|
||||
source_file = bios_sets.get(set_name, {}).get("source_file", "")
|
||||
source_line = bios_sets.get(set_name, {}).get("source_line", "")
|
||||
ref = f"{source_file}:{source_line}" if source_file else ""
|
||||
lines.append(f" + {set_name}.zip ({ref}, {rom_count} ROMs)")
|
||||
elif added:
|
||||
lines.append(f" + {len(added)} new sets available (main profile only)")
|
||||
|
||||
lines.extend(f" ~ {set_name}.zip (refreshed)" for set_name in updated)
|
||||
|
||||
oos = diff.get("out_of_scope", 0)
|
||||
lines.append(f" = {unchanged} unchanged")
|
||||
if oos:
|
||||
lines.append(f" . {oos} out of scope (not BIOS root sets)")
|
||||
return lines
|
||||
|
||||
|
||||
# Main
|
||||
|
||||
|
||||
def _fetch_hashes(force: bool) -> dict[str, Any]:
|
||||
cache = None if force else fresh_cache(_CACHE_PATH, _STALE_HOURS)
|
||||
if cache is not None:
|
||||
log.info("using cached data from %s", cache.get("fetched_at", ""))
|
||||
return cache
|
||||
|
||||
try:
|
||||
tag = fetch_github_latest_version(MAME_REPO)
|
||||
commit = _sparse_clone(tag)
|
||||
bios_sets = parse_mame_source_tree(str(_CLONE_DIR))
|
||||
version = mame_version(tag)
|
||||
if not bios_sets:
|
||||
# An empty read was cached for a day and every profile entry
|
||||
# came out "out of scope", so nothing was refreshed and the
|
||||
# pipeline step reported OK.
|
||||
raise RuntimeError(f"no BIOS root set read at {tag}")
|
||||
|
||||
data: dict[str, Any] = {
|
||||
"source": "mamedev/mame",
|
||||
"version": version,
|
||||
"commit": commit,
|
||||
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
||||
"bios_sets": bios_sets,
|
||||
}
|
||||
_write_cache(data)
|
||||
return data
|
||||
finally:
|
||||
remove_clone(_CLONE_DIR)
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> None:
|
||||
hashes = _fetch_hashes(args.force)
|
||||
|
||||
total_sets = len(hashes.get("bios_sets", {}))
|
||||
version = hashes.get("version", "unknown")
|
||||
commit = hashes.get("commit", "")[:12]
|
||||
|
||||
if args.json:
|
||||
json.dump(hashes, sys.stdout, indent=2, ensure_ascii=False)
|
||||
sys.stdout.write("\n")
|
||||
return
|
||||
|
||||
print(
|
||||
f"mame-hashes: {total_sets} BIOS root sets from mamedev/mame"
|
||||
f" @ {version} ({commit})"
|
||||
)
|
||||
print()
|
||||
|
||||
profiles = _find_mame_profiles()
|
||||
if not profiles:
|
||||
print(" no profiles with mamedev/mame upstream found")
|
||||
return
|
||||
|
||||
main_profile = _EMULATORS_DIR / "mame.yml"
|
||||
pinned_before = _pinned_version(main_profile)
|
||||
for profile_path in profiles:
|
||||
is_main = profile_path.name == "mame.yml"
|
||||
profile = load_profile(profile_path)
|
||||
diff = compute_diff(profile, hashes, mode="mame")
|
||||
lines = _format_diff(profile_path, diff, hashes, show_added=is_main)
|
||||
for line in lines:
|
||||
print(line)
|
||||
|
||||
if not args.dry_run:
|
||||
updated = diff.get("updated", [])
|
||||
added = diff.get("added", []) if is_main else []
|
||||
if added or updated or diff.get("pin"):
|
||||
write_mame_profile(
|
||||
profile_path, merge_mame_profile(profile, hashes, add_new=is_main),
|
||||
)
|
||||
log.info("merged into %s", profile_path.name)
|
||||
|
||||
print()
|
||||
if args.dry_run:
|
||||
print("(dry run, no files modified)")
|
||||
return
|
||||
pinned_after = _pinned_version(main_profile)
|
||||
if pinned_after != pinned_before:
|
||||
# The device sets describe the release mame.yml is pinned on: left
|
||||
# behind, the profile names two releases at once.
|
||||
print(f"mame.yml moved from {pinned_before} to {pinned_after}: "
|
||||
"merging the device ROM sets of that release")
|
||||
_merge_devices(argparse.Namespace(
|
||||
listxml=fetch_release_listxml(pinned_after), dry_run=False,
|
||||
))
|
||||
|
||||
|
||||
def _pinned_version(profile_path: Path) -> str:
|
||||
profile = yaml_load(profile_path.read_text(encoding="utf-8")) if profile_path.is_file() else {}
|
||||
return str((profile or {}).get("core_version") or "")
|
||||
|
||||
|
||||
def fetch_release_listxml(version: str) -> Path:
|
||||
"""The -listxml MAME publishes for a release, in the shared DAT cache.
|
||||
|
||||
0.289 is the tag mame0289 and the asset mame0289lx.zip.
|
||||
"""
|
||||
return fetch_pack("mame", mame_tag(version), REPO_ROOT / ".cache" / "dats")[0]
|
||||
|
||||
|
||||
def release_profile(
|
||||
release: str,
|
||||
bios_sets: dict[str, Any],
|
||||
upstream_commit: str,
|
||||
source_commit: str,
|
||||
cores: list[str],
|
||||
reference: dict[str, Any],
|
||||
built_by: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""A profile for one MAME release a platform builds, from its own source.
|
||||
|
||||
Recalbox ships libretro/mame twice, built at 0.258 and at 0.278. The
|
||||
BIOS root sets and their ROMs change between releases, so the current
|
||||
MAME profile does not describe them. Each set keeps the system and the
|
||||
required flag the current profile gives it, while the contents and the line
|
||||
are the release's own, and so is a set the release runs without: recel is
|
||||
undumped at 0.258 and dumped later.
|
||||
"""
|
||||
version = mame_version(release)
|
||||
known = {
|
||||
str(f.get("name")): f for f in reference.get("files") or []
|
||||
if f.get("category") == "bios_zip"
|
||||
}
|
||||
files = []
|
||||
for set_name, data in sorted(bios_sets.items()):
|
||||
name = f"{set_name}.zip"
|
||||
entry: dict[str, Any] = {
|
||||
"name": name,
|
||||
# The libretro build searches the content folder, then
|
||||
# <system>/mame/bios and <system>/mame/roms (retro_init.cpp,
|
||||
# Set_Path_Option): the system folder itself is not read.
|
||||
"path": f"mame/bios/{name}",
|
||||
"required": settled_required(known.get(name, {}), data),
|
||||
"category": "bios_zip",
|
||||
}
|
||||
if known.get(name, {}).get("system"):
|
||||
entry["system"] = known[name]["system"]
|
||||
entry["source_ref"] = _build_source_ref(data, "upstream ")
|
||||
entry["contents"] = _build_contents(data.get("roms", []))
|
||||
files.append(entry)
|
||||
return {
|
||||
"emulator": f"MAME {version}",
|
||||
"type": "libretro",
|
||||
"core_classification": "frozen_snapshot",
|
||||
"source": "https://github.com/libretro/mame",
|
||||
"upstream": f"https://github.com/mamedev/mame/tree/{release}",
|
||||
"profiled_date": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
"source_commit": source_commit,
|
||||
"upstream_commit": upstream_commit,
|
||||
"core_version": version,
|
||||
# Where profile_sync reads it again: the makefile of the libretro/mame
|
||||
# tree the platform builds, at source_commit.
|
||||
"version_basis": {
|
||||
"kind": "file",
|
||||
"path": "makefile",
|
||||
"pattern": '#define BARE_BUILD_VERSION "([^"]+)"',
|
||||
},
|
||||
"display_name": f"Arcade (MAME {version})",
|
||||
"cores": cores,
|
||||
"built_by": built_by,
|
||||
# The pin is the commit the platform builds, so the profile is judged
|
||||
# against its own revision: libretro/mame HEAD is a later release.
|
||||
"pin_frozen": (
|
||||
f"{', '.join(built_by)} build{'s' if len(built_by) == 1 else ''} "
|
||||
f"libretro/mame at this revision for the {version} release. "
|
||||
"Later commits are not part of that build."
|
||||
),
|
||||
"systems": list(reference.get("systems") or []),
|
||||
"notes": (
|
||||
f"libretro/mame built at the {version} release. BIOS root sets "
|
||||
f"read from mamedev/mame at {release}: the sets and their ROMs "
|
||||
"are that release's, not the current one's."
|
||||
),
|
||||
"files": files,
|
||||
}
|
||||
|
||||
|
||||
_QUOTE_REF = re.compile(r'^(\s*source_ref: )([^"\'\n].*)$', re.MULTILINE)
|
||||
|
||||
|
||||
def _write_release(args: argparse.Namespace) -> None:
|
||||
"""Write the profile of one MAME release, read from its own tag."""
|
||||
try:
|
||||
commit = _sparse_clone(args.release)
|
||||
bios_sets = parse_mame_source_tree(str(_CLONE_DIR))
|
||||
finally:
|
||||
remove_clone(_CLONE_DIR)
|
||||
if not bios_sets:
|
||||
raise RuntimeError(f"no BIOS root set read at {args.release}")
|
||||
reference = yaml_load((_EMULATORS_DIR / "mame.yml").read_text(encoding="utf-8"))
|
||||
profile = release_profile(
|
||||
args.release, bios_sets, commit, args.source_commit, args.core, reference,
|
||||
args.built_by,
|
||||
)
|
||||
# A reason a reader wrote, citing the platform's own build file, outlives
|
||||
# a regeneration: the derived one says less.
|
||||
if Path(args.profile).is_file():
|
||||
previous = yaml_load(Path(args.profile).read_text(encoding="utf-8")) or {}
|
||||
if str(previous.get("pin_frozen") or "").strip():
|
||||
profile["pin_frozen"] = previous["pin_frozen"]
|
||||
text = yaml.safe_dump(profile, sort_keys=False, allow_unicode=True, width=100)
|
||||
# Citations are written double-quoted in every profile: left bare, each
|
||||
# regeneration rewrote all of them.
|
||||
text = _QUOTE_REF.sub(r'\g<1>"\g<2>"', text)
|
||||
write_text_atomic(str(args.profile), text)
|
||||
print(f"{args.profile}: {len(profile['files'])} BIOS root sets at {args.release}")
|
||||
|
||||
|
||||
def _platform_archives() -> list[tuple[str, str]]:
|
||||
"""(file name, system) for every file a registered platform declares."""
|
||||
stated: list[tuple[str, str]] = []
|
||||
for name in list_registered_platforms(str(_PLATFORMS_DIR)):
|
||||
config = load_platform_config(name, str(_PLATFORMS_DIR))
|
||||
for system, data in (config.get("systems") or {}).items():
|
||||
stated.extend(
|
||||
(str(entry.get("name") or ""), str(system))
|
||||
for entry in (data or {}).get("files") or []
|
||||
)
|
||||
return stated
|
||||
|
||||
|
||||
def _merge_devices(args: argparse.Namespace) -> None:
|
||||
"""Document the device ROM sets of the release mame.yml is pinned on.
|
||||
|
||||
The listxml must be that release's: the lines are read at its tag and
|
||||
have to be the lines of the profile's upstream_commit.
|
||||
"""
|
||||
profile_path = _EMULATORS_DIR / "mame.yml"
|
||||
text = profile_path.read_text(encoding="utf-8")
|
||||
profile = yaml_load(text) or {}
|
||||
with open_listxml(args.listxml) as stream:
|
||||
tag, devices, machines = scan_release(stream)
|
||||
version = mame_version(tag)
|
||||
if str(profile.get("core_version")) != version:
|
||||
raise RuntimeError(
|
||||
f"{args.listxml} is MAME {version}, mame.yml is pinned on "
|
||||
f"{profile.get('core_version')}: refresh the BIOS root sets first"
|
||||
)
|
||||
repo = upstream.parse_repo(_REPO_URL)
|
||||
commit = upstream.tag_commit(repo, tag, upstream.CACHE_DIR)
|
||||
if not commit or commit != profile.get("upstream_commit"):
|
||||
raise RuntimeError(
|
||||
f"{tag} is {commit}, mame.yml upstream_commit is "
|
||||
f"{profile.get('upstream_commit')}"
|
||||
)
|
||||
|
||||
def fetch(path: str) -> list[str] | None:
|
||||
return upstream.fetch_file(repo, commit, path, upstream.CACHE_DIR)
|
||||
|
||||
unplaced = locate_sources(devices, fetch)
|
||||
written = profile_seeds(text)
|
||||
stated, conflicts = platform_seeds(
|
||||
_platform_archives(), machines, profile.get("systems") or [], written
|
||||
)
|
||||
seeds = {**stated, **written}
|
||||
systems = attribute_systems(machines, seeds)
|
||||
listed = profile.get("systems") or []
|
||||
filed = device_systems(
|
||||
machines, seeds, UNPLACED_SYSTEM if UNPLACED_SYSTEM in listed else ""
|
||||
)
|
||||
for set_name, device in devices.items():
|
||||
device["systems"] = filed.get(set_name, [])
|
||||
report = merge_mame_devices(str(profile_path), devices, write=not args.dry_run)
|
||||
|
||||
shipped = upstreamtree.list_directory(repo, commit, "hash", upstream.CACHE_DIR)
|
||||
if shipped is None:
|
||||
raise RuntimeError(f"hash/ of {repo.slug} at {commit} could not be listed")
|
||||
present = {name[:-4] for name in shipped if name.endswith(".xml")}
|
||||
declared = attribute_softlists(machines, systems)
|
||||
lists = {name: found for name, found in declared.items() if name in present}
|
||||
floppy = fetch(_FLOPPY_SOURCE)
|
||||
if floppy is None:
|
||||
raise RuntimeError(f"{_FLOPPY_SOURCE} is absent at {commit}")
|
||||
samples = default_floppy_samples("\n".join(floppy))
|
||||
form_factors: dict[str, str] = {}
|
||||
for drive in floppy_drives(machines):
|
||||
lines = fetch(source_path(machines[drive].sourcefile))
|
||||
form_factors[drive] = drive_form_factor("\n".join(lines or []), drive)
|
||||
sample_systems = floppy_sample_systems(machines, systems, samples, form_factors)
|
||||
support = merge_mame_support(
|
||||
str(profile_path), lists, sample_systems, write=not args.dry_run
|
||||
)
|
||||
|
||||
print(f"mame-devices: {len(devices)} device ROM sets in the {tag} listxml")
|
||||
print(f" {profile_path.name}:")
|
||||
print(f" + {len(report['added'])} added")
|
||||
print(f" ~ {len(report['updated'])} updated")
|
||||
print(f" = {len(report['unchanged'])} unchanged")
|
||||
for set_name in report["conflict"]:
|
||||
print(f" ! {set_name}.zip is listed under another category, left as written")
|
||||
by_count = Counter(len(device["systems"]) for device in devices.values())
|
||||
fallen = sum(1 for device in devices.values() if UNPLACED_SYSTEM in device["systems"])
|
||||
print(
|
||||
f" systems: {by_count[1]} sets under one system, "
|
||||
f"{sum(n for k, n in by_count.items() if k > 1)} under several, "
|
||||
f"{fallen} of them under {UNPLACED_SYSTEM} (loaded by machines no entry places), "
|
||||
f"{by_count[0]} instantiated by no machine of the release "
|
||||
"(they serve every system of the profile)"
|
||||
)
|
||||
print(
|
||||
f" seeds: {len(written)} written in {profile_path.name}, "
|
||||
f"{len(stated)} from platform files"
|
||||
)
|
||||
for set_name, found in sorted(conflicts.items()):
|
||||
print(f" {set_name}.zip stated under {', '.join(found)}, left unseeded")
|
||||
print(
|
||||
f" software lists: {len(lists)} filed under their systems, "
|
||||
f"{len(present) - len(lists)} declared by no placed machine stay with hash/, "
|
||||
f"{len(set(declared) - present)} placed lists absent from hash/"
|
||||
)
|
||||
unread = sorted(drive for drive, found in form_factors.items() if not found)
|
||||
print(
|
||||
f" floppy samples: {len(sample_systems)} of {len(samples)} filed, "
|
||||
f"{len(support['samples'])} entries rewritten"
|
||||
)
|
||||
for drive in unread:
|
||||
print(f" {drive}: no form factor read, taken to load every list")
|
||||
if unplaced:
|
||||
print(f" {len(unplaced)} without source lines:")
|
||||
for set_name, reason in sorted(unplaced.items()):
|
||||
print(f" {set_name} ({devices[set_name]['source_file']}, {reason})")
|
||||
if args.dry_run:
|
||||
print("(dry run, no files modified)")
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
allow_abbrev=False,
|
||||
prog="mame_hash_scraper",
|
||||
description="Fetch MAME BIOS hashes from source and merge into profiles.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="show diff only, do not modify profiles",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="output raw JSON to stdout",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="re-fetch even if cache is fresh",
|
||||
)
|
||||
devices = parser.add_argument_group(
|
||||
"device ROM sets",
|
||||
"document every device set with dumped ROMs from the release's "
|
||||
"-listxml (e.g. --devices --listxml .cache/dats/mame0289lx.zip)",
|
||||
)
|
||||
devices.add_argument(
|
||||
"--devices", action="store_true",
|
||||
help="merge device ROM sets into mame.yml instead of BIOS root sets",
|
||||
)
|
||||
devices.add_argument(
|
||||
"--listxml", type=Path,
|
||||
help="MAME -listxml, plain or as the release's mameNNNNlx.zip",
|
||||
)
|
||||
release = parser.add_argument_group(
|
||||
"release profile",
|
||||
"write the profile of one MAME release a platform builds "
|
||||
"(e.g. --release mame0278 --profile emulators/mame0278.yml "
|
||||
"--source-commit <libretro/mame sha> --core mame0278 --built-by recalbox)",
|
||||
)
|
||||
release.add_argument("--release", help="mamedev/mame tag, such as mame0278")
|
||||
release.add_argument("--profile", type=Path, help="profile file to write")
|
||||
release.add_argument("--source-commit", help="libretro/mame commit the platform builds")
|
||||
release.add_argument("--core", action="append", default=[], help="core name, repeatable")
|
||||
release.add_argument(
|
||||
"--built-by", action="append", default=[],
|
||||
help="platform that compiles this build, repeatable",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
)
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
if args.devices or args.listxml:
|
||||
if not (args.devices and args.listxml):
|
||||
parser.error("--devices and --listxml go together")
|
||||
if args.release or args.profile or args.json or args.force:
|
||||
parser.error("--devices takes only --listxml and --dry-run")
|
||||
_merge_devices(args)
|
||||
return
|
||||
if args.release or args.profile:
|
||||
missing = [
|
||||
flag for flag, value in (
|
||||
("--release", args.release), ("--profile", args.profile),
|
||||
("--source-commit", args.source_commit), ("--core", args.core),
|
||||
("--built-by", args.built_by),
|
||||
) if not value
|
||||
]
|
||||
if missing:
|
||||
parser.error(f"a release profile needs {', '.join(missing)}")
|
||||
if args.dry_run or args.json:
|
||||
parser.error("--release writes a profile; --dry-run and --json do not apply")
|
||||
_write_release(args)
|
||||
return
|
||||
_run(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,374 @@
|
||||
"""Parser for MAME C source files.
|
||||
|
||||
Extracts BIOS root sets and ROM definitions from MAME driver sources.
|
||||
Handles GAME/GAMEL/SYST/COMP/CONS macros with MACHINE_IS_BIOS_ROOT flag,
|
||||
ROM_START/ROM_END blocks, ROM_LOAD variants, ROM_REGION, ROM_SYSTEM_BIOS,
|
||||
NO_DUMP filtering, BAD_DUMP and ROM_OPTIONAL flagging, and whether a missing
|
||||
set stops the machine.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.lines import LineIndex
|
||||
|
||||
from .clex import DriverSourceError, blank_comments, call_span
|
||||
|
||||
# Macros that declare a machine entry. GAMEL is GAME plus a layout and is
|
||||
# the only suffixed form MAME declares (src/emu/gamedrv.h): a BIOS root that
|
||||
# ships a layout, such as gq863 or aristmk5, is written with it.
|
||||
MACHINE_MACROS = re.compile(
|
||||
r"\b(GAMEL|GAME|SYST|COMP|CONS)\s*\(",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# ROM block boundaries
|
||||
_ROM_START = re.compile(r"ROM_START\s*\(\s*(\w+)\s*\)")
|
||||
_ROM_END = re.compile(r"ROM_END")
|
||||
|
||||
# Offsets and sizes are literals or arithmetic over them, as in 128*1024.
|
||||
_NUMBER = r"(?:0x[\da-fA-F]+|\d+)(?:\s*[*+]\s*(?:0x[\da-fA-F]+|\d+))*"
|
||||
|
||||
# ROM_REGION variants: ROM_REGION, ROM_REGION16_BE, ROM_REGION16_LE, ROM_REGION32_LE, etc.
|
||||
_ROM_REGION = re.compile(
|
||||
r"ROM_REGION\w*\s*\("
|
||||
rf"\s*({_NUMBER})\s*," # size
|
||||
r'\s*"([^"]+)"\s*,', # tag
|
||||
)
|
||||
|
||||
# ROM_SYSTEM_BIOS( index, label, description )
|
||||
_ROM_SYSTEM_BIOS = re.compile(
|
||||
r"ROM_SYSTEM_BIOS\s*\("
|
||||
r"\s*(\d+)\s*," # index
|
||||
r'\s*"([^"]+)"\s*,' # label
|
||||
r'\s*"([^"]+)"\s*\)', # description
|
||||
)
|
||||
|
||||
# All ROM_LOAD variants including custom BIOS macros.
|
||||
# Standard: ROM_LOAD("name", offset, size, hash)
|
||||
# BIOS variant: ROM_LOAD_BIOS(biosidx, "name", offset, size, hash)
|
||||
# ROM_LOAD16_WORD_SWAP_BIOS(biosidx, "name", offset, size, hash)
|
||||
# The key pattern: any macro containing "ROM_LOAD" or "ROMX_LOAD" in its name,
|
||||
# with the first quoted string being the ROM filename.
|
||||
_ROM_LOAD = re.compile(
|
||||
r"\b\w*ROMX?_LOAD\w*\s*\("
|
||||
r'[^"]*' # skip any args before the filename (e.g., bios index)
|
||||
r'"([^"]+)"\s*,' # name (first quoted string)
|
||||
rf"\s*({_NUMBER})\s*," # offset
|
||||
rf"\s*({_NUMBER})\s*,", # size
|
||||
)
|
||||
|
||||
# CRC32 and SHA1 within a ROM_LOAD line
|
||||
_CRC_SHA = re.compile(
|
||||
r"CRC\s*\(\s*([0-9a-fA-F]+)\s*\)"
|
||||
r"\s+"
|
||||
r"SHA1\s*\(\s*([0-9a-fA-F]+)\s*\)",
|
||||
)
|
||||
|
||||
_NO_DUMP = re.compile(r"\bNO_DUMP\b")
|
||||
_BAD_DUMP = re.compile(r"\bBAD_DUMP\b")
|
||||
_ROM_BIOS = re.compile(r"ROM_BIOS\s*\(\s*(\d+)\s*\)")
|
||||
# ROM_LOAD_OPTIONAL expands to ROMX_LOAD(..., ROM_OPTIONAL) (src/emu/romentry.h)
|
||||
_OPTIONAL = re.compile(r"\bROM_OPTIONAL\b|\bROMX?_LOAD\w*_OPTIONAL\b")
|
||||
|
||||
|
||||
def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]:
|
||||
"""Find machine entries flagged as BIOS root sets.
|
||||
|
||||
Scans for GAME/GAMEL/SYST/COMP/CONS macros where the args include
|
||||
MACHINE_IS_BIOS_ROOT, returns set names with source location.
|
||||
"""
|
||||
results: dict[str, dict] = {}
|
||||
lines = LineIndex(source)
|
||||
# Drivers disable a flag by commenting it out inside the macro call, as
|
||||
# in MACHINE_IMPERFECT_SOUND /*| MACHINE_IS_BIOS_ROOT*/: a substring test
|
||||
# on the raw text reads those as active. Blanking keeps every offset.
|
||||
code = blank_comments(source)
|
||||
|
||||
for match in MACHINE_MACROS.finditer(code):
|
||||
try:
|
||||
args, block_end = call_span(code, match.end())
|
||||
except DriverSourceError:
|
||||
continue
|
||||
if "MACHINE_IS_BIOS_ROOT" not in code[match.end() : block_end]:
|
||||
continue
|
||||
|
||||
# The set name position varies by macro type
|
||||
# GAME(year, setname, parent, machine, input, init, monitor, company, fullname, flags)
|
||||
# GAMEL(year, setname, parent, machine, input, init, monitor, company, fullname, flags, layout)
|
||||
# CONS(year, setname, parent, compat, machine, input, init, company, fullname, flags)
|
||||
# COMP(year, setname, parent, compat, machine, input, init, company, fullname, flags)
|
||||
# SYST(year, setname, parent, compat, machine, input, init, company, fullname, flags)
|
||||
# In all cases, setname is the second arg (index 1)
|
||||
if len(args) < 2:
|
||||
continue
|
||||
|
||||
set_name = args[1].strip()
|
||||
line_no = lines.line(match.start())
|
||||
|
||||
results[set_name] = {
|
||||
"source_file": filename,
|
||||
"source_line": line_no,
|
||||
}
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def parse_rom_block(
|
||||
source: str, set_name: str, keep_no_dump: bool = False,
|
||||
) -> list[dict]:
|
||||
"""Parse ROM definitions for a given set name.
|
||||
|
||||
Finds the ROM_START(set_name)...ROM_END block, expands local
|
||||
#define macros that contain ROM_LOAD/ROM_REGION calls, then
|
||||
extracts all ROM entries. Skips NO_DUMP unless keep_no_dump, which
|
||||
returns them flagged no_dump. Flags BAD_DUMP and ROM_OPTIONAL.
|
||||
"""
|
||||
pattern = re.compile(
|
||||
r"ROM_START\s*\(\s*" + re.escape(set_name) + r"\s*\)",
|
||||
)
|
||||
start_match = pattern.search(source)
|
||||
if not start_match:
|
||||
return []
|
||||
|
||||
end_match = _ROM_END.search(source, start_match.end())
|
||||
if not end_match:
|
||||
return []
|
||||
|
||||
block = source[start_match.end() : end_match.start()]
|
||||
|
||||
# Pre-expand macros: find #define macros in the file that contain
|
||||
# ROM_LOAD/ROM_REGION/ROM_SYSTEM_BIOS calls, then expand their
|
||||
# invocations within the ROM block.
|
||||
macros = _collect_rom_macros(source)
|
||||
block = _expand_macros(block, macros, depth=5)
|
||||
|
||||
return _parse_rom_entries(block, keep_no_dump)
|
||||
|
||||
|
||||
def set_is_required(entries: list[dict]) -> bool | None:
|
||||
"""Whether MAME refuses to run the machine when the set is missing.
|
||||
|
||||
handle_missing_file (src/emu/romload.cpp) counts a missing ROM_OPTIONAL
|
||||
as a warning and a missing NO_DUMP as known bad. Any other ROM raises
|
||||
an error, and display_rom_load_results throws
|
||||
EMU_ERR_MISSING_FILES on errors. A set whose every ROM is optional or
|
||||
undumped warns and the machine runs. None when the block holds no
|
||||
ROM_LOAD at all: nothing was read, so nothing is decided.
|
||||
"""
|
||||
if not entries:
|
||||
return None
|
||||
return any(not e.get("no_dump") and not e.get("optional") for e in entries)
|
||||
|
||||
|
||||
def parse_mame_source_tree(base_path: str) -> dict[str, dict]:
|
||||
"""Walk MAME source tree and extract all BIOS root sets with ROMs.
|
||||
|
||||
Scans src/mame/ and src/devices/ for C/C++ source files.
|
||||
"""
|
||||
results: dict[str, dict] = {}
|
||||
root = Path(base_path)
|
||||
|
||||
search_dirs = [root / "src" / "mame", root / "src" / "devices"]
|
||||
|
||||
for search_dir in search_dirs:
|
||||
if not search_dir.is_dir():
|
||||
continue
|
||||
for dirpath, _dirnames, filenames in os.walk(search_dir):
|
||||
for fname in filenames:
|
||||
if not fname.endswith((".cpp", ".c", ".h", ".hxx")):
|
||||
continue
|
||||
filepath = Path(dirpath) / fname
|
||||
rel_path = str(filepath.relative_to(root))
|
||||
content = filepath.read_text(encoding="utf-8", errors="replace")
|
||||
|
||||
bios_sets = find_bios_root_sets(content, rel_path)
|
||||
for set_name, info in bios_sets.items():
|
||||
entries = parse_rom_block(content, set_name, keep_no_dump=True)
|
||||
results[set_name] = {
|
||||
"source_file": info["source_file"],
|
||||
"source_line": info["source_line"],
|
||||
"roms": [e for e in entries if not e.get("no_dump")],
|
||||
}
|
||||
required = set_is_required(entries)
|
||||
if required is not None:
|
||||
results[set_name]["required"] = required
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# Regex for #define macros that span multiple lines (backslash continuation)
|
||||
_DEFINE_RE = re.compile(
|
||||
r"^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s*((?:.*\\\n)*.*)",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# ROM-related tokens that indicate a macro is relevant for expansion
|
||||
_ROM_TOKENS = {
|
||||
"ROM_LOAD",
|
||||
"ROMX_LOAD",
|
||||
"ROM_REGION",
|
||||
"ROM_SYSTEM_BIOS",
|
||||
"ROM_FILL",
|
||||
"ROM_COPY",
|
||||
"ROM_RELOAD",
|
||||
}
|
||||
|
||||
|
||||
def _collect_rom_macros(source: str) -> dict[str, str]:
|
||||
"""Collect #define macros that contain ROM-related calls.
|
||||
|
||||
Returns {macro_name: expanded_body} with backslash continuations joined.
|
||||
Only collects macros that contain actual ROM data (quoted filenames),
|
||||
not wrapper macros like ROM_LOAD16_WORD_SWAP_BIOS that just redirect
|
||||
to ROMX_LOAD with formal parameters.
|
||||
"""
|
||||
macros: dict[str, str] = {}
|
||||
for m in _DEFINE_RE.finditer(source):
|
||||
name = m.group(1)
|
||||
body = m.group(2)
|
||||
# Join backslash-continued lines
|
||||
body = body.replace("\\\n", " ")
|
||||
# Only keep macros that contain ROM-related tokens
|
||||
if not any(tok in body for tok in _ROM_TOKENS):
|
||||
continue
|
||||
# Skip wrapper macros: if the body contains ROMX_LOAD/ROM_LOAD
|
||||
# with unquoted args (formal parameters), it's a wrapper.
|
||||
# These are already recognized by the _ROM_LOAD regex directly.
|
||||
if re.search(r"ROMX?_LOAD\s*\(\s*\w+\s*,\s*\w+\s*,", body):
|
||||
continue
|
||||
macros[name] = body
|
||||
return macros
|
||||
|
||||
|
||||
def _expand_macros(block: str, macros: dict[str, str], depth: int = 5) -> str:
|
||||
"""Expand macro invocations in a ROM block.
|
||||
|
||||
Handles both simple macros (NEOGEO_BIOS) and parameterized ones
|
||||
(NEOGEO_UNIBIOS_2_2_AND_NEWER(16)). Recurses up to `depth` levels
|
||||
for nested macros.
|
||||
"""
|
||||
if depth <= 0 or not macros:
|
||||
return block
|
||||
|
||||
changed = True
|
||||
iterations = 0
|
||||
while changed and iterations < depth:
|
||||
changed = False
|
||||
iterations += 1
|
||||
for name, body in macros.items():
|
||||
# Match macro invocation: NAME or NAME(args)
|
||||
pattern = re.compile(r"\b" + re.escape(name) + r"(?:\s*\([^)]*\))?")
|
||||
if pattern.search(block):
|
||||
block = pattern.sub(body, block)
|
||||
changed = True
|
||||
|
||||
return block
|
||||
|
||||
|
||||
def _parse_rom_entries(block: str, keep_no_dump: bool = False) -> list[dict]:
|
||||
"""Parse ROM entries from a ROM block (content between ROM_START and ROM_END).
|
||||
|
||||
Uses regex scanning over the entire block (not line-by-line) to handle
|
||||
macro-expanded content where multiple statements may be on one line.
|
||||
Processes matches in order of appearance to track region and BIOS context.
|
||||
"""
|
||||
roms: list[dict] = []
|
||||
current_region = ""
|
||||
bios_labels: dict[int, tuple[str, str]] = {}
|
||||
|
||||
# Build a combined pattern that matches all interesting tokens
|
||||
# and process them in order of occurrence
|
||||
token_patterns = [
|
||||
("region", _ROM_REGION),
|
||||
("bios_label", _ROM_SYSTEM_BIOS),
|
||||
("rom_load", _ROM_LOAD),
|
||||
]
|
||||
|
||||
events: list[tuple[int, str, re.Match]] = []
|
||||
for tag, pat in token_patterns:
|
||||
events.extend((m.start(), tag, m) for m in pat.finditer(block))
|
||||
|
||||
# Walked in source order: a ROM_LOAD belongs to the last ROM_REGION above it.
|
||||
events.sort(key=lambda e: e[0])
|
||||
|
||||
for _pos, tag, m in events:
|
||||
if tag == "region":
|
||||
current_region = m.group(2)
|
||||
elif tag == "bios_label":
|
||||
idx = int(m.group(1))
|
||||
bios_labels[idx] = (m.group(2), m.group(3))
|
||||
elif tag == "rom_load":
|
||||
# Get the full macro call as context (find closing paren)
|
||||
context_start = m.start()
|
||||
# Find the opening paren of the ROM_LOAD macro
|
||||
paren_pos = block.find("(", context_start)
|
||||
try:
|
||||
if paren_pos == -1:
|
||||
raise DriverSourceError("no call")
|
||||
context_end = call_span(block, paren_pos + 1)[1]
|
||||
except DriverSourceError:
|
||||
context_end = m.end() + 200
|
||||
context = block[context_start : min(context_end, len(block))]
|
||||
|
||||
no_dump = bool(_NO_DUMP.search(context))
|
||||
if no_dump and not keep_no_dump:
|
||||
continue
|
||||
|
||||
rom_name = m.group(1)
|
||||
rom_size = _parse_int(m.group(3))
|
||||
|
||||
crc_sha_match = _CRC_SHA.search(context)
|
||||
crc32 = ""
|
||||
sha1 = ""
|
||||
if crc_sha_match:
|
||||
crc32 = crc_sha_match.group(1).lower()
|
||||
sha1 = crc_sha_match.group(2).lower()
|
||||
|
||||
bad_dump = bool(_BAD_DUMP.search(context))
|
||||
|
||||
bios_index = None
|
||||
bios_label = ""
|
||||
bios_description = ""
|
||||
bios_ref = _ROM_BIOS.search(context)
|
||||
if bios_ref:
|
||||
bios_index = int(bios_ref.group(1))
|
||||
if bios_index in bios_labels:
|
||||
bios_label, bios_description = bios_labels[bios_index]
|
||||
|
||||
entry: dict = {
|
||||
"name": rom_name,
|
||||
"size": rom_size,
|
||||
"crc32": crc32,
|
||||
"sha1": sha1,
|
||||
"region": current_region,
|
||||
"bad_dump": bad_dump,
|
||||
}
|
||||
|
||||
if bios_index is not None:
|
||||
entry["bios_index"] = bios_index
|
||||
entry["bios_label"] = bios_label
|
||||
entry["bios_description"] = bios_description
|
||||
if _OPTIONAL.search(context):
|
||||
entry["optional"] = True
|
||||
if no_dump:
|
||||
entry["no_dump"] = True
|
||||
|
||||
roms.append(entry)
|
||||
|
||||
return roms
|
||||
|
||||
|
||||
def _parse_int(value: str) -> int:
|
||||
"""Parse a hex or decimal literal, or arithmetic over them as in 128*1024."""
|
||||
total = 0
|
||||
for term in value.split("+"):
|
||||
product = 1
|
||||
for factor in term.split("*"):
|
||||
factor = factor.strip()
|
||||
product *= int(factor, 16 if factor[:2].lower() == "0x" else 10)
|
||||
total += product
|
||||
return total
|
||||
@@ -0,0 +1,575 @@
|
||||
"""Import romset recipes from a MAME or FBNeo DAT.
|
||||
|
||||
A DAT states, per set, the members an emulator version expects: name, size
|
||||
and CRC32. That is a recipe, and TorrentZip turns a recipe plus the ROM bytes
|
||||
into the exact archive. Profiles document a few hundred sets by hand, while a DAT
|
||||
documents every set of one version at once.
|
||||
|
||||
MAME ships its ``-listxml`` output as a release asset and FBNeo keeps its DATs
|
||||
in its repository, so both are fetched without a browser:
|
||||
|
||||
python -m scripts.scraper.arcade.romset_dat_importer --source mame --fetch
|
||||
python -m scripts.scraper.arcade.romset_dat_importer --source mame --fetch mame0289
|
||||
python -m scripts.scraper.arcade.romset_dat_importer --source fbneo --fetch
|
||||
python -m scripts.scraper.arcade.romset_dat_importer --source fbneo --fetch v1.0.0.02
|
||||
python -m scripts.scraper.arcade.romset_dat_importer --source mame --pack local.dat
|
||||
|
||||
Only sets the collection has a reason to know are kept, so the committed
|
||||
snapshot stays small: the archive names that emulator profiles or platform
|
||||
BIOS lists reference, the archives the collection holds, the sets holding a
|
||||
dump-catalog entry the collection lacks (provenance_report names the set as
|
||||
where to find it), and every set whose members equal an archive the
|
||||
collection keeps under another name. That last entry carries the
|
||||
collection's name and keeps the upstream one in ``set``. ``--all`` keeps
|
||||
everything.
|
||||
|
||||
Members without a CRC32 are undumped. A real romset does not carry them, so
|
||||
they are dropped from the recipe rather than disqualifying the whole set.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import IO
|
||||
|
||||
from core.paths import RECIPES_DIR
|
||||
from core.ziptools import is_archive_path, zip_members
|
||||
from model.registry import list_registered_platforms
|
||||
from model.profiles import load_emulator_profiles
|
||||
from model.platforms import load_platform_config
|
||||
from core.cli import add_repo_inputs, run_cli
|
||||
from model.database import load_database
|
||||
from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot
|
||||
from resolve.lookup import variant_base_name
|
||||
from ..base_scraper import BlobMismatchError, fetch_github_latest_version
|
||||
from .dat_fetch import fetch_pack, mame_label
|
||||
from ..dats.listxml import (
|
||||
Opener,
|
||||
iter_dat_documents,
|
||||
iter_elements,
|
||||
open_listxml,
|
||||
rom_members,
|
||||
xml_members,
|
||||
)
|
||||
from ..dats.logiqx_parser import LogiqxDat, parse_logiqx
|
||||
|
||||
SOURCES = ("mame", "fbneo")
|
||||
DEFAULT_OUTPUT = f"{RECIPES_DIR}/{{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 in load_emulator_profiles(
|
||||
emulators_dir, skip_aliases=False
|
||||
).values():
|
||||
for entry in profile.get("files", []) or []:
|
||||
name = entry.get("name", "")
|
||||
if name.endswith(".zip"):
|
||||
names.add(name)
|
||||
archive = entry.get("archive", "")
|
||||
if archive:
|
||||
names.add(archive)
|
||||
for platform_name in list_registered_platforms(platforms_dir):
|
||||
config = load_platform_config(platform_name, platforms_dir)
|
||||
for system in config.get("systems", {}).values():
|
||||
for entry in system.get("files", []) or []:
|
||||
name = entry.get("name", "")
|
||||
if name.endswith(".zip"):
|
||||
names.add(name)
|
||||
return names
|
||||
|
||||
|
||||
Targets = dict[tuple[str, int], set[str]]
|
||||
MemberList = tuple[tuple[str, str], ...]
|
||||
ByMembers = dict[MemberList, set[str]]
|
||||
|
||||
def member_list(members: list[dict]) -> MemberList:
|
||||
"""Sorted (name, crc32) of a recipe, the key an archive is matched on."""
|
||||
return tuple(
|
||||
sorted((str(m["name"]), str(m.get("crc32") or "").lower()) for m in members)
|
||||
)
|
||||
|
||||
|
||||
def collection_archives(db: dict) -> tuple[set[str], ByMembers]:
|
||||
"""Names and member lists of every archive the collection holds.
|
||||
|
||||
A set the collection keeps under another name is still that set:
|
||||
``aga.zip`` holds exactly MAME's ``isa_aga`` and ``votrax.zip`` its
|
||||
``votrsc01a``. Matched by name alone, neither ever entered the snapshot.
|
||||
A ``.variants/`` copy stands for the name its tag is cut from.
|
||||
"""
|
||||
names: set[str] = set()
|
||||
by_members: ByMembers = {}
|
||||
for entry in db.get("files", {}).values():
|
||||
path = Path(entry.get("path", ""))
|
||||
name = variant_base_name(path.name)
|
||||
if not is_archive_path(path.name) or not path.is_file():
|
||||
continue
|
||||
try:
|
||||
held = [
|
||||
{"name": member.name, "crc32": member.crc32}
|
||||
for member in zip_members(path)
|
||||
]
|
||||
except (OSError, zipfile.BadZipFile) as exc:
|
||||
print(f" UNREADABLE: {path}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
names.add(name)
|
||||
if held:
|
||||
by_members.setdefault(member_list(held), set()).add(name)
|
||||
return names, by_members
|
||||
|
||||
|
||||
def _entry(
|
||||
dat: str, archive: str, set_name: str, description: str, members: list[dict]
|
||||
) -> dict:
|
||||
return {
|
||||
"dat": dat,
|
||||
"name": archive,
|
||||
"set": set_name,
|
||||
"description": description,
|
||||
"members": sorted(members, key=lambda member: member["name"]),
|
||||
}
|
||||
|
||||
|
||||
def named_entries(
|
||||
dat: str,
|
||||
set_name: str,
|
||||
description: str,
|
||||
members: list[dict],
|
||||
kept: bool,
|
||||
by_members: ByMembers | None,
|
||||
) -> list[dict]:
|
||||
"""The snapshot entries one upstream set gives.
|
||||
|
||||
Under its own name when kept, and under every collection name whose
|
||||
archive holds exactly its members. ``set`` keeps the upstream name.
|
||||
"""
|
||||
archives = {f"{set_name}.zip"} if kept else set()
|
||||
if by_members:
|
||||
archives |= by_members.get(member_list(members), set())
|
||||
return [
|
||||
_entry(dat, archive, set_name, description, members)
|
||||
for archive in sorted(archives)
|
||||
]
|
||||
|
||||
|
||||
def catalog_targets(provenance_dir: str, db: dict) -> Targets:
|
||||
"""(crc32, size) -> sha1 of each dump-catalog entry the collection lacks.
|
||||
|
||||
fm7740sx carries DICROM.rom, EXTSUB.rom and KANJI2.rom, which No-Intro
|
||||
lists and the collection misses: filtered on archive names alone, the
|
||||
snapshot never held the set and the missing report named no source.
|
||||
"""
|
||||
held = set(db.get("files", {}))
|
||||
targets: Targets = {}
|
||||
for snapshot in load_provenance_snapshots(provenance_dir).values():
|
||||
for entry in snapshot.get("entries", []):
|
||||
crc, size = str(entry.get("crc32") or "").lower(), entry.get("size")
|
||||
sha1 = str(entry.get("sha1") or "").lower()
|
||||
if not crc or size is None or (sha1 and sha1 in held):
|
||||
continue
|
||||
targets.setdefault((crc.zfill(8), int(size)), set()).add(sha1)
|
||||
return targets
|
||||
|
||||
|
||||
def holds_target(members: list[dict], targets: Targets | None) -> bool:
|
||||
"""Whether a set carries a missing catalog dump. A sha1 on both sides
|
||||
must agree: crc32 and size alone collide across 40 000 ROMs."""
|
||||
if not targets:
|
||||
return False
|
||||
for member in members:
|
||||
key = (str(member.get("crc32") or "").lower().zfill(8), int(member.get("size") or 0))
|
||||
wanted = targets.get(key)
|
||||
sha1 = str(member.get("sha1") or "").lower()
|
||||
if wanted is not None and (not sha1 or "" in wanted or sha1 in wanted):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def one_set_per_archive(entries: list[dict]) -> list[dict]:
|
||||
"""One entry per archive and member list, its own set preferred.
|
||||
|
||||
Thirty MAME keyboard sets carry the same ROM, so ``a500kbd_ch.zip``
|
||||
matches all of them. The set named like the archive is the one kept,
|
||||
then the first by name.
|
||||
"""
|
||||
chosen: dict[tuple[str, MemberList], dict] = {}
|
||||
for entry in entries:
|
||||
key = (entry["name"], member_list(entry["members"]))
|
||||
current = chosen.get(key)
|
||||
own = entry["name"] == f"{entry['set']}.zip"
|
||||
if current is None or (own and current["name"] != f"{current['set']}.zip"):
|
||||
chosen[key] = entry
|
||||
return sorted(chosen.values(), key=lambda e: (e["name"], e["set"]))
|
||||
|
||||
|
||||
def recipe_entries(
|
||||
dat: LogiqxDat,
|
||||
keep: set[str] | None = None,
|
||||
targets: Targets | None = None,
|
||||
by_members: ByMembers | None = None,
|
||||
) -> list[dict]:
|
||||
"""Group a parsed DAT into one recipe per set."""
|
||||
by_set: dict[str, list] = {}
|
||||
for rom in dat.roms:
|
||||
if not rom.crc32:
|
||||
continue
|
||||
by_set.setdefault(rom.game, []).append(rom)
|
||||
|
||||
entries: list[dict] = []
|
||||
for set_name, roms in sorted(by_set.items()):
|
||||
members = [
|
||||
{"name": rom.name, "size": rom.size, "crc32": rom.crc32, "sha1": rom.sha1}
|
||||
for rom in roms
|
||||
]
|
||||
kept = (
|
||||
keep is None
|
||||
or f"{set_name}.zip" in keep
|
||||
or holds_target(members, targets)
|
||||
)
|
||||
entries.extend(
|
||||
named_entries(
|
||||
dat.name or "unnamed", set_name, roms[0].description, members,
|
||||
kept, by_members,
|
||||
)
|
||||
)
|
||||
return one_set_per_archive(entries)
|
||||
|
||||
|
||||
def _scan_listxml(
|
||||
stream: IO[bytes],
|
||||
selector: Callable[[str], bool],
|
||||
targets: Targets | None = None,
|
||||
) -> dict[str, tuple[str | None, list[dict]]]:
|
||||
"""Stream a MAME -listxml document, keeping the machines *selector* wants
|
||||
and those holding one of *targets*."""
|
||||
found: dict[str, tuple[str | None, list[dict]]] = {}
|
||||
for element in iter_elements(stream):
|
||||
name = element.attrs.get("name", "")
|
||||
wanted = selector(name)
|
||||
if wanted or targets:
|
||||
roms = rom_members(element.body)
|
||||
if wanted or holds_target(roms, targets):
|
||||
found[name] = (element.attrs.get("romof") or None, roms)
|
||||
return found
|
||||
|
||||
|
||||
def listxml_entries(
|
||||
open_stream: Opener,
|
||||
label: str,
|
||||
keep: set[str] | None,
|
||||
targets: Targets | None = None,
|
||||
by_members: ByMembers | None = None,
|
||||
) -> list[dict]:
|
||||
"""Recipes from a MAME -listxml document, parents resolved.
|
||||
|
||||
A non-merged archive carries its parent set's ROMs as well as its own, so
|
||||
a machine with ``romof`` is read as the union, its own members winning a
|
||||
name collision. Two passes: the parents a set needs are only known once
|
||||
that set has been seen. Matching by member list reads every machine in
|
||||
one pass, every parent included.
|
||||
"""
|
||||
def kept(name: str) -> bool:
|
||||
return keep is None or f"{name}.zip" in keep
|
||||
|
||||
with open_stream() as stream:
|
||||
wanted = _scan_listxml(
|
||||
stream, (lambda _name: True) if by_members else kept, targets
|
||||
)
|
||||
requested = (
|
||||
{
|
||||
name for name, (_parent, roms) in wanted.items()
|
||||
if kept(name) or holds_target(roms, targets)
|
||||
}
|
||||
if by_members
|
||||
else set(wanted)
|
||||
)
|
||||
parents = {
|
||||
parent for parent, _roms in wanted.values() if parent and parent not in wanted
|
||||
}
|
||||
if parents:
|
||||
with open_stream() as stream:
|
||||
for name, value in _scan_listxml(stream, parents.__contains__).items():
|
||||
wanted.setdefault(name, value)
|
||||
|
||||
entries: list[dict] = []
|
||||
for name, (parent, roms) in sorted(wanted.items()):
|
||||
if not by_members and name not in requested:
|
||||
# A parent read only to complete a child is not itself an entry.
|
||||
continue
|
||||
members = {member["name"]: member for member in wanted.get(parent, (None, []))[1]} if parent else {}
|
||||
members.update({member["name"]: member for member in roms})
|
||||
if not members:
|
||||
continue
|
||||
entries.extend(
|
||||
named_entries(
|
||||
label, name, f"parent {parent}" if parent else name,
|
||||
list(members.values()), name in requested, by_members,
|
||||
)
|
||||
)
|
||||
return one_set_per_archive(entries)
|
||||
|
||||
|
||||
def _recipe_key(entry: dict) -> tuple[str, str]:
|
||||
"""Identity of a recipe: which archive, and exactly which members."""
|
||||
members = json.dumps(entry.get("members", []), sort_keys=True)
|
||||
return entry.get("name", ""), hashlib.sha1(members.encode()).hexdigest()
|
||||
|
||||
|
||||
def compact_entries(entries: list[dict]) -> list[dict]:
|
||||
"""Collapse identical recipes shared by several versions.
|
||||
|
||||
Most sets do not change between MAME releases: 22 imported versions give
|
||||
23,679 entries but only 1,726 distinct recipes. Each is stored once, with
|
||||
``dats`` listing every version that agrees and ``dat`` naming the earliest,
|
||||
so a match reads as "unchanged since that version" rather than "is that
|
||||
version".
|
||||
"""
|
||||
grouped: dict[tuple[str, str], dict] = {}
|
||||
for entry in entries:
|
||||
key = _recipe_key(entry)
|
||||
existing = grouped.get(key)
|
||||
labels = entry.get("dats") or ([entry["dat"]] if entry.get("dat") else [])
|
||||
if existing is None:
|
||||
merged = dict(entry)
|
||||
merged["dats"] = sorted(set(labels))
|
||||
grouped[key] = merged
|
||||
else:
|
||||
existing["dats"] = sorted(set(existing["dats"]) | set(labels))
|
||||
for entry in grouped.values():
|
||||
entry["dat"] = entry["dats"][0]
|
||||
return sorted(grouped.values(), key=lambda e: (e["name"], e["dat"]))
|
||||
|
||||
|
||||
def merge_snapshot(
|
||||
output: str,
|
||||
source: str,
|
||||
dats: dict[str, str],
|
||||
entries: list[dict],
|
||||
upstream: dict[str, str] | None = None,
|
||||
) -> bool:
|
||||
"""Accumulate recipes across versions instead of replacing them.
|
||||
|
||||
A platform pins the archive of whichever version its list was built
|
||||
against, so the snapshot is a growing library of versions, not a picture
|
||||
of the newest one. ``upstream`` (DAT file -> git blob sha) replaces the
|
||||
previous one: it describes the files this import read, not a history.
|
||||
"""
|
||||
path = Path(output)
|
||||
known_entries: list[dict] = []
|
||||
known_dats: dict[str, str] = {}
|
||||
known_upstream: dict = {}
|
||||
if path.is_file():
|
||||
with path.open(encoding="utf-8") as handle:
|
||||
existing = json.load(handle)
|
||||
known_entries = list(existing.get("entries", []))
|
||||
known_dats = dict(existing.get("dats", {}))
|
||||
known_upstream = dict(existing.get("upstream", {}))
|
||||
|
||||
known_dats.update(dats)
|
||||
if upstream:
|
||||
known_upstream["blobs"] = dict(sorted(upstream.items()))
|
||||
snapshot = build_snapshot(
|
||||
source,
|
||||
datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
known_dats,
|
||||
compact_entries(known_entries + entries),
|
||||
)
|
||||
if known_upstream:
|
||||
snapshot["upstream"] = dict(sorted(known_upstream.items()))
|
||||
return write_snapshot(output, snapshot)
|
||||
|
||||
|
||||
MAME_REPO = "mamedev/mame"
|
||||
|
||||
|
||||
def fetch_tag(source: str, requested: str) -> str:
|
||||
"""The revision a ``--fetch`` names: bare, the newest MAME release or
|
||||
the tip of FBNeo's default branch."""
|
||||
if source == "mame" and requested == "latest":
|
||||
tag = fetch_github_latest_version(MAME_REPO)
|
||||
print(f" Derniere release MAME : {tag}")
|
||||
return tag
|
||||
return requested
|
||||
|
||||
|
||||
def _is_listxml(pack: Path) -> bool:
|
||||
"""Whether *pack* holds a MAME -listxml document rather than a DAT.
|
||||
|
||||
A ZIP of several XML documents is a DAT collection."""
|
||||
if pack.is_dir():
|
||||
return False
|
||||
if pack.suffix.lower() == ".zip":
|
||||
with zipfile.ZipFile(pack) as archive:
|
||||
if len(xml_members(archive)) != 1:
|
||||
return False
|
||||
with open_listxml(pack) as handle:
|
||||
return b"<!ELEMENT mame" in handle.read(4096)
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__)
|
||||
parser.add_argument(
|
||||
"--source", choices=SOURCES, required=True,
|
||||
help="emulator whose DATs are imported",
|
||||
)
|
||||
parser.add_argument("--pack", help="DAT file, ZIP or directory")
|
||||
parser.add_argument(
|
||||
"--fetch",
|
||||
nargs="?",
|
||||
const="latest",
|
||||
help="download upstream instead of using --pack: a MAME tag such as "
|
||||
"mame0289 or an FBNeo tag, branch or commit; bare, the newest MAME "
|
||||
"release or the tip of FBNeo's default branch",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cache-dir", default=".cache/dats",
|
||||
help="download cache directory (default: %(default)s)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", default="",
|
||||
help="snapshot to write (default: recipes/<source>.json)",
|
||||
)
|
||||
add_repo_inputs(parser, "emulators", "platforms", "db")
|
||||
parser.add_argument(
|
||||
"--all", action="store_true", help="keep every set, not only referenced ones"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--provenance-dir", default="provenance",
|
||||
help="dump catalogs whose missing entries keep the sets holding them "
|
||||
"(default: %(default)s)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--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()
|
||||
db = load_database(args.db)
|
||||
held, by_members = collection_archives(db)
|
||||
keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held
|
||||
targets = catalog_targets(args.provenance_dir, db)
|
||||
return _Selection(keep, targets, by_members)
|
||||
|
||||
|
||||
def _import_listxml(pack: Path, args: argparse.Namespace, output: str, chosen: _Selection) -> int:
|
||||
label = mame_label(pack.stem)
|
||||
entries = listxml_entries(
|
||||
lambda: open_listxml(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_documents(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] = {}
|
||||
# FBNeo's DAT headers keep one version across commits, so a DAT read at
|
||||
# a named revision is labelled with it: under the bare header name it
|
||||
# merged into the tip's recipes. Its blobs describe that revision, not
|
||||
# the upstream state the freshness check compares with, and are not
|
||||
# recorded.
|
||||
revision = ""
|
||||
if args.fetch:
|
||||
try:
|
||||
pack, blobs = fetch_pack(
|
||||
args.source, fetch_tag(args.source, args.fetch), Path(args.cache_dir)
|
||||
)
|
||||
except (BlobMismatchError, ConnectionError, RuntimeError) as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(f" Recupere {pack}")
|
||||
if args.source == "fbneo" and args.fetch != "latest":
|
||||
revision = args.fetch
|
||||
blobs = {}
|
||||
elif args.pack:
|
||||
pack = Path(args.pack)
|
||||
else:
|
||||
parser.error("either --pack or --fetch is required")
|
||||
if not pack.exists():
|
||||
print(f"ERROR: {pack} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
output = args.output or DEFAULT_OUTPUT.format(source=args.source)
|
||||
Path(output).parent.mkdir(parents=True, exist_ok=True)
|
||||
chosen = _selection(args)
|
||||
|
||||
if _is_listxml(pack):
|
||||
return _import_listxml(pack, args, output, chosen)
|
||||
|
||||
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")
|
||||
|
||||
if args.dry_run:
|
||||
return 0
|
||||
|
||||
changed = merge_snapshot(output, args.source, dats, entries, blobs)
|
||||
print(f"{'Wrote' if changed else 'Unchanged'} {output}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_cli(main)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""A shallow sparse clone of an upstream tree, and the day-long cache of what
|
||||
was read from it (the MAME and FBNeo hash scrapers)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def fresh_cache(path: Path, hours: int = 24) -> dict[str, Any] | None:
|
||||
"""The cache at `path` when it holds BIOS sets read less than `hours` ago.
|
||||
|
||||
A missing, unreadable or damaged file, an empty read and a timestamp
|
||||
without a time zone all count as stale: the caller reads upstream again.
|
||||
"""
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
cache = json.load(handle)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
log.warning("ignoring the cache %s: %s", path, exc)
|
||||
return None
|
||||
if not isinstance(cache, dict) or not cache.get("bios_sets"):
|
||||
return None
|
||||
try:
|
||||
age = datetime.now(timezone.utc) - datetime.fromisoformat(cache["fetched_at"])
|
||||
except (KeyError, ValueError, TypeError):
|
||||
return None
|
||||
return cache if age < timedelta(hours=hours) else None
|
||||
|
||||
|
||||
def _git(args: list[str], cwd: Path | None = None) -> str:
|
||||
return subprocess.run(
|
||||
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
|
||||
).stdout
|
||||
|
||||
|
||||
def sparse_clone(url: str, dest: Path, dirs: list[str], ref: str | None = None) -> str:
|
||||
"""Clone `dirs` of `url` at `ref` (the default branch when None) into
|
||||
`dest`, replacing what is there, and return the commit cloned.
|
||||
|
||||
Never an empty commit: returned empty, it was cached for a day and a
|
||||
merge advanced core_version and the refs while upstream_commit stayed
|
||||
on the previous release, a profile describing two revisions at once.
|
||||
"""
|
||||
remove_clone(dest)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
log.info("sparse cloning %s %s into %s", url, ref or "HEAD", dest)
|
||||
branch = ["--branch", ref] if ref else []
|
||||
_git(["clone", "--depth", "1", *branch, "--filter=blob:none", "--sparse", url, str(dest)])
|
||||
_git(["sparse-checkout", "set", *dirs], cwd=dest)
|
||||
try:
|
||||
commit = _git(["rev-parse", "HEAD"], cwd=dest).strip()
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise RuntimeError(f"cannot read the commit of the clone in {dest}: {exc}") from exc
|
||||
if not commit:
|
||||
raise RuntimeError(f"the clone in {dest} names no commit")
|
||||
return commit
|
||||
|
||||
|
||||
def remove_clone(dest: Path) -> None:
|
||||
if dest.exists():
|
||||
log.info("cleaning up %s", dest)
|
||||
shutil.rmtree(dest)
|
||||
Reference in new issue
Block a user