diff --git a/backend/tests/utils/test_gamelist_exporter.py b/backend/tests/utils/test_gamelist_exporter.py
index b3f283d36..aacf8fb78 100644
--- a/backend/tests/utils/test_gamelist_exporter.py
+++ b/backend/tests/utils/test_gamelist_exporter.py
@@ -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(
+ """
+
+
+ ./Super Mario World (USA).sfc
+ true
+
+
+""",
+ 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,
+ """
+
+
+ ./Super Mario World (USA).sfc
+ true
+
+
+ ./Hacks/Super Mario World (USA).sfc
+ Kaizo
+ 9
+
+
+""",
+ )
+
+ 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 , inside it, and inside a ."""
+ platform, _ = platform_with_roms
+ gamelist = _write_gamelist(
+ isolated_filesystem,
+ platform,
+ """
+
+
+
+
+
+ ./Super Mario World (USA).sfc
+
+ true
+
+
+""",
+ )
+
+ 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 (
+ '',
+ "",
+ "",
+ "",
+ ):
+ assert content.count(kept) == 1, kept
+ assert content.index("") < content.index("")
+
+ parsed = [
+ (g.findtext("path"), g.findtext("favorite"))
+ for g in GamelistHandler()._iter_game_elements(gamelist)
+ ]
+ assert parsed == [("./Super Mario World (USA).sfc", "true")]
diff --git a/backend/tests/utils/test_pegasus_exporter.py b/backend/tests/utils/test_pegasus_exporter.py
index a8d2c139a..c1d059ca0 100644
--- a/backend/tests/utils/test_pegasus_exporter.py
+++ b/backend/tests/utils/test_pegasus_exporter.py
@@ -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"
diff --git a/backend/utils/gamelist_exporter.py b/backend/utils/gamelist_exporter.py
index a17f80d26..45f368722 100644
--- a/backend/utils/gamelist_exporter.py
+++ b/backend/utils/gamelist_exporter.py
@@ -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"{body}")
+ parser = ET.XMLParser(target=TreeBuilder(insert_comments=True, insert_pis=True))
+ parser.feed(f"{body}")
+ 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)."""
diff --git a/backend/utils/pegasus_exporter.py b/backend/utils/pegasus_exporter.py
index 67545721f..d0e307266 100644
--- a/backend/utils/pegasus_exporter.py
+++ b/backend/utils/pegasus_exporter.py
@@ -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,