mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 12:52:19 +01:00
feat: opt-in per-platform subfolder scanning with non-destructive identity
Adds opt-in, per-platform subfolder scanning (closes #2050). When enabled for a platform, RomM recurses that platform's subfolders and treats each nested file as its own ROM, instead of collapsing a subfolder into one multi-file ROM — so libraries organized into Hacks/, Translations/, Homebrew/, etc. are scanned correctly. Enable per platform in config.yml (default off, existing setups unaffected): scan: subfolders: nes: true # recurse every subfolder snes: ["Hacks", "Translations"] # recurse only these; keep others whole Key difference from a naive path-identity approach: identity is reconciled by content hash on scan. Moving or renaming a ROM between subfolders is detected by its hash against a now-missing ROM and relocated in place, so saves, play history, favorites and collection membership follow it. Falls back to path identity when hashing is unavailable (skip_hash_calculation or a non-hashable platform). A cheap size pre-filter avoids hashing every newly-seen file (e.g. on first enable). Details: - Per-platform opt-in via scan.subfolders (fs_slug -> bool | list[str]); no DB schema change. - Recursion skips hidden (dot-prefixed) folders, and keeps a folder whole as a single multi-file ROM when it holds a disc/playlist descriptor (.m3u/.cue/.gdi/.ccd/.toc) — covers cue+bin / multi-disc games. - Path-based keying for the steady-state lookup (get_roms_by_fs_name and mark_missing_roms key on full path) so identically-named files in different subfolders stay distinct; the (platform_id, fs_name) index is non-unique. - File resolution (download/delete/hash) uses the ROM's stored fs_path. - Scan log flags entries that became "missing" because a folder is now recursed, so stale entries are easy to clean up. - Frontend: the Files tab shows a ROM's on-disk Location (click-to-copy), built as a shared LocationChip mirroring HashChip's RTag-based pattern. New i18n keys added to all locales. Tests: backend unit tests for recursion (collisions, hidden folders, descriptor dirs kept whole, named-list form), full-path keying in get_roms_by_fs_name / mark_missing_roms, and hash-based relocation. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Sk2dzM3K9qxWBdPAeGb7us
This commit is contained in:
@@ -1171,7 +1171,11 @@ class DBRomsHandler(DBBaseHandler):
|
||||
fs_names: Iterable[str],
|
||||
session: Session = None, # type: ignore
|
||||
) -> dict[str, Rom]:
|
||||
"""Retrieve a dictionary of roms by their filesystem names.
|
||||
"""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.
|
||||
|
||||
Eager-loads only `platform` (used downstream by the scan loop via
|
||||
`rom.platform_slug` / `rom.platform.fs_slug`). This deliberately
|
||||
@@ -1195,7 +1199,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
.all()
|
||||
)
|
||||
|
||||
return {rom.fs_name: rom for rom in roms}
|
||||
return {rom.full_path: rom for rom in roms}
|
||||
|
||||
@begin_session
|
||||
def update_rom(
|
||||
@@ -1278,19 +1282,23 @@ class DBRomsHandler(DBBaseHandler):
|
||||
) -> Sequence[Rom]:
|
||||
"""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.
|
||||
|
||||
Reads the rows once and writes only those whose state actually
|
||||
changes, so a re-scan of an unchanged platform issues no updates.
|
||||
"""
|
||||
keep_set = set(fs_roms_to_keep)
|
||||
rows = session.execute(
|
||||
select(Rom.id, Rom.fs_name, Rom.missing_from_fs).where(
|
||||
select(Rom.id, Rom.fs_path, Rom.fs_name, Rom.missing_from_fs).where(
|
||||
Rom.platform_id == platform_id
|
||||
)
|
||||
).all()
|
||||
|
||||
flips: dict[bool, list[int]] = {True: [], False: []}
|
||||
for rom_id, fs_name, was_missing in rows:
|
||||
is_missing = fs_name not in keep_set
|
||||
for rom_id, fs_path, fs_name, was_missing in rows:
|
||||
is_missing = f"{fs_path}/{fs_name}" not in keep_set
|
||||
if is_missing != was_missing:
|
||||
flips[is_missing].append(rom_id)
|
||||
|
||||
@@ -1305,8 +1313,12 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
return (
|
||||
session.scalars(
|
||||
# `fs_path` is eager-loaded alongside `fs_name` so callers can
|
||||
# read `rom.full_path` after the session closes (the returned
|
||||
# instances are detached); without it that lazy-loads and raises
|
||||
# DetachedInstanceError.
|
||||
select(Rom)
|
||||
.options(load_only(Rom.id, Rom.fs_name))
|
||||
.options(load_only(Rom.id, Rom.fs_name, Rom.fs_path))
|
||||
.where(
|
||||
and_(
|
||||
Rom.platform_id == platform_id,
|
||||
@@ -1319,6 +1331,40 @@ class DBRomsHandler(DBBaseHandler):
|
||||
.all()
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_roms_for_relocation(
|
||||
self,
|
||||
platform_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Rom]:
|
||||
"""Light-weight load of a platform's roms for relocation matching.
|
||||
|
||||
Returns detached rom instances carrying only the columns needed to
|
||||
detect a moved/renamed file by content (identity hashes + size) and to
|
||||
resolve its current `full_path`. Used by the scan loop to relocate a
|
||||
rom whose on-disk path changed instead of re-importing it as new.
|
||||
"""
|
||||
return (
|
||||
session.scalars(
|
||||
select(Rom)
|
||||
.options(
|
||||
load_only(
|
||||
Rom.id,
|
||||
Rom.fs_name,
|
||||
Rom.fs_path,
|
||||
Rom.fs_size_bytes,
|
||||
Rom.crc_hash,
|
||||
Rom.md5_hash,
|
||||
Rom.sha1_hash,
|
||||
Rom.ra_hash,
|
||||
)
|
||||
)
|
||||
.where(Rom.platform_id == platform_id)
|
||||
)
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def add_rom_user(
|
||||
self,
|
||||
|
||||
@@ -88,6 +88,7 @@ NON_HASHABLE_PLATFORMS = frozenset(
|
||||
|
||||
class FSRom(TypedDict):
|
||||
fs_name: str
|
||||
fs_path: str
|
||||
flat: bool
|
||||
nested: bool
|
||||
files: list[RomFile]
|
||||
@@ -316,10 +317,11 @@ class FSRomsHandler(FSHandler):
|
||||
from adapters.services.rahasher import RAHasherService
|
||||
from handler.metadata import meta_ra_handler
|
||||
|
||||
rel_roms_path = self.get_roms_fs_structure(
|
||||
rom.platform.fs_slug
|
||||
) # Relative path to roms
|
||||
abs_fs_path = self.validate_path(rel_roms_path) # Absolute path to roms
|
||||
# The rom's stored directory is the source of truth for its location, so
|
||||
# roms inside a platform subfolder (subfolder scanning) 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
|
||||
rom_files: list[RomFile] = []
|
||||
|
||||
# Skip hashing games for platforms that don't have a hash database or when hashes are disabled
|
||||
@@ -392,14 +394,19 @@ class FSRomsHandler(FSHandler):
|
||||
try:
|
||||
if is_top_level:
|
||||
# Include this file in the main ROM hash calculation
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(f_path, file_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
rom_sha1_h,
|
||||
)
|
||||
(
|
||||
crc_c,
|
||||
rom_crc_c,
|
||||
md5_h,
|
||||
rom_md5_h,
|
||||
sha1_h,
|
||||
rom_sha1_h,
|
||||
) = await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(f_path, file_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
rom_sha1_h,
|
||||
)
|
||||
else:
|
||||
# Calculate individual file hash only
|
||||
@@ -529,14 +536,19 @@ class FSRomsHandler(FSHandler):
|
||||
)
|
||||
elif hashable_platform:
|
||||
try:
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(abs_fs_path, rom.fs_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
rom_sha1_h,
|
||||
)
|
||||
(
|
||||
crc_c,
|
||||
rom_crc_c,
|
||||
md5_h,
|
||||
rom_md5_h,
|
||||
sha1_h,
|
||||
rom_sha1_h,
|
||||
) = await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(abs_fs_path, rom.fs_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
rom_sha1_h,
|
||||
)
|
||||
except zlib.error:
|
||||
crc_c = 0
|
||||
@@ -664,21 +676,93 @@ 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")
|
||||
|
||||
@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.
|
||||
"""
|
||||
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,
|
||||
}
|
||||
)
|
||||
|
||||
return fs_roms
|
||||
|
||||
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)
|
||||
fs_single_roms = await self.list_files(path=rel_roms_path)
|
||||
fs_multi_roms = await self.list_directories(path=rel_roms_path)
|
||||
return len(await self._collect_fs_roms(rel_roms_path, recurse))
|
||||
except FileNotFoundError as e:
|
||||
raise RomsNotFoundException(platform=platform.fs_slug) from e
|
||||
|
||||
return len(self.exclude_single_files(fs_single_roms)) + len(
|
||||
self.exclude_multi_roms(fs_multi_roms)
|
||||
)
|
||||
|
||||
async def get_roms(self, platform: Platform) -> list[FSRom]:
|
||||
"""Gets all filesystem roms for a platform
|
||||
|
||||
@@ -687,28 +771,20 @@ 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_single_roms = await self.list_files(path=rel_roms_path)
|
||||
fs_multi_roms = await self.list_directories(path=rel_roms_path)
|
||||
fs_roms = await self._collect_fs_roms(rel_roms_path, recurse)
|
||||
except FileNotFoundError as e:
|
||||
raise RomsNotFoundException(platform=platform.fs_slug) from e
|
||||
|
||||
fs_roms: list[dict] = [
|
||||
{"fs_name": rom, "flat": True, "nested": False}
|
||||
for rom in self.exclude_single_files(fs_single_roms)
|
||||
] + [
|
||||
{"fs_name": rom, "flat": False, "nested": True}
|
||||
for rom in self.exclude_multi_roms(fs_multi_roms)
|
||||
]
|
||||
|
||||
return sorted(
|
||||
[
|
||||
FSRom(
|
||||
fs_name=rom["fs_name"],
|
||||
fs_path=rom["fs_path"],
|
||||
flat=rom["flat"],
|
||||
nested=rom["nested"],
|
||||
files=[],
|
||||
@@ -719,7 +795,7 @@ class FSRomsHandler(FSHandler):
|
||||
)
|
||||
for rom in fs_roms
|
||||
],
|
||||
key=lambda rom: rom["fs_name"],
|
||||
key=lambda rom: (rom["fs_path"], rom["fs_name"]),
|
||||
)
|
||||
|
||||
async def rename_fs_rom(self, old_name: str, new_name: str, fs_path: str) -> None:
|
||||
|
||||
Reference in New Issue
Block a user