Coverage for src/romfarmer/organizers/base.py: 0%
210 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""
2Base organizer classes and types.
4Provides the foundation for ROM organization with support for:
5- Physical organization (moving/copying files)
6- Virtual organization (creating symlinks)
7- Dry-run mode for preview
8"""
10import logging
11import shutil
12from abc import ABC, abstractmethod
13from dataclasses import dataclass
14from enum import Enum
15from pathlib import Path
17logger = logging.getLogger(__name__)
20class OrganizeMode(str, Enum):
21 """How to organize files."""
23 MOVE = "move" # Move files (physical organization)
24 COPY = "copy" # Copy files (physical organization)
25 SYMLINK = "symlink" # Create symlinks (virtual organization)
26 HARDLINK = "hardlink" # Create hardlinks (zero-cost duplicates on same FS)
29# Directories that contain metadata/media, not ROMs.
30# Files inside these are always skipped by organizers.
31METADATA_DIRS = frozenset(
32 {
33 "media",
34 "images",
35 "videos",
36 "manuals",
37 "thumbnails",
38 "screenshots",
39 "marquees",
40 "boxart",
41 "cartridges",
42 "mix",
43 "titles",
44 "downloaded_images",
45 "downloaded_videos",
46 }
47)
50@dataclass
51class OrganizeStats:
52 """Statistics from an organization operation."""
54 files_processed: int = 0
55 files_moved: int = 0
56 files_copied: int = 0
57 symlinks_created: int = 0
58 directories_created: int = 0
59 errors: int = 0
60 skipped: int = 0
62 def __str__(self) -> str:
63 """Return a human-readable summary."""
64 lines = [
65 f"Files processed: {self.files_processed}",
66 f"Files moved: {self.files_moved}",
67 f"Files copied: {self.files_copied}",
68 f"Symlinks created: {self.symlinks_created}",
69 f"Directories created: {self.directories_created}",
70 f"Files skipped: {self.skipped}",
71 f"Errors: {self.errors}",
72 ]
73 return "\n".join(lines)
76class BaseOrganizer(ABC):
77 """
78 Base class for ROM organizers.
80 Provides common functionality for organizing ROMs by different criteria
81 (region, kind, language, etc.).
83 Args:
84 mode: How to organize files (move, copy, or symlink)
85 dry_run: Preview changes without actually making them
86 keep_in_place: List of values to keep in root (not organize)
87 exclude_values: List of values to exclude from organization
88 """
90 def __init__(
91 self,
92 mode: OrganizeMode = OrganizeMode.MOVE,
93 dry_run: bool = False,
94 keep_in_place: list[str] | None = None,
95 exclude_values: list[str] | None = None,
96 ):
97 self.mode = mode
98 self.dry_run = dry_run
99 self.keep_in_place = set(keep_in_place or [])
100 self.exclude_values = set(exclude_values or [])
101 self.stats = OrganizeStats()
103 @abstractmethod
104 def get_organization_value(self, filename: str) -> str | None:
105 """
106 Extract the organization value from a filename.
108 For example:
109 - RegionOrganizer extracts region: "Super Mario (USA).nes" -> "USA"
110 - KindOrganizer extracts kind: "Demo (Demo).nes" -> "Demo"
111 - LanguageOrganizer extracts language: "Game (En).nes" -> "En"
113 Args:
114 filename: The ROM filename
116 Returns:
117 The organization value, or None if not detected
118 """
119 pass
121 @abstractmethod
122 def get_organization_dir_name(self) -> str:
123 """
124 Get the directory name for this organization type.
126 Returns:
127 Directory name (e.g., "By Region", "By Kind", "By Language")
128 """
129 pass
131 def should_organize(self, value: str) -> bool:
132 """
133 Check if a value should be organized.
135 Args:
136 value: The value to check
138 Returns:
139 True if the value should be organized, False if kept in place
140 """
141 # Excluded values are never organized
142 if value in self.exclude_values:
143 logger.debug(f"Skipping '{value}' (excluded)")
144 return False
146 # Values in keep_in_place stay in root
147 if value in self.keep_in_place:
148 logger.debug(f"Keeping '{value}' in place")
149 return False
151 return True
153 def create_directory(self, path: Path) -> bool:
154 """
155 Create a directory if it doesn't exist.
157 Args:
158 path: Directory path to create
160 Returns:
161 True if directory was created, False if it already existed
162 """
163 if path.exists():
164 return False
166 if self.dry_run:
167 logger.info(f"Would create directory: {path}")
168 return True
170 path.mkdir(parents=True, exist_ok=True)
171 logger.info(f"Created directory: {path}")
172 self.stats.directories_created += 1
173 return True
175 def move_file(self, source: Path, dest_dir: Path) -> bool:
176 """
177 Move a file to a destination directory.
179 Args:
180 source: Source file path
181 dest_dir: Destination directory
183 Returns:
184 True if successful, False otherwise
185 """
186 dest_file = dest_dir / source.name
188 if dest_file.exists():
189 logger.debug(f"Skipping {source.name} (already exists)")
190 self.stats.skipped += 1
191 return False
193 if self.dry_run:
194 logger.debug(f"Would move: {source} -> {dest_file}")
195 return True
197 try:
198 # Create destination directory
199 self.create_directory(dest_dir)
201 # Move the file
202 shutil.move(str(source), str(dest_file))
203 logger.debug(f"Moved: {source.name} -> {dest_dir.name}/")
204 self.stats.files_moved += 1
205 return True
207 except Exception as e:
208 logger.error(f"Failed to move {source}: {e}")
209 self.stats.errors += 1
210 return False
212 def copy_file(self, source: Path, dest_dir: Path) -> bool:
213 """
214 Copy a file to a destination directory.
216 Args:
217 source: Source file path
218 dest_dir: Destination directory
220 Returns:
221 True if successful, False otherwise
222 """
223 dest_file = dest_dir / source.name
225 if dest_file.exists():
226 logger.debug(f"Skipping {source.name} (already exists)")
227 self.stats.skipped += 1
228 return False
230 if self.dry_run:
231 logger.debug(f"Would copy: {source} -> {dest_file}")
232 return True
234 try:
235 # Create destination directory
236 self.create_directory(dest_dir)
238 # Copy the file
239 shutil.copy2(str(source), str(dest_file))
240 logger.debug(f"Copied: {source.name} -> {dest_dir.name}/")
241 self.stats.files_copied += 1
242 return True
244 except Exception as e:
245 logger.error(f"Failed to copy {source}: {e}")
246 self.stats.errors += 1
247 return False
249 def create_symlink(self, source: Path, dest_dir: Path) -> bool:
250 """
251 Create a symlink in the destination directory.
253 Args:
254 source: Source file path
255 dest_dir: Destination directory for symlink
257 Returns:
258 True if successful, False otherwise
259 """
260 dest_link = dest_dir / source.name
262 if dest_link.exists():
263 logger.debug(f"Skipping {source.name} (already exists)")
264 self.stats.skipped += 1
265 return False
267 # Calculate relative path from symlink to source
268 try:
269 relative_path = source.resolve().relative_to(dest_dir.resolve())
270 except ValueError:
271 # Can't make relative path, use absolute
272 relative_path = source.resolve()
274 if self.dry_run:
275 logger.debug(f"Would create symlink: {dest_link} -> {relative_path}")
276 return True
278 try:
279 # Create destination directory
280 self.create_directory(dest_dir)
282 # Create symlink
283 dest_link.symlink_to(relative_path)
284 logger.debug(f"Created symlink: {dest_dir.name}/{source.name} -> {relative_path}")
285 self.stats.symlinks_created += 1
286 return True
288 except Exception as e:
289 logger.error(f"Failed to create symlink for {source}: {e}")
290 self.stats.errors += 1
291 return False
293 def hardlink_file(self, source: Path, dest_dir: Path) -> bool:
294 """
295 Create a hardlink in the destination directory.
297 Hardlinks are zero-cost on the same filesystem — the file appears
298 in multiple places but uses no additional disk space. Ideal for
299 organizing ROMs into multiple views (by region, language, etc.)
300 without duplicating data.
302 Args:
303 source: Source file path
304 dest_dir: Destination directory
306 Returns:
307 True if successful, False otherwise
308 """
309 import os
311 dest_file = dest_dir / source.name
313 if dest_file.exists():
314 logger.debug(f"Skipping {source.name} (already exists)")
315 self.stats.skipped += 1
316 return False
318 if self.dry_run:
319 logger.debug(f"Would hardlink: {source} -> {dest_file}")
320 return True
322 try:
323 self.create_directory(dest_dir)
324 os.link(source, dest_file)
325 logger.debug(f"Hardlinked: {source.name} -> {dest_dir.name}/")
326 self.stats.files_copied += 1 # Count as copy in stats (file in two places)
327 return True
328 except OSError as e:
329 logger.error(f"Failed to hardlink {source} (cross-filesystem?): {e}")
330 self.stats.errors += 1
331 return False
333 def organize_file(self, source: Path, dest_dir: Path) -> bool:
334 """
335 Organize a file (or directory) based on the configured mode.
337 Directories cannot be hardlinked; when the source is a directory
338 a symlink is always created regardless of the configured mode.
340 Args:
341 source: Source file or directory path
342 dest_dir: Destination directory
344 Returns:
345 True if successful, False otherwise
346 """
347 # Directories can't be hardlinked or copied atomically — use symlinks
348 if source.is_dir():
349 return self.create_symlink(source, dest_dir)
351 if self.mode == OrganizeMode.MOVE:
352 return self.move_file(source, dest_dir)
353 elif self.mode == OrganizeMode.COPY:
354 return self.copy_file(source, dest_dir)
355 elif self.mode == OrganizeMode.SYMLINK:
356 return self.create_symlink(source, dest_dir)
357 elif self.mode == OrganizeMode.HARDLINK:
358 return self.hardlink_file(source, dest_dir)
359 else:
360 logger.error(f"Unknown organize mode: {self.mode}")
361 return False
363 def _collect_rom_files(
364 self,
365 source_dir: Path,
366 org_dir_name: str,
367 recursive: bool = False,
368 extensions: list[str] | None = None,
369 ) -> list[Path]:
370 """
371 Collect ROM files eligible for organization.
373 Skips:
374 - Non-file entries (directories)
375 - Files inside the target organization folder (e.g., ``By Genre/``)
376 - Files inside any other known organization folder (``By Kind/``, etc.)
377 - Files inside metadata/media directories (``media/``, ``images/``, etc.)
378 - Files inside any existing subdirectory when ``recursive=False`` (default)
380 The default ``recursive=False`` means only root-level files are
381 processed. Curated subdirectories like ``Best Games/`` or
382 ``English Translations/`` are left untouched.
383 """
384 # All known organization directory names
385 org_dir_names = {
386 "By Genre",
387 "By Kind",
388 "By Language",
389 "By Region",
390 "By Letter",
391 org_dir_name,
392 }
394 if recursive:
395 files = list(source_dir.glob("**/*"))
396 else:
397 files = list(source_dir.glob("*"))
399 # Normalize extensions
400 if extensions:
401 extensions = [
402 ext.lower() if ext.startswith(".") else f".{ext.lower()}" for ext in extensions
403 ]
404 files = [f for f in files if f.suffix.lower() in extensions]
406 # Filter: files only, skip metadata and organization dirs
407 result = []
408 for f in files:
409 if not f.is_file():
410 continue
412 # Get the path parts relative to source_dir
413 try:
414 rel = f.relative_to(source_dir)
415 except ValueError:
416 continue
418 # Skip files inside organization directories
419 if org_dir_names & set(rel.parts):
420 continue
422 # Skip files inside metadata/media directories
423 if METADATA_DIRS & {p.lower() for p in rel.parts}:
424 continue
426 result.append(f)
428 return result
430 def _collect_rom_dirs(
431 self,
432 source_dir: Path,
433 org_dir_name: str,
434 ) -> list[Path]:
435 """
436 Collect root-level ROM directories eligible for organization.
438 Used for directory-based ROM formats (e.g., PS3 JB folders with
439 ``.ps3`` suffix, PS2 ISO folders, etc.) where each game is a
440 directory rather than a single file.
442 Skips organization directories (``By Genre/`` etc.), metadata
443 directories, and any directory without a file-extension suffix
444 (those are assumed to be curated subdirs, not ROM containers).
445 """
446 org_dir_names = {
447 "By Genre",
448 "By Kind",
449 "By Language",
450 "By Region",
451 "By Letter",
452 org_dir_name,
453 }
455 result = []
456 for entry in source_dir.iterdir():
457 if not entry.is_dir():
458 continue
460 name = entry.name
462 # Skip organization and metadata directories
463 if name in org_dir_names:
464 continue
465 if name.lower() in METADATA_DIRS:
466 continue
468 # Only treat directories with a suffix as ROM containers
469 # (e.g. "007 - Blood Stone.ps3") — bare dirs are curated subdirs
470 if not entry.suffix:
471 continue
473 result.append(entry)
475 return result
477 def organize(
478 self,
479 source_dir: Path,
480 dest_dir: Path | None = None,
481 recursive: bool = False,
482 extensions: list[str] | None = None,
483 ) -> OrganizeStats:
484 """
485 Organize ROMs in a directory.
487 Args:
488 source_dir: Directory containing ROMs to organize
489 dest_dir: Base destination directory (defaults to source_dir)
490 recursive: Whether to process subdirectories (default False —
491 only root-level files are organized; curated subdirs
492 like Best Games/ are left alone)
493 extensions: File extensions to process (e.g., ['.nes', '.sfc'])
494 If None, processes all files
496 Returns:
497 OrganizeStats object with operation statistics
498 """
499 if dest_dir is None:
500 dest_dir = source_dir
502 # Reset stats
503 self.stats = OrganizeStats()
505 logger.info(f"Starting {self.__class__.__name__}")
506 logger.info(f"Source: {source_dir}")
507 logger.info(f"Mode: {self.mode.value}")
508 logger.info(f"Dry run: {self.dry_run}")
510 # Get organization directory name
511 org_dir_name = self.get_organization_dir_name()
513 # Collect eligible ROM files
514 files = self._collect_rom_files(source_dir, org_dir_name, recursive, extensions)
516 logger.info(f"Found {len(files)} file(s) to process")
518 # Process each file
519 for file_path in files:
520 self.stats.files_processed += 1
522 # Get organization value from filename
523 value = self.get_organization_value(file_path.name)
525 if value is None:
526 logger.debug(f"No {org_dir_name} value detected: {file_path.name}")
527 continue
529 # Check if should organize this value
530 if not self.should_organize(value):
531 continue
533 # Build destination path
534 target_dir = dest_dir / org_dir_name / value
536 # Organize the file
537 self.organize_file(file_path, target_dir)
539 logger.info(f"Organization complete: {self.stats}")
540 return self.stats