refactor: split export_native and the exporters

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:54:04 +01:00
1 parent e27a808f1b
commit fd60b10de6
14 files changed
+685 -514

No files matched your search

+8 -3
View File
@@ -9,11 +9,16 @@ the data block hands the maintainer something that no longer runs.
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Generic, TypeVar, Union
from .baseline import NativeFile, NativeSystem, Report
# What a produced file holds: text for every format, bytes besides for one
# that also hands back an archive (MiSTer's bios_db.json.zip).
Content = TypeVar("Content", bound=Union[str, bytes])
class BaseExporter(ABC):
class BaseExporter(ABC, Generic[Content]):
"""Base class for writing a platform's own BIOS file, corrected."""
# A hash field the checker compares to one value: an addition the
@@ -77,14 +82,14 @@ class BaseExporter(ABC):
report: Report,
originals: dict[str, str],
scraped: dict | None = None,
) -> dict[str, str]:
) -> dict[str, Content]:
"""Return {relative output path: file content}."""
@abstractmethod
def validate(
self,
systems: dict[str, NativeSystem],
produced: dict[str, str],
produced: dict[str, Content],
) -> list[str]:
"""Check the produced files against what was asked of them."""
+168 -136
View File
@@ -121,7 +121,7 @@ def _field_sets(entry: dict | None) -> dict[str, set[str]]:
return {f: set(_hash_values(entry or {}, f)) for f in HASH_FIELDS}
def _single_size(value: object) -> int | None:
def _single_size(value: int | str | list[int | str]) -> int | None:
"""One size, or None: a list names several accepted revisions, which a
single size field cannot state (int() on it stopped the whole export)."""
if isinstance(value, list):
@@ -499,22 +499,9 @@ def platform_declares(truth_entry: dict, candidates: list[dict]) -> bool:
)
def build_native_model(
truth: dict,
scraped: dict | None,
) -> tuple[dict[str, NativeSystem], Report]:
"""Rebuild the platform's systems, corrected by the truth.
Returns the systems keyed by native id, in the platform's own order
first and truth-only additions after, plus what changed.
"""
report = Report()
def _platform_systems(scraped_systems: dict, report: Report) -> dict[str, NativeSystem]:
"""Pass 1: the platform's own file, grouped as the platform groups it."""
systems: dict[str, NativeSystem] = {}
scraped_systems = (scraped or {}).get("systems", {})
composite_zips = (scraped or {}).get("zip_digest") == "composite"
# Pass 1: the platform's own file, grouped as the platform groups it.
for sys_key, sys_data in scraped_systems.items():
for file_entry in sys_data.get("files", []):
native_id = _native_id_of(sys_key, sys_data, file_entry)
@@ -540,31 +527,83 @@ def build_native_model(
)
)
report.files_kept += 1
return systems
def _correct_matched(matched: NativeFile, truth_entry: dict, report: Report) -> None:
"""Record what the truth corrects or fills on the platform's own entry."""
matched.truth = truth_entry
checked = checked_hashes(truth_entry) or {}
contradicted = contradicted_hashes(truth_entry, matched.platform)
for field_name in HASH_FIELDS:
if field_name == "md5" and matched.composite_md5:
continue
if field_name in contradicted:
matched.corrections.append(field_name)
report.hashes_corrected.append(
f"{matched.native_system}/{matched.name} {field_name}"
)
elif _hash_values(checked, field_name) and not _hash_values(
comparable(matched.platform), field_name
):
matched.filled.append(field_name)
t_req = truth_entry.get("required")
p_req = (matched.platform or {}).get("required")
# A file a core takes as one of a set has no requirement of
# its own: a platform line cannot say "one of these", so
# truth leaves its value as written rather than claim
# every member optional or every member needed.
if (
t_req is not None
and p_req is not None
and bool(t_req) != bool(p_req)
and not (truth_entry.get("one_of_required") and not t_req)
):
matched.corrections.append("required")
report.required_corrected.append(
f"{matched.native_system}/{matched.name}"
)
@dataclass
class _TruthPass:
"""Pass 2: the truth applied onto the platform's grouping."""
systems: dict[str, NativeSystem]
report: Report
scraped_systems: dict
composite_zips: bool
# Which native ids a truth system may contribute to.
norm_to_scraped: dict[str, str] = {
_norm_system_id(key): key for key in scraped_systems
}
norm_to_scraped: dict[str, str] = field(init=False)
# Every system the platform names, files or none: an addition elsewhere
# is filed under our own slug.
platform_ids = {
native_id
for key, sys_data in scraped_systems.items()
for native_id in (
sys_data.get("native_id") or key,
*(_native_id_of(key, sys_data, fe) for fe in sys_data.get("files", [])),
)
}
native_by_norm: dict[str, str] = {}
for system in systems.values():
native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id)
platform_ids: set[str] = field(init=False)
native_by_norm: dict[str, str] = field(init=False)
def _target_native_ids(truth_sid: str) -> tuple[list[str], bool]:
def __post_init__(self) -> None:
scraped_systems = self.scraped_systems
self.norm_to_scraped = {
_norm_system_id(key): key for key in scraped_systems
}
self.platform_ids = {
native_id
for key, sys_data in scraped_systems.items()
for native_id in (
sys_data.get("native_id") or key,
*(_native_id_of(key, sys_data, fe) for fe in sys_data.get("files", [])),
)
}
self.native_by_norm = {}
for system in self.systems.values():
self.native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id)
def target_native_ids(self, truth_sid: str) -> tuple[list[str], bool]:
"""The native ids a truth system spans, and whether the first one
is where an addition belongs without asking which core reads it."""
scraped_systems = self.scraped_systems
scraped_key = truth_sid if truth_sid in scraped_systems else None
if scraped_key is None:
scraped_key = norm_to_scraped.get(_norm_system_id(truth_sid))
scraped_key = self.norm_to_scraped.get(_norm_system_id(truth_sid))
if scraped_key is not None:
sys_data = scraped_systems[scraped_key]
ids = {
@@ -583,28 +622,28 @@ def build_native_model(
ordered.remove(primary)
ordered.insert(0, primary)
return ordered, primary in ids or len(ordered) == 1
direct = native_by_norm.get(_norm_system_id(truth_sid))
direct = self.native_by_norm.get(_norm_system_id(truth_sid))
return ([direct] if direct else [truth_sid]), True
# Pass 2: apply the truth onto that grouping.
for truth_sid in sorted(truth.get("systems", {})):
truth_sys = truth["systems"][truth_sid]
def _files_of(self, target_ids: list[str]) -> list[NativeFile]:
return [
candidate
for native_id in target_ids
for candidate in self.systems.get(native_id, NativeSystem(native_id)).files
]
def apply(self, truth_sid: str, truth_sys: dict) -> None:
truth_files = truth_sys.get("files", [])
if not truth_files:
continue
return
target_ids, settled_id = _target_native_ids(truth_sid)
target_ids, settled_id = self.target_native_ids(truth_sid)
truth_files = [
entry for entry in truth_files
if (name := str(entry.get("name", "")))
and not name.startswith("_") and not _is_placeholder(name)
]
candidates = [
candidate
for native_id in target_ids
for candidate in systems.get(native_id, NativeSystem(native_id)).files
if candidate.truth is None
]
candidates = [c for c in self._files_of(target_ids) if c.truth is None]
pairs = pair_entries(truth_files, [c.platform or {} for c in candidates])
# The cores that read what the platform files under each native id,
# from the truth entries its declarations pair with.
@@ -613,109 +652,102 @@ def build_native_model(
readers.setdefault(candidates[index].native_system, set()).update(
truth_files[t_index].get("_cores") or ()
)
for candidate in (
c
for native_id in target_ids
for c in systems.get(native_id, NativeSystem(native_id)).files
if c.platform is not None
):
for candidate in (c for c in self._files_of(target_ids) if c.platform is not None):
own = str(candidate.name).casefold()
candidate.namesakes.extend(
entry for entry in truth_files if own in _names(entry)
)
for t_index, truth_entry in enumerate(truth_files):
name = str(truth_entry["name"])
index = pairs.get(t_index)
matched = candidates[index] if index is not None else None
if matched is not None:
matched.truth = truth_entry
checked = checked_hashes(truth_entry) or {}
contradicted = contradicted_hashes(truth_entry, matched.platform)
for field_name in HASH_FIELDS:
if field_name == "md5" and matched.composite_md5:
continue
if field_name in contradicted:
matched.corrections.append(field_name)
report.hashes_corrected.append(
f"{matched.native_system}/{matched.name} {field_name}"
)
elif _hash_values(checked, field_name) and not _hash_values(
comparable(matched.platform), field_name
):
matched.filled.append(field_name)
t_req = truth_entry.get("required")
p_req = (matched.platform or {}).get("required")
# A file a core takes as one of a set has no requirement of
# its own: a platform line cannot say "one of these", so
# truth leaves its value as written rather than claim
# every member optional or every member needed.
if (
t_req is not None
and p_req is not None
and bool(t_req) != bool(p_req)
and not (truth_entry.get("one_of_required") and not t_req)
):
matched.corrections.append("required")
report.required_corrected.append(
f"{matched.native_system}/{matched.name}"
)
paired = pairs.get(t_index)
if paired is not None:
_correct_matched(candidates[paired], truth_entry, self.report)
continue
self._add(truth_sid, truth_entry, target_ids, settled_id, readers)
if is_label(truth_entry):
report.labels += 1
continue
# The emulator installs it: no user is asked to bring it.
if truth_entry.get("bundled"):
continue
def _add(
self,
truth_sid: str,
truth_entry: dict,
target_ids: list[str],
settled_id: bool,
readers: dict[str, set[str]],
) -> None:
"""File a truth entry the platform does not declare, when it can be."""
name = str(truth_entry["name"])
if is_label(truth_entry):
self.report.labels += 1
return
# The emulator installs it: no user is asked to bring it.
if truth_entry.get("bundled"):
return
# A file another core's entry already claimed is still the
# platform's file, not a new one: scph101.bin, declared by two
# PSX cores, was written into RetroDECK's manifest a second time.
declared = [
candidate.platform
for native_id in target_ids
for candidate in systems.get(native_id, NativeSystem(native_id)).files
if candidate.platform is not None
]
if platform_declares(truth_entry, declared):
continue
# A file another core's entry already claimed is still the
# platform's file, not a new one: scph101.bin, declared by two
# PSX cores, was written into RetroDECK's manifest a second time.
declared = [
candidate.platform
for candidate in self._files_of(target_ids)
if candidate.platform is not None
]
if platform_declares(truth_entry, declared):
return
# The truth knows a file the platform does not declare. Across
# several native ids and no primary, it joins the one whose files
# its cores read: RetroDECK's arcade spans mame and fbneo, and
# MAME device archives were filed as FBNeo BIOS because fbneo
# sorts first. With no single answer it is not written.
native_id = target_ids[0]
if not settled_id:
wanted = set(truth_entry.get("_cores") or ())
shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids}
best = max(shared.values())
winners = [nid for nid, count in shared.items() if count == best]
if not best or len(winners) > 1:
report.unattributed.append(f"{truth_sid}/{name}")
continue
native_id = winners[0]
system = systems.get(native_id)
if system is None:
system = NativeSystem(native_id=native_id, from_platform=False)
systems[native_id] = system
report.systems_added += 1
destination = str(
truth_entry.get("path") or truth_entry.get("destination") or name
# The truth knows a file the platform does not declare. Across
# several native ids and no primary, it joins the one whose files
# its cores read: RetroDECK's arcade spans mame and fbneo, and
# MAME device archives were filed as FBNeo BIOS because fbneo
# sorts first. With no single answer it is not written.
native_id = target_ids[0]
if not settled_id:
wanted = set(truth_entry.get("_cores") or ())
shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids}
best = max(shared.values())
winners = [nid for nid, count in shared.items() if count == best]
if not best or len(winners) > 1:
self.report.unattributed.append(f"{truth_sid}/{name}")
return
native_id = winners[0]
system = self.systems.get(native_id)
if system is None:
system = NativeSystem(native_id=native_id, from_platform=False)
self.systems[native_id] = system
self.report.systems_added += 1
destination = str(
truth_entry.get("path") or truth_entry.get("destination") or name
)
system.files.append(
NativeFile(
name=name,
destination=destination,
native_system=native_id,
truth=truth_entry,
foreign_system=native_id not in self.platform_ids,
composite_md5=self.composite_zips and name.lower().endswith(".zip"),
)
system.files.append(
NativeFile(
name=name,
destination=destination,
native_system=native_id,
truth=truth_entry,
foreign_system=native_id not in platform_ids,
composite_md5=composite_zips and name.lower().endswith(".zip"),
)
)
report.files_added += 1
)
self.report.files_added += 1
def build_native_model(
truth: dict,
scraped: dict | None,
) -> tuple[dict[str, NativeSystem], Report]:
"""Rebuild the platform's systems, corrected by the truth.
Returns the systems keyed by native id, in the platform's own order
first and truth-only additions after, plus what changed.
"""
report = Report()
scraped_systems = (scraped or {}).get("systems", {})
systems = _platform_systems(scraped_systems, report)
truth_pass = _TruthPass(
systems, report, scraped_systems,
(scraped or {}).get("zip_digest") == "composite",
)
for truth_sid in sorted(truth.get("systems", {})):
truth_pass.apply(truth_sid, truth["systems"][truth_sid])
# A reader takes the files in the order the list gives, so the one the
# code looks for first is named first. Only what we add is ordered: what
+49 -35
View File
@@ -134,6 +134,35 @@ def md5_list_support(script: str) -> frozenset[str]:
return frozenset(support)
def _md5_patched(item: str, md5: str | list[str]) -> str:
"""An item's text with only its md5 value replaced."""
return _MD5_VALUE.sub(
lambda m: m.group(1) + _md5_literal(
md5, spaced=not m.group(2).startswith("[\"")
),
item,
count=1,
)
def _appended_items(
added: list[str], last: re.Match[str], joined: str, original: list[str],
) -> str:
"""The text that follows an entry's last item with the items it gains,
in the form that item is written."""
# Their spacing before the closing brace: '"x"}' or '"x" }'.
tight = not last.group(0).endswith(" }")
added = [a[:-2] + "}" if tight and a.endswith(" }") else a for a in added]
if len(original) == 1:
return ", " + ", ".join(added)
line_start = joined.rfind("\n", 0, last.start()) + 1
indent = joined[line_start:last.start()]
return "," + "".join(
f"\n{indent}{a}" + ("," if i < len(added) - 1 else "")
for i, a in enumerate(added)
)
def _md5_literal(value: str | list[str], spaced: bool = True) -> str:
"""An md5 as the script writes it: a quoted string, or a list of them
with Batocera's spacing inside the brackets (`[ "a", "b" ]`)."""
@@ -152,7 +181,7 @@ def _note_key(text: str) -> tuple[str, str]:
return (path.group(1) if path else "", member.group(1) if member else "")
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Write Batocera's batocera-systems, corrected."""
# checkBios compares one md5 for a plain file. altmd5 is read only for
@@ -180,7 +209,7 @@ class Exporter(BaseExporter):
super().__init__()
# The emulator and core each system entry of the original is gated
# on, read by render.
self._gates: dict[str, tuple[str, str] | None] = {}
self._gates: dict[str, tuple[str, str | None] | None] = {}
# The items the pinned checker reads an md5 list for, read by
# render from the platform's own file.
self._md5_lists: frozenset[str] = frozenset()
@@ -338,11 +367,11 @@ class Exporter(BaseExporter):
for item in (before or {}).get("biosFiles", [])
if isinstance(item, dict)
}
parts: list[str] = []
for fe in files:
for runner in self._item_runners(fe):
parts.append(self._bios_item(fe, runner, originals))
return parts
return [
self._bios_item(fe, runner, originals)
for fe in files
for runner in self._item_runners(fe)
]
def _item_runners(self, fe: NativeFile) -> list[list[str] | None]:
"""One item per runner an addition names. None keeps the original's."""
@@ -431,7 +460,6 @@ class Exporter(BaseExporter):
trailing[key] = line[hash_at:].rstrip()
return trailing, leading
def _entry_block(
self,
system: NativeSystem,
@@ -443,7 +471,9 @@ class Exporter(BaseExporter):
before = self._parse_entry(original)
own = self._own_entry(system, before)
items = self._bios_items(files, own)
indent = _ENTRY_START.match(original[0]).group(1)
start = _ENTRY_START.match(original[0])
assert start is not None, original[0]
indent = start.group(1)
one_line = len(original) == 1 and not trailing and not leading
if one_line:
return [self._entry_line(system, files, before, indent)]
@@ -483,7 +513,7 @@ class Exporter(BaseExporter):
before = self._parse_entry(original)
own = self._own_entry(system, before)
wanted: dict[tuple, list[dict]] = {}
order: list[tuple[tuple, dict]] = []
order: list[tuple[tuple, str]] = []
for text in self._bios_items(files, own):
item = ast.literal_eval(text)
key = tuple(item.get(k) for k in ("file", "zippedFile", "emulator", "core"))
@@ -517,14 +547,7 @@ class Exporter(BaseExporter):
continue
if {k for k in {*ours, *theirs} if ours.get(k) != theirs.get(k)} - {"md5"}:
return None
patched = _MD5_VALUE.sub(
lambda m: m.group(1) + _md5_literal(
ours["md5"], spaced=not m.group(2).startswith("[\"")
),
match.group(0),
count=1,
)
edits.append((match.start(), match.end(), patched))
edits.append((match.start(), match.end(), _md5_patched(match.group(0), ours["md5"])))
if last is None:
return None
@@ -535,19 +558,7 @@ class Exporter(BaseExporter):
if seen[key] > consumed.get(key, 0):
added.append(text)
if added:
# Their spacing before the closing brace: '"x"}' or '"x" }'.
tight = not last.group(0).endswith(" }")
added = [a[:-2] + "}" if tight and a.endswith(" }") else a for a in added]
if len(original) == 1:
insert = ", " + ", ".join(added)
else:
line_start = joined.rfind("\n", 0, last.start()) + 1
indent = joined[line_start:last.start()]
insert = "," + "".join(
f"\n{indent}{a}" + ("," if i < len(added) - 1 else "")
for i, a in enumerate(added)
)
edits.append((last.end(), last.end(), insert))
edits.append((last.end(), last.end(), _appended_items(added, last, joined, original)))
for start, end, text in sorted(edits, reverse=True):
joined = joined[:start] + text + joined[end:]
@@ -638,7 +649,8 @@ class Exporter(BaseExporter):
spans = self._entry_spans(body)
for key, (start, end) in spans.items():
parsed = self._parse_entry(body[start:end + 1]) or {}
own = parsed.get(key) if isinstance(parsed.get(key), dict) else {}
value = parsed.get(key)
own = value if isinstance(value, dict) else {}
emulator, core = own.get("emulator"), own.get("core")
self._gates[key] = (
(emulator, core if isinstance(core, str) else None)
@@ -716,9 +728,11 @@ class Exporter(BaseExporter):
issues.append(f"system absent: {system.native_id}")
continue
declared = {bios.get("file", "") for bios in entry.get("biosFiles", [])}
for fe in files:
if self.declared_path(fe) not in declared:
issues.append(f"absent: {system.native_id}/{fe.name}")
issues.extend(
f"absent: {system.native_id}/{fe.name}"
for fe in files
if self.declared_path(fe) not in declared
)
for native_id, entry in exported.items():
if not entry.get("biosFiles"):
+1 -1
View File
@@ -18,7 +18,7 @@ SOURCE_URL = (
)
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Serve BizHawk's FirmwareDatabase.cs as BizHawk wrote it."""
@staticmethod
+7 -5
View File
@@ -22,6 +22,7 @@ from common import _norm_system_id, resolve_platform_cores, unresolved_platform_
from exporter.baseline import HASH_FIELDS, NativeSystem, _hash_values
from launchers import _names as launcher_names
def _tails(path: str) -> list[str]:
"""Every trailing run of segments of a path, longest first."""
parts = [p for p in path.casefold().strip("/").split("/") if p]
@@ -431,11 +432,12 @@ class EntryCategories:
def cited(f: dict) -> dict:
return {k: f[k] for k in ("name", "source_ref") if f.get(k)}
found: dict[int, dict] = {}
for values in declared.values():
for value in values:
for position, f in by_hash_index.get(value, ()):
found[position] = f
found: dict[int, dict] = {
position: f
for values in declared.values()
for value in values
for position, f in by_hash_index.get(value, ())
}
if found:
return [cited(found[p]) for p in sorted(found)]
named = {position: f for n in names for position, f in by_name_index.get(n, ())}
+2 -4
View File
@@ -27,7 +27,7 @@ SOURCE_URL = (
_MD5 = re.compile(r"^[0-9a-f]{32}$")
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Write EmuDeck's checkBIOS.sh, corrected."""
@staticmethod
@@ -227,7 +227,5 @@ class Exporter(BaseExporter):
if not _RE_LOCAL_HASHES.search(body):
# A check with no hash list is a path check, not a hash check.
continue
for md5 in md5s:
if md5 not in body:
issues.append(f"absent from {name}: {md5}")
issues.extend(f"absent from {name}: {md5}" for md5 in md5s if md5 not in body)
return issues
+5 -4
View File
@@ -11,6 +11,7 @@ import io
import json
import zipfile
from collections import OrderedDict
from typing import Union
from .base_exporter import BaseExporter
from .baseline import NativeFile, NativeSystem, Report
@@ -42,7 +43,7 @@ def rebuild_archive(original: bytes, member: str, text: str) -> bytes:
return buffer.getvalue()
class Exporter(BaseExporter):
class Exporter(BaseExporter[Union[str, bytes]]):
"""Write MiSTer's bios_db.json, corrected."""
@staticmethod
@@ -99,8 +100,8 @@ class Exporter(BaseExporter):
"""
return fe.record_hash(field_name)
def _by_path(self, systems: dict[str, NativeSystem]) -> dict[str, object]:
indexed: dict[str, object] = {}
def _by_path(self, systems: dict[str, NativeSystem]) -> dict[str, NativeFile]:
indexed: dict[str, NativeFile] = {}
for system in systems.values():
for fe in system.files:
if fe.destination:
@@ -173,7 +174,7 @@ class Exporter(BaseExporter):
def validate(
self,
systems: dict[str, NativeSystem],
produced: dict[str, str],
produced: dict[str, str | bytes],
) -> list[str]:
try:
database = json.loads(produced[_DB_NAME])
+89 -65
View File
@@ -42,6 +42,36 @@ _SYSTEM_BLOCK = re.compile(r"<system\b.*?</system>", re.S)
_BIOS_ELEMENT = re.compile(r"[ \t]*<bios\b.*?/>", re.S)
def _bios_line(attrs: dict[str, str]) -> str:
rendered = " ".join(f"{k}={quoteattr(v)}" for k, v in attrs.items())
return f" <bios {rendered} />"
def _block_body(
children: list[dict[str, str] | str],
elements: dict[str, tuple[NativeFile, str]],
raw: dict[str, str],
) -> list[str]:
"""One block of theirs, each element corrected where ours differs."""
body: list[str] = []
for child in children:
if isinstance(child, str):
body.append(f" {child}")
continue
path = child.get("path", "")
mine = elements.pop(path, None)
kept = raw.get(" ".join(path.split()))
if kept is not None and (mine is None or _stated(mine[1]) == _stated(kept)):
body.append(kept)
elif kept is not None and mine is not None and _stated(
patched := patch_element(kept, mine[1])
) == _stated(mine[1]):
body.append(patched)
else:
body.append(mine[1] if mine else _bios_line(child))
return body
def _stated(text: str) -> dict[str, str]:
"""What an element says, without its layout: attribute order, spacing,
line breaks inside a value and the case of a digest are not content."""
@@ -110,7 +140,7 @@ def _original_elements(original: str) -> list[dict[str, str]]:
return blocks
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Write Recalbox's es_bios.xml, corrected."""
@staticmethod
@@ -299,6 +329,50 @@ class Exporter(BaseExporter):
return False
return bool(fe.hashes("md5")) and bool(fe.cores())
def _their_blocks(self, original: str) -> list[tuple[str, str, list[dict[str, str] | str]]]:
"""Recalbox's blocks: platform, full name, and each bios element or
comment they hold."""
if not original:
return []
try:
root = parse_untrusted_xml(original, self.native_filename(), comments=True)
except (ParseError, ValueError) as exc:
# Rebuilt from our model alone, the export would drop every
# system we do not transcribe and the maintainer's comments.
raise ValueError(
f"Recalbox's {self.native_filename()} does not parse ({exc}); "
"fetch it again with --refresh-cache"
) from exc
if root is None:
return []
return [
(s.get("platform", ""), s.get("fullname", ""), [
f"<!--{child.text}-->" if child.tag is Comment else dict(child.attrib)
for child in s
if child.tag is Comment or child.tag == "bios"
])
for s in root.iter("system")
]
def _our_elements(
self, systems: dict[str, NativeSystem],
) -> dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]]:
ours: dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]] = {}
for system in systems.values():
# Two additions at one path (two cores, two dumps) are one
# element: keyed by path, the second replaced the first and its
# md5 left the file while both were counted added.
at_path: dict[str, list[NativeFile]] = {}
for fe in system.files:
if self.writable(fe):
at_path.setdefault(self._path(fe), []).append(fe)
if at_path:
ours[system.native_id] = (system, {
path: (group[0], self._bios_element(group[0], system.native_id, tuple(group[1:])))
for path, group in at_path.items()
})
return ours
def render(
self,
systems: dict[str, NativeSystem],
@@ -316,27 +390,8 @@ class Exporter(BaseExporter):
# and its system order with it. A platform can hold several blocks
# (Pentagon and Scorpion are both zxspectrum), and an entry the
# maintainer commented out stays commented out.
theirs: list[tuple[str, str, list[dict[str, str] | str]]] = []
original = originals.get(self.native_filename(), "")
if original:
try:
root = parse_untrusted_xml(original, self.native_filename(), comments=True)
except (ParseError, ValueError) as exc:
# Rebuilt from our model alone, the export would drop every
# system we do not transcribe and the maintainer's comments.
raise ValueError(
f"Recalbox's {self.native_filename()} does not parse ({exc}); "
"fetch it again with --refresh-cache"
) from exc
if root is not None:
theirs = [
(s.get("platform", ""), s.get("fullname", ""), [
f"<!--{child.text}-->" if child.tag is Comment else dict(child.attrib)
for child in s
if child.tag is Comment or child.tag == "bios"
])
for s in root.iter("system")
]
theirs = self._their_blocks(original)
# Elements of theirs written back as they stand, by (platform, path).
held = {
@@ -353,24 +408,7 @@ class Exporter(BaseExporter):
and not self.writable(fe)
and (system.native_id, " ".join(self._path(fe).split())) in held
}
ours: dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]] = {}
for system in systems.values():
# Two additions at one path (two cores, two dumps) are one
# element: keyed by path, the second replaced the first and its
# md5 left the file while both were counted added.
at_path: dict[str, list[NativeFile]] = {}
for fe in system.files:
if self.writable(fe):
at_path.setdefault(self._path(fe), []).append(fe)
if at_path:
ours[system.native_id] = (system, {
path: (group[0], self._bios_element(group[0], system.native_id, tuple(group[1:])))
for path, group in at_path.items()
})
def element(attrs: dict[str, str]) -> str:
rendered = " ".join(f"{k}={quoteattr(v)}" for k, v in attrs.items())
return f" <bios {rendered} />"
ours = self._our_elements(systems)
def emit(platform: str, fullname: str, body: list[str], opening: str = "") -> None:
stated = _stated(opening) if opening else {}
@@ -392,23 +430,7 @@ class Exporter(BaseExporter):
for index, (platform, fullname, children) in enumerate(theirs):
elements = ours.get(platform, (None, {}))[1]
raw = written[index] if index < len(written) else {}
body: list[str] = []
for child in children:
if isinstance(child, str):
body.append(f" {child}")
continue
path = child.get("path", "")
mine = elements.pop(path, None)
kept = raw.get(" ".join(path.split()))
if kept is not None and (mine is None or _stated(mine[1]) == _stated(kept)):
body.append(kept)
elif kept is not None and mine is not None and _stated(
patched := patch_element(kept, mine[1])
) == _stated(mine[1]):
body.append(patched)
else:
body.append(mine[1] if mine else element(child))
blocks.append((platform, fullname, body))
blocks.append((platform, fullname, _block_body(children, elements, raw)))
# An addition joins the block named like its file, else the first
# block of its platform.
@@ -446,18 +468,20 @@ class Exporter(BaseExporter):
return [f"the XML does not parse: {exc}"]
for element in root.iter("bios"):
for attribute in ("path", "md5", "core"):
if not element.get(attribute):
issues.append(
f"es_bios.xsd requires {attribute}: "
f"{element.get('path', '?')}"
)
issues.extend(
f"es_bios.xsd requires {attribute}: "
f"{element.get('path', '?')}"
for attribute in ("path", "md5", "core")
if not element.get(attribute)
)
for element in root.iter("system"):
if not list(element):
issues.append(f"empty system: {element.get('platform', '?')}")
for attribute in ("fullname", "platform"):
if not element.get(attribute):
issues.append(f"es_bios.xsd requires {attribute} on system")
issues.extend(
f"es_bios.xsd requires {attribute} on system"
for attribute in ("fullname", "platform")
if not element.get(attribute)
)
exported = {
element.get("path", "").casefold() for element in root.iter("bios")
+17 -12
View File
@@ -46,7 +46,7 @@ def keep_blank_lines(original: str, produced: str) -> str:
return _TOP_KEY.sub(separate, produced)
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Write RetroBat's batocera-systems.json, corrected."""
# One md5 per entry, compared as Batocera's checkBios does.
@@ -152,9 +152,10 @@ class Exporter(BaseExporter):
if fe.platform is not None and fe.platform.get("required") is False:
entry["optional"] = True
ours.setdefault(path, entry)
bios_files = []
for theirs in (base.get(key) or {}).get("biosFiles", []):
bios_files.append(ours.pop(theirs.get("file"), theirs))
bios_files = [
ours.pop(theirs.get("file"), theirs)
for theirs in (base.get(key) or {}).get("biosFiles", [])
]
bios_files.extend(ours.values())
system_entry: OrderedDict[str, object] = OrderedDict()
system_entry["name"] = self.display_name(system)
@@ -181,11 +182,13 @@ class Exporter(BaseExporter):
issues.append(f"system without a name: {key}")
if not entry.get("biosFiles"):
issues.append(f"empty entry: {key}")
for bios in entry.get("biosFiles", []):
# RetroBat states an unhashed file with an empty md5, so only
# a missing path makes an entry unusable.
if "md5" not in bios or not bios.get("file"):
issues.append(f"incomplete entry: {key}/{bios.get('file', '?')}")
# RetroBat states an unhashed file with an empty md5, so only
# a missing path makes an entry unusable.
issues.extend(
f"incomplete entry: {key}/{bios.get('file', '?')}"
for bios in entry.get("biosFiles", [])
if "md5" not in bios or not bios.get("file")
)
for system, files in self.exportable(systems, require="md5"):
entry = data.get(system.native_id)
@@ -193,7 +196,9 @@ class Exporter(BaseExporter):
issues.append(f"system absent: {system.native_id}")
continue
declared = {bios.get("file") for bios in entry.get("biosFiles", [])}
for fe in files:
if self._path(fe) not in declared:
issues.append(f"absent: {system.native_id}/{fe.name}")
issues.extend(
f"absent: {system.native_id}/{fe.name}"
for fe in files
if self._path(fe) not in declared
)
return issues
+42 -34
View File
@@ -62,7 +62,7 @@ def _matching_keys(
return named if len(named) == 1 else []
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Write RetroDECK's component manifests, corrected."""
@staticmethod
@@ -229,10 +229,10 @@ class Exporter(BaseExporter):
# ATARIOSB.ROM for atari5200 and atari800 with different md5 lists,
# and a name-only key wrote the first of ours over both.
by_key: OrderedDict[tuple[str, str], OrderedDict] = OrderedDict()
for entry in ours:
key = (str(entry.get("filename", "")), str(entry.get("system", "")))
for own in ours:
key = (str(own.get("filename", "")), str(own.get("system", "")))
if key[0] and key not in by_key:
by_key[key] = entry
by_key[key] = own
merged: list[OrderedDict] = []
corrected: set[tuple[str, str]] = set()
@@ -261,31 +261,7 @@ class Exporter(BaseExporter):
if other_revision or not keys:
merged.append(OrderedDict(entry))
continue
declared = entry.get("system")
combined = OrderedDict(entry)
# Only what the format says it corrects: the maintainer's
# description and search paths are theirs (neogeo.zip lost its
# four roms directories to a path that does not exist).
combined.update(
(field, value) for field, value in by_key[keys[0]].items()
if field in cls.carries() and not (field == "system" and declared)
)
# A hash of theirs that ours no longer carries is one the truth
# contradicts: kept, it went on rejecting the dump the emulator
# loads while the summary counted it cleared.
for field in ("md5", "sha256"):
if field in cls.carries() and field not in by_key[keys[0]]:
combined.pop(field, None)
if _md5_set(entry.get("md5")) == _md5_set(combined.get("md5")):
# Their own spelling, and no key where they wrote none: an
# equal empty set wrote "md5": null 39 times.
if "md5" in entry:
combined["md5"] = entry["md5"]
else:
combined.pop("md5", None)
elif isinstance(entry.get("md5"), list) and isinstance(combined.get("md5"), str):
combined["md5"] = [combined["md5"]]
merged.append(combined)
merged.append(cls._corrected(entry, by_key[keys[0]]))
corrected.update(keys)
uncorrected = [key for key in by_key if key not in corrected]
@@ -302,15 +278,47 @@ class Exporter(BaseExporter):
for e in merged
for system in (_systems_of(e) or [""])
}
for index, entry in enumerate(additions or []):
key = (str(entry.get("filename", "")), str(entry.get("system", "")), _paths_key(entry))
if key[0] and key not in held:
held.add(key)
merged.append(entry)
for index, addition in enumerate(additions or []):
slot = (
str(addition.get("filename", "")), str(addition.get("system", "")),
_paths_key(addition),
)
if slot[0] and slot not in held:
held.add(slot)
merged.append(addition)
elif held_back is not None:
held_back.append(index)
return merged
@classmethod
def _corrected(cls, entry: dict, own: OrderedDict) -> OrderedDict:
"""The platform's entry with the fields ours corrects."""
declared = entry.get("system")
combined = OrderedDict(entry)
# Only what the format says it corrects: the maintainer's
# description and search paths are theirs (neogeo.zip lost its
# four roms directories to a path that does not exist).
combined.update(
(field, value) for field, value in own.items()
if field in cls.carries() and not (field == "system" and declared)
)
# A hash of theirs that ours no longer carries is one the truth
# contradicts: kept, it went on rejecting the dump the emulator
# loads while the summary counted it cleared.
for field in ("md5", "sha256"):
if field in cls.carries() and field not in own:
combined.pop(field, None)
if _md5_set(entry.get("md5")) == _md5_set(combined.get("md5")):
# Their own spelling, and no key where they wrote none: an
# equal empty set wrote "md5": null 39 times.
if "md5" in entry:
combined["md5"] = entry["md5"]
else:
combined.pop("md5", None)
elif isinstance(entry.get("md5"), list) and isinstance(combined.get("md5"), str):
combined["md5"] = [combined["md5"]]
return combined
def lands(self, fe: NativeFile) -> bool:
"""An addition the list already held is not written a second time."""
return self.writable(fe) and id(fe) not in getattr(self, "_held_back", set())
+103 -81
View File
@@ -53,7 +53,13 @@ _SEPARATOR = re.compile(r"\s*(?:,\s*(?:and\s+)?|and\s+)")
_EXAMPLES = re.compile(r"\b(?:e\.?g\b|for example|for instance|such as|like)\W*$", re.I)
class Exporter(BaseExporter):
def _aliases(fe: NativeFile) -> list[object]:
"""The other names a file is declared under."""
aliases = fe.native("aliases", []) or []
return list(aliases) if isinstance(aliases, (list, tuple)) else []
class Exporter(BaseExporter[str]):
"""Write RetroPie's scriptmodules, corrected."""
@staticmethod
@@ -332,108 +338,124 @@ class Exporter(BaseExporter):
systems_of: dict[str, set[str]] = {}
for system in systems.values():
for fe in system.files:
for name in [fe.name, *(fe.native("aliases", []) or [])]:
for name in [fe.name, *_aliases(fe)]:
systems_of.setdefault(str(name).lower(), set()).add(fe.native_system)
known = set(systems_of)
self._skipped: dict[str, list[str]] = {}
# Rewritten, with a file of a system no clause lists left out.
self._partial: list[str] = []
self._named: set[int] = set()
produced: dict[str, str] = {}
def skip(reason: str, module: str) -> None:
self._skipped.setdefault(reason, []).append(module)
for relative, (module_id, help_text) in sorted(modules.items()):
build = "libretro" if module_id.startswith("lr-") else "standalone"
core = index[build].get(module_id.removeprefix("lr-").replace("-", "_").lower())
files = by_core.get(core or "", [])
if not files:
skip("which no profiled core matches", module_id)
self._skip("which no profiled core matches", module_id)
continue
listed = self._listed(help_text)
unknown = sorted(listed - known)
if unknown:
skip(
f"whose help text names a file no profile documents yet ({', '.join(unknown)})",
module_id,
)
new_help = self._new_help(module_id, help_text, files, core, systems_of)
if new_help is None:
continue
# A file already listed under one of its other names is not
# missing: proposing the primary would name the same bytes twice.
# A system RetroPie does not have is no package's: lr-geargrafx
# adds pcengine only, not the LaserActive its core also reads.
candidates = [
fe
for fe in files
if not fe.foreign_system
and self._required_for(fe, core)
and not (
{fe.name.lower()}
| {str(a).lower() for a in (fe.native("aliases", []) or [])}
)
& listed
]
filled = {
slot
for fe in files
if ({fe.name.lower()}
| {str(a).lower() for a in (fe.native("aliases", []) or [])}) & listed
and (slot := self._slot_of(fe)) is not None
}
proposed = self._one_per_slot(candidates, filled)
if not proposed:
continue
# A file joins the list of its own system: the clause whose
# names the platform files under that system, and only one.
clauses = self._clauses(help_text)
homes: dict[int, list[NativeFile]] = {}
homeless = False
for fe in proposed:
owners = [
i for i, (_, names, _) in enumerate(clauses)
if fe.native_system in set().union(
*(systems_of.get(n.lower(), set()) for n in names))
]
if len(owners) == 1 and clauses[owners[0]][2] is not None:
homes.setdefault(owners[0], []).append(fe)
else:
homeless = True
# No enumeration of that system to extend, and a sentence we
# would have to write ourselves is a documentation change, not a
# correction. With nothing placed the package is left as is.
if not homes:
skip("whose help text lists no files of that system to add to", module_id)
continue
added = sum(len(self._in_search_order(fes)) for fes in homes.values())
if len(listed) + added > self._longest:
skip("whose help text would grow longer than any it has today", module_id)
continue
new_help = help_text
for i in sorted(homes, reverse=True):
start, _, enumeration = clauses[i]
missing = self._in_search_order(homes[i])
new_help = self._extended(new_help, enumeration, missing)
if len(enumeration[2]) + len(missing) > 1:
new_help = new_help[:start] + _BIOS_NOUN.sub(
r"\1 files", new_help[start:enumeration[0]], count=1
) + new_help[enumeration[0]:]
self._named.update(id(fe) for fe in homes[i])
produced[relative] = originals[relative].replace(
f'rp_module_help="{help_text}"',
f'rp_module_help="{new_help}"',
1,
)
if homeless:
self._partial.append(module_id)
return produced
def _skip(self, reason: str, module: str) -> None:
self._skipped.setdefault(reason, []).append(module)
def _new_help(
self,
module_id: str,
help_text: str,
files: list[NativeFile],
core: str | None,
systems_of: dict[str, set[str]],
) -> str | None:
"""The help sentence with the files it lacks, None when left as is."""
listed = self._listed(help_text)
unknown = sorted(listed - set(systems_of))
if unknown:
self._skip(
f"whose help text names a file no profile documents yet ({', '.join(unknown)})",
module_id,
)
return None
# A file already listed under one of its other names is not
# missing: proposing the primary would name the same bytes twice.
# A system RetroPie does not have is no package's: lr-geargrafx
# adds pcengine only, not the LaserActive its core also reads.
candidates = [
fe
for fe in files
if not fe.foreign_system
and self._required_for(fe, core)
and not (
{fe.name.lower()}
| {str(a).lower() for a in _aliases(fe)}
)
& listed
]
filled = {
slot
for fe in files
if ({fe.name.lower()}
| {str(a).lower() for a in _aliases(fe)}) & listed
and (slot := self._slot_of(fe)) is not None
}
proposed = self._one_per_slot(candidates, filled)
if not proposed:
return None
# A file joins the list of its own system: the clause whose
# names the platform files under that system, and only one.
clauses = self._clauses(help_text)
homes: dict[int, list[NativeFile]] = {}
enumerations: dict[int, tuple[int, int, list[str]]] = {}
homeless = False
for fe in proposed:
owners = [
i for i, (_, names, _) in enumerate(clauses)
if fe.native_system in set().union(
*(systems_of.get(n.lower(), set()) for n in names))
]
enumeration = clauses[owners[0]][2] if len(owners) == 1 else None
if enumeration is not None:
homes.setdefault(owners[0], []).append(fe)
enumerations[owners[0]] = enumeration
else:
homeless = True
# No enumeration of that system to extend, and a sentence we
# would have to write ourselves is a documentation change, not a
# correction. With nothing placed the package is left as is.
if not homes:
self._skip("whose help text lists no files of that system to add to", module_id)
return None
added = sum(len(self._in_search_order(fes)) for fes in homes.values())
if len(listed) + added > self._longest:
self._skip("whose help text would grow longer than any it has today", module_id)
return None
new_help = help_text
for i in sorted(homes, reverse=True):
start = clauses[i][0]
enumeration = enumerations[i]
missing = self._in_search_order(homes[i])
new_help = self._extended(new_help, enumeration, missing)
if len(enumeration[2]) + len(missing) > 1:
new_help = new_help[:start] + _BIOS_NOUN.sub(
r"\1 files", new_help[start:enumeration[0]], count=1
) + new_help[enumeration[0]:]
self._named.update(id(fe) for fe in homes[i])
if homeless:
self._partial.append(module_id)
return new_help
def lands(self, fe: NativeFile) -> bool:
"""An addition lands only where a help sentence now names it.
+1 -1
View File
@@ -30,7 +30,7 @@ SOURCE_URL = (
_FIELDS = (("size", "size"), ("crc", "crc32"), ("md5", "md5"), ("sha1", "sha1"))
class Exporter(BaseExporter):
class Exporter(BaseExporter[str]):
"""Write RomM's known_bios_files.json, corrected."""
def __init__(self) -> None:
+20 -14
View File
@@ -77,7 +77,25 @@ def _sections(original: str) -> list[tuple[str, list[str]]]:
return sections
class Exporter(BaseExporter):
def _rom_fields(fe: NativeFile, name: str) -> list[str]:
"""The fields of a rom line, in the order clrmamepro writes them."""
parts = [f"name {name}"]
size = fe.size()
if size:
parts.append(f"size {size}")
crc = fe.record_hash("crc32")
if crc:
parts.append(f"crc {crc.upper()}")
md5 = fe.record_hash("md5")
if md5:
parts.append(f"md5 {md5}")
sha1 = fe.record_hash("sha1")
if sha1:
parts.append(f"sha1 {sha1}")
return parts
class Exporter(BaseExporter[str]):
"""Write libretro's System.dat, corrected."""
@staticmethod
@@ -184,19 +202,7 @@ class Exporter(BaseExporter):
if not any(fe.hash(h) for h in ("crc32", "md5", "sha1")):
continue
name = _quote(self._rom_name(fe), quoted)
parts = [f"name {name}"]
size = fe.size()
if size:
parts.append(f"size {size}")
crc = fe.record_hash("crc32")
if crc:
parts.append(f"crc {crc.upper()}")
md5 = fe.record_hash("md5")
if md5:
parts.append(f"md5 {md5}")
sha1 = fe.record_hash("sha1")
if sha1:
parts.append(f"sha1 {sha1}")
parts = _rom_fields(fe, name)
if name in rendered:
if fe.platform is None:
self._shadowed.add(id(fe))