From b5f457b53a2d4cfddd1208b5232d2c8151e2322d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 21 Jun 2026 22:01:05 +0000 Subject: [PATCH] feat: replace subfolder flag with per-platform custom library structure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalizes the opt-in subfolder scanning into a per-platform custom library structure template, modeled on Retrom's. Replaces the `scan.subfolders` (bool | list) flag with `filesystem.structure` (fs_slug -> template); platforms without a template keep RomM's default discovery (top-level files and folders), so existing setups are unaffected. A template is relative to the platform's ROM folder (RomM already resolves the library root, roms_folder and platform directory) and is a sequence of `/`-separated path sections: - a braced section is a macro, a bare section is a literal folder matched exactly; - the last section must be the terminal {gameFile} (each file is a game) or {gameDir} (each folder is a single multi-file game); - any other braced section ({region}, {category}, ...) is a wildcard directory level that matches any folder (organizational only). Examples: filesystem: structure: nes: "{category}/{gameFile}" # roms/nes/Hacks/foo.nes ps3: "{category}/{gameDir}" # roms/ps3/PSN/Game/ snes: "{region}/{gameFile}" # roms/snes/USA/foo.sfc Declaring {gameFile} vs {gameDir} removes the previous disc-descriptor guessing entirely — the user states file-vs-folder. Hidden (dot-prefixed) folders are never descended into. Hash-based non-destructive identity (relocate a moved/renamed game in place, preserving saves/history/favorites/ collections) is retained and now triggers for any platform with a custom structure. - config: parse + validate templates at load (parse_library_structure, LibraryStructure); reject {platform}/{library} (RomM resolves those) and malformed templates. - fs handler: _discover_structured_roms walks literal/wildcard levels to the terminal; _discover_default_roms preserves the default behavior. - Tests: template parser (valid/invalid), per-platform config loading, and structured discovery (wildcard/literal levels, file/dir terminals, depth>1, hidden-folder skip, cross-folder name collisions). Subfolder-flag tests replaced. - Docs: config.example.yml documents filesystem.structure; scan.subfolders removed. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Sk2dzM3K9qxWBdPAeGb7us --- backend/config/config_manager.py | 153 ++++++++-- backend/endpoints/sockets/scan.py | 30 +- backend/handler/database/roms_handler.py | 8 +- backend/handler/filesystem/roms_handler.py | 152 +++++----- .../tests/config/fixtures/config/config.yml | 3 + backend/tests/config/test_config_loader.py | 51 ++++ backend/tests/endpoints/sockets/test_scan.py | 8 +- .../handler/filesystem/test_roms_handler.py | 273 +++++++++--------- backend/tests/handler/test_db_handler.py | 2 +- examples/config.example.yml | 70 +++-- 10 files changed, 451 insertions(+), 299 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 91edc4626..1e414ba0b 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -4,6 +4,7 @@ import glob import json import os import sys +from dataclasses import dataclass from pathlib import Path from typing import Final, NotRequired, TypedDict @@ -28,6 +29,98 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log + +# Terminal macros for a custom library structure template. Exactly one must +# appear, as the last path segment. +STRUCTURE_GAME_FILE: Final = "gameFile" +STRUCTURE_GAME_DIR: Final = "gameDir" +# Macros that belong to Retrom's full-path templates but are resolved by RomM +# itself (library base + roms folder + platform discovery). A per-platform +# template is relative to the platform's ROM folder, so these are rejected with +# a helpful message instead of being silently treated as wildcard levels. +_STRUCTURE_RESERVED_NONTERMINAL: Final = frozenset({"platform", "library"}) + + +@dataclass(frozen=True) +class StructureLevel: + """One intermediate directory level of a custom structure template. + + ``literal`` is the exact folder name to match, or ``None`` for a wildcard + macro level (``{region}``, ``{category}``, …) that matches any folder. + """ + + literal: str | None + + +@dataclass(frozen=True) +class LibraryStructure: + """A parsed per-platform custom library structure. + + Relative to the platform's ROM folder: ``levels`` are the intermediate + directory levels to descend (literal or wildcard), and ``each_file_is_game`` + selects the terminal — ``{gameFile}`` (each file is a ROM) vs ``{gameDir}`` + (each directory is a multi-file ROM). + """ + + levels: tuple[StructureLevel, ...] + each_file_is_game: bool + + +def parse_library_structure(template: str) -> LibraryStructure: + """Parse a custom structure template into a ``LibraryStructure``. + + Template syntax mirrors Retrom: ``/``-separated path sections where a + section wrapped in braces is a macro and a bare section is a literal folder + name. The last section must be the terminal ``{gameFile}`` or ``{gameDir}``; + every other braced section is a wildcard directory level. The template is + relative to the platform's ROM folder, so ``{platform}`` / ``{library}`` are + not used here. + + Raises ``ValueError`` on an invalid template. + """ + sections = [s for s in template.split("/") if s != ""] + if not sections: + raise ValueError("template is empty") + + levels: list[StructureLevel] = [] + each_file_is_game: bool | None = None + + for index, section in enumerate(sections): + is_last = index == len(sections) - 1 + is_macro = section.startswith("{") and section.endswith("}") + + if not is_macro: + if "{" in section or "}" in section: + raise ValueError(f"malformed macro in section '{section}'") + levels.append(StructureLevel(literal=section)) + continue + + name = section[1:-1].strip() + if name in (STRUCTURE_GAME_FILE, STRUCTURE_GAME_DIR): + if not is_last: + raise ValueError( + f"'{{{name}}}' must be the last path section of the template" + ) + each_file_is_game = name == STRUCTURE_GAME_FILE + continue + + if name in _STRUCTURE_RESERVED_NONTERMINAL: + raise ValueError( + f"'{{{name}}}' is not supported: a platform template is relative " + "to that platform's ROM folder (RomM resolves library root, roms " + "folder and platform on its own)" + ) + if not name: + raise ValueError("empty macro '{}'") + # Any other braced section is an organizational wildcard directory level. + levels.append(StructureLevel(literal=None)) + + if each_file_is_game is None: + raise ValueError("template must end with '{gameFile}' or '{gameDir}'") + + return LibraryStructure(levels=tuple(levels), each_file_is_game=each_file_is_game) + + ROMM_USER_CONFIG_PATH: Final = f"{ROMM_BASE_PATH}/config" ROMM_USER_CONFIG_FILE: Final = f"{ROMM_USER_CONFIG_PATH}/config.yml" SQLITE_DB_BASE_PATH: Final = f"{ROMM_BASE_PATH}/database" @@ -118,6 +211,7 @@ class Config: PLATFORMS_VERSIONS: dict[str, str] ROMS_FOLDER_NAME: str FIRMWARE_FOLDER_NAME: str + STRUCTURE_TEMPLATES: dict[str, str] SKIP_HASH_CALCULATION: bool EJS_DEBUG: bool EJS_CACHE_LIMIT: int | None @@ -132,7 +226,6 @@ class Config: SCAN_REGION_PRIORITY: list[str] SCAN_LANGUAGE_PRIORITY: list[str] SCAN_MEDIA: list[str] - SCAN_SUBFOLDERS: dict[str, bool | list[str]] GAMELIST_MEDIA_THUMBNAIL: MetadataMediaType GAMELIST_MEDIA_IMAGE: MetadataMediaType @@ -161,24 +254,18 @@ class Config: return False - def subfolder_scan_spec(self, fs_slug: str) -> bool | frozenset[str]: - """How the scanner should recurse into a platform's subfolders. + def platform_structure(self, fs_slug: str) -> LibraryStructure | None: + """The custom library structure for a platform, or ``None``. - Opt-in per platform via `scan.subfolders` in config.yml, where the - value is either: - - ``True`` -> recurse every subfolder (each nested file becomes its - own rom); - - a list of folder names -> recurse only those folders, leaving every - other folder as a single multi-file rom (so folder-based multi-file - games elsewhere on the platform stay intact); - - ``False`` / omitted -> don't recurse (default behavior). - - Returns ``True``, a ``frozenset`` of folder names, or ``False``. + Opt-in per platform via `filesystem.structure` in config.yml (a map of + ``fs_slug -> template``). When unset, the platform uses RomM's default + discovery (top-level files and folders). The template is validated at + load time, so parsing here is expected to succeed. """ - value = getattr(self, "SCAN_SUBFOLDERS", {}).get(fs_slug, False) - if isinstance(value, list): - return frozenset(value) - return bool(value) + template = getattr(self, "STRUCTURE_TEMPLATES", {}).get(fs_slug) + if not template: + return None + return parse_library_structure(template) class ConfigManager: @@ -466,7 +553,9 @@ class ConfigManager: PEGASUS_AUTO_EXPORT_ON_SCAN=pydash.get( self._raw_config, "scan.pegasus.export", False ), - SCAN_SUBFOLDERS=pydash.get(self._raw_config, "scan.subfolders", {}), + STRUCTURE_TEMPLATES=pydash.get( + self._raw_config, "filesystem.structure", {} + ), ) def _get_ejs_controls(self) -> dict[str, EjsControls]: @@ -681,18 +770,24 @@ class ConfigManager: log.critical("Invalid config.yml: scan.media must be a list") sys.exit(3) - if not isinstance(self.config.SCAN_SUBFOLDERS, dict): - log.critical("Invalid config.yml: scan.subfolders must be a dictionary") - sys.exit(3) - for fs_slug, value in self.config.SCAN_SUBFOLDERS.items(): - is_bool = isinstance(value, bool) - is_str_list = isinstance(value, list) and all( - isinstance(name, str) for name in value + if not isinstance(self.config.STRUCTURE_TEMPLATES, dict): + log.critical( + "Invalid config.yml: filesystem.structure must be a dictionary" ) - if not (is_bool or is_str_list): + sys.exit(3) + for fs_slug, template in self.config.STRUCTURE_TEMPLATES.items(): + if not isinstance(template, str): log.critical( - f"Invalid config.yml: scan.subfolders.{fs_slug} must be a " - "boolean or a list of folder names" + f"Invalid config.yml: filesystem.structure.{fs_slug} must be a " + "string template" + ) + sys.exit(3) + try: + parse_library_structure(template) + except ValueError as exc: + log.critical( + f"Invalid config.yml: filesystem.structure.{fs_slug} " + f"('{template}'): {exc}" ) sys.exit(3) @@ -789,6 +884,7 @@ class ConfigManager: "filesystem": { "roms_folder": self.config.ROMS_FOLDER_NAME, "firmware_folder": self.config.FIRMWARE_FOLDER_NAME, + "structure": self.config.STRUCTURE_TEMPLATES, "skip_hash_calculation": self.config.SKIP_HASH_CALCULATION, }, "system": { @@ -815,7 +911,6 @@ class ConfigManager: "language": self.config.SCAN_LANGUAGE_PRIORITY, }, "media": self.config.SCAN_MEDIA, - "subfolders": self.config.SCAN_SUBFOLDERS, "gamelist": { "export": self.config.GAMELIST_AUTO_EXPORT_ON_SCAN, "media": { diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index e12be729b..08cb4ac24 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -249,8 +249,8 @@ async def _identify_rom( # Update properties that don't require metadata parsed_tags = fs_rom_handler.parse_tags(fs_rom["fs_name"]) - # The discovered path is the rom's actual directory, which may be a - # subfolder of the platform roms folder when subfolder scanning is enabled. + # The discovered path is the rom's actual directory, which may be nested + # under the platform roms folder when a custom structure is configured. roms_path = fs_rom["fs_path"] # Create the entry early so we have the ID @@ -541,7 +541,7 @@ async def _reconcile_relocated_roms( ) -> set[str]: """Relocate roms whose on-disk path changed instead of re-importing them. - When subfolder scanning is enabled, moving (or renaming) a file reads as a + Under a custom library structure, moving (or renaming) a file reads as a new path. Rather than insert a fresh rom and mark the old one missing — which would drop saves, play history, favorites and collection membership — match a newly-seen file to a now-missing rom by content hash and update that @@ -562,7 +562,7 @@ async def _reconcile_relocated_roms( # Group candidates by total size: a moved file keeps its size, so this is a # cheap pre-filter that avoids hashing every newly-seen file (e.g. on first - # enable, where the whole subfolder tree reads as new). + # enable, where the whole structure reads as new). by_size: dict[int, list[Rom]] = defaultdict(list) for rom in disappeared: by_size[rom.fs_size_bytes].append(rom) @@ -739,12 +739,12 @@ async def _identify_platform( else: log.info(f"{hl(str(len(fs_roms)))} roms found in the file system") - # Detect roms that simply moved on disk (subfolder scanning) and relocate - # them in place so their saves/history/favorites/collections follow, - # instead of re-importing them as new and orphaning the old entry. Only - # runs when subfolder scanning is enabled for the platform, so default - # libraries pay no extra cost. - if cm.get_config().subfolder_scan_spec(platform.fs_slug): + # Detect roms that simply moved on disk (custom library structure) and + # relocate them in place so their saves/history/favorites/collections + # follow, instead of re-importing them as new and orphaning the old entry. + # Only runs for platforms with a custom structure, so default libraries pay + # no extra cost. + if cm.get_config().platform_structure(platform.fs_slug) is not None: relocated_paths = await _reconcile_relocated_roms(platform, fs_roms) if relocated_paths: await scan_stats.increment( @@ -778,8 +778,8 @@ async def _identify_platform( for fs_roms_batch in batched(fs_roms, 200, strict=False): # Key matches on the rom's full path (fs_path/fs_name), not just the - # file name, so identically-named files in different subfolders don't - # collide when subfolder scanning is enabled. + # file name, so identically-named files in different folders don't + # collide under a custom library structure. roms_by_full_path = db_rom_handler.get_roms_by_fs_name( platform_id=platform.id, fs_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch}, @@ -826,15 +826,15 @@ async def _identify_platform( ) if len(missing_roms) > 0: log.warning(f"{hl('Missing')} roms from filesystem:") - # A folder that subfolder scanning now recurses into used to be a single + # A folder a custom structure now descends into used to be a single # multi-file rom; that old entry shows up here as missing. Flag those so # it's clear the "missing" is expected and the stale entry can be # deleted. A superseded folder's path is a parent of a discovered rom. - recursed_paths = {rom["fs_path"] for rom in fs_roms} + descended_paths = {rom["fs_path"] for rom in fs_roms} for r in missing_roms: superseded = any( p == r.full_path or p.startswith(f"{r.full_path}/") - for p in recursed_paths + for p in descended_paths ) if superseded: log.warning( diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 34c4830eb..9a2fe24e0 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1174,8 +1174,8 @@ class DBRomsHandler(DBBaseHandler): """Retrieve a dictionary of roms keyed by their full path (fs_path/fs_name). Filters by file name for an indexed lookup, but keys the result on the - full path so identically-named files in different subfolders (subfolder - scanning) remain distinct. + full path so identically-named files in different folders (custom + library structures) remain distinct. Eager-loads only `platform` (used downstream by the scan loop via `rom.platform_slug` / `rom.platform.fs_slug`). This deliberately @@ -1283,8 +1283,8 @@ class DBRomsHandler(DBBaseHandler): """Sync `missing_from_fs` for a platform against the keep-list. The keep-list holds rom full paths (fs_path/fs_name) so that - identically-named files in different subfolders are tracked - independently when subfolder scanning is enabled. + identically-named files in different folders are tracked + independently under a custom library structure. Reads the rows once and writes only those whose state actually changes, so a re-scan of an unchanged platform issues no updates. diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 4d5de00a7..a407a6601 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -15,6 +15,7 @@ from config import LIBRARY_BASE_PATH from config.config_manager import ( DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_FILES, + LibraryStructure, ) from config.config_manager import config_manager as cm from exceptions.fs_exceptions import ( @@ -318,7 +319,7 @@ class FSRomsHandler(FSHandler): from handler.metadata import meta_ra_handler # The rom's stored directory is the source of truth for its location, so - # roms inside a platform subfolder (subfolder scanning) resolve to their + # roms inside a nested folder (custom library structure) resolve to their # real path rather than the platform roms root. rel_roms_path = rom.fs_path # Relative path to the rom's directory abs_fs_path = self.validate_path(rel_roms_path) # Absolute path to that dir @@ -676,90 +677,91 @@ class FSRomsHandler(FSHandler): rom_sha1_h, ) - # Disc/playlist descriptors that mark a folder as a single multi-file game - # (a multi-disc title), so it is kept whole instead of being recursed into - # when subfolder scanning is enabled — preventing it from being split into - # one rom per disc. - _MULTI_DISC_DESCRIPTOR_EXTS = (".m3u", ".cue", ".gdi", ".ccd", ".toc") + async def _discover_default_roms(self, rel_roms_path: str) -> list[dict]: + """Default discovery: top-level files and folders of the roms path. - @staticmethod - def _should_recurse_dir(directory: str, recurse: bool | frozenset[str]) -> bool: - """Whether to descend into ``directory`` (collecting its contents as - individual roms) rather than treat it as one multi-file rom. - - Hidden (dot-prefixed) folders are never descended into. Otherwise - ``recurse`` is ``True`` (all folders), a set of folder names (only - those), or ``False`` (none). - """ - if directory.startswith("."): - return False - if isinstance(recurse, frozenset): - return directory in recurse - return recurse - - async def _is_multi_disc_dir(self, rel_dir_path: str) -> bool: - """True if a directory directly contains a disc/playlist descriptor. - - Such a directory is a single multi-file rom (a multi-disc game), so it - is kept whole instead of being recursed into when subfolder scanning is - enabled — preventing a multi-disc game from being split into one rom per - disc. Covers ``.m3u`` playlists as well as ``.cue``/``.gdi``/``.ccd``/ - ``.toc`` track descriptors (the ``.cue``+``.bin`` case raised in review). - """ - return any( - f.lower().endswith(self._MULTI_DISC_DESCRIPTOR_EXTS) - for f in await self.list_files(rel_dir_path) - ) - - async def _collect_fs_roms( - self, rel_roms_path: str, recurse: bool | frozenset[str] - ) -> list[dict]: - """Discover roms under ``rel_roms_path``. - - Single files are flat roms (``fs_path`` = their parent directory). A - directory is a single multi-file rom unless ``recurse`` says to descend - into it, in which case its contents are collected as individual roms. - ``recurse`` is ``True`` (descend every folder), a set of folder names - (descend only those — every other folder stays a multi-file rom), or - ``False`` (descend none). - - Hidden (dot-prefixed) directories are never descended into, and a - directory holding a disc/playlist descriptor is kept whole as a single - multi-file rom (a multi-disc game) even while recursing. + Each top-level file is a flat rom; each top-level directory is a single + multi-file rom. This is RomM's behavior for platforms without a custom + structure template. """ fs_roms: list[dict] = [ {"fs_name": rom, "fs_path": rel_roms_path, "flat": True, "nested": False} for rom in self.exclude_single_files(await self.list_files(rel_roms_path)) ] - - for directory in self.exclude_multi_roms( - await self.list_directories(rel_roms_path) - ): - dir_path = f"{rel_roms_path}/{directory}" - if self._should_recurse_dir( - directory, recurse - ) and not await self._is_multi_disc_dir(dir_path): - fs_roms.extend(await self._collect_fs_roms(dir_path, recurse)) - else: - fs_roms.append( - { - "fs_name": directory, - "fs_path": rel_roms_path, - "flat": False, - "nested": True, - } - ) - + fs_roms += [ + {"fs_name": rom, "fs_path": rel_roms_path, "flat": False, "nested": True} + for rom in self.exclude_multi_roms( + await self.list_directories(rel_roms_path) + ) + ] return fs_roms + async def _discover_structured_roms( + self, rel_roms_path: str, structure: LibraryStructure + ) -> list[dict]: + """Discover roms following a custom library structure template. + + Descends the template's intermediate directory levels (literal names + matched exactly, wildcard macros matching any folder), then collects + roms at the terminal: ``{gameFile}`` makes each file a rom, ``{gameDir}`` + makes each directory a (multi-file) rom. Each rom records its real + ``fs_path``. Hidden (dot-prefixed) folders are never descended into or + surfaced. + """ + dirs = [rel_roms_path] + for level in structure.levels: + next_dirs: list[str] = [] + for directory in dirs: + for sub in await self.list_directories(directory): + if sub.startswith("."): + continue + if level.literal is not None and sub != level.literal: + continue + next_dirs.append(f"{directory}/{sub}") + dirs = next_dirs + + fs_roms: list[dict] = [] + for directory in dirs: + if structure.each_file_is_game: + for name in self.exclude_single_files(await self.list_files(directory)): + fs_roms.append( + { + "fs_name": name, + "fs_path": directory, + "flat": True, + "nested": False, + } + ) + else: + for name in self.exclude_multi_roms( + await self.list_directories(directory) + ): + if name.startswith("."): + continue + fs_roms.append( + { + "fs_name": name, + "fs_path": directory, + "flat": False, + "nested": True, + } + ) + return fs_roms + + async def _collect_fs_roms(self, platform: Platform) -> list[dict]: + """Discover a platform's roms, honoring its custom structure if set.""" + rel_roms_path = self.get_roms_fs_structure(platform.fs_slug) + structure = cm.get_config().platform_structure(platform.fs_slug) + if structure is None: + return await self._discover_default_roms(rel_roms_path) + return await self._discover_structured_roms(rel_roms_path, structure) + async def count_roms(self, platform: Platform) -> int: """Return the number of filesystem roms for a platform without materializing FSRom objects. """ - recurse = cm.get_config().subfolder_scan_spec(platform.fs_slug) try: - rel_roms_path = self.get_roms_fs_structure(platform.fs_slug) - return len(await self._collect_fs_roms(rel_roms_path, recurse)) + return len(await self._collect_fs_roms(platform)) except FileNotFoundError as e: raise RomsNotFoundException(platform=platform.fs_slug) from e @@ -771,12 +773,8 @@ class FSRomsHandler(FSHandler): Returns: list with all the filesystem roms for a platform """ - recurse = cm.get_config().subfolder_scan_spec(platform.fs_slug) try: - rel_roms_path = self.get_roms_fs_structure( - platform.fs_slug - ) # Relative path to roms - fs_roms = await self._collect_fs_roms(rel_roms_path, recurse) + fs_roms = await self._collect_fs_roms(platform) except FileNotFoundError as e: raise RomsNotFoundException(platform=platform.fs_slug) from e diff --git a/backend/tests/config/fixtures/config/config.yml b/backend/tests/config/fixtures/config/config.yml index 1e7c22a0d..1bf6ecfb6 100644 --- a/backend/tests/config/fixtures/config/config.yml +++ b/backend/tests/config/fixtures/config/config.yml @@ -30,6 +30,9 @@ filesystem: roms_folder: "ROMS" firmware_folder: "BIOS" skip_hash_calculation: true + structure: + psx: "{category}/{gameDir}" + nes: "{gameFile}" scan: priority: diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index b1763319b..a1468042f 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -1,11 +1,14 @@ import os from pathlib import Path +import pytest + from config.config_manager import ( DEFAULT_EXCLUDED_DIRS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_FILES, ConfigManager, + parse_library_structure, ) @@ -79,6 +82,18 @@ def test_config_loader(): assert loader.config.SCAN_LANGUAGE_PRIORITY == ["jp", "es"] assert loader.config.GAMELIST_MEDIA_THUMBNAIL == "box3d" assert loader.config.GAMELIST_MEDIA_IMAGE == "title_screen" + assert loader.config.STRUCTURE_TEMPLATES == { + "psx": "{category}/{gameDir}", + "nes": "{gameFile}", + } + # The accessor parses templates on demand; unset platforms get None. + psx = loader.config.platform_structure("psx") + assert psx is not None and psx.each_file_is_game is False + assert len(psx.levels) == 1 and psx.levels[0].literal is None + nes = loader.config.platform_structure("nes") + assert nes is not None and nes.each_file_is_game is True + assert nes.levels == () + assert loader.config.platform_structure("snes") is None def test_empty_config_loader(): @@ -113,6 +128,42 @@ def test_empty_config_loader(): assert loader.config.EJS_CONTROLS == {} assert loader.config.GAMELIST_MEDIA_THUMBNAIL == "box2d" assert loader.config.GAMELIST_MEDIA_IMAGE == "screenshot" + assert loader.config.STRUCTURE_TEMPLATES == {} + + +@pytest.mark.parametrize( + ("template", "levels", "each_file_is_game"), + [ + ("{gameFile}", (), True), + ("{gameDir}", (), False), + ("{category}/{gameFile}", (None,), True), + ("Hacks/{gameFile}", ("Hacks",), True), + ("{region}/{system}/{gameDir}", (None, None), False), + ("roms/{region}/{gameFile}", ("roms", None), True), + ], +) +def test_parse_library_structure_valid(template, levels, each_file_is_game): + structure = parse_library_structure(template) + assert structure.each_file_is_game is each_file_is_game + assert tuple(level.literal for level in structure.levels) == levels + + +@pytest.mark.parametrize( + "template", + [ + "", + "justliteral", + "{category}", # no terminal + "{gameFile}/{gameDir}", # terminal not last + "{gameDir}/extra", # terminal not last + "{platform}/{gameFile}", # reserved macro RomM resolves itself + "{library}/{gameFile}", + "{}/{gameFile}", # empty macro + ], +) +def test_parse_library_structure_invalid(template): + with pytest.raises(ValueError): + parse_library_structure(template) def test_missing_config_file_is_created(tmp_path): diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 0dfd2ee52..9c1929993 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -352,9 +352,9 @@ def _fs_rom(fs_name: str, fs_path: str) -> FSRom: class TestReconcileRelocatedRoms: - """A rom whose on-disk path changed (subfolder scanning) is relocated in - place by content hash instead of being re-imported as new, so its DB row — - and the saves/history/favorites/collections attached to it — survives.""" + """A rom whose on-disk path changed (custom library structure) is relocated + in place by content hash instead of being re-imported as new, so its DB row + — and the saves/history/favorites/collections attached to it — survives.""" @pytest.mark.asyncio async def test_moved_file_is_relocated_not_reimported( @@ -377,7 +377,7 @@ class TestReconcileRelocatedRoms: ) ) - # On disk the file now lives inside a subfolder (same bytes). + # On disk the file now lives inside a nested folder (same bytes). sub = tmp_path / base / "Hacks" sub.mkdir(parents=True) (sub / "Mover.bin").write_bytes(content) diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 536e14efd..c0a053a59 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -377,7 +377,7 @@ class TestFSRomsHandler: # Check excluded files are not present assert "excluded_test.tmp" not in rom_names - def _make_subfolder_config(self, subfolders: dict[str, bool | list[str]]) -> Config: + def _make_structure_config(self, templates: dict[str, str]) -> Config: return Config( EXCLUDED_PLATFORMS=[], EXCLUDED_SINGLE_EXT=["tmp"], @@ -389,176 +389,175 @@ class TestFSRomsHandler: PLATFORMS_VERSIONS={}, ROMS_FOLDER_NAME="roms", FIRMWARE_FOLDER_NAME="bios", - SCAN_SUBFOLDERS=subfolders, + STRUCTURE_TEMPLATES=templates, ) - def _build_subfolder_library(self, tmp_path: Path, platform: Platform) -> None: - """Library with a flat rom, a grouping subfolder (with a nested - sub-subfolder and a basename colliding with the root), a hidden folder, - and a folder-style multi-file rom.""" - roms = tmp_path / platform.fs_slug / "roms" + def _build_structure_library(self, tmp_path: Path, base: str) -> None: + """Library exercising literal/wildcard levels, file-vs-folder terminals, + a name collision across folders, a hidden folder, and depth > 1.""" + roms = tmp_path / base roms.mkdir(parents=True) - (roms / "Game A.zip").write_text("a") - group = roms / "All but the Best" - group.mkdir() - (group / "Game A.zip").write_text("dup") # same basename, different folder - (group / "Hidden Gem.zip").write_text("c") - deeper = group / "deeper" - deeper.mkdir() - (deeper / "Way Down.zip").write_text("d") + (roms / "Top.zip").write_text("t") + hacks = roms / "Hacks" + hacks.mkdir() + (hacks / "Shared.zip").write_text("a") + (hacks / "HackOnly.zip").write_text("b") + inner = hacks / "Inner" + inner.mkdir() + (inner / "x.bin").write_text("x") + trans = roms / "Translations" + trans.mkdir() + (trans / "Shared.zip").write_text("c") # collides with Hacks/Shared.zip hidden = roms / ".hidden" hidden.mkdir() - (hidden / "disc.chd").write_text("x") - multi = roms / "Multi Disc Game" - multi.mkdir() - (multi / "disc1.bin").write_text("p") + (hidden / "secret.zip").write_text("s") + region = roms / "Region" + region.mkdir() + usa = region / "USA" + usa.mkdir() + (usa / "usagame.zip").write_text("u") @pytest.mark.asyncio - async def test_get_roms_subfolders_disabled( + async def test_get_roms_no_structure_is_default( self, platform: Platform, tmp_path: Path ): - """By default a subfolder is a single multi-file rom, not a group.""" - self._build_subfolder_library(tmp_path, platform) + """Without a template, only top-level files and folders are surfaced + (each file a flat rom, each folder a single multi-file rom).""" handler = FSRomsHandler() handler.base_path = tmp_path - with patch( "handler.filesystem.roms_handler.cm.get_config", - lambda: self._make_subfolder_config({}), + lambda: self._make_structure_config({}), ): + base = handler.get_roms_fs_structure(platform.fs_slug) + self._build_structure_library(tmp_path, base) roms = await handler.get_roms(platform) count = await handler.count_roms(platform) keys = {(r["fs_path"], r["fs_name"]) for r in roms} - base = f"{platform.fs_slug}/roms" - assert (base, "Game A.zip") in keys - # Directories surface as multi-file roms, not as groups. - assert (base, "All but the Best") in keys - assert (base, "Multi Disc Game") in keys + assert (base, "Top.zip") in keys + assert (base, "Hacks") in keys + assert (base, "Translations") in keys + assert (base, "Region") in keys assert (base, ".hidden") in keys - # Nothing inside any subfolder is surfaced. - assert not any(r["fs_path"] != base for r in roms) - assert len(roms) == 4 + # Nothing nested is surfaced. + assert all(r["fs_path"] == base for r in roms) + assert len(roms) == 5 assert count == len(roms) @pytest.mark.asyncio - async def test_get_roms_subfolders_enabled( + async def test_get_roms_structure_wildcard_file_terminal( self, platform: Platform, tmp_path: Path ): - """With subfolder scanning on, groups are descended into (recursively), - hidden folders are skipped, and identically-named files in different - folders stay distinct via their full path.""" - self._build_subfolder_library(tmp_path, platform) - handler = FSRomsHandler() - handler.base_path = tmp_path - - with patch( - "handler.filesystem.roms_handler.cm.get_config", - lambda: self._make_subfolder_config({platform.fs_slug: True}), - ): - roms = await handler.get_roms(platform) - count = await handler.count_roms(platform) - - base = f"{platform.fs_slug}/roms" - keys = {(r["fs_path"], r["fs_name"]) for r in roms} - assert (base, "Game A.zip") in keys - assert (f"{base}/All but the Best", "Game A.zip") in keys # collision kept - assert (f"{base}/All but the Best", "Hidden Gem.zip") in keys - assert (f"{base}/All but the Best/deeper", "Way Down.zip") in keys - # Group folders are descended into, so "Multi Disc Game" parts surface. - assert (f"{base}/Multi Disc Game", "disc1.bin") in keys - # Hidden folder is not descended into; it remains a multi-file rom. - assert (base, ".hidden") in keys - assert (f"{base}/.hidden", "disc.chd") not in keys - # All full-path keys are unique and count matches. - full_paths = [f"{r['fs_path']}/{r['fs_name']}" for r in roms] - assert len(full_paths) == len(set(full_paths)) - assert sum(1 for r in roms if r["fs_name"] == "Game A.zip") == 2 - assert count == len(roms) - - @pytest.mark.asyncio - async def test_get_roms_subfolders_descriptor_dir_kept_whole( - self, platform: Platform, tmp_path: Path - ): - """A subfolder holding a disc/playlist descriptor (.m3u, .cue, ...) is a - multi-disc game: it stays a single multi-file rom even with subfolder - scanning on (not split per disc), while a plain grouping folder is still - recursed.""" - roms = tmp_path / platform.fs_slug / "roms" - roms.mkdir(parents=True) - (roms / "Flat Game.zip").write_text("a") - # Multi-disc game declared by an .m3u playlist -> one rom. - md = roms / "Final Fantasy VII" - md.mkdir() - (md / "disc1.chd").write_text("1") - (md / "disc2.chd").write_text("2") - (md / "Final Fantasy VII.m3u").write_text("disc1.chd\ndisc2.chd") - # Multi-file game declared by a .cue descriptor (cue+bin) -> one rom. - cue = roms / "Some CD Game" - cue.mkdir() - (cue / "Some CD Game.cue").write_text('FILE "Some CD Game.bin" BINARY') - (cue / "Some CD Game.bin").write_text("data") - # Plain grouping folder (no descriptor) -> recursed into. - grp = roms / "Hacks" - grp.mkdir() - (grp / "Hack A.zip").write_text("h") - + """`{category}/{gameFile}` descends one wildcard level and treats each + file as a rom; hidden folders are skipped and identically-named files in + different folders stay distinct via their full path.""" handler = FSRomsHandler() handler.base_path = tmp_path with patch( "handler.filesystem.roms_handler.cm.get_config", - lambda: self._make_subfolder_config({platform.fs_slug: True}), - ): - roms_found = await handler.get_roms(platform) - count = await handler.count_roms(platform) - - base = f"{platform.fs_slug}/roms" - keys = {(r["fs_path"], r["fs_name"]) for r in roms_found} - # The .m3u folder stays a single multi-file rom (not split per disc). - assert (base, "Final Fantasy VII") in keys - assert (f"{base}/Final Fantasy VII", "disc1.chd") not in keys - # The .cue+.bin folder stays whole too (the case raised in review). - assert (base, "Some CD Game") in keys - assert (f"{base}/Some CD Game", "Some CD Game.bin") not in keys - # A normal grouping folder is still recursed. - assert (f"{base}/Hacks", "Hack A.zip") in keys - assert (base, "Flat Game.zip") in keys - assert count == len(roms_found) - - @pytest.mark.asyncio - async def test_get_roms_subfolders_named_list( - self, platform: Platform, tmp_path: Path - ): - """A list value recurses only the named folders; every other folder - (including a folder-based multi-file game) stays a single multi-file - rom, and a non-named folder nested inside a named one is not split.""" - self._build_subfolder_library(tmp_path, platform) - handler = FSRomsHandler() - handler.base_path = tmp_path - - with patch( - "handler.filesystem.roms_handler.cm.get_config", - lambda: self._make_subfolder_config( - {platform.fs_slug: ["All but the Best"]} + lambda: self._make_structure_config( + {platform.fs_slug: "{category}/{gameFile}"} ), ): + base = handler.get_roms_fs_structure(platform.fs_slug) + self._build_structure_library(tmp_path, base) roms = await handler.get_roms(platform) count = await handler.count_roms(platform) - base = f"{platform.fs_slug}/roms" keys = {(r["fs_path"], r["fs_name"]) for r in roms} - # Named folder is recursed -> its files become individual roms. - assert (f"{base}/All but the Best", "Game A.zip") in keys - assert (f"{base}/All but the Best", "Hidden Gem.zip") in keys - # A non-named folder nested inside it is kept whole (not recursed). - assert (f"{base}/All but the Best", "deeper") in keys - assert (f"{base}/All but the Best/deeper", "Way Down.zip") not in keys - # Folders NOT in the list stay as single multi-file roms. - assert (base, "Multi Disc Game") in keys - assert (f"{base}/Multi Disc Game", "disc1.bin") not in keys - # Top-level flat file and hidden folder behave as usual. - assert (base, "Game A.zip") in keys - assert (base, ".hidden") in keys + assert (f"{base}/Hacks", "Shared.zip") in keys + assert (f"{base}/Hacks", "HackOnly.zip") in keys + assert (f"{base}/Translations", "Shared.zip") in keys # collision kept + # Top-level file isn't surfaced (template requires one level down). + assert (base, "Top.zip") not in keys + # A folder at the terminal level isn't a {gameFile} rom. + assert (f"{base}/Hacks", "Inner") not in keys + # Hidden folder is never descended into. + assert not any(r["fs_path"].endswith("/.hidden") for r in roms) + full_paths = [f"{r['fs_path']}/{r['fs_name']}" for r in roms] + assert len(full_paths) == len(set(full_paths)) + assert sum(1 for r in roms if r["fs_name"] == "Shared.zip") == 2 + assert count == len(roms) + + @pytest.mark.asyncio + async def test_get_roms_structure_wildcard_dir_terminal( + self, platform: Platform, tmp_path: Path + ): + """`{category}/{gameDir}` treats each folder at the terminal level as a + single multi-file rom (kept whole — no disc-splitting guesswork).""" + handler = FSRomsHandler() + handler.base_path = tmp_path + with patch( + "handler.filesystem.roms_handler.cm.get_config", + lambda: self._make_structure_config( + {platform.fs_slug: "{category}/{gameDir}"} + ), + ): + base = handler.get_roms_fs_structure(platform.fs_slug) + self._build_structure_library(tmp_path, base) + roms = await handler.get_roms(platform) + count = await handler.count_roms(platform) + + keys = {(r["fs_path"], r["fs_name"]) for r in roms} + # Folders at the terminal level become whole multi-file roms... + assert (f"{base}/Hacks", "Inner") in keys + assert (f"{base}/Region", "USA") in keys + # ...and are not split into their contents. + assert (f"{base}/Hacks/Inner", "x.bin") not in keys + # Files at the terminal level are not {gameDir} roms. + assert (f"{base}/Hacks", "Shared.zip") not in keys + assert all(r["nested"] for r in roms) + assert count == len(roms) + + @pytest.mark.asyncio + async def test_get_roms_structure_two_wildcard_levels( + self, platform: Platform, tmp_path: Path + ): + """Multiple wildcard levels descend depth-first to the terminal.""" + handler = FSRomsHandler() + handler.base_path = tmp_path + with patch( + "handler.filesystem.roms_handler.cm.get_config", + lambda: self._make_structure_config( + {platform.fs_slug: "{region}/{system}/{gameFile}"} + ), + ): + base = handler.get_roms_fs_structure(platform.fs_slug) + self._build_structure_library(tmp_path, base) + roms = await handler.get_roms(platform) + count = await handler.count_roms(platform) + + keys = {(r["fs_path"], r["fs_name"]) for r in roms} + assert (f"{base}/Hacks/Inner", "x.bin") in keys + assert (f"{base}/Region/USA", "usagame.zip") in keys + # Depth-1 files are not surfaced at a depth-2 terminal. + assert (f"{base}/Hacks", "Shared.zip") not in keys + assert count == len(roms) + + @pytest.mark.asyncio + async def test_get_roms_structure_literal_level( + self, platform: Platform, tmp_path: Path + ): + """A literal section matches that exact folder only; sibling folders are + ignored.""" + handler = FSRomsHandler() + handler.base_path = tmp_path + with patch( + "handler.filesystem.roms_handler.cm.get_config", + lambda: self._make_structure_config({platform.fs_slug: "Hacks/{gameFile}"}), + ): + base = handler.get_roms_fs_structure(platform.fs_slug) + self._build_structure_library(tmp_path, base) + roms = await handler.get_roms(platform) + count = await handler.count_roms(platform) + + keys = {(r["fs_path"], r["fs_name"]) for r in roms} + assert (f"{base}/Hacks", "Shared.zip") in keys + assert (f"{base}/Hacks", "HackOnly.zip") in keys + # The literal only matched "Hacks"; "Translations" is ignored. + assert (f"{base}/Translations", "Shared.zip") not in keys + assert all(r["fs_path"] == f"{base}/Hacks" for r in roms) assert count == len(roms) @pytest.mark.asyncio diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index 932dc058d..1561c8eeb 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -546,7 +546,7 @@ def test_bulk_mark_present_chunking(platform: Platform): def test_get_roms_by_fs_name_keys_on_full_path(platform: Platform): - """Identically-named files in different subfolders must stay distinct: the + """Identically-named files in different folders must stay distinct: the result is keyed on full path (fs_path/fs_name), not just the file name.""" root = db_rom_handler.add_rom( Rom( diff --git a/examples/config.example.yml b/examples/config.example.yml index e37976922..c7a7d7dab 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -76,6 +76,44 @@ # roms_folder: 'roms' # # Skip file hash calculations on low power devices (eg. Raspberry PI) # skip_hash_calculation: false +# # Custom library structure, per platform. By default a platform's ROM folder +# # is scanned one level deep: each top-level file is a game and each top-level +# # folder is a single multi-file game. A template lets you describe a deeper / +# # organized layout instead. It is opt-in per platform (by fs_slug); platforms +# # left out keep the default behavior. +# # +# # Syntax (Retrom-style): `/`-separated path sections, relative to the +# # platform's ROM folder (RomM already resolves the library root, the +# # roms_folder above, and the platform directory — so {library}/{platform} +# # are not used here). A section wrapped in braces is a macro; a bare section +# # is a literal folder name matched exactly. The LAST section must be a +# # terminal macro: +# # - {gameFile} -> each file at that level is its own game; +# # - {gameDir} -> each folder at that level is a single multi-file game. +# # Any other braced section (e.g. {region}, {category}) is a wildcard +# # directory level: it matches any folder and is purely organizational. +# # +# # Notes: +# # - Hidden (dot-prefixed) folders are never descended into or surfaced. +# # - {gameDir} keeps a folder whole (multi-disc / cue+bin games), so there +# # is no guessing — you declare file-vs-folder explicitly. +# # - Identity is content-based on scan: moving or renaming a game within the +# # structure is detected by its hash and relocated in place, so its saves, +# # play history, favorites and collection membership follow it (as long as +# # hashing is enabled and the platform is hashable). When a folder that was +# # previously scanned as one multi-file game is now descended into, the old +# # entry is marked "missing from filesystem" (the scan log flags it); +# # delete the stale entry to clean up. +# # - Two files with the same name in different folders become distinct games; +# # gamelist.xml metadata matching is by filename, so both may match the +# # same gamelist entry. +# structure: +# # roms/nes/Hacks/foo.nes, roms/nes/Translations/bar.nes -> each file a game +# nes: '{category}/{gameFile}' +# # roms/ps3/Disc/Game/, roms/ps3/PSN/Game/ -> each folder a multi-file game +# ps3: '{category}/{gameDir}' +# # roms/snes/USA/foo.sfc, roms/snes/Japan/bar.sfc +# snes: '{region}/{gameFile}' # scan: # # Metadata priority during scans @@ -145,38 +183,6 @@ # image: screenshot # Use as the tag in the exported gamelist.xml # pegasus: # export: false # Whether to export metadata.pegasus.txt for Pegasus -# # Recurse into platform subfolders, treating nested files as their own -# # ROMs rather than collapsing each subfolder into a single multi-file ROM. -# # Opt-in per platform. The value is either: -# # - true -> recurse EVERY subfolder of the platform; -# # - a list of folder names -> recurse ONLY those folders, leaving every -# # other folder as a single multi-file ROM (so folder-based multi-file -# # games elsewhere on the platform stay intact — the recommended form -# # when a platform mixes grouping folders with multi-file games); -# # - false / omitted -> default behavior (a subfolder is one multi-file ROM). -# # -# # Behavior & notes (read before enabling): -# # - Hidden (dot-prefixed) folders are never descended into. -# # - A subfolder containing a disc/playlist descriptor (.m3u, .cue, .gdi, -# # .ccd, .toc) is kept whole as a single multi-file ROM (a multi-disc -# # game) and is NOT split into one ROM per disc, even when recursed. -# # - With `true`, a multi-file game stored as a bare folder with no such -# # descriptor WOULD be split into separate ROMs. Use the named-list form -# # (don't list that game's folder) to keep it whole. -# # - Identity is content-based on scan: moving (or renaming) a ROM between -# # subfolders is detected by its hash and relocated in place, so its -# # saves, play history, favorites and collection membership follow it — -# # as long as hashing is enabled and the platform is hashable. When a -# # folder previously scanned as one multi-file ROM is now recursed, that -# # old entry is marked "missing from filesystem" (the scan log flags it); -# # delete the stale entry to clean up. -# # - Two files with the same name in different subfolders become distinct -# # ROMs; gamelist.xml metadata matching is by filename, so both may match -# # the same gamelist entry. -# subfolders: -# nes: true # recurse every NES subfolder -# snes: ["Hacks", "Translations"] # recurse only these; keep other folders whole -# megadrive: false # EmulatorJS per-core options # emulatorjs: