mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
fix(rom): keep a disc an .m3u lists in place when promoting to a folder (#5076)
This commit is contained in:
@@ -41,7 +41,10 @@ from endpoints.responses.rom import (
|
||||
SimpleRomSchema,
|
||||
)
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from exceptions.fs_exceptions import (
|
||||
RomAlreadyExistsException,
|
||||
RomListedByPlaylistException,
|
||||
)
|
||||
from handler.audit_handler import (
|
||||
AuditActor,
|
||||
AuditDraft,
|
||||
@@ -2436,7 +2439,8 @@ async def convert_rom_to_folder(
|
||||
"""Promote a single-file ROM to a folder ROM in place.
|
||||
|
||||
Keeps the same id and all relations; no rescan. A no-op (clean success) if
|
||||
the ROM is already folder-based. Returns 409 on a folder-name collision.
|
||||
the ROM is already folder-based. Returns 409 on a folder-name collision, or
|
||||
when an .m3u beside the file lists it.
|
||||
"""
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
if not rom:
|
||||
@@ -2446,7 +2450,7 @@ async def convert_rom_to_folder(
|
||||
|
||||
try:
|
||||
rom = await promote_single_file_to_folder(rom)
|
||||
except RomAlreadyExistsException as exc:
|
||||
except (RomAlreadyExistsException, RomListedByPlaylistException) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
|
||||
) from exc
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
@@ -16,13 +17,17 @@ from streaming_form_data.targets import FileTarget, NullTarget
|
||||
from config import ROM_UPLOAD_TMP_BASE, ROM_UPLOAD_TTL
|
||||
from decorators.auth import protected_route
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from exceptions.fs_exceptions import (
|
||||
RomAlreadyExistsException,
|
||||
RomListedByPlaylistException,
|
||||
)
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_rom_visible, get_permissions
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from handler.redis_handler import async_cache
|
||||
from handler.rom_conversion import assert_promotable
|
||||
from handler.rom_upload import (
|
||||
UploadConflictException,
|
||||
UploadDestination,
|
||||
@@ -139,7 +144,7 @@ async def _prepare_rom_destination(
|
||||
return await prepare_upload_destination(
|
||||
rom, folder, filename, overwrite=overwrite
|
||||
)
|
||||
except UploadRejectedException as exc:
|
||||
except (UploadRejectedException, RomListedByPlaylistException) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
||||
) from exc
|
||||
@@ -347,7 +352,9 @@ async def start_chunked_upload(
|
||||
resolve_upload_destination(
|
||||
rom, rel_folder, safe_filename, overwrite=overwrite
|
||||
)
|
||||
except UploadRejectedException as exc:
|
||||
# Refused before any bytes arrive, though promotion checks it again.
|
||||
await asyncio.to_thread(assert_promotable, rom)
|
||||
except (UploadRejectedException, RomListedByPlaylistException) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
||||
) from exc
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
@@ -12,12 +13,15 @@ from fastapi.responses import Response
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.roms.upload import receive_rom_file
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from exceptions.fs_exceptions import (
|
||||
RomAlreadyExistsException,
|
||||
RomListedByPlaylistException,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_rom_visible
|
||||
from handler.database import db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from handler.rom_conversion import promote_single_file_to_folder
|
||||
from handler.rom_conversion import assert_promotable, promote_single_file_to_folder
|
||||
from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS
|
||||
from handler.walkthrough import fetch_gamefaqs_guide, validate_gamefaqs_url
|
||||
from handler.walkthrough.gamefaqs import GameFAQsFetchError
|
||||
@@ -127,7 +131,9 @@ async def add_rom_gamefaqs_walkthrough(
|
||||
url = (body.get("url") or "").strip()
|
||||
try:
|
||||
validate_gamefaqs_url(url)
|
||||
except ValueError as exc:
|
||||
# Checked before the remote fetch, though promotion checks it again.
|
||||
await asyncio.to_thread(assert_promotable, rom)
|
||||
except (ValueError, RomListedByPlaylistException) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
||||
) from exc
|
||||
@@ -142,6 +148,10 @@ async def add_rom_gamefaqs_walkthrough(
|
||||
if rom.has_simple_single_file:
|
||||
try:
|
||||
rom = await promote_single_file_to_folder(rom)
|
||||
except RomListedByPlaylistException as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
||||
) from exc
|
||||
except RomAlreadyExistsException as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
|
||||
|
||||
@@ -40,6 +40,18 @@ class RomAlreadyExistsException(Exception):
|
||||
return self.message
|
||||
|
||||
|
||||
class RomListedByPlaylistException(Exception):
|
||||
def __init__(self, playlist: str) -> None:
|
||||
self.message = (
|
||||
f"{playlist} lists this disc, so moving it into a folder would break "
|
||||
"the playlist. Move the set into a folder of its own first"
|
||||
)
|
||||
super().__init__(self.message)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.message
|
||||
|
||||
|
||||
class FirmwareNotFoundException(Exception):
|
||||
def __init__(self, platform: str) -> None:
|
||||
self.message = f"Firmware not found for platform {hl(platform, color=BLUE)}. {FOLDER_STRUCT_MSG }"
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
import asyncio
|
||||
|
||||
from exceptions.fs_exceptions import (
|
||||
RomAlreadyExistsException,
|
||||
RomListedByPlaylistException,
|
||||
)
|
||||
from handler.database import db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from handler.redis_handler import redis_lock
|
||||
@@ -6,6 +11,7 @@ from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.rom import Rom
|
||||
from utils.m3u import listing_playlist
|
||||
|
||||
# Scans and the watcher skip dot-prefixed entries, so staged files stay unseen.
|
||||
STAGE_PREFIX = ".romm_tmp_"
|
||||
@@ -19,10 +25,23 @@ def promotion_lock_key(rom: Rom) -> str:
|
||||
return f"rom_promotion:{rom.fs_path}/{rom.fs_name_no_ext}"
|
||||
|
||||
|
||||
def assert_promotable(rom: Rom) -> None:
|
||||
"""Refuse to move a lone file into a folder when a playlist beside it lists it.
|
||||
|
||||
Raises:
|
||||
RomListedByPlaylistException: An .m3u in the file's folder lists it.
|
||||
"""
|
||||
if not rom.has_simple_single_file:
|
||||
return
|
||||
playlist = listing_playlist(fs_rom_handler.validate_path(rom.full_path))
|
||||
if playlist:
|
||||
raise RomListedByPlaylistException(playlist)
|
||||
|
||||
|
||||
async def promote_single_file_to_folder(rom: Rom) -> Rom:
|
||||
"""Promote a simple single-file ROM to a folder ROM in place, keeping rom.id
|
||||
and every relation. Idempotent; raises RomAlreadyExistsException on a
|
||||
folder-name collision.
|
||||
folder-name collision and RomListedByPlaylistException when an .m3u lists it.
|
||||
"""
|
||||
async with redis_lock(
|
||||
promotion_lock_key(rom), timeout_seconds=PROMOTION_LOCK_TIMEOUT_SECONDS
|
||||
@@ -33,6 +52,7 @@ async def promote_single_file_to_folder(rom: Rom) -> Rom:
|
||||
async def _promote(rom: Rom) -> Rom:
|
||||
if not rom.has_simple_single_file:
|
||||
return rom
|
||||
await asyncio.to_thread(assert_promotable, rom)
|
||||
|
||||
folder = rom.fs_name_no_ext
|
||||
fs_path = rom.fs_path
|
||||
|
||||
@@ -160,7 +160,8 @@ async def prepare_upload_destination(
|
||||
create the target directory.
|
||||
|
||||
Raises the same as `resolve_upload_destination`, plus
|
||||
RomAlreadyExistsException when the promotion collides with a folder.
|
||||
RomAlreadyExistsException when the promotion collides with a folder and
|
||||
RomListedByPlaylistException when a playlist lists the lone file.
|
||||
"""
|
||||
rel_dir, location = resolve_upload_destination(
|
||||
rom, folder, filename, overwrite=overwrite
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
from tests.factories import make_rom
|
||||
|
||||
from endpoints.roms import walkthrough as walkthrough_endpoint
|
||||
from handler import rom_conversion
|
||||
from handler.database import db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
@@ -330,6 +332,120 @@ def test_screenshot_upload_auto_converts_single_file_rom(
|
||||
assert any(f.category == RomFileCategory.SCREENSHOT for f in after.files)
|
||||
|
||||
|
||||
DISC_1 = "Game (Disc 1).chd"
|
||||
|
||||
|
||||
def _lone_disc(platform: Platform, admin_user: User, lib: Path) -> Rom:
|
||||
"""Disc 1 of a flat set, its own single-file ROM beside disc 2."""
|
||||
rom = _single_file_rom(
|
||||
platform, admin_user, lib, "Game (Disc 1)", fs_extension="chd"
|
||||
)
|
||||
(lib / rom.fs_path / "Game (Disc 2).chd").write_bytes(b"disc2")
|
||||
return rom
|
||||
|
||||
|
||||
MEDIA_UPLOADS = [
|
||||
pytest.param(
|
||||
"manuals/files", "manual.pdf", PDF_BYTES, "application/pdf", id="manual"
|
||||
),
|
||||
pytest.param("soundtracks", "track1.mp3", MP3_BYTES, "audio/mpeg", id="soundtrack"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route,filename,data,mime", MEDIA_UPLOADS)
|
||||
def test_upload_to_a_disc_a_playlist_lists_returns_400(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
real_library: Path,
|
||||
route: str,
|
||||
filename: str,
|
||||
data: bytes,
|
||||
mime: str,
|
||||
):
|
||||
rom = _lone_disc(platform, admin_user, real_library)
|
||||
roms_dir = real_library / rom.fs_path
|
||||
# Windows tools write backslashed paths, often in another case.
|
||||
(roms_dir / "Game.m3u").write_text(
|
||||
"#EXTM3U\r\n.\\GAME (DISC 1).CHD\r\nGame (Disc 2).chd\r\n"
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
f"/api/roms/{rom.id}/{route}",
|
||||
headers={**_auth(access_token), "x-upload-filename": filename},
|
||||
files={filename: (filename, data, mime)},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "Game.m3u" in response.json()["detail"]
|
||||
assert (roms_dir / DISC_1).read_bytes() == b"romdata"
|
||||
assert not (roms_dir / "Game (Disc 1)").exists()
|
||||
after = db_rom_handler.get_rom(rom.id)
|
||||
assert after is not None
|
||||
assert after.fs_name == DISC_1
|
||||
assert [f.file_name for f in after.files] == [DISC_1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route,filename,data,mime", MEDIA_UPLOADS)
|
||||
def test_upload_to_a_lone_disc_no_playlist_lists_promotes_it(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
real_library: Path,
|
||||
route: str,
|
||||
filename: str,
|
||||
data: bytes,
|
||||
mime: str,
|
||||
):
|
||||
rom = _lone_disc(platform, admin_user, real_library)
|
||||
roms_dir = real_library / rom.fs_path
|
||||
(roms_dir / "Other.m3u").write_text("Other (Disc 1).chd\nOther (Disc 2).chd\n")
|
||||
|
||||
response = client.post(
|
||||
f"/api/roms/{rom.id}/{route}",
|
||||
headers={**_auth(access_token), "x-upload-filename": filename},
|
||||
files={filename: (filename, data, mime)},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert (roms_dir / "Game (Disc 1)" / DISC_1).read_bytes() == b"romdata"
|
||||
assert not (roms_dir / DISC_1).exists()
|
||||
after = db_rom_handler.get_rom(rom.id)
|
||||
assert after is not None
|
||||
assert after.fs_name == "Game (Disc 1)"
|
||||
|
||||
|
||||
def test_gamefaqs_import_to_a_disc_a_playlist_lists_returns_400(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
real_library: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
rom = _lone_disc(platform, admin_user, real_library)
|
||||
roms_dir = real_library / rom.fs_path
|
||||
(roms_dir / "Game.m3u").write_text(f"{DISC_1}\nGame (Disc 2).chd\n")
|
||||
fetch = AsyncMock()
|
||||
monkeypatch.setattr(walkthrough_endpoint, "fetch_gamefaqs_guide", fetch)
|
||||
|
||||
response = client.post(
|
||||
f"/api/roms/{rom.id}/walkthroughs/gamefaqs",
|
||||
headers=_auth(access_token),
|
||||
json={"url": "https://gamefaqs.gamespot.com/ps/196821-game/faqs/1"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "Game.m3u" in response.json()["detail"]
|
||||
fetch.assert_not_called()
|
||||
assert (roms_dir / DISC_1).exists()
|
||||
after = db_rom_handler.get_rom(rom.id)
|
||||
assert after is not None
|
||||
assert after.fs_name == DISC_1
|
||||
|
||||
|
||||
async def test_second_upload_racing_a_promotion_keeps_the_rom_in_its_folder(
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
@@ -421,6 +537,30 @@ async def test_promotion_racing_across_workers_does_not_destroy_the_folder(
|
||||
assert inside.read_bytes() == b"romdata"
|
||||
|
||||
|
||||
def test_convert_a_disc_a_playlist_lists_returns_409(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
real_library: Path,
|
||||
):
|
||||
rom = _lone_disc(platform, admin_user, real_library)
|
||||
roms_dir = real_library / rom.fs_path
|
||||
(roms_dir / "Game.m3u").write_text(f"{DISC_1}\nGame (Disc 2).chd\n")
|
||||
|
||||
response = client.post(
|
||||
f"/api/roms/{rom.id}/convert-to-folder", headers=_auth(access_token)
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_409_CONFLICT
|
||||
assert "Game.m3u" in response.json()["detail"]
|
||||
assert (roms_dir / DISC_1).read_bytes() == b"romdata"
|
||||
assert not (roms_dir / "Game (Disc 1)").exists()
|
||||
after = db_rom_handler.get_rom(rom.id)
|
||||
assert after is not None
|
||||
assert after.fs_name == DISC_1
|
||||
|
||||
|
||||
async def test_promotion_waits_for_a_lock_held_by_another_worker(
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
|
||||
@@ -862,6 +862,27 @@ def test_start_into_single_file_rom_rejects_its_own_name(
|
||||
assert refreshed.fs_name == "solo.zip"
|
||||
|
||||
|
||||
def test_start_into_a_file_a_playlist_lists_returns_400(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
rom_upload_fs: Path,
|
||||
tmp_path: Path,
|
||||
):
|
||||
rom = _single_file_rom(platform, admin_user, rom_upload_fs)
|
||||
_write(rom_upload_fs, f"{rom.fs_path}/solo.m3u", b"solo.zip\n")
|
||||
|
||||
response = _start_into_rom(
|
||||
client, access_token, rom, filename="notes.txt", folder=None, total_size=5
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "solo.m3u" in response.json()["detail"]
|
||||
assert not (tmp_path / "uploads").exists()
|
||||
assert (rom_upload_fs / rom.fs_path / "solo.zip").read_bytes() == b"romdata"
|
||||
|
||||
|
||||
def test_complete_collision_does_not_promote_a_single_file_rom(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
|
||||
@@ -1,13 +1,131 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from utils.m3u import (
|
||||
disc_number,
|
||||
first_playlist_entry,
|
||||
generate_m3u_content,
|
||||
listing_playlist,
|
||||
playlist_files,
|
||||
)
|
||||
|
||||
|
||||
class TestListingPlaylist:
|
||||
def test_names_the_playlist_listing_the_disc(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Game.m3u").write_text("Game (Disc 1).chd\nGame (Disc 2).chd\n")
|
||||
|
||||
assert listing_playlist(disc) == "Game.m3u"
|
||||
|
||||
def test_matches_backslashed_entries_ignoring_case(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "GAME.M3U").write_bytes(b"\xef\xbb\xbf.\\GAME (DISC 1).CHD\r\n")
|
||||
|
||||
assert listing_playlist(disc) == "GAME.M3U"
|
||||
|
||||
def test_none_when_no_playlist_lists_the_disc(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Other.m3u").write_text("Other (Disc 1).chd\n")
|
||||
(tmp_path / "notes.txt").write_text("Game (Disc 1).chd\n")
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_none_when_the_playlist_lists_a_namesake_in_another_folder(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Other.m3u").write_text(
|
||||
"Other Set/Game (Disc 1).chd\nOther Set\\Game (Disc 1).chd\n"
|
||||
)
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_matches_a_literal_backslash_in_the_file_name(self, tmp_path):
|
||||
disc = tmp_path / "Game\\Disc 1.chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Game.m3u").write_text("Game\\Disc 1.chd\n")
|
||||
|
||||
assert listing_playlist(disc) == "Game.m3u"
|
||||
|
||||
def test_matches_an_entry_through_a_symlinked_folder(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "link").symlink_to(tmp_path)
|
||||
(tmp_path / "Game.m3u").write_text("link/Game (Disc 1).chd\n")
|
||||
|
||||
assert listing_playlist(disc) == "Game.m3u"
|
||||
|
||||
def test_none_when_the_literal_backslash_file_is_the_one_listed(self, tmp_path):
|
||||
(tmp_path / ".\\Disc 1.chd").write_bytes(b"x")
|
||||
disc = tmp_path / "Disc 1.chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Game.m3u").write_text(".\\Disc 1.chd\n")
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_none_when_the_playlist_names_a_symlinked_discs_target(self, tmp_path):
|
||||
target = tmp_path / "store" / "Game (Disc 1).chd"
|
||||
target.parent.mkdir()
|
||||
target.write_bytes(b"x")
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.symlink_to(target)
|
||||
(tmp_path / "Game.m3u").write_text("store/Game (Disc 1).chd\n")
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_names_the_playlist_listing_a_symlink_to_the_disc(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "links").mkdir()
|
||||
(tmp_path / "links" / "hop.chd").symlink_to(disc)
|
||||
(tmp_path / "Disc 1.chd").symlink_to("links/hop.chd")
|
||||
(tmp_path / "Game.m3u").write_text("Disc 1.chd\n")
|
||||
|
||||
assert listing_playlist(disc) == "Game.m3u"
|
||||
|
||||
def test_none_when_the_playlist_lists_a_hardlink_to_the_disc(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Disc 1.chd").hardlink_to(disc)
|
||||
(tmp_path / "Game.m3u").write_text("Disc 1.chd\n")
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_tolerates_an_entry_through_a_symlink_loop(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "a").symlink_to(tmp_path / "b")
|
||||
(tmp_path / "b").symlink_to(tmp_path / "a")
|
||||
(tmp_path / "Other.m3u").write_text("a/Other.chd\n")
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_ignores_comment_lines(self, tmp_path):
|
||||
disc = tmp_path / "Game (Disc 1).chd"
|
||||
disc.write_bytes(b"x")
|
||||
(tmp_path / "Game.m3u").write_text("#Game (Disc 1).chd\n")
|
||||
|
||||
assert listing_playlist(disc) is None
|
||||
|
||||
def test_none_for_a_namesake_differing_only_in_case(self, tmp_path):
|
||||
listed = tmp_path / "Game.chd"
|
||||
listed.write_bytes(b"x")
|
||||
namesake = tmp_path / "game.chd"
|
||||
namesake.write_bytes(b"y")
|
||||
if listed.samefile(namesake):
|
||||
pytest.skip("case-insensitive filesystem")
|
||||
(tmp_path / "Game.m3u").write_text("Game.chd\n")
|
||||
|
||||
assert listing_playlist(namesake) is None
|
||||
assert listing_playlist(listed) == "Game.m3u"
|
||||
|
||||
def test_none_when_the_folder_is_missing(self, tmp_path):
|
||||
assert listing_playlist(tmp_path / "gone" / "disc.chd") is None
|
||||
|
||||
|
||||
class TestFirstPlaylistEntry:
|
||||
def test_returns_first_entry_relative_to_playlist_folder(self, tmp_path):
|
||||
disc1 = tmp_path / "game (Disc 1).rvz"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -45,34 +46,101 @@ def _disc_order(file: RomFile) -> tuple[bool, int, str]:
|
||||
return (number is None, number or 0, file.file_name)
|
||||
|
||||
|
||||
def first_playlist_entry(m3u_path: Path) -> Path | None:
|
||||
"""Resolve an .m3u playlist to the first disc file it lists.
|
||||
|
||||
Returns:
|
||||
The first non-comment entry, relative to the playlist's folder unless
|
||||
absolute, or None when the playlist can't be read or that entry isn't
|
||||
a file on disk.
|
||||
"""
|
||||
def _playlist_entries(m3u_path: Path) -> list[list[Path]] | None:
|
||||
"""Each disc line's possible paths, literal first since a POSIX name may
|
||||
hold the backslashes Windows playlists separate folders with."""
|
||||
try:
|
||||
lines = m3u_path.read_text(encoding="utf-8-sig", errors="replace").splitlines()
|
||||
except OSError:
|
||||
return None
|
||||
entries = []
|
||||
for line in lines:
|
||||
entry = line.strip()
|
||||
if not entry or entry.startswith("#"):
|
||||
continue
|
||||
# Playlists written on Windows separate folders with backslashes, which
|
||||
# a POSIX file name may also contain, so the literal path is tried first.
|
||||
candidates = [entry]
|
||||
if "\\" in entry:
|
||||
candidates.append(entry.replace("\\", "/"))
|
||||
for candidate in candidates:
|
||||
entry_path = Path(candidate)
|
||||
if not entry_path.is_absolute():
|
||||
entry_path = m3u_path.parent / entry_path
|
||||
if entry_path.is_file():
|
||||
return entry_path
|
||||
entries.append(
|
||||
[
|
||||
path if path.is_absolute() else m3u_path.parent / path
|
||||
for path in map(Path, candidates)
|
||||
]
|
||||
)
|
||||
return entries
|
||||
|
||||
|
||||
def first_playlist_entry(m3u_path: Path) -> Path | None:
|
||||
"""Resolve an .m3u playlist to the first disc file it lists.
|
||||
|
||||
Returns:
|
||||
The first entry's path, or None when the playlist can't be read or that
|
||||
entry isn't a file on disk.
|
||||
"""
|
||||
entries = _playlist_entries(m3u_path)
|
||||
if not entries:
|
||||
return None
|
||||
return next((path for path in entries[0] if path.is_file()), None)
|
||||
|
||||
|
||||
def _path_key(path: Path) -> str:
|
||||
# Only the folders resolve: promotion moves a symlinked disc, not its target.
|
||||
return os.path.normcase(str(path.parent.resolve() / path.name)).casefold()
|
||||
|
||||
|
||||
def _same_entry(a: Path, b: Path) -> bool:
|
||||
"""Whether two paths name one directory entry, so a hardlink is another."""
|
||||
try:
|
||||
if not os.path.samestat(os.stat(a.parent), os.stat(b.parent)):
|
||||
return False
|
||||
if a.name == b.name:
|
||||
return True
|
||||
# A case-insensitive filesystem spells one entry several ways.
|
||||
return a.name.casefold() == b.name.casefold() and os.path.samestat(
|
||||
os.lstat(a), os.lstat(b)
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
# Linux's own limit on symlinks followed while resolving a path.
|
||||
_MAX_LINK_HOPS = 40
|
||||
|
||||
|
||||
def _leads_to(entry: Path, disc: Path) -> bool:
|
||||
"""Whether entry is disc, or a symlink chain that passes through it."""
|
||||
for _ in range(_MAX_LINK_HOPS):
|
||||
if _same_entry(entry, disc):
|
||||
return True
|
||||
try:
|
||||
entry = entry.parent / os.readlink(entry)
|
||||
except OSError:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def listing_playlist(disc: Path) -> str | None:
|
||||
"""The name of an .m3u beside a lone disc that lists it, or None."""
|
||||
# An entry missing as spelled is matched ignoring case, since Windows-authored
|
||||
# playlists often differ in case from the files.
|
||||
target = _path_key(disc)
|
||||
try:
|
||||
playlists = [
|
||||
entry
|
||||
for entry in disc.parent.iterdir()
|
||||
if entry.suffix.lower() == ".m3u" and entry.is_file()
|
||||
]
|
||||
except OSError:
|
||||
return None
|
||||
for playlist in playlists:
|
||||
for candidates in _playlist_entries(playlist) or []:
|
||||
# The path an emulator would open, as first_playlist_entry picks it.
|
||||
on_disk = next((path for path in candidates if path.is_file()), None)
|
||||
if on_disk:
|
||||
if _leads_to(on_disk, disc):
|
||||
return playlist.name
|
||||
elif any(_path_key(path) == target for path in candidates):
|
||||
return playlist.name
|
||||
return None
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user