fix(export): harden the gamelist and Pegasus merge against review findings

Decode both files with utf-8-sig so a BOM from a Windows editor no longer
blocks the gamelist parse or hides the Pegasus collection header. Parse
gamelist.xml with comments and processing instructions retained so they
are written back. Keep a second <game> whose path shares a filename with
an earlier one as an unmanaged entry instead of overwriting it. Index a
Pegasus block by the top folder of each listed file as well, so a block
listing the discs of a game folder merges into RomM's multi-file entry.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Sam DornanandClaude Fable 5.1 committed 2026-09-05 20:45:50 -05:00
1 parent 08c9d1862b
commit 6bc88f5cb3
4 files changed
+200 -7

No files matched your search

@@ -807,3 +807,114 @@ async def test_export_platform_to_file_refuses_to_overwrite_unparseable_gamelist
exporter = GamelistExporter(local_export=True)
assert await exporter.export_platform_to_file(platform.id, request=None) is False
assert gamelist.read_text() == broken
async def test_export_platform_to_file_reads_bom_prefixed_gamelist(
platform_with_roms, isolated_filesystem
):
"""A UTF-8 BOM, as Windows editors write it, does not block the merge."""
platform, _ = platform_with_roms
gamelist = isolated_filesystem.platform_dir(platform) / "gamelist.xml"
gamelist.parent.mkdir(parents=True, exist_ok=True)
gamelist.write_text(
"""<?xml version="1.0"?>
<gameList>
<game>
<path>./Super Mario World (USA).sfc</path>
<favorite>true</favorite>
</game>
</gameList>
""",
encoding="utf-8-sig",
)
exporter = GamelistExporter(local_export=True)
assert await exporter.export_platform_to_file(platform.id, request=None) is True
games = fromstring(gamelist.read_text(encoding="utf-8")).findall("game")
assert [g.findtext("favorite") for g in games] == ["true"]
async def test_export_platform_to_file_keeps_colliding_filenames(
platform_with_roms, isolated_filesystem
):
"""Two entries whose paths share a filename are both kept: the first is
merged with RomM's data, the second is carried over untouched."""
platform, _ = platform_with_roms
gamelist = _write_gamelist(
isolated_filesystem,
platform,
"""<?xml version="1.0"?>
<gameList>
<game>
<path>./Super Mario World (USA).sfc</path>
<favorite>true</favorite>
</game>
<game>
<path>./Hacks/Super Mario World (USA).sfc</path>
<name>Kaizo</name>
<playcount>9</playcount>
</game>
</gameList>
""",
)
exporter = GamelistExporter(local_export=True)
assert await exporter.export_platform_to_file(platform.id, request=None) is True
by_path = {
g.findtext("path"): g for g in fromstring(gamelist.read_text()).findall("game")
}
assert set(by_path) == {
"./Super Mario World (USA).sfc",
"./Hacks/Super Mario World (USA).sfc",
}
assert by_path["./Super Mario World (USA).sfc"].findtext("favorite") == "true"
assert by_path["./Super Mario World (USA).sfc"].find("scrap") is not None
hack = by_path["./Hacks/Super Mario World (USA).sfc"]
assert hack.findtext("name") == "Kaizo"
assert hack.findtext("playcount") == "9"
assert hack.find("scrap") is None
async def test_export_platform_to_file_keeps_comments_and_instructions(
platform_with_roms, isolated_filesystem
):
"""XML comments and processing instructions are written back wherever
they sat: beside <gameList>, inside it, and inside a <game>."""
platform, _ = platform_with_roms
gamelist = _write_gamelist(
isolated_filesystem,
platform,
"""<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="gamelist.xsl"?>
<!-- edited by hand -->
<gameList>
<!-- section: platformers -->
<game>
<path>./Super Mario World (USA).sfc</path>
<!-- do not rescrape -->
<favorite>true</favorite>
</game>
</gameList>
""",
)
exporter = GamelistExporter(local_export=True)
assert await exporter.export_platform_to_file(platform.id, request=None) is True
content = gamelist.read_text()
for kept in (
'<?xml-stylesheet type="text/xsl" href="gamelist.xsl"?>',
"<!-- edited by hand -->",
"<!-- section: platformers -->",
"<!-- do not rescrape -->",
):
assert content.count(kept) == 1, kept
assert content.index("<!-- edited by hand -->") < content.index("<gameList>")
parsed = [
(g.findtext("path"), g.findtext("favorite"))
for g in GamelistHandler()._iter_game_elements(gamelist)
]
assert parsed == [("./Super Mario World (USA).sfc", "true")]
@@ -661,3 +661,71 @@ file: hack.sfc
is False
)
assert _read_metadata_bytes(metadata_file) == b"\xff\xfe not utf-8"
async def test_reads_bom_prefixed_file(
self, snes_platform: Platform, metadata_file: Path
):
"""A UTF-8 BOM does not hide the collection header or the game keys."""
_write_metadata(
metadata_file,
"collection: SNES\nshortname: snes\n\n"
"game: Old\nfile: Super Mario World (USA).sfc\nx-favorite: yes\n",
)
exporter = PegasusExporter(local_export=True)
assert (
await exporter.export_platform_to_file(snes_platform.id, request=None)
is True
)
content = _read_metadata(metadata_file)
assert content.count("collection:") == 1
assert content.startswith("collection: Super Nintendo Entertainment System\n")
assert content.count("game:") == 1
assert _parse_pegasus(content)["games"][0]["x-favorite"] == "yes"
async def test_matches_multi_file_rom_by_folder(
self, admin_user: User, snes_platform: Platform, metadata_file: Path
):
"""A block listing the discs of a game folder merges into RomM's entry
for that folder instead of being duplicated."""
rom = db_rom_handler.add_rom(
Rom(
platform_id=snes_platform.id,
name="Multi Disc Game",
slug="multi-disc-game",
fs_name="Multi Disc Game (USA)",
fs_name_no_tags="Multi Disc Game",
fs_name_no_ext="Multi Disc Game (USA)",
fs_extension="",
fs_path="snes/roms",
multi_file=True,
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
_write_metadata(
metadata_file,
"""collection: SNES
shortname: snes
game: Multi Disc
files:
./Multi Disc Game (USA)/disc1.chd
./Multi Disc Game (USA)/disc2.chd
x-note: discs
""",
)
exporter = PegasusExporter(local_export=True)
assert (
await exporter.export_platform_to_file(snes_platform.id, request=None)
is True
)
content = _read_metadata(metadata_file)
assert "files:" not in content
assert "game: Multi Disc\n" not in content
games = {g["game"]: g for g in _parse_pegasus(content)["games"]}
assert set(games) == {"Super Mario World", "Multi Disc Game"}
assert games["Multi Disc Game"]["file"] == "Multi Disc Game (USA)"
assert games["Multi Disc Game"]["x-note"] == "discs"
+13 -4
View File
@@ -7,6 +7,7 @@ from xml.etree.ElementTree import ( # trunk-ignore(bandit/B405)
Element,
ParseError,
SubElement,
TreeBuilder,
indent,
tostring,
)
@@ -76,7 +77,9 @@ def parse_existing_gamelist(content: str) -> ExistingGamelist:
return existing
body = XML_DECLARATION_RE.sub("", content, count=1)
wrapper = ET.fromstring(f"<romm>{body}</romm>")
parser = ET.XMLParser(target=TreeBuilder(insert_comments=True, insert_pis=True))
parser.feed(f"<romm>{body}</romm>")
wrapper = parser.close()
gamelist = wrapper.find("gameList")
for elem in wrapper:
@@ -88,8 +91,14 @@ def parse_existing_gamelist(content: str) -> ExistingGamelist:
for elem in gamelist:
path_elem = elem.find("path") if elem.tag == "game" else None
if path_elem is not None and path_elem.text:
existing.games[gamelist_path_to_filename(path_elem.text)] = elem
filename = (
gamelist_path_to_filename(path_elem.text)
if path_elem is not None and path_elem.text
else None
)
# A second entry with the same filename is carried over, not dropped.
if filename and filename not in existing.games:
existing.games[filename] = elem
else:
existing.others.append(elem)
@@ -413,7 +422,7 @@ class GamelistExporter:
return ExistingGamelist()
content = await fs_platform_handler.read_file(gamelist_path)
return parse_existing_gamelist(content.decode("utf-8"))
return parse_existing_gamelist(content.decode("utf-8-sig"))
def export_platform_to_xml(self, platform_id: int, request: Request | None) -> str:
"""Export a platform's ROMs to gamelist.xml format (no asset files copied)."""
+8 -3
View File
@@ -170,14 +170,19 @@ class PegasusBlock:
return [line for key, lines in self.fields if key not in skip for line in lines]
def file_names(self) -> set[str]:
"""Each listed filename, plus its top folder (a multi-file ROM's fs_name)."""
names: set[str] = set()
for key, lines in self.fields:
if key != "file":
continue
_, _, value = lines[0].partition(":")
for raw in [value, *lines[1:]]:
if raw.strip():
names.add(Path(raw.strip().removeprefix("./")).name)
if not raw.strip():
continue
path = Path(raw.strip().removeprefix("./"))
names.add(path.name)
if len(path.parts) > 1 and not path.is_absolute():
names.add(path.parts[0])
return names
@@ -505,7 +510,7 @@ class PegasusExporter:
return ExistingPegasus()
content = await fs_platform_handler.read_file(metadata_path)
return parse_existing_pegasus(content.decode("utf-8"))
return parse_existing_pegasus(content.decode("utf-8-sig"))
async def export_platform_to_file(
self,