mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
feat: allow a list of structure templates per platform (union discovery)
A single fixed-depth template can't describe a platform that holds loose
games in its root AND organizes others into grouping subfolders — `{gameFile}`
drops the grouped games, `{category}/{gameFile}` drops the loose ones. Let a
platform's `filesystem.structure` value be a list of templates; discovery is
their union, deduplicated by full path:
structure:
nes:
- "{gameFile}" # loose top-level games
- "{category}/{gameFile}" # games inside grouping subfolders
- config: accept str | list[str]; platform_structure() returns a tuple of
parsed structures; parse_platform_structures() + validation handle both forms.
- fs handler: _collect_fs_roms unions each structure's discovery, dedup by
(fs_path, fs_name).
- tests: list parsing, per-platform list config loading, and the mixed
loose+grouped discovery case.
- docs: config.example.yml leads with the mixed-layout list example.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sk2dzM3K9qxWBdPAeGb7us
This commit is contained in:
@@ -121,6 +121,26 @@ def parse_library_structure(template: str) -> LibraryStructure:
|
||||
return LibraryStructure(levels=tuple(levels), each_file_is_game=each_file_is_game)
|
||||
|
||||
|
||||
def parse_platform_structures(
|
||||
value: str | list[str],
|
||||
) -> tuple[LibraryStructure, ...]:
|
||||
"""Parse a platform's custom structure config into one or more structures.
|
||||
|
||||
A platform may declare a single template (string) or several (list) — the
|
||||
list form lets one platform mix layouts, e.g. loose games at the root plus
|
||||
games inside grouping subfolders::
|
||||
|
||||
nes:
|
||||
- "{gameFile}"
|
||||
- "{category}/{gameFile}"
|
||||
|
||||
Discovery is the union of all listed templates. Raises ``ValueError`` if any
|
||||
template is invalid.
|
||||
"""
|
||||
templates = [value] if isinstance(value, str) else list(value)
|
||||
return tuple(parse_library_structure(template) for template in templates)
|
||||
|
||||
|
||||
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"
|
||||
@@ -211,7 +231,7 @@ class Config:
|
||||
PLATFORMS_VERSIONS: dict[str, str]
|
||||
ROMS_FOLDER_NAME: str
|
||||
FIRMWARE_FOLDER_NAME: str
|
||||
STRUCTURE_TEMPLATES: dict[str, str]
|
||||
STRUCTURE_TEMPLATES: dict[str, str | list[str]]
|
||||
SKIP_HASH_CALCULATION: bool
|
||||
EJS_DEBUG: bool
|
||||
EJS_CACHE_LIMIT: int | None
|
||||
@@ -254,18 +274,20 @@ class Config:
|
||||
|
||||
return False
|
||||
|
||||
def platform_structure(self, fs_slug: str) -> LibraryStructure | None:
|
||||
"""The custom library structure for a platform, or ``None``.
|
||||
def platform_structure(self, fs_slug: str) -> tuple[LibraryStructure, ...] | None:
|
||||
"""The custom library structure(s) for a platform, or ``None``.
|
||||
|
||||
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.
|
||||
``fs_slug -> template`` or ``fs_slug -> [template, ...]``). When unset,
|
||||
the platform uses RomM's default discovery (top-level files and
|
||||
folders). Returns the parsed structures whose discovery is unioned;
|
||||
templates are validated at load time, so parsing here is expected to
|
||||
succeed.
|
||||
"""
|
||||
template = getattr(self, "STRUCTURE_TEMPLATES", {}).get(fs_slug)
|
||||
if not template:
|
||||
value = getattr(self, "STRUCTURE_TEMPLATES", {}).get(fs_slug)
|
||||
if not value:
|
||||
return None
|
||||
return parse_library_structure(template)
|
||||
return parse_platform_structures(value)
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
@@ -775,21 +797,27 @@ class ConfigManager:
|
||||
"Invalid config.yml: filesystem.structure must be a dictionary"
|
||||
)
|
||||
sys.exit(3)
|
||||
for fs_slug, template in self.config.STRUCTURE_TEMPLATES.items():
|
||||
if not isinstance(template, str):
|
||||
for fs_slug, value in self.config.STRUCTURE_TEMPLATES.items():
|
||||
is_str = isinstance(value, str)
|
||||
is_str_list = isinstance(value, list) and all(
|
||||
isinstance(t, str) for t in value
|
||||
)
|
||||
if not (is_str or is_str_list):
|
||||
log.critical(
|
||||
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}"
|
||||
"template string or a list of template strings"
|
||||
)
|
||||
sys.exit(3)
|
||||
templates = [value] if is_str else value
|
||||
for template in templates:
|
||||
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)
|
||||
|
||||
# Drop unknown media types rather than exiting, since a newer release
|
||||
# may ship sample configs referencing media types this version doesn't know.
|
||||
|
||||
@@ -749,12 +749,28 @@ class FSRomsHandler(FSHandler):
|
||||
return fs_roms
|
||||
|
||||
async def _collect_fs_roms(self, platform: Platform) -> list[dict]:
|
||||
"""Discover a platform's roms, honoring its custom structure if set."""
|
||||
"""Discover a platform's roms, honoring its custom structure if set.
|
||||
|
||||
A platform may declare several structure templates (e.g. loose games at
|
||||
the root plus games inside grouping subfolders); discovery is their
|
||||
union, deduplicated by full path so overlapping templates don't surface
|
||||
a rom twice.
|
||||
"""
|
||||
rel_roms_path = self.get_roms_fs_structure(platform.fs_slug)
|
||||
structure = cm.get_config().platform_structure(platform.fs_slug)
|
||||
if structure is None:
|
||||
structures = cm.get_config().platform_structure(platform.fs_slug)
|
||||
if structures is None:
|
||||
return await self._discover_default_roms(rel_roms_path)
|
||||
return await self._discover_structured_roms(rel_roms_path, structure)
|
||||
|
||||
fs_roms: list[dict] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for structure in structures:
|
||||
for rom in await self._discover_structured_roms(rel_roms_path, structure):
|
||||
key = (rom["fs_path"], rom["fs_name"])
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
fs_roms.append(rom)
|
||||
return fs_roms
|
||||
|
||||
async def count_roms(self, platform: Platform) -> int:
|
||||
"""Return the number of filesystem roms for a platform without
|
||||
|
||||
@@ -32,7 +32,9 @@ filesystem:
|
||||
skip_hash_calculation: true
|
||||
structure:
|
||||
psx: "{category}/{gameDir}"
|
||||
nes: "{gameFile}"
|
||||
nes:
|
||||
- "{gameFile}"
|
||||
- "{category}/{gameFile}"
|
||||
|
||||
scan:
|
||||
priority:
|
||||
|
||||
@@ -9,6 +9,7 @@ from config.config_manager import (
|
||||
DEFAULT_EXCLUDED_FILES,
|
||||
ConfigManager,
|
||||
parse_library_structure,
|
||||
parse_platform_structures,
|
||||
)
|
||||
|
||||
|
||||
@@ -84,15 +85,19 @@ def test_config_loader():
|
||||
assert loader.config.GAMELIST_MEDIA_IMAGE == "title_screen"
|
||||
assert loader.config.STRUCTURE_TEMPLATES == {
|
||||
"psx": "{category}/{gameDir}",
|
||||
"nes": "{gameFile}",
|
||||
"nes": ["{gameFile}", "{category}/{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
|
||||
assert psx is not None and len(psx) == 1
|
||||
assert psx[0].each_file_is_game is False
|
||||
assert len(psx[0].levels) == 1 and psx[0].levels[0].literal is None
|
||||
# The list form yields one structure per template (union on discovery).
|
||||
nes = loader.config.platform_structure("nes")
|
||||
assert nes is not None and nes.each_file_is_game is True
|
||||
assert nes.levels == ()
|
||||
assert nes is not None and len(nes) == 2
|
||||
assert nes[0].each_file_is_game is True and nes[0].levels == ()
|
||||
assert nes[1].each_file_is_game is True
|
||||
assert len(nes[1].levels) == 1 and nes[1].levels[0].literal is None
|
||||
assert loader.config.platform_structure("snes") is None
|
||||
|
||||
|
||||
@@ -166,6 +171,23 @@ def test_parse_library_structure_invalid(template):
|
||||
parse_library_structure(template)
|
||||
|
||||
|
||||
def test_parse_platform_structures_string_and_list():
|
||||
# A bare string yields a single structure.
|
||||
single = parse_platform_structures("{gameFile}")
|
||||
assert len(single) == 1 and single[0].each_file_is_game is True
|
||||
|
||||
# A list yields one structure per template, preserving order.
|
||||
multi = parse_platform_structures(["{gameFile}", "{category}/{gameDir}"])
|
||||
assert len(multi) == 2
|
||||
assert multi[0].levels == () and multi[0].each_file_is_game is True
|
||||
assert len(multi[1].levels) == 1 and multi[1].each_file_is_game is False
|
||||
|
||||
|
||||
def test_parse_platform_structures_propagates_invalid():
|
||||
with pytest.raises(ValueError):
|
||||
parse_platform_structures(["{gameFile}", "nope"])
|
||||
|
||||
|
||||
def test_missing_config_file_is_created(tmp_path):
|
||||
config_file = tmp_path / "config" / "config.yml"
|
||||
|
||||
|
||||
@@ -560,6 +560,40 @@ class TestFSRomsHandler:
|
||||
assert all(r["fs_path"] == f"{base}/Hacks" for r in roms)
|
||||
assert count == len(roms)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_roms_structure_list_unions_loose_and_grouped(
|
||||
self, platform: Platform, tmp_path: Path
|
||||
):
|
||||
"""A list of templates unions their discovery: loose top-level games
|
||||
(`{gameFile}`) plus games inside grouping subfolders
|
||||
(`{category}/{gameFile}`) — the common mixed layout — without dropping
|
||||
either, deduplicated by full path."""
|
||||
handler = FSRomsHandler()
|
||||
handler.base_path = tmp_path
|
||||
with patch(
|
||||
"handler.filesystem.roms_handler.cm.get_config",
|
||||
lambda: self._make_structure_config(
|
||||
{platform.fs_slug: ["{gameFile}", "{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)
|
||||
|
||||
keys = {(r["fs_path"], r["fs_name"]) for r in roms}
|
||||
# Loose top-level game ({gameFile}).
|
||||
assert (base, "Top.zip") in keys
|
||||
# Grouped games one level down ({category}/{gameFile}).
|
||||
assert (f"{base}/Hacks", "Shared.zip") in keys
|
||||
assert (f"{base}/Hacks", "HackOnly.zip") in keys
|
||||
assert (f"{base}/Translations", "Shared.zip") in keys
|
||||
# Hidden folder still skipped; no duplicate full paths.
|
||||
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 count == len(roms)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_rom_files_single_rom(
|
||||
self, handler: FSRomsHandler, rom_single, config
|
||||
|
||||
@@ -93,6 +93,11 @@
|
||||
# # Any other braced section (e.g. {region}, {category}) is a wildcard
|
||||
# # directory level: it matches any folder and is purely organizational.
|
||||
# #
|
||||
# # A platform may also declare a LIST of templates instead of one; discovery
|
||||
# # is their union. This covers the common mixed layout — loose games at the
|
||||
# # platform root AND games inside grouping subfolders below it — which a
|
||||
# # single fixed-depth template can't express on its own.
|
||||
# #
|
||||
# # Notes:
|
||||
# # - Hidden (dot-prefixed) folders are never descended into or surfaced.
|
||||
# # - {gameDir} keeps a folder whole (multi-disc / cue+bin games), so there
|
||||
@@ -108,8 +113,12 @@
|
||||
# # 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}'
|
||||
# # Mixed: loose top-level games AND grouping subfolders below them, e.g.
|
||||
# # roms/nes/game01.nes (matched by {gameFile})
|
||||
# # roms/nes/Hacks/game03.nes (matched by {category}/{gameFile})
|
||||
# nes:
|
||||
# - '{gameFile}'
|
||||
# - '{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
|
||||
|
||||
Reference in New Issue
Block a user