refactor(scan): tighten the sigil title id plumbing

Rename embedding now goes through the handler's own rename primitive
(`rename_fs_rom`), so it inherits the library-root path validation and
per-path locking every other write in that class gets, and builds the new
name with the repo's multi-part extension helpers.

Extraction no longer reads files it can never parse: archives, manuals,
soundtracks and screenshots are skipped, and on non-Switch platforms it
stops after the first result, since only Switch looks at a per-file
content type.

Also collapses the two rom-level branches (dropping a closure), gives the
Switch family one home in RomM's own terms instead of deriving it from
sigil's slug string, logs an unrecognized save target layout instead of
dropping it silently, deletes the `ScannedFSRomValues` mirror of `FSRom`,
drops a dead `rom.version` locale key, and slims the sigil Docker builds
to one layer with a filtered clone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-02 16:34:36 -04:00
parent 6534f4ad9d
commit bcafc3d504
30 changed files with 499 additions and 727 deletions

View File

@@ -80,21 +80,25 @@ ENV PATH="/app/.venv/bin:${PATH}"
# Build and install sigil (optional, for title ID extraction)
# Placed after `uv sync` because the extension is compiled with the venv's
# Python so the ABI matches.
# Python so the ABI matches. Keep the pin in sync with docker/Dockerfile.
ARG SIGIL_VERSION=9665f03c04d0f547ed38dd5e5e31916c1da5f2e9
RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil
WORKDIR /tmp/argosy-sigil
RUN git checkout "${SIGIL_VERSION}" \
ARG PYTHON_VERSION=3.13
# One layer so the clone and the cmake tree never reach the image, which rules
# out WORKDIR between the steps.
# trunk-ignore(hadolint/DL3003)
RUN git clone --filter=blob:none https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil \
&& cd /tmp/argosy-sigil \
&& git checkout "${SIGIL_VERSION}" \
&& git submodule update --init --recursive \
&& cmake -B ./build-python -S . -DSIGIL_BUILD_CLI=OFF -DSIGIL_BUILD_TESTS=OFF \
&& cmake --build ./build-python --target sigil
WORKDIR /tmp/argosy-sigil/bindings/python
RUN uv pip install --python /app/.venv/bin/python cffi setuptools \
&& cmake --build ./build-python --target sigil \
&& uv pip install --python /app/.venv/bin/python cffi setuptools \
&& cd ./bindings/python \
&& /app/.venv/bin/python build_sigil.py \
&& mkdir -p /app/.venv/lib/python3.13/site-packages/sigil \
&& cp ./sigil/*.py ./sigil/_sigil.*.so /app/.venv/lib/python3.13/site-packages/sigil/
&& mkdir -p "/app/.venv/lib/python${PYTHON_VERSION}/site-packages/sigil" \
&& cp ./sigil/*.py ./sigil/_sigil.*.so "/app/.venv/lib/python${PYTHON_VERSION}/site-packages/sigil/" \
&& rm -rf /tmp/argosy-sigil
WORKDIR /app
RUN rm -rf /tmp/argosy-sigil
# Copy entrypoint script
COPY entrypoint.sh /entrypoint.sh

View File

@@ -1,6 +1,6 @@
import asyncio
from dataclasses import dataclass
from typing import Any, Final
from typing import Final
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from logger.logger import log
@@ -11,15 +11,17 @@ except ImportError:
sigil = None # type: ignore[assignment]
log.debug("sigil binding not installed, title id extraction disabled")
SWITCH_SIGIL_SLUG: Final = "switch"
# The Switch family needs prod.keys to decrypt headers, and is the only family
# whose files may have their title id embedded in the filename.
SWITCH_PLATFORM_SLUGS: Final = frozenset({UPS.SWITCH, UPS.SWITCH_2})
SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = {
SIGIL_PLATFORM_SLUGS: Final[dict[str, str]] = {
UPS.PSP: "psp",
UPS.PSX: "psx",
UPS.PS2: "ps2",
UPS.PSVITA: "psvita",
UPS.SWITCH: SWITCH_SIGIL_SLUG,
UPS.SWITCH_2: SWITCH_SIGIL_SLUG,
UPS.SWITCH: "switch",
UPS.SWITCH_2: "switch",
UPS.N3DS: "3ds",
UPS.WII: "wii",
UPS.WIIU: "wiiu",
@@ -30,14 +32,6 @@ SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = {
UPS.XBOX360: "xbox360",
}
# The Switch family needs prod.keys to decrypt headers, and is the only family
# whose files may have their title id embedded in the filename.
SWITCH_PLATFORM_SLUGS: Final = frozenset(
slug
for slug, sigil_slug in SIGIL_PLATFORM_SLUGS.items()
if sigil_slug == SWITCH_SIGIL_SLUG
)
# Errors that are expected for arbitrary library files (no title id present,
# format sigil can't parse, missing decryption keys). Logged at debug level.
ROUTINE_SIGIL_ERROR_CODES: Final = frozenset(
@@ -60,20 +54,20 @@ class SigilService:
async def extract_title_id(
self,
platform_slug: UPS | str,
platform_slug: str,
file_path: str,
) -> SigilExtractionResult | None:
if sigil is None:
return None
sigil_slug = SIGIL_PLATFORM_SLUGS.get(platform_slug) # type: ignore[arg-type]
sigil_slug = SIGIL_PLATFORM_SLUGS.get(platform_slug)
if sigil_slug is None:
return None
kwargs: dict[str, Any] = {"platform": sigil_slug, "filename_fallback": False}
try:
result = await asyncio.to_thread(sigil.extract, file_path, **kwargs)
result = await asyncio.to_thread(
sigil.extract, file_path, platform=sigil_slug, filename_fallback=False
)
except Exception as exc:
code = getattr(exc, "code", None)
if code in ROUTINE_SIGIL_ERROR_CODES:

View File

@@ -10,13 +10,7 @@ from rq import Worker, get_current_job
from rq.job import Job, JobStatus
from sqlalchemy.exc import IntegrityError
from config import (
DEV_MODE,
REDIS_URL,
SCAN_TIMEOUT,
SCAN_WORKERS,
TASK_RESULT_TTL,
)
from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL
from config.config_manager import MetadataMediaType
from config.config_manager import config_manager as cm
from endpoints.responses import TaskType
@@ -43,11 +37,7 @@ from handler.filesystem import (
fs_resource_handler,
fs_rom_handler,
)
from handler.filesystem.roms_handler import (
FSRom,
ParsedRomFiles,
ScannedFSRomValues,
)
from handler.filesystem.roms_handler import FSRom, ParsedRomFiles
from handler.metadata import (
meta_gamelist_handler,
meta_hltb_handler,
@@ -384,19 +374,20 @@ def _should_hash_firmware(
def _apply_scanned_values(fs_rom: FSRom, parsed: ParsedRomFiles) -> None:
values = ScannedFSRomValues(
files=parsed.rom_files,
crc_hash=parsed.crc_hash,
md5_hash=parsed.md5_hash,
sha1_hash=parsed.sha1_hash,
ra_hash=parsed.ra_hash,
title_id=parsed.title_id,
save_target=parsed.save_target,
save_target_layout=parsed.save_target_layout,
fs_rom.update(
{
"files": parsed.rom_files,
"crc_hash": parsed.crc_hash,
"md5_hash": parsed.md5_hash,
"sha1_hash": parsed.sha1_hash,
"ra_hash": parsed.ra_hash,
"title_id": parsed.title_id,
"save_target": parsed.save_target,
"save_target_layout": parsed.save_target_layout,
}
)
if parsed.renamed_rom_fs_name:
values["fs_name"] = parsed.renamed_rom_fs_name
fs_rom.update(values)
fs_rom["fs_name"] = parsed.renamed_rom_fs_name
# There's an order of operations here that is important:

View File

@@ -7,7 +7,7 @@ import re
import zlib
from dataclasses import dataclass
from pathlib import Path
from typing import Any, NotRequired, TypedDict
from typing import Any, Final, NotRequired, TypedDict
from anyio import Path as AnyioPath
@@ -29,8 +29,16 @@ from exceptions.fs_exceptions import (
)
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from logger.logger import log
from models.base import compute_file_extension, compute_file_name_no_ext
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout, TrackMeta
from models.rom import (
DOCUMENT_CATEGORIES,
Rom,
RomFile,
RomFileCategory,
SaveTargetLayout,
TrackMeta,
)
from utils import switch
from utils.archives import (
ArchiveReadError,
@@ -109,20 +117,6 @@ class FSRom(TypedDict):
save_target_layout: NotRequired[SaveTargetLayout | None]
class ScannedFSRomValues(TypedDict, total=False):
"""The subset of `FSRom` a file rebuild produces, for `FSRom.update`."""
fs_name: str
files: list[RomFile]
crc_hash: str
md5_hash: str
sha1_hash: str
ra_hash: str
title_id: str | None
save_target: str | None
save_target_layout: SaveTargetLayout | None
class FileHash(TypedDict):
crc_hash: str
md5_hash: str
@@ -201,46 +195,19 @@ class ParsedRomFiles:
renamed_rom_fs_name: str | None = None
def _embed_switch_title_id_in_name(
abs_file_path: Path, title_id: str, title_version: int | None
) -> Path | None:
"""Rename a Switch ROM file to embed ` [TITLEID][vVERSION]` before the
extension.
Returns:
The new absolute path, or None when the file was left untouched.
"""
name = abs_file_path.name
if switch.TITLE_ID_BRACKET_REGEX.search(name):
log.debug(f"{name} already has an embedded title id, skipping rename")
return None
if not switch.TITLE_ID_REGEX.fullmatch(title_id):
log.debug(f"Title id {title_id!r} is not a 16-hex value, skipping rename")
return None
version = title_version if title_version is not None else 0
new_name = (
f"{abs_file_path.stem} [{title_id.upper()}][v{version}]{abs_file_path.suffix}"
)
new_path = abs_file_path.with_name(new_name)
if new_path.exists():
log.warning(
f"Cannot embed title id: target {new_name} already exists, skipping rename"
)
return None
os.rename(abs_file_path, new_path)
log.info(f"Embedded Switch title id: renamed {name} to {new_name}")
return new_path
# File categories that never hold a ROM binary, so sigil has nothing to read.
NON_BINARY_FILE_CATEGORIES: Final = DOCUMENT_CATEGORIES | {
RomFileCategory.SOUNDTRACK,
RomFileCategory.SCREENSHOT,
RomFileCategory.CHEAT,
}
def _parse_save_target_layout(usage: str) -> SaveTargetLayout | None:
try:
return SaveTargetLayout(usage)
except ValueError:
log.warning(f"Unrecognized sigil save target layout {usage!r}")
return None
@@ -252,24 +219,19 @@ def _rom_level_title_values(
return None, None, None
if platform_slug in SWITCH_PLATFORM_SLUGS:
base = next(
chosen = next(
(e for e in extractions if switch.is_base_title_id(e.title_id)), None
)
if base is not None:
return (
base.title_id,
base.save_target,
_parse_save_target_layout(base.usage),
)
if chosen is None:
derived = switch.derive_base_title_id(extractions[0].title_id)
if derived is None:
return None, None, None
# Switch saves are keyed by the base title id itself.
return derived, derived, SaveTargetLayout.FOLDER_EXACT
else:
chosen = extractions[0]
derived = switch.derive_base_title_id(extractions[0].title_id)
if derived is None:
return None, None, None
# Switch saves are keyed by the base title id itself.
return derived, derived, SaveTargetLayout.FOLDER_EXACT
first = extractions[0]
return first.title_id, first.save_target, _parse_save_target_layout(first.usage)
return chosen.title_id, chosen.save_target, _parse_save_target_layout(chosen.usage)
class FSRomsHandler(FSHandler):
@@ -458,23 +420,25 @@ class FSRomsHandler(FSHandler):
# Title id extraction is independent of hashing support: it covers
# non-hashable platforms like Switch.
sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS
is_switch = rom.platform_slug in SWITCH_PLATFORM_SLUGS
sigil_extractions: list[SigilExtractionResult] = []
sigil_service = SigilService()
# Embedding is Switch-only even though sigil covers more platforms.
embed_switch = embed_title_ids and rom.platform_slug in SWITCH_PLATFORM_SLUGS
embed_switch = embed_title_ids and is_switch
renamed_rom_fs_name: str | None = None
async def _extract_title_id(
rom_file: RomFile, abs_file_path: Path
) -> str | None:
async def _extract_title_id(rom_file: RomFile) -> str | None:
"""Populate the file's title id fields, returning its new name if
embedding renamed it on disk."""
if not sigil_platform:
# Only Switch reads a per-file content type, so elsewhere every
# extraction past the first is parsed and then discarded.
if not sigil_platform or (sigil_extractions and not is_switch):
return None
rel_file_path = Path(rom_file.file_path, rom_file.file_name)
extraction = await sigil_service.extract_title_id(
rom.platform_slug, str(abs_file_path)
rom.platform_slug, str(Path(self.base_path, rel_file_path))
)
if extraction is None:
return None
@@ -489,29 +453,12 @@ class FSRomsHandler(FSHandler):
if not (embed_switch and extraction.title_id):
return None
new_path = _embed_switch_title_id_in_name(
abs_file_path, extraction.title_id, extraction.version
new_name = await self._embed_switch_title_id_in_name(
rel_file_path, extraction.title_id, extraction.version
)
if new_path is None:
return None
rom_file.file_name = new_path.name
return new_path.name
async def _append_rom_level_file(file_hash: FileHash) -> str | None:
"""Emit the single RomFile that stands for the whole rom, returning
its new name if embedding renamed it on disk."""
rom_file = self._build_rom_file(
rom=rom,
rom_path=Path(rel_roms_path),
file_name=rom.fs_name,
file_hash=file_hash,
)
rom_files.append(rom_file)
# Archives keep hashes only; sigil reads title ids from the ROM
# binary itself.
if rom_ext in ARCHIVE_READERS:
return None
return await _extract_title_id(rom_file, rom_dir)
if new_name is not None:
rom_file.file_name = new_name
return new_name
cnfg = cm.get_config()
excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES
@@ -619,9 +566,13 @@ class FSRomsHandler(FSHandler):
file_name=file_name,
file_hash=file_hash,
)
# Extract from every file (base, updates, DLC in subfolders), not
# just the top-level one: sigil returns None for unparseable files.
await _extract_title_id(rom_file, abs_file_path)
# Extract from every ROM file (base, updates and DLC in
# subfolders), not just the top-level one.
if (
abs_file_path.suffix.lower() not in ARCHIVE_READERS
and rom_file.category not in NON_BINARY_FILE_CATEGORIES
):
await _extract_title_id(rom_file)
rom_files.append(rom_file)
elif hashable_platform and rom_ext in ARCHIVE_READERS:
# Multi-file archive: compute a composite hash across all
@@ -720,47 +671,56 @@ class FSRomsHandler(FSHandler):
file_hash=_make_file_hash(rom_crc_c, rom_md5_h, rom_sha1_h),
)
)
elif hashable_platform:
try:
crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread(
self._calculate_rom_hashes,
Path(abs_fs_path, rom.fs_name),
)
except zlib.error:
crc_c = 0
md5_h = hashlib.md5(usedforsecurity=False)
sha1_h = hashlib.sha1(usedforsecurity=False)
# A single-file ROM spans exactly one file, so its ROM-level hashes
# are that file's hashes.
rom_crc_c, rom_md5_h, rom_sha1_h = crc_c, md5_h, sha1_h
# Calculate the RA hash if the platform has a slug that matches a known RA slug
if calculate_hashes:
ra_platform = meta_ra_handler.get_platform(rom.platform_slug)
if ra_platform and ra_platform["ra_id"]:
rom_ra_h = await RAHasherService().calculate_hash(
ra_platform,
f"{abs_fs_path}/{rom.fs_name}",
else:
if hashable_platform:
try:
crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread(
self._calculate_rom_hashes,
Path(abs_fs_path, rom.fs_name),
)
except zlib.error:
crc_c = 0
md5_h = hashlib.md5(usedforsecurity=False)
sha1_h = hashlib.sha1(usedforsecurity=False)
renamed_rom_fs_name = await _append_rom_level_file(
_make_file_hash(
# A single-file ROM spans exactly one file, so its ROM-level
# hashes are that file's hashes.
rom_crc_c, rom_md5_h, rom_sha1_h = crc_c, md5_h, sha1_h
# Calculate the RA hash if the platform has a slug that matches a known RA slug
if calculate_hashes:
ra_platform = meta_ra_handler.get_platform(rom.platform_slug)
if ra_platform and ra_platform["ra_id"]:
rom_ra_h = await RAHasherService().calculate_hash(
ra_platform,
f"{abs_fs_path}/{rom.fs_name}",
)
file_hash = _make_file_hash(
crc_c,
md5_h,
sha1_h,
chd_sha1_hash=_chd_sha1_hash(rom_dir),
)
)
else:
renamed_rom_fs_name = await _append_rom_level_file(
FileHash(
else:
file_hash = FileHash(
crc_hash="",
md5_hash="",
sha1_hash="",
chd_sha1_hash="",
)
rom_file = self._build_rom_file(
rom=rom,
rom_path=Path(rel_roms_path),
file_name=rom.fs_name,
file_hash=file_hash,
)
rom_files.append(rom_file)
# Archives keep hashes only; sigil reads title ids from the ROM
# binary itself.
if rom_ext not in ARCHIVE_READERS:
renamed_rom_fs_name = await _extract_title_id(rom_file)
rom_title_id, rom_save_target, rom_save_target_layout = _rom_level_title_values(
rom.platform_slug, sigil_extractions
@@ -926,6 +886,47 @@ class FSRomsHandler(FSHandler):
f"{fs_path}/{old_name}", f"{fs_path}/{new_name}"
)
async def _embed_switch_title_id_in_name(
self, rel_file_path: Path, title_id: str, title_version: int | None
) -> str | None:
"""Rename a Switch ROM file to embed ` [TITLEID][vVERSION]` before the
extension.
Args:
rel_file_path: The file's path relative to the library root.
Returns:
The new file name, or None when the file was left untouched.
"""
name = rel_file_path.name
if switch.TITLE_ID_BRACKET_REGEX.search(name):
log.debug(f"{name} already has an embedded title id, skipping rename")
return None
if not switch.TITLE_ID_REGEX.fullmatch(title_id):
log.debug(f"Title id {title_id!r} is not a 16-hex value, skipping rename")
return None
version = title_version if title_version is not None else 0
extension = compute_file_extension(name)
new_name = (
f"{compute_file_name_no_ext(name)} [{title_id.upper()}][v{version}]"
f"{'.' + extension if extension else ''}"
)
try:
await self.rename_fs_rom(
name, new_name, str(rel_file_path.parent.as_posix())
)
except RomAlreadyExistsException:
log.warning(
f"Cannot embed title id: target {new_name} already exists, skipping rename"
)
return None
log.info(f"Embedded Switch title id: renamed {name} to {new_name}")
return new_name
def get_pico8_cover_url(
self, platform_slug: str, fs_name: str, fs_path: str
) -> str | None:

View File

@@ -4,11 +4,7 @@ from unittest.mock import Mock
import pytest
import adapters.services.sigil as sigil_adapter
from adapters.services.sigil import (
SIGIL_PLATFORM_SLUGS,
SigilExtractionResult,
SigilService,
)
from adapters.services.sigil import SigilExtractionResult, SigilService
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
@@ -19,7 +15,7 @@ class FakeSigilError(Exception):
def make_fake_sigil(extract: Mock) -> types.SimpleNamespace:
return types.SimpleNamespace(SigilError=FakeSigilError, extract=extract)
return types.SimpleNamespace(extract=extract)
def make_result(
@@ -31,12 +27,8 @@ def make_result(
) -> types.SimpleNamespace:
return types.SimpleNamespace(
title_id=title_id,
raw_serial="serial",
save_id=save_id,
platform="switch",
source="binary",
usage=usage,
experimental=False,
switch_content_type=switch_content_type,
title_version=title_version,
)
@@ -91,13 +83,21 @@ class TestSigilService:
)
@pytest.mark.asyncio
# Version 0 is a real base-game version, not a missing one.
@pytest.mark.parametrize(
("content_type", "version"), [("patch", 196608), ("application", 0)]
)
async def test_maps_switch_content_type_and_version(
self, service: SigilService, monkeypatch
self,
service: SigilService,
monkeypatch,
content_type: str,
version: int,
):
extract = Mock(
return_value=make_result(
switch_content_type="patch",
title_version=196608,
switch_content_type=content_type,
title_version=version,
)
)
monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract))
@@ -105,24 +105,8 @@ class TestSigilService:
result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.nsp")
assert result is not None
assert result.content_type == "patch"
assert result.version == 196608
@pytest.mark.asyncio
async def test_version_zero_is_preserved(self, service: SigilService, monkeypatch):
extract = Mock(
return_value=make_result(
switch_content_type="application",
title_version=0,
)
)
monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract))
result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.xci")
assert result is not None
assert result.content_type == "application"
assert result.version == 0
assert result.content_type == content_type
assert result.version == version
@pytest.mark.asyncio
@pytest.mark.parametrize("raw", ["unknown", "", None])
@@ -176,12 +160,3 @@ class TestSigilService:
platform="switch",
filename_fallback=False,
)
def test_platform_slug_mapping(self):
assert SIGIL_PLATFORM_SLUGS[UPS.SWITCH_2] == "switch"
assert SIGIL_PLATFORM_SLUGS[UPS.N3DS] == "3ds"
assert SIGIL_PLATFORM_SLUGS[UPS.NGC] == "gamecube"
assert SIGIL_PLATFORM_SLUGS[UPS.DC] == "dreamcast"
assert SIGIL_PLATFORM_SLUGS[UPS.PS3] == "ps3"
assert SIGIL_PLATFORM_SLUGS[UPS.XBOX] == "xbox"
assert SIGIL_PLATFORM_SLUGS[UPS.XBOX360] == "xbox360"

View File

@@ -730,7 +730,7 @@ def patch_identify_rom(
roms_fs_structure: str,
name_with_no_tags: str,
platform_slug: str,
**config_flags: bool,
embed_switch_title_ids: bool = False,
) -> tuple[Mock, Platform]:
"""Stub out everything `_identify_rom` reaches so only the wiring under test
is exercised, returning the patched db handler and the platform to scan."""
@@ -752,8 +752,8 @@ def patch_identify_rom(
config = MagicMock()
config.SKIP_HASH_CALCULATION = False
for flag, value in config_flags.items():
setattr(config, flag, value)
config.SKIP_TITLE_ID_EXTRACTION = False
config.EMBED_SWITCH_TITLE_IDS = embed_switch_title_ids
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
mocker.patch.object(
@@ -805,84 +805,30 @@ class TestIdentifyRomReassociation:
@pytest.fixture
def patched(self, mocker):
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
fs = scan_module.fs_rom_handler
mocker.patch.object(
fs,
"parse_tags",
return_value=ParsedTags(
version="", revision="", regions=[], languages=[], other_tags=[]
),
)
mocker.patch.object(fs, "get_roms_fs_structure", return_value="test/roms")
mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="New Name")
mocker.patch.object(
fs,
"get_rom_files",
AsyncMock(
return_value=ParsedRomFiles(
rom_files=[],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="",
)
return patch_identify_rom(
mocker,
parsed=ParsedRomFiles(
rom_files=[],
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
ra_hash="",
),
roms_fs_structure="test/roms",
name_with_no_tags="New Name",
platform_slug="test",
)
config = MagicMock()
config.SKIP_HASH_CALCULATION = False
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
mocker.patch.object(
scan_module,
"scan_rom",
AsyncMock(return_value=MagicMock(is_identified=False)),
)
db = mocker.patch.object(scan_module, "db_rom_handler")
db.add_rom.return_value = MagicMock(is_identified=False, id=99)
return db
def _platform(self):
platform = Platform(name="Test", slug="test", fs_slug="test")
platform.id = 1
return platform
async def _run(self, db):
fs_rom: FSRom = {
"fs_name": "New Name.zip",
"flat": True,
"nested": False,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
}
await _identify_rom(
platform=self._platform(),
fs_rom=fs_rom,
rom=None,
scan_type=ScanType.HASHES,
roms_ids=[],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
)
async def _run(self, platform: Platform) -> None:
await run_identify_rom(platform, make_fs_rom("New Name.zip"))
async def test_reassociates_with_missing_entry(self, patched):
db = patched
db, platform = patched
missing = MagicMock(id=42, name="Old Game", fs_name="old.zip")
db.get_matching_missing_rom.return_value = missing
db.update_rom.return_value = missing
await self._run(db)
await self._run(platform)
db.get_matching_missing_rom.assert_called_once_with(
platform_id=1,
@@ -907,7 +853,7 @@ class TestIdentifyRomReassociation:
Without it a renamed Switch file lands as a duplicate and strands the
original entry, along with its collections and notes, as missing.
"""
db = patched
db, platform = patched
db.get_matching_missing_rom.return_value = None
mocker.patch.object(
scan_module.fs_rom_handler,
@@ -924,7 +870,7 @@ class TestIdentifyRomReassociation:
),
)
await self._run(db)
await self._run(platform)
db.get_matching_missing_rom.assert_called_once_with(
platform_id=1,
@@ -935,34 +881,34 @@ class TestIdentifyRomReassociation:
)
async def test_files_are_reconciled_in_place(self, patched):
db = patched
db, platform = patched
db.get_matching_missing_rom.return_value = None
db.sync_rom_files.return_value = SyncedRomFiles(
files=[], orphaned_cover_paths=[]
)
await self._run(db)
await self._run(platform)
# Rows are reconciled against the scan, so file ids survive the rescan.
db.sync_rom_files.assert_called_once_with(99, [])
async def test_orphaned_soundtrack_covers_are_unlinked(self, patched, mocker):
db = patched
db, platform = patched
db.get_matching_missing_rom.return_value = None
db.sync_rom_files.return_value = SyncedRomFiles(
files=[], orphaned_cover_paths=["covers/track01.png"]
)
remove = mocker.patch.object(scan_module, "remove_persisted_cover")
await self._run(db)
await self._run(platform)
remove.assert_called_once_with("covers/track01.png")
async def test_creates_new_entry_when_no_match(self, patched):
db = patched
db, platform = patched
db.get_matching_missing_rom.return_value = None
await self._run(db)
await self._run(platform)
db.get_matching_missing_rom.assert_called_once()
# No reassociation update happens on the create path.
@@ -996,8 +942,7 @@ class TestIdentifyRomTitleIdEmbedRename:
roms_fs_structure="switch/roms",
name_with_no_tags="Game",
platform_slug="switch",
SKIP_TITLE_ID_EXTRACTION=False,
EMBED_SWITCH_TITLE_IDS=True,
embed_switch_title_ids=True,
)
db.get_matching_missing_rom.return_value = None
return db, platform
@@ -1042,8 +987,6 @@ class TestIdentifyRomPersistsFileCategory:
roms_fs_structure="switch/roms",
name_with_no_tags="Game",
platform_slug="switch",
SKIP_TITLE_ID_EXTRACTION=False,
EMBED_SWITCH_TITLE_IDS=False,
)
# The persist loop calls this per saved file; keep it inert.
mocker.patch.object(scan_module, "persist_soundtrack_cover")

View File

@@ -16,11 +16,7 @@ from handler.filesystem.base_handler import (
LANGUAGES_BY_SHORTCODE,
REGIONS_BY_SHORTCODE,
)
from handler.filesystem.roms_handler import (
FileHash,
FSRomsHandler,
_embed_switch_title_id_in_name,
)
from handler.filesystem.roms_handler import FileHash, FSRomsHandler
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout
from utils.archives import extract_chd_hash
@@ -1375,6 +1371,8 @@ class TestFSRomsHandler:
SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id"
SWITCH_PLATFORM = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
@pytest.fixture
def sigil_config(monkeypatch):
@@ -1395,6 +1393,15 @@ def sigil_config(monkeypatch):
return cnfg
@pytest.fixture
def stub_ra_hasher(monkeypatch):
"""Keep the hashable-platform cases off the real RAHasher binary."""
monkeypatch.setattr(
"adapters.services.rahasher.RAHasherService.calculate_hash",
AsyncMock(return_value=""),
)
def make_sigil_handler(tmp_path: Path) -> FSRomsHandler:
handler = FSRomsHandler()
handler.base_path = tmp_path
@@ -1431,6 +1438,35 @@ def make_multi_part_rom(
)
async def switch_family_extract(
platform_slug: str, file_path: str
) -> SigilExtractionResult:
"""Stand in for sigil over a base/update/DLC folder, keyed by file name."""
if "update" in file_path:
return SigilExtractionResult(
title_id="0100ABCD12340800",
save_target="0100ABCD12340800",
usage="folder-exact",
content_type="patch",
version=196608,
)
if "dlc" in file_path:
return SigilExtractionResult(
title_id="0100ABCD12341001",
save_target="0100ABCD12341001",
usage="folder-exact",
content_type="addon",
version=0,
)
return SigilExtractionResult(
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
usage="folder-exact",
content_type="application",
version=0,
)
class TestSigilTitleIdExtraction:
"""Title id extraction via the sigil adapter during get_rom_files."""
@@ -1438,9 +1474,8 @@ class TestSigilTitleIdExtraction:
async def test_single_file_extraction_attaches_values(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Game.nsp")
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
@@ -1465,11 +1500,10 @@ class TestSigilTitleIdExtraction:
async def test_multi_part_extraction_covers_nested_files(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(
tmp_path,
platform,
SWITCH_PLATFORM,
"Zelda",
[
"Zelda [base].nsp",
@@ -1478,34 +1512,7 @@ class TestSigilTitleIdExtraction:
],
)
async def fake_extract(
platform_slug: str, file_path: str
) -> SigilExtractionResult:
if "update" in file_path:
return SigilExtractionResult(
title_id="0100ABCD12340800",
save_target="0100ABCD12340800",
usage="folder-exact",
content_type="patch",
version=196608,
)
if "dlc" in file_path:
return SigilExtractionResult(
title_id="0100ABCD12341001",
save_target="0100ABCD12341001",
usage="folder-exact",
content_type="addon",
version=0,
)
return SigilExtractionResult(
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
usage="folder-exact",
content_type="application",
version=0,
)
mock_extract = AsyncMock(side_effect=fake_extract)
mock_extract = AsyncMock(side_effect=switch_family_extract)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
@@ -1528,11 +1535,12 @@ class TestSigilTitleIdExtraction:
async def test_content_type_overrides_folder_category(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
# Folder name "dlc" would otherwise derive category DLC, but the binary
# content type says this is the base application.
rom = make_multi_part_rom(tmp_path, platform, "Zelda", ["dlc/Zelda [base].nsp"])
rom = make_multi_part_rom(
tmp_path, SWITCH_PLATFORM, "Zelda", ["dlc/Zelda [base].nsp"]
)
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
@@ -1553,10 +1561,9 @@ class TestSigilTitleIdExtraction:
async def test_folder_category_preserved_when_content_type_absent(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(
tmp_path, platform, "Zelda", ["dlc/Zelda [addon].nsp"]
tmp_path, SWITCH_PLATFORM, "Zelda", ["dlc/Zelda [addon].nsp"]
)
# CNMT miss: title id is present but content type is None.
@@ -1577,17 +1584,55 @@ class TestSigilTitleIdExtraction:
assert parsed.rom_files[0].category == RomFileCategory.DLC
@pytest.mark.asyncio
async def test_switch_base_derivation_from_update_only_folder(
async def test_non_rom_files_are_not_read(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(tmp_path, platform, "Zelda", ["Zelda [update].nsp"])
rom = make_multi_part_rom(
tmp_path,
SWITCH_PLATFORM,
"Zelda",
[
"Zelda [base].nsp",
"manuals/Zelda.pdf",
"soundtracks/Zelda.mp3",
"screenshots/Zelda.png",
],
)
mock_extract = AsyncMock(side_effect=switch_family_extract)
with patch(SIGIL_PATCH_TARGET, mock_extract):
await handler.get_rom_files(rom)
# Only the ROM file itself is worth a native parse.
assert mock_extract.await_count == 1
@pytest.mark.asyncio
@pytest.mark.parametrize(
("fs_name", "title_id", "expected"),
[
# A patch id carries bitmask 0x800.
("Zelda [update].nsp", "0100ABCD12340800", "0100ABCD12340000"),
# A DLC id carries an odd program-index nibble.
("Game [DLC].nsp", "0100ABCD12351064", "0100ABCD12350000"),
],
)
async def test_switch_base_id_is_derived_when_no_base_file_is_present(
self,
tmp_path: Path,
sigil_config: Config,
fs_name: str,
title_id: str,
expected: str,
):
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, fs_name)
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
title_id="0100ABCD12340800",
save_target="0100ABCD12340800",
title_id=title_id,
save_target=title_id,
usage="folder-exact",
)
)
@@ -1595,159 +1640,107 @@ class TestSigilTitleIdExtraction:
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
assert parsed.title_id == "0100ABCD12340000"
assert parsed.save_target == "0100ABCD12340000"
# Switch saves are keyed by the base title id itself.
assert parsed.title_id == expected
assert parsed.save_target == expected
assert parsed.save_target_layout == SaveTargetLayout.FOLDER_EXACT
@pytest.mark.asyncio
async def test_switch_base_derivation_from_dlc_odd_nibble(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game [DLC].nsp")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
title_id="0100ABCD12351064",
save_target="0100ABCD12351064",
usage="folder-exact",
)
)
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
assert parsed.title_id == "0100ABCD12350000"
assert parsed.save_target == "0100ABCD12350000"
assert parsed.save_target_layout == SaveTargetLayout.FOLDER_EXACT
@pytest.mark.asyncio
async def test_non_switch_platform_uses_first_extraction(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.iso")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
title_id="ULUS-10041",
save_target="ULUS10041",
usage="folder-prefix",
)
)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
@pytest.mark.parametrize(
("platform", "fs_name", "extraction", "expected_layout"),
[
(
Platform(name="PlayStation Portable", slug="psp", fs_slug="psp"),
"Game.iso",
SigilExtractionResult(
title_id="ULUS-10041",
save_target="ULUS10041",
usage="folder-prefix",
),
SaveTargetLayout.FOLDER_PREFIX,
),
):
parsed = await handler.get_rom_files(rom)
assert parsed.title_id == "ULUS-10041"
assert parsed.save_target == "ULUS10041"
assert parsed.save_target_layout == SaveTargetLayout.FOLDER_PREFIX
@pytest.mark.asyncio
async def test_3ds_extraction_maps_folder_split_usage(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo 3DS", slug="3ds", fs_slug="3ds")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.3ds")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
title_id="0004000E0011C500",
# The split path in the emulator's case, not the flat id.
save_target="0004000e/0011c500",
usage="folder-split",
)
)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
(
Platform(name="Nintendo 3DS", slug="3ds", fs_slug="3ds"),
"Game.3ds",
SigilExtractionResult(
title_id="0004000E0011C500",
# The split path in the emulator's case, not the flat id.
save_target="0004000e/0011c500",
usage="folder-split",
),
SaveTargetLayout.FOLDER_SPLIT,
),
):
parsed = await handler.get_rom_files(rom)
assert parsed.save_target == "0004000e/0011c500"
assert parsed.title_id == "0004000E0011C500"
assert parsed.save_target_layout == SaveTargetLayout.FOLDER_SPLIT
@pytest.mark.asyncio
async def test_dreamcast_extraction_maps_file_prefix_usage(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Dreamcast", slug="dc", fs_slug="dc")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.chd")
mock_extract = AsyncMock(
return_value=SigilExtractionResult(
title_id="MK-51035",
save_target="MK-51035",
usage="file-prefix",
)
)
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
(
Platform(name="Dreamcast", slug="dc", fs_slug="dc"),
"Game.chd",
SigilExtractionResult(
title_id="MK-51035",
save_target="MK-51035",
usage="file-prefix",
),
SaveTargetLayout.FILE_PREFIX,
),
):
],
)
async def test_non_switch_platform_uses_first_extraction_verbatim(
self,
tmp_path: Path,
sigil_config: Config,
stub_ra_hasher: None,
platform: Platform,
fs_name: str,
extraction: SigilExtractionResult,
expected_layout: SaveTargetLayout,
):
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, fs_name)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom)
assert parsed.save_target == "MK-51035"
assert parsed.save_target_layout == SaveTargetLayout.FILE_PREFIX
assert parsed.title_id == extraction.title_id
assert parsed.save_target == extraction.save_target
assert parsed.save_target_layout == expected_layout
@pytest.mark.asyncio
async def test_non_sigil_platform_skips_extraction(
self, tmp_path: Path, sigil_config: Config
@pytest.mark.parametrize(
("platform", "fs_name", "kwargs"),
[
# Not a platform sigil covers.
(
Platform(name="Nintendo 64", slug="n64", fs_slug="n64"),
"Game.z64",
{"calculate_hashes": False},
),
# Turned off by config.
(SWITCH_PLATFORM, "Game.nsp", {"extract_title_ids": False}),
# An archive holds no ROM binary sigil can read.
(SWITCH_PLATFORM, "game.zip", {}),
],
)
async def test_extraction_is_skipped(
self,
tmp_path: Path,
sigil_config: Config,
platform: Platform,
fs_name: str,
kwargs: dict[str, bool],
):
platform = Platform(name="Nintendo 64", slug="n64", fs_slug="n64")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.z64")
rom = make_single_file_rom(tmp_path, platform, fs_name)
mock_extract = AsyncMock()
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom, calculate_hashes=False)
parsed = await handler.get_rom_files(rom, **kwargs)
mock_extract.assert_not_awaited()
assert parsed.title_id is None
assert parsed.save_target_layout is None
@pytest.mark.asyncio
async def test_extraction_disabled_skips_extraction(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
mock_extract = AsyncMock()
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom, extract_title_ids=False)
mock_extract.assert_not_awaited()
assert parsed.title_id is None
@pytest.mark.asyncio
async def test_archive_rom_skips_extraction(
self, tmp_path: Path, sigil_config: Config
async def test_hashable_archive_rom_skips_extraction(
self, tmp_path: Path, sigil_config: Config, stub_ra_hasher: None
):
import io
import zipfile
@@ -1771,29 +1764,6 @@ class TestSigilTitleIdExtraction:
mock_extract = AsyncMock()
with (
patch(SIGIL_PATCH_TARGET, mock_extract),
patch(
"adapters.services.rahasher.RAHasherService.calculate_hash",
new_callable=AsyncMock,
return_value="",
),
):
parsed = await handler.get_rom_files(rom)
mock_extract.assert_not_awaited()
assert parsed.title_id is None
@pytest.mark.asyncio
async def test_non_hashable_archive_rom_skips_extraction(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "game.zip")
mock_extract = AsyncMock()
with patch(SIGIL_PATCH_TARGET, mock_extract):
parsed = await handler.get_rom_files(rom)
@@ -1802,58 +1772,95 @@ class TestSigilTitleIdExtraction:
class TestEmbedSwitchTitleIdInName:
"""The pure rename helper that embeds a Switch title id into a filename."""
"""The rename helper that embeds a Switch title id into a filename."""
def test_embeds_id_and_version(self, tmp_path: Path):
src = tmp_path / "Moonlighter.xci"
src.write_bytes(b"rom")
@pytest.fixture
def handler(self, tmp_path: Path) -> FSRomsHandler:
(tmp_path / "switch/roms").mkdir(parents=True)
return make_sigil_handler(tmp_path)
new_path = _embed_switch_title_id_in_name(src, "0100f4700b2e0000", 3)
@staticmethod
def _write(handler: FSRomsHandler, name: str, content: bytes = b"rom") -> Path:
path = handler.base_path / "switch/roms" / name
path.write_bytes(content)
return path
assert new_path is not None
assert new_path.name == "Moonlighter [0100F4700B2E0000][v3].xci"
assert new_path.exists()
@pytest.mark.asyncio
@pytest.mark.parametrize(
("name", "title_id", "version", "expected"),
[
(
"Moonlighter.xci",
"0100f4700b2e0000",
3,
"Moonlighter [0100F4700B2E0000][v3].xci",
),
# A missing version is a base game's version 0.
(
"Game.nsp",
"0100ABCD12340000",
None,
"Game [0100ABCD12340000][v0].nsp",
),
(
"Game (USA) (Rev 1).xci",
"0100ABCD12340000",
0,
"Game (USA) (Rev 1) [0100ABCD12340000][v0].xci",
),
],
)
async def test_embeds_id_and_version(
self,
handler: FSRomsHandler,
name: str,
title_id: str,
version: int | None,
expected: str,
):
src = self._write(handler, name)
new_name = await handler._embed_switch_title_id_in_name(
Path("switch/roms", name), title_id, version
)
assert new_name == expected
assert (handler.base_path / "switch/roms" / expected).exists()
assert not src.exists()
def test_version_none_defaults_to_zero(self, tmp_path: Path):
src = tmp_path / "Game.nsp"
src.write_bytes(b"rom")
@pytest.mark.asyncio
@pytest.mark.parametrize(
("name", "title_id"),
[
# Already embedded, so renaming again would stack the tags.
("Game [0100ABCD12340000][v0].nsp", "0100ABCD12340000"),
("Game.nsp", "NOT-A-TITLE-ID"),
],
)
async def test_file_is_left_alone(
self, handler: FSRomsHandler, name: str, title_id: str
):
src = self._write(handler, name)
new_path = _embed_switch_title_id_in_name(src, "0100ABCD12340000", None)
assert new_path is not None
assert new_path.name == "Game [0100ABCD12340000][v0].nsp"
def test_preserves_existing_tags(self, tmp_path: Path):
src = tmp_path / "Game (USA) (Rev 1).xci"
src.write_bytes(b"rom")
new_path = _embed_switch_title_id_in_name(src, "0100ABCD12340000", 0)
assert new_path is not None
assert new_path.name == "Game (USA) (Rev 1) [0100ABCD12340000][v0].xci"
def test_idempotent_when_bracket_already_present(self, tmp_path: Path):
src = tmp_path / "Game [0100ABCD12340000][v0].nsp"
src.write_bytes(b"rom")
assert _embed_switch_title_id_in_name(src, "0100ABCD12340000", 0) is None
assert (
await handler._embed_switch_title_id_in_name(
Path("switch/roms", name), title_id, 0
)
is None
)
assert src.exists()
def test_invalid_title_id_skips(self, tmp_path: Path):
src = tmp_path / "Game.nsp"
src.write_bytes(b"rom")
@pytest.mark.asyncio
async def test_collision_skips_and_leaves_both_files(self, handler: FSRomsHandler):
src = self._write(handler, "Game.nsp", b"original")
target = self._write(handler, "Game [0100ABCD12340000][v0].nsp", b"existing")
assert _embed_switch_title_id_in_name(src, "NOT-A-TITLE-ID", 0) is None
assert src.exists()
def test_collision_skips_and_leaves_original(self, tmp_path: Path):
src = tmp_path / "Game.nsp"
src.write_bytes(b"original")
target = tmp_path / "Game [0100ABCD12340000][v0].nsp"
target.write_bytes(b"existing")
assert _embed_switch_title_id_in_name(src, "0100ABCD12340000", 0) is None
assert (
await handler._embed_switch_title_id_in_name(
Path("switch/roms/Game.nsp"), "0100ABCD12340000", 0
)
is None
)
assert src.read_bytes() == b"original"
assert target.read_bytes() == b"existing"
@@ -1865,9 +1872,8 @@ class TestSwitchTitleIdEmbedding:
async def test_flag_off_leaves_file_unchanged(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Game.nsp")
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
@@ -1886,9 +1892,8 @@ class TestSwitchTitleIdEmbedding:
async def test_single_file_renamed_and_reconciled(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Moonlighter.xci")
rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Moonlighter.xci")
extraction = SigilExtractionResult(
title_id="0100F4700B2E0000",
@@ -1907,31 +1912,9 @@ class TestSwitchTitleIdEmbedding:
assert (tmp_path / "switch/roms" / new_name).exists()
assert not (tmp_path / "switch/roms/Moonlighter.xci").exists()
@pytest.mark.asyncio
async def test_already_embedded_file_skipped(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
fs_name = "Game [0100ABCD12340000][v0].nsp"
rom = make_single_file_rom(tmp_path, platform, fs_name)
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
usage="folder-exact",
)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
assert parsed.rom_files[0].file_name == fs_name
assert parsed.renamed_rom_fs_name is None
assert (tmp_path / "switch/roms" / fs_name).exists()
@pytest.mark.asyncio
async def test_non_switch_platform_never_renamed(
self, tmp_path: Path, sigil_config: Config
self, tmp_path: Path, sigil_config: Config, stub_ra_hasher: None
):
platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp")
handler = make_sigil_handler(tmp_path)
@@ -1950,35 +1933,10 @@ class TestSwitchTitleIdEmbedding:
assert parsed.renamed_rom_fs_name is None
assert (tmp_path / "psp/roms/Game.iso").exists()
@pytest.mark.asyncio
async def test_collision_target_exists_skips(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
target = tmp_path / "switch/roms/Game [0100ABCD12340000][v0].nsp"
target.write_bytes(b"existing")
extraction = SigilExtractionResult(
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
usage="folder-exact",
)
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
assert parsed.rom_files[0].file_name == "Game.nsp"
assert parsed.renamed_rom_fs_name is None
assert (tmp_path / "switch/roms/Game.nsp").read_bytes() == b"rom-bytes"
assert target.read_bytes() == b"existing"
@pytest.mark.asyncio
async def test_no_title_id_not_renamed(self, tmp_path: Path, sigil_config: Config):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_single_file_rom(tmp_path, platform, "Game.nsp")
rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Game.nsp")
with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=None)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
@@ -1991,43 +1949,15 @@ class TestSwitchTitleIdEmbedding:
async def test_multi_part_nested_files_renamed(
self, tmp_path: Path, sigil_config: Config
):
platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
handler = make_sigil_handler(tmp_path)
rom = make_multi_part_rom(
tmp_path,
platform,
SWITCH_PLATFORM,
"Zelda",
["Zelda base.nsp", "updates/Zelda update.nsp", "dlc/Zelda dlc.nsp"],
)
async def fake_extract(
platform_slug: str, file_path: str
) -> SigilExtractionResult:
if "update" in file_path:
return SigilExtractionResult(
title_id="0100ABCD12340800",
save_target="0100ABCD12340800",
usage="folder-exact",
content_type="patch",
version=196608,
)
if "dlc" in file_path:
return SigilExtractionResult(
title_id="0100ABCD12341001",
save_target="0100ABCD12341001",
usage="folder-exact",
content_type="addon",
version=0,
)
return SigilExtractionResult(
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
usage="folder-exact",
content_type="application",
version=0,
)
with patch(SIGIL_PATCH_TARGET, AsyncMock(side_effect=fake_extract)):
with patch(SIGIL_PATCH_TARGET, AsyncMock(side_effect=switch_family_extract)):
parsed = await handler.get_rom_files(rom, embed_title_ids=True)
names = {rf.file_name for rf in parsed.rom_files}

View File

@@ -197,62 +197,21 @@ async def test_scan_rom_complete_clears_unselected_metadata(
assert result.hasheous_id == 999
@pytest.mark.parametrize(
("stored_title_id", "extracted_title_id"),
[
# A first extraction lands on a rom that has no identity yet.
(None, "0100ABCD12340000"),
# A hash-only or extraction-disabled rescan must not wipe what is there.
("0100ABCD12340000", None),
],
)
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
async def test_scan_rom_folds_extracted_title_id_values(mock_playmatch_enabled):
"""Extracted title id values on the parsed files must land on the Rom."""
platform = Platform(id=1, slug="switch", fs_slug="switch", name="Nintendo Switch")
platform = db_platform_handler.add_platform(platform)
rom = Rom(
platform_id=platform.id,
fs_name="Game.nsp",
fs_path="switch/roms",
name="Game",
fs_size_bytes=1024,
tags=[],
)
rom = db_rom_handler.add_rom(rom)
async with initialize_context():
result = await scan_rom(
platform=platform,
scan_type=ScanType.QUICK,
rom=rom,
fs_rom={
"fs_name": "Game.nsp",
"flat": True,
"nested": False,
"files": [
RomFile(
rom=rom,
file_name="Game.nsp",
file_path="switch/roms",
file_size_bytes=1024,
last_modified=1620000000,
)
],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
"title_id": "0100ABCD12340000",
"save_target": "0100ABCD12340000",
"save_target_layout": SaveTargetLayout.FOLDER_EXACT,
},
metadata_sources=[],
newly_added=False,
)
assert result.title_id == "0100ABCD12340000"
assert result.save_target == "0100ABCD12340000"
assert result.save_target_layout == SaveTargetLayout.FOLDER_EXACT
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
async def test_scan_rom_preserves_title_id_when_extraction_yields_nothing(
async def test_scan_rom_folds_extracted_title_id_values(
mock_playmatch_enabled,
stored_title_id: str | None,
extracted_title_id: str | None,
):
"""A rescan without extracted values must not wipe existing title ids."""
platform = Platform(id=1, slug="switch", fs_slug="switch", name="Nintendo Switch")
platform = db_platform_handler.add_platform(platform)
@@ -263,9 +222,9 @@ async def test_scan_rom_preserves_title_id_when_extraction_yields_nothing(
name="Game",
fs_size_bytes=1024,
tags=[],
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
save_target_layout=SaveTargetLayout.FOLDER_EXACT,
title_id=stored_title_id,
save_target=stored_title_id,
save_target_layout=(SaveTargetLayout.FOLDER_EXACT if stored_title_id else None),
)
rom = db_rom_handler.add_rom(rom)
@@ -291,9 +250,11 @@ async def test_scan_rom_preserves_title_id_when_extraction_yields_nothing(
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
"title_id": None,
"save_target": None,
"save_target_layout": None,
"title_id": extracted_title_id,
"save_target": extracted_title_id,
"save_target_layout": (
SaveTargetLayout.FOLDER_EXACT if extracted_title_id else None
),
},
metadata_sources=[],
newly_added=False,

View File

@@ -1,6 +1,5 @@
import pytest
from models.rom import RomFileCategory
from utils import switch
@@ -45,15 +44,6 @@ class TestDeriveBaseTitleId:
assert switch.derive_base_title_id(title_id) is None
class TestContentTypeCategories:
def test_each_content_type_maps_to_its_category(self):
assert switch.CONTENT_TYPE_CATEGORIES == {
"application": RomFileCategory.GAME,
"patch": RomFileCategory.UPDATE,
"addon": RomFileCategory.DLC,
}
class TestTitleIdRegexes:
def test_a_bare_id_matches_the_plain_regex(self):
assert switch.TITLE_ID_REGEX.match("0100ABCD12340000")

View File

@@ -116,9 +116,10 @@ RUN apk add --no-cache \
make \
musl-dev
# Keep this pin in sync with the dev image's SIGIL_VERSION in ../Dockerfile.
ARG SIGIL_VERSION=9665f03c04d0f547ed38dd5e5e31916c1da5f2e9
RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \
RUN git clone --filter=blob:none https://github.com/rommforge/argosy-sigil.git && \
cd ./argosy-sigil && \
git checkout "${SIGIL_VERSION}" && \
git submodule update --init --recursive && \

View File

@@ -478,7 +478,6 @@
"verification": "Потвърждение",
"verified-rom": "Потвърден ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Версия",
"versions-count": "{n} версии",
"volume-mute": "Заглуши",
"volume-unmute": "Включи звука",

View File

@@ -478,7 +478,6 @@
"verification": "Ověření",
"verified-rom": "Ověřená ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Verze",
"versions-count": "{n} verzí",
"volume-mute": "Ztlumit",
"volume-unmute": "Zrušit ztlumení",

View File

@@ -478,7 +478,6 @@
"verification": "Verifizierung",
"verified-rom": "Verifizierte ROM",
"verified-rom-hint": "Hash mit ROM-Datenbank abgeglichen",
"version": "Version",
"versions-count": "{n} Versionen",
"volume-mute": "Stummschalten",
"volume-unmute": "Stummschaltung aufheben",

View File

@@ -478,7 +478,6 @@
"verification": "Verification",
"verified-rom": "Verified ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Version",
"versions-count": "{n} versions",
"volume-mute": "Mute",
"volume-unmute": "Unmute",

View File

@@ -478,7 +478,6 @@
"verification": "Verification",
"verified-rom": "Verified ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Version",
"versions-count": "{n} versions",
"volume-mute": "Mute",
"volume-unmute": "Unmute",

View File

@@ -478,7 +478,6 @@
"verification": "Verificación",
"verified-rom": "ROM verificada",
"verified-rom-hint": "Hash verificado contra una base de datos de ROM",
"version": "Versión",
"versions-count": "{n} versiones",
"volume-mute": "Silenciar",
"volume-unmute": "Quitar silencio",

View File

@@ -478,7 +478,6 @@
"verification": "Vérification",
"verified-rom": "ROM vérifiée",
"verified-rom-hint": "Empreinte vérifiée dans une base de données de ROM",
"version": "Version",
"versions-count": "{n} versions",
"volume-mute": "Couper le son",
"volume-unmute": "Activer le son",

View File

@@ -478,7 +478,6 @@
"verification": "Ellenőrzés",
"verified-rom": "Ellenőrzött ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Verzió",
"versions-count": "{n} verzió",
"volume-mute": "Némítás",
"volume-unmute": "Némítás feloldása",

View File

@@ -478,7 +478,6 @@
"verification": "Verifica",
"verified-rom": "ROM verificata",
"verified-rom-hint": "Hash verificato su un database di ROM",
"version": "Versione",
"versions-count": "{n} versioni",
"volume-mute": "Disattiva audio",
"volume-unmute": "Riattiva audio",

View File

@@ -478,7 +478,6 @@
"verification": "検証",
"verified-rom": "確認済みROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "バージョン",
"versions-count": "{n}件のバージョン",
"volume-mute": "ミュート",
"volume-unmute": "ミュート解除",

View File

@@ -478,7 +478,6 @@
"verification": "검증",
"verified-rom": "검증된 ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "버전",
"versions-count": "{n}개 버전",
"volume-mute": "음소거",
"volume-unmute": "음소거 해제",

View File

@@ -478,7 +478,6 @@
"verification": "Weryfikacja",
"verified-rom": "Zweryfikowany ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Wersja",
"versions-count": "{n} wersji",
"volume-mute": "Wycisz",
"volume-unmute": "Wyłącz wyciszenie",

View File

@@ -478,7 +478,6 @@
"verification": "Verificação",
"verified-rom": "ROM verificada",
"verified-rom-hint": "Hash verificado em banco de dados de ROM",
"version": "Versão",
"versions-count": "{n} versões",
"volume-mute": "Silenciar",
"volume-unmute": "Reativar som",

View File

@@ -478,7 +478,6 @@
"verification": "Verificare",
"verified-rom": "ROM verificat",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Versiune",
"versions-count": "{n} versiuni",
"volume-mute": "Mut",
"volume-unmute": "Activează sunetul",

View File

@@ -478,7 +478,6 @@
"verification": "Проверка",
"verified-rom": "Проверенный ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Версия",
"versions-count": "{n} версий",
"volume-mute": "Отключить звук",
"volume-unmute": "Включить звук",

View File

@@ -478,7 +478,6 @@
"verification": "Doğrulama",
"verified-rom": "Doğrulanmış ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "Sürüm",
"versions-count": "{n} sürüm",
"volume-mute": "Sesi kapat",
"volume-unmute": "Sesi aç",

View File

@@ -478,7 +478,6 @@
"verification": "验证",
"verified-rom": "已验证 ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "版本",
"versions-count": "{n} 个版本",
"volume-mute": "静音",
"volume-unmute": "取消静音",

View File

@@ -478,7 +478,6 @@
"verification": "驗證",
"verified-rom": "已驗證 ROM",
"verified-rom-hint": "Hash verified against ROM database",
"version": "版本",
"versions-count": "{n} 個版本",
"volume-mute": "靜音",
"volume-unmute": "取消靜音",

View File

@@ -97,16 +97,15 @@ const audioDuration = computed(() =>
formatDuration(props.file.track_meta?.duration_seconds),
);
const identifierChips = computed(() => {
const hashChips = computed(() => {
const f = props.file;
const chips: { label: string; value: string | null }[] = [
return [
{ label: "SHA-1", value: f.sha1_hash },
{ label: "CHD SHA-1", value: f.chd_sha1_hash },
{ label: "MD5", value: f.md5_hash },
{ label: "CRC", value: f.crc_hash },
{ label: "RA", value: f.ra_hash },
];
return chips.filter((chip) => Boolean(chip.value));
].flatMap((chip) => (chip.value ? [{ ...chip, value: chip.value }] : []));
});
</script>
@@ -172,12 +171,12 @@ const identifierChips = computed(() => {
</template>
</div>
<div v-if="identifierChips.length" class="r-v2-file-row__identifiers">
<div v-if="hashChips.length" class="r-v2-file-row__hashes">
<HashChip
v-for="chip in identifierChips"
v-for="chip in hashChips"
:key="chip.label"
:label="chip.label"
:value="chip.value!"
:value="chip.value"
compact
/>
</div>
@@ -302,7 +301,7 @@ const identifierChips = computed(() => {
opacity: 0.5;
}
.r-v2-file-row__identifiers {
.r-v2-file-row__hashes {
display: flex;
flex-wrap: wrap;
gap: 4px;

View File

@@ -30,15 +30,16 @@ type Row = { label: string; value: string };
const fileRows = computed<Row[]>(() => {
const r = props.rom;
const size = r.fs_size_bytes != null ? formatBytes(r.fs_size_bytes) : "—";
return [
const rows: Row[] = [
{ label: t("rom.filename"), value: r.fs_name },
{ label: t("common.size"), value: size },
// Only the sigil platforms carry these, so skip rather than dash them.
...(r.title_id ? [{ label: t("rom.title-id"), value: r.title_id }] : []),
...(r.save_target
? [{ label: t("rom.save-target"), value: r.save_target }]
: []),
];
// Present only for platforms with a readable binary id, so skip rather
// than dash them.
if (r.title_id) rows.push({ label: t("rom.title-id"), value: r.title_id });
if (r.save_target)
rows.push({ label: t("rom.save-target"), value: r.save_target });
return rows;
});
// Hash rows accept `value: string | null` because HashChip's click-to-