diff --git a/backend/handler/metadata/gamelist_handler.py b/backend/handler/metadata/gamelist_handler.py index 81e443759..881e21944 100644 --- a/backend/handler/metadata/gamelist_handler.py +++ b/backend/handler/metadata/gamelist_handler.py @@ -2,6 +2,7 @@ import glob import os import re import uuid +from collections.abc import Iterator from pathlib import Path from typing import Final, NotRequired, TypedDict from xml.etree.ElementTree import Element # trunk-ignore(bandit/B405) @@ -351,6 +352,33 @@ class GamelistHandler(MetadataHandler): return None + def _iter_game_elements(self, gamelist_path: Path) -> Iterator[Element]: + """Yield each top-level game/folder element of a gamelist.xml. + + Parsing incrementally keeps one entry alive at a time instead of + holding a tree for the whole document, which matters on platforms + with thousands of games. + + ES-DE writes an sibling to , producing + invalid multi-root XML that the incremental parser rejects. Those files + fall back to stripping the element from the document first. Entries are + keyed by filename by the caller, so re-yielding any element already + consumed before the failure is harmless. + """ + try: + for _, elem in ET.iterparse(gamelist_path, events=("end",)): + if elem.tag in ("game", "folder"): + yield elem + elem.clear() + return + except ET.ParseError: + pass + + xml_content = gamelist_path.read_text(encoding="utf-8", errors="replace") + xml_content = ALTERNATIVE_EMULATOR_SELF_CLOSING_RE.sub("", xml_content) + xml_content = ALTERNATIVE_EMULATOR_PAIRED_RE.sub("", xml_content) + yield from ET.fromstring(xml_content) + def _parse_gamelist_xml( self, gamelist_path: Path, platform: Platform ) -> dict[str, GamelistRom]: @@ -367,22 +395,7 @@ class GamelistHandler(MetadataHandler): roms_data: dict[str, GamelistRom] = {} try: - xml_content = gamelist_path.read_text(encoding="utf-8", errors="replace") - xml_content = ALTERNATIVE_EMULATOR_SELF_CLOSING_RE.sub("", xml_content) - xml_content = ALTERNATIVE_EMULATOR_PAIRED_RE.sub("", xml_content) - root: Element | None = ET.fromstring(xml_content) - except ET.ParseError as e: - log.warning(f"Failed to parse gamelist.xml at {gamelist_path}: {e}") - root = None - except Exception as e: - log.error(f"Error reading gamelist.xml at {gamelist_path}: {e}") - root = None - - if root is None: - return roms_data - - try: - for game in root: + for game in self._iter_game_elements(gamelist_path): if game.tag not in ("game", "folder"): continue @@ -466,6 +479,8 @@ class GamelistHandler(MetadataHandler): # Cache the parsed data for this platform self._gamelist_cache[cache_key] = roms_data + except ET.ParseError as e: + log.warning(f"Failed to parse gamelist.xml at {gamelist_path}: {e}") except Exception as e: log.error(f"Error reading gamelist.xml at {gamelist_path}: {e}") diff --git a/backend/tests/handler/metadata/test_gamelist_handler.py b/backend/tests/handler/metadata/test_gamelist_handler.py index e6c3c0ffc..7159bc4e4 100644 --- a/backend/tests/handler/metadata/test_gamelist_handler.py +++ b/backend/tests/handler/metadata/test_gamelist_handler.py @@ -247,3 +247,70 @@ class TestGamelistHandler: assert "Tetris.gb" in roms_data assert roms_data["Tetris.gb"].get("name") == "Tetris" assert roms_data["Tetris.gb"].get("summary") == "Block stacking" + + def test_parse_gamelist_with_trailing_alternative_emulator_sibling(self, tmp_path): + """ES-DE may write the sibling after . + + Games are parsed incrementally, so entries are already consumed by the + time the trailing element makes the document invalid. + """ + gamelist_path = tmp_path / "gamelist.xml" + gamelist_path.write_text( + """ + + + ./Tetris.gb + Tetris + Block stacking + + + ./Zelda.gb + Zelda + Adventure + + + + + +""", + encoding="utf-8", + ) + + handler = GamelistHandler() + platform = SimpleNamespace(id=3, fs_slug="gb") + + with ( + patch( + "handler.metadata.gamelist_handler.get_preferred_media_types", + return_value=[], + ), + patch( + "handler.metadata.gamelist_handler.extract_metadata_from_gamelist_rom", + return_value=dict(MOCK_METADATA), + ), + ): + roms_data = handler._parse_gamelist_xml( + gamelist_path, cast(Platform, platform) + ) + + assert set(roms_data) == {"Tetris.gb", "Zelda.gb"} + assert roms_data["Tetris.gb"].get("name") == "Tetris" + assert roms_data["Zelda.gb"].get("summary") == "Adventure" + + def test_iter_game_elements_yields_only_game_and_folder(self, tmp_path): + gamelist_path = tmp_path / "gamelist.xml" + gamelist_path.write_text( + """ + + gb + ./Tetris.gb + ./Sub + +""", + encoding="utf-8", + ) + + handler = GamelistHandler() + tags = [elem.tag for elem in handler._iter_game_elements(gamelist_path)] + + assert tags == ["game", "folder"]