mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 02:27:52 -06:00
refactor: read listxml through one streamer
scripts/scraper/listxml.py holds the element window, attribute reader, ROM member extraction and open_listxml that romset_dat_importer, mame_devices and arcade_parent_importer each wrote. On mame0289lx.zip and the 19 FBNeo DATs the three produce the same recipes, release and sets as before. Attribute values are entity-decoded everywhere: romset_dat_importer kept f&m.basic.bin where the archive member is f&m.basic.bin. The five comx_eb member names of recipes/mame.json are corrected to what a re-import now writes. A release zip with no or several .xml members is refused by name instead of raising StopIteration.
This commit is contained in:
1 parent
3505eaa835
commit
db1446079a
10 files changed
+317
-254
No files matched your search
@@ -45,7 +45,7 @@ import sys
|
||||
import urllib.parse
|
||||
import zipfile
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Iterator
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import IO
|
||||
@@ -56,13 +56,11 @@ from model.profiles import load_emulator_profiles
|
||||
from core.cli import run_cli
|
||||
from core.hashing import compute_hashes
|
||||
from .base_scraper import download
|
||||
from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members
|
||||
from .romset_dat_importer import (
|
||||
LISTXML_CHUNK,
|
||||
MAME_LISTXML_URL,
|
||||
BlobMismatchError,
|
||||
_api_json,
|
||||
_listxml_opener,
|
||||
_machine_roms,
|
||||
fetch_pack,
|
||||
git_blob_sha,
|
||||
)
|
||||
@@ -129,61 +127,26 @@ class SetEntry:
|
||||
source: str | None = None
|
||||
|
||||
|
||||
_ELEMENT = re.compile(rb"<(machine|game)\b([^>]*)>")
|
||||
_ATTR = re.compile(rb'([\w:-]+)="([^"]*)"')
|
||||
_DEVICE_REF = re.compile(rb'<device_ref\b[^>]*\bname="([^"]+)"')
|
||||
_DISK = re.compile(rb"<disk\b([^>]*)>")
|
||||
# Longer than any start tag the DATs write, shorter than any element.
|
||||
_TAG_TAIL = 4096
|
||||
|
||||
|
||||
def _attrs(raw: bytes) -> dict[str, str]:
|
||||
return {k.decode(): v.decode() for k, v in _ATTR.findall(raw)}
|
||||
|
||||
|
||||
def iter_sets(stream: IO[bytes]) -> Iterator[SetEntry]:
|
||||
"""Every machine or game element of a DAT or -listxml, streamed.
|
||||
|
||||
Attributes come in any order (mame2003 writes ``<game runnable="no"
|
||||
name="neogeo">``), and the document is never held whole: the window
|
||||
keeps only the element being closed.
|
||||
"""
|
||||
buffer = b""
|
||||
while True:
|
||||
chunk = stream.read(LISTXML_CHUNK)
|
||||
buffer += chunk
|
||||
position = 0
|
||||
# Where the next read has to resume: the start of an element still
|
||||
# open, else a tail long enough to hold a start tag cut in two.
|
||||
keep_from = max(0, len(buffer) - _TAG_TAIL)
|
||||
while True:
|
||||
match = _ELEMENT.search(buffer, position)
|
||||
if not match:
|
||||
break
|
||||
closing = b"</" + match.group(1) + b">"
|
||||
end = buffer.find(closing, match.end())
|
||||
if end == -1:
|
||||
keep_from = match.start()
|
||||
break
|
||||
attrs = _attrs(match.group(2))
|
||||
body = buffer[match.end() : end]
|
||||
disks = [_attrs(d) for d in _DISK.findall(body)]
|
||||
yield SetEntry(
|
||||
name=attrs.get("name", ""),
|
||||
romof=attrs.get("romof") or None,
|
||||
isbios=attrs.get("isbios") == "yes",
|
||||
isdevice=attrs.get("isdevice") == "yes",
|
||||
runnable=attrs.get("runnable", "yes") != "no",
|
||||
has_roms=bool(_machine_roms(body)),
|
||||
disks=any(d.get("status") != "nodump" for d in disks),
|
||||
devices=[d.decode() for d in _DEVICE_REF.findall(body)],
|
||||
source=attrs.get("sourcefile"),
|
||||
)
|
||||
position = end + len(closing)
|
||||
keep_from = max(position, len(buffer) - _TAG_TAIL)
|
||||
if not chunk:
|
||||
return
|
||||
buffer = buffer[keep_from:]
|
||||
"""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:
|
||||
@@ -313,7 +276,7 @@ def _fbneo_driver_names(entries: list[SetEntry], names: dict[str, set[str]]) ->
|
||||
|
||||
|
||||
def fbneo_sets(
|
||||
openers: list[Callable[[], IO[bytes]]], names: dict[str, set[str]]
|
||||
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.
|
||||
@@ -1012,11 +975,11 @@ def _cached_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tup
|
||||
return destination, git_blob_sha(destination.read_bytes())
|
||||
|
||||
|
||||
def _file_opener(path: Path) -> Callable[[], IO[bytes]]:
|
||||
def _file_opener(path: Path) -> Opener:
|
||||
return lambda: path.open("rb")
|
||||
|
||||
|
||||
def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]:
|
||||
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":
|
||||
@@ -1035,7 +998,7 @@ def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]:
|
||||
yield opener
|
||||
|
||||
|
||||
def read_sets(openers: list[Callable[[], IO[bytes]]]) -> dict[str, SetEntry]:
|
||||
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] = {}
|
||||
@@ -1059,7 +1022,7 @@ def import_profile(
|
||||
source_url = str(data.get("source") or "")
|
||||
kind = spec["kind"]
|
||||
source: dict[str, object]
|
||||
openers: list[Callable[[], IO[bytes]]]
|
||||
openers: list[Opener]
|
||||
if kind == "listxml":
|
||||
tag = "mame" + str(data["core_version"]).replace(".", "").zfill(4)
|
||||
if offline:
|
||||
@@ -1073,7 +1036,7 @@ def import_profile(
|
||||
"url": MAME_LISTXML_URL.format(tag=tag),
|
||||
"sha256": compute_hashes(pack, frozenset({"sha256"}), cache=False)["sha256"],
|
||||
}
|
||||
index = build_index(read_sets([_listxml_opener(pack)]), spec["marker"])
|
||||
index = build_index(read_sets([lambda: open_listxml(pack)]), spec["marker"])
|
||||
elif kind == "fbneo":
|
||||
if offline:
|
||||
folder = cache_dir / "fbneo-dats"
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Streaming reader for MAME -listxml documents and Logiqx DATs.
|
||||
|
||||
The 0.289 listxml is 311 MB, so a document is read through a sliding window
|
||||
and never held whole. romset_dat_importer, mame_devices and
|
||||
arcade_parent_importer read elements, attributes and ROM members here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
import zipfile
|
||||
from collections.abc import Callable, Collection, Iterator
|
||||
from contextlib import AbstractContextManager, contextmanager
|
||||
from pathlib import Path
|
||||
from typing import IO, NamedTuple
|
||||
|
||||
LISTXML_CHUNK = 8 * 1024 * 1024
|
||||
# Longer than any start tag the documents write, shorter than any element.
|
||||
_TAG_TAIL = 4096
|
||||
|
||||
_ATTR = re.compile(rb'([\w:-]+)="([^"]*)"')
|
||||
_ROM = re.compile(rb"<rom\b([^>]*)>")
|
||||
|
||||
Opener = Callable[[], AbstractContextManager[IO[bytes]]]
|
||||
|
||||
|
||||
class Element(NamedTuple):
|
||||
tag: str
|
||||
attrs: dict[str, str]
|
||||
body: bytes
|
||||
|
||||
|
||||
def attrs(raw: bytes) -> dict[str, str]:
|
||||
"""Attributes of a start tag, entities decoded (``f&m.basic.bin``)."""
|
||||
return {
|
||||
key.decode(): html.unescape(value.decode())
|
||||
for key, value in _ATTR.findall(raw)
|
||||
}
|
||||
|
||||
|
||||
def iter_elements(
|
||||
stream: IO[bytes], tags: Collection[str] = ("machine",), head: bytes = b"",
|
||||
) -> Iterator[Element]:
|
||||
"""Every element named in *tags*, in document order.
|
||||
|
||||
Attributes come in any order (mame2003 writes ``<game runnable="no"
|
||||
name="neogeo">``). The window keeps the element still open from its start
|
||||
tag and grows until that element closes, whatever its size. *head* is
|
||||
what the caller already read from *stream*.
|
||||
"""
|
||||
element = re.compile(rb"<(" + b"|".join(t.encode() for t in tags) + rb")\b([^>]*)>")
|
||||
buffer = head
|
||||
while True:
|
||||
chunk = stream.read(LISTXML_CHUNK)
|
||||
buffer += chunk
|
||||
position = 0
|
||||
# Where the next read has to resume: the start of an element still
|
||||
# open, else a tail long enough to hold a start tag cut in two.
|
||||
keep_from = max(0, len(buffer) - _TAG_TAIL)
|
||||
while match := element.search(buffer, position):
|
||||
closing = b"</" + match.group(1) + b">"
|
||||
end = buffer.find(closing, match.end())
|
||||
if end == -1:
|
||||
keep_from = match.start()
|
||||
break
|
||||
yield Element(
|
||||
match.group(1).decode(), attrs(match.group(2)), buffer[match.end() : end]
|
||||
)
|
||||
position = end + len(closing)
|
||||
keep_from = max(position, len(buffer) - _TAG_TAIL)
|
||||
if not chunk:
|
||||
return
|
||||
buffer = buffer[keep_from:]
|
||||
|
||||
|
||||
def rom_members(
|
||||
body: bytes, dedupe: bool = False, extra: Collection[str] = (),
|
||||
) -> list[dict]:
|
||||
"""Dumped ROMs of one element: name, size, crc32, sha1.
|
||||
|
||||
A ROM without a crc is undumped and left out. *dedupe* keeps the first
|
||||
ROM of each name, as the loader does. *extra* names attributes copied
|
||||
when the ROM writes them.
|
||||
"""
|
||||
members: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for match in _ROM.finditer(body):
|
||||
found = attrs(match.group(1))
|
||||
name, crc = found.get("name", ""), found.get("crc", "").lower()
|
||||
if not name or not crc or (dedupe and name in seen):
|
||||
continue
|
||||
seen.add(name)
|
||||
try:
|
||||
size = int(found.get("size", "0") or 0)
|
||||
except ValueError:
|
||||
size = 0
|
||||
member = {"name": name, "size": size, "crc32": crc, "sha1": found.get("sha1", "").lower()}
|
||||
member.update((key, found[key]) for key in extra if key in found)
|
||||
members.append(member)
|
||||
return members
|
||||
|
||||
|
||||
def xml_members(archive: zipfile.ZipFile) -> list[str]:
|
||||
return [n for n in archive.namelist() if n.lower().endswith(".xml")]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_listxml(path: Path) -> Iterator[IO[bytes]]:
|
||||
"""Byte stream over a -listxml document, plain or as MAME's release zip."""
|
||||
if path.suffix.lower() != ".zip":
|
||||
with path.open("rb") as stream:
|
||||
yield stream
|
||||
return
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
names = xml_members(archive)
|
||||
if len(names) != 1:
|
||||
raise ValueError(f"{path}: expected one .xml member, found {len(names)}")
|
||||
with archive.open(names[0]) as stream:
|
||||
yield stream
|
||||
@@ -20,26 +20,19 @@ from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
import zipfile
|
||||
from collections.abc import Callable, Collection, Iterable, Iterator
|
||||
from collections.abc import Callable, Collection, Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import IO, NamedTuple
|
||||
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
from ._hash_merge import generated_start
|
||||
from .listxml import LISTXML_CHUNK, attrs, iter_elements, rom_members
|
||||
from .mame_parser import _collect_rom_macros, _expand_macros, _parse_rom_entries
|
||||
|
||||
LISTXML_CHUNK = 8 * 1024 * 1024
|
||||
|
||||
_BUILD = re.compile(rb'<mame build="[^"]*\((mame\d+)\)"')
|
||||
_MACHINE = re.compile(rb'<machine name="([^"]+)"([^>]*)>')
|
||||
_ATTR = re.compile(rb'(\w+)="([^"]*)"')
|
||||
_DESCRIPTION = re.compile(rb"<description>(.*?)</description>", re.S)
|
||||
_BIOSSET = re.compile(rb"<biosset\b([^>]*)>")
|
||||
_ROM = re.compile(rb"<rom\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="([^"]+)"')
|
||||
@@ -60,53 +53,21 @@ AMBIGUOUS = "ambiguous"
|
||||
NO_FILE = "no file"
|
||||
|
||||
|
||||
def _attrs(raw: bytes) -> dict[str, str]:
|
||||
return {
|
||||
key.decode(): html.unescape(value.decode())
|
||||
for key, value in _ATTR.findall(raw)
|
||||
}
|
||||
|
||||
|
||||
def _device_roms(body: bytes) -> list[dict]:
|
||||
"""Dumped ROMs of one machine element, first of each name kept."""
|
||||
bios_names = {
|
||||
attrs.get("name", ""): attrs.get("description", "")
|
||||
for attrs in map(_attrs, _BIOSSET.findall(body))
|
||||
found.get("name", ""): found.get("description", "")
|
||||
for found in map(attrs, _BIOSSET.findall(body))
|
||||
}
|
||||
roms: dict[str, dict] = {}
|
||||
for match in _ROM.finditer(body):
|
||||
attrs = _attrs(match.group(1))
|
||||
name, crc = attrs.get("name", ""), attrs.get("crc", "").lower()
|
||||
if not name or not crc or name in roms:
|
||||
continue
|
||||
rom: dict = {
|
||||
"name": name,
|
||||
"size": int(attrs.get("size", "0") or 0),
|
||||
"crc32": crc,
|
||||
"sha1": attrs.get("sha1", "").lower(),
|
||||
}
|
||||
if attrs.get("status") == "baddump":
|
||||
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(attrs.get("bios", ""), "")
|
||||
description = bios_names.get(rom.pop("bios", ""), "")
|
||||
if description:
|
||||
rom["bios_description"] = description
|
||||
roms[name] = rom
|
||||
return list(roms.values())
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_listxml(path: Path) -> Iterator[IO[bytes]]:
|
||||
"""Byte stream over a -listxml document, plain or as MAME's release zip."""
|
||||
if path.suffix.lower() != ".zip":
|
||||
with path.open("rb") as stream:
|
||||
yield stream
|
||||
return
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
names = [n for n in archive.namelist() if n.lower().endswith(".xml")]
|
||||
if len(names) != 1:
|
||||
raise ValueError(f"{path}: expected one .xml member, found {len(names)}")
|
||||
with archive.open(names[0]) as stream:
|
||||
yield stream
|
||||
roms.append(rom)
|
||||
return roms
|
||||
|
||||
|
||||
class MachineLinks(NamedTuple):
|
||||
@@ -144,48 +105,37 @@ def scan_release(stream: IO[bytes]) -> Release:
|
||||
configuration (2184-2198). device_t::searchpath puts the parent ROM
|
||||
device after the device itself (src/emu/device.cpp:140-152).
|
||||
"""
|
||||
tag = ""
|
||||
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] = {}
|
||||
buffer = b""
|
||||
while chunk := stream.read(LISTXML_CHUNK):
|
||||
buffer += chunk
|
||||
if not tag and (build := _BUILD.search(buffer)):
|
||||
tag = build.group(1).decode()
|
||||
position = 0
|
||||
while match := _MACHINE.search(buffer, position):
|
||||
end = buffer.find(b"</machine>", match.end())
|
||||
if end == -1:
|
||||
break
|
||||
name = match.group(1).decode()
|
||||
attrs = _attrs(match.group(2))
|
||||
body = buffer[match.end() : end]
|
||||
isdevice = attrs.get("isdevice") == "yes"
|
||||
romof = attrs.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 = {found.decode() for found in _SOFTWARE_LIST.findall(body)}
|
||||
machines[name] = MachineLinks(
|
||||
romof, isdevice, tuple(sorted(uses)), tuple(sorted(softlists)),
|
||||
attrs.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": attrs.get("sourcefile", ""),
|
||||
"roms": roms,
|
||||
}
|
||||
position = end + len(b"</machine>")
|
||||
buffer = buffer[position:] if position else buffer[-(2 * LISTXML_CHUNK) :]
|
||||
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)
|
||||
|
||||
@@ -49,12 +49,12 @@ from .mame_devices import (
|
||||
floppy_drives,
|
||||
floppy_sample_systems,
|
||||
locate_sources,
|
||||
open_listxml,
|
||||
platform_seeds,
|
||||
profile_seeds,
|
||||
scan_release,
|
||||
source_path,
|
||||
)
|
||||
from .listxml import open_listxml
|
||||
from .mame_parser import parse_mame_source_tree
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ from model.platforms import load_platform_config
|
||||
from core.cli import add_repo_inputs, run_cli
|
||||
from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot
|
||||
from .base_scraper import download, fetch_github_latest_version, github_json
|
||||
from .listxml import Opener, iter_elements, open_listxml, rom_members, xml_members
|
||||
from .logiqx_parser import LogiqxDat, parse_logiqx
|
||||
|
||||
MAX_MEMBER_SIZE = 200 * 1024 * 1024
|
||||
@@ -243,87 +244,26 @@ def recipe_entries(
|
||||
return one_set_per_archive(entries)
|
||||
|
||||
|
||||
_MACHINE = re.compile(rb'<machine name="([^"]+)"([^>]*)>')
|
||||
_ROM = re.compile(
|
||||
rb'<rom name="([^"]+)"(?=[^>]*\bcrc="([0-9a-fA-F]+)")[^>]*>'
|
||||
)
|
||||
_ROM_ATTR = re.compile(rb'(\w+)="([^"]*)"')
|
||||
_ROMOF = re.compile(r'romof="([^"]+)"')
|
||||
LISTXML_CHUNK = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def _machine_roms(blob: bytes) -> list[dict]:
|
||||
"""ROM members of one machine element, undumped ones dropped."""
|
||||
members: list[dict] = []
|
||||
for match in re.finditer(rb"<rom\b([^>]*)>", blob):
|
||||
attrs = {
|
||||
key.decode(): value.decode()
|
||||
for key, value in _ROM_ATTR.findall(match.group(1))
|
||||
}
|
||||
crc = attrs.get("crc", "").lower()
|
||||
name = attrs.get("name", "")
|
||||
if not name or not crc:
|
||||
continue
|
||||
try:
|
||||
size = int(attrs.get("size", "0"))
|
||||
except ValueError:
|
||||
size = 0
|
||||
members.append(
|
||||
{
|
||||
"name": name,
|
||||
"size": size,
|
||||
"crc32": crc,
|
||||
"sha1": attrs.get("sha1", "").lower(),
|
||||
}
|
||||
)
|
||||
return members
|
||||
|
||||
|
||||
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*.
|
||||
|
||||
The document is 311 MB for MAME 0.289, so it is never held whole: the
|
||||
window keeps the element still open from its start tag, and grows until
|
||||
that element closes, whatever its size.
|
||||
"""
|
||||
and those holding one of *targets*."""
|
||||
found: dict[str, tuple[str | None, list[dict]]] = {}
|
||||
buffer = b""
|
||||
while chunk := stream.read(LISTXML_CHUNK):
|
||||
buffer += chunk
|
||||
position = 0
|
||||
keep_from = None
|
||||
while True:
|
||||
match = _MACHINE.search(buffer, position)
|
||||
if not match:
|
||||
break
|
||||
end = buffer.find(b"</machine>", match.end())
|
||||
if end == -1:
|
||||
keep_from = match.start()
|
||||
break
|
||||
name = match.group(1).decode()
|
||||
wanted = selector(name)
|
||||
if wanted or targets:
|
||||
roms = _machine_roms(buffer[match.end() : end])
|
||||
if wanted or holds_target(roms, targets):
|
||||
parent = _ROMOF.search(match.group(2).decode())
|
||||
found[name] = (parent.group(1) if parent else None, roms)
|
||||
position = end + len(b"</machine>")
|
||||
if keep_from is None:
|
||||
# No element open: only a start tag cut by the read can follow.
|
||||
start = buffer.rfind(b"<machine", position)
|
||||
tail = max(position, len(buffer) - len(b"<machine"))
|
||||
keep_from = start if start != -1 else tail
|
||||
buffer = buffer[keep_from:]
|
||||
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: Callable[[], IO[bytes]],
|
||||
open_stream: Opener,
|
||||
label: str,
|
||||
keep: set[str] | None,
|
||||
targets: Targets | None = None,
|
||||
@@ -564,34 +504,19 @@ def fetch_pack(
|
||||
|
||||
|
||||
def _is_listxml(pack: Path) -> bool:
|
||||
"""Whether *pack* holds a MAME -listxml document rather than a DAT."""
|
||||
"""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:
|
||||
names = [n for n in archive.namelist() if n.lower().endswith(".xml")]
|
||||
if not names:
|
||||
if len(xml_members(archive)) != 1:
|
||||
return False
|
||||
with archive.open(names[0]) as handle:
|
||||
return b"<!ELEMENT mame" in handle.read(4096)
|
||||
with pack.open("rb") as handle:
|
||||
with open_listxml(pack) as handle:
|
||||
return b"<!ELEMENT mame" in handle.read(4096)
|
||||
|
||||
|
||||
def _listxml_opener(pack: Path) -> Callable[[], IO[bytes]]:
|
||||
"""A callable giving a fresh byte stream over the listxml document."""
|
||||
if pack.suffix.lower() == ".zip":
|
||||
def opener() -> IO[bytes]:
|
||||
archive = zipfile.ZipFile(pack)
|
||||
name = next(n for n in archive.namelist() if n.lower().endswith(".xml"))
|
||||
# The member keeps the archive alive: its shared file closes
|
||||
# through the archive's own _fpclose.
|
||||
return archive.open(name)
|
||||
|
||||
return opener
|
||||
return lambda: pack.open("rb")
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__)
|
||||
parser.add_argument(
|
||||
@@ -656,7 +581,7 @@ def _selection(args: argparse.Namespace) -> _Selection:
|
||||
def _import_listxml(pack: Path, args: argparse.Namespace, output: str, chosen: _Selection) -> int:
|
||||
label = f"MAME {pack.stem.replace('lx', '')}"
|
||||
entries = listxml_entries(
|
||||
_listxml_opener(pack), label, chosen.keep, chosen.targets, chosen.by_members
|
||||
lambda: open_listxml(pack), label, chosen.keep, chosen.targets, chosen.by_members
|
||||
)
|
||||
dats = {label: pack.stem}
|
||||
print(f" {label}: {len(entries)} sets retenus")
|
||||
|
||||
Reference in new issue
Block a user