Coverage for src/romfarmer/cli/organize.py: 0%
170 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""
2Organization CLI commands.
4Provides commands for organizing ROM collections by region, kind, and language.
5"""
7import logging
8from pathlib import Path
10import click
11from rich.console import Console
12from rich.table import Table
14from ..organizers import (
15 AlphabeticalOrganizer,
16 GenreOrganizer,
17 KindOrganizer,
18 LanguageOrganizer,
19 OrganizeMode,
20 RegionOrganizer,
21)
23logger = logging.getLogger(__name__)
24console = Console()
27@click.group("organize")
28def organize_group():
29 """Organize ROM collections by various criteria."""
30 pass
33@organize_group.command("region")
34@click.argument("source_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
35@click.option(
36 "--mode",
37 type=click.Choice(["move", "copy", "symlink", "hardlink"], case_sensitive=False),
38 default="move",
39 help="How to organize files (move, copy, symlink, or hardlink)",
40)
41@click.option(
42 "--keep-in-place",
43 multiple=True,
44 help="Regions to keep in root directory (e.g., --keep-in-place USA --keep-in-place World)",
45)
46@click.option(
47 "--exclude",
48 multiple=True,
49 help="Regions to exclude from organization",
50)
51@click.option(
52 "--priority",
53 multiple=True,
54 help="Region priority for multi-region ROMs (e.g., --priority USA --priority Europe)",
55)
56@click.option(
57 "--extensions",
58 multiple=True,
59 help="File extensions to process (e.g., --extensions .nes --extensions .sfc)",
60)
61@click.option(
62 "--recursive/--no-recursive",
63 default=False,
64 help="Process subdirectories recursively (default: root-level only)",
65)
66@click.option(
67 "--dry-run",
68 is_flag=True,
69 help="Preview changes without making them",
70)
71def organize_region(
72 source_dir: Path,
73 mode: str,
74 keep_in_place: tuple,
75 exclude: tuple,
76 priority: tuple,
77 extensions: tuple,
78 recursive: bool,
79 dry_run: bool,
80):
81 """
82 Organize ROMs by region.
84 Examples:
86 # Keep USA and World in root, organize others
87 romfarmer organize region /roms/nes --keep-in-place USA --keep-in-place World
89 # Create symlinks instead of moving files
90 romfarmer organize region /roms/nes --mode symlink
92 # Dry run to preview changes
93 romfarmer organize region /roms/nes --dry-run
94 """
95 console.print("\n[bold cyan]Region Organization[/bold cyan]")
96 console.print(f"Source: {source_dir}")
97 console.print(f"Mode: {mode}")
98 if dry_run:
99 console.print("[yellow]DRY RUN MODE - No changes will be made[/yellow]")
100 console.print()
102 # Create organizer
103 organizer = RegionOrganizer(
104 mode=OrganizeMode(mode),
105 dry_run=dry_run,
106 region_priority=list(priority) if priority else None,
107 keep_in_place=list(keep_in_place) if keep_in_place else None,
108 exclude_regions=list(exclude) if exclude else None,
109 )
111 # Organize
112 stats = organizer.organize(
113 source_dir=source_dir,
114 recursive=recursive,
115 extensions=list(extensions) if extensions else None,
116 )
118 # Display results
119 console.print("\n[bold green]Organization Complete![/bold green]")
120 _display_stats(stats)
123@organize_group.command("kind")
124@click.argument("source_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
125@click.option(
126 "--mode",
127 type=click.Choice(["move", "copy", "symlink", "hardlink"], case_sensitive=False),
128 default="move",
129 help="How to organize files (move, copy, symlink, or hardlink)",
130)
131@click.option(
132 "--keep-in-place",
133 multiple=True,
134 help="Kinds to keep in root directory (e.g., --keep-in-place Demo --keep-in-place Beta)",
135)
136@click.option(
137 "--exclude",
138 multiple=True,
139 help="Kinds to exclude from organization",
140)
141@click.option(
142 "--extensions",
143 multiple=True,
144 help="File extensions to process",
145)
146@click.option(
147 "--recursive/--no-recursive",
148 default=False,
149 help="Process subdirectories recursively (default: root-level only)",
150)
151@click.option(
152 "--dry-run",
153 is_flag=True,
154 help="Preview changes without making them",
155)
156def organize_kind(
157 source_dir: Path,
158 mode: str,
159 keep_in_place: tuple,
160 exclude: tuple,
161 extensions: tuple,
162 recursive: bool,
163 dry_run: bool,
164):
165 """
166 Organize ROMs by kind (Demo, Beta, Homebrew, etc.).
168 Examples:
170 # Keep Demos in place, organize others
171 romfarmer organize kind /roms/nes --keep-in-place Demo
173 # Exclude pirate ROMs from organization
174 romfarmer organize kind /roms/nes --exclude Pirate
176 # Create symlinks for virtual organization
177 romfarmer organize kind /roms/nes --mode symlink
178 """
179 console.print("\n[bold cyan]Kind Organization[/bold cyan]")
180 console.print(f"Source: {source_dir}")
181 console.print(f"Mode: {mode}")
182 if dry_run:
183 console.print("[yellow]DRY RUN MODE - No changes will be made[/yellow]")
184 console.print()
186 # Create organizer
187 organizer = KindOrganizer(
188 mode=OrganizeMode(mode),
189 dry_run=dry_run,
190 keep_in_place=list(keep_in_place) if keep_in_place else None,
191 exclude_kinds=list(exclude) if exclude else None,
192 )
194 # Organize
195 stats = organizer.organize(
196 source_dir=source_dir,
197 recursive=recursive,
198 extensions=list(extensions) if extensions else None,
199 )
201 # Display results
202 console.print("\n[bold green]Organization Complete![/bold green]")
203 _display_stats(stats)
206@organize_group.command("language")
207@click.argument("source_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
208@click.option(
209 "--mode",
210 type=click.Choice(["move", "copy", "symlink", "hardlink"], case_sensitive=False),
211 default="symlink", # Symlink is typical for language organization
212 help="How to organize files (move, copy, or symlink)",
213)
214@click.option(
215 "--keep-in-place",
216 multiple=True,
217 help="Languages to keep in root directory",
218)
219@click.option(
220 "--exclude",
221 multiple=True,
222 help="Languages to exclude from organization (e.g., --exclude En for English)",
223)
224@click.option(
225 "--priority",
226 multiple=True,
227 help="Language priority for multi-language ROMs",
228)
229@click.option(
230 "--use-codes",
231 is_flag=True,
232 help="Use language codes (En, Fr) instead of full names (English, French)",
233)
234@click.option(
235 "--extensions",
236 multiple=True,
237 help="File extensions to process",
238)
239@click.option(
240 "--recursive/--no-recursive",
241 default=False,
242 help="Process subdirectories recursively (default: root-level only)",
243)
244@click.option(
245 "--dry-run",
246 is_flag=True,
247 help="Preview changes without making them",
248)
249def organize_language(
250 source_dir: Path,
251 mode: str,
252 keep_in_place: tuple,
253 exclude: tuple,
254 priority: tuple,
255 use_codes: bool,
256 extensions: tuple,
257 recursive: bool,
258 dry_run: bool,
259):
260 """
261 Organize ROMs by language.
263 Creates language-specific directories (typically using symlinks for virtual organization).
265 Examples:
267 # Create language symlinks, exclude English (default)
268 romfarmer organize language /roms/nes --exclude En
270 # Use full language names instead of codes
271 romfarmer organize language /roms/nes --exclude English
273 # Move files instead of symlinking
274 romfarmer organize language /roms/nes --mode move
275 """
276 console.print("\n[bold cyan]Language Organization[/bold cyan]")
277 console.print(f"Source: {source_dir}")
278 console.print(f"Mode: {mode}")
279 if dry_run:
280 console.print("[yellow]DRY RUN MODE - No changes will be made[/yellow]")
281 console.print()
283 # Create organizer
284 organizer = LanguageOrganizer(
285 mode=OrganizeMode(mode),
286 dry_run=dry_run,
287 language_priority=list(priority) if priority else None,
288 keep_in_place=list(keep_in_place) if keep_in_place else None,
289 exclude_languages=list(exclude) if exclude else None,
290 use_full_names=not use_codes,
291 )
293 # Organize
294 stats = organizer.organize(
295 source_dir=source_dir,
296 recursive=recursive,
297 extensions=list(extensions) if extensions else None,
298 )
300 # Display results
301 console.print("\n[bold green]Organization Complete![/bold green]")
302 _display_stats(stats)
305@organize_group.command("all")
306@click.argument("source_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
307@click.option(
308 "--region-keep",
309 multiple=True,
310 help="Regions to keep in root",
311)
312@click.option(
313 "--kind-keep",
314 multiple=True,
315 help="Kinds to keep in place",
316)
317@click.option(
318 "--lang-exclude",
319 multiple=True,
320 help="Languages to exclude (e.g., --lang-exclude En)",
321)
322@click.option(
323 "--extensions",
324 multiple=True,
325 help="File extensions to process",
326)
327@click.option(
328 "--dry-run",
329 is_flag=True,
330 help="Preview changes without making them",
331)
332def organize_all(
333 source_dir: Path,
334 region_keep: tuple,
335 kind_keep: tuple,
336 lang_exclude: tuple,
337 extensions: tuple,
338 dry_run: bool,
339):
340 """
341 Organize ROMs by region, kind, AND language in one command.
343 This runs all three organizers in sequence:
344 1. Region (move files)
345 2. Kind (move files recursively in each region)
346 3. Language (create symlinks)
348 Example:
350 # Full organization: Keep USA in root, organize kinds, symlink languages
351 romfarmer organize all /roms/nes --region-keep USA --lang-exclude En
352 """
353 console.print("\n[bold cyan]Full Organization[/bold cyan]")
354 console.print(f"Source: {source_dir}")
355 if dry_run:
356 console.print("[yellow]DRY RUN MODE - No changes will be made[/yellow]")
357 console.print()
359 ext_list = list(extensions) if extensions else None
361 # Phase 1: Region organization
362 console.print("[bold]Phase 1: Organizing by region...[/bold]")
363 region_org = RegionOrganizer(
364 mode=OrganizeMode.MOVE,
365 dry_run=dry_run,
366 keep_in_place=list(region_keep) if region_keep else None,
367 )
368 region_stats = region_org.organize(source_dir, recursive=True, extensions=ext_list)
369 console.print(f" Files moved: {region_stats.files_moved}")
371 # Phase 2: Kind organization (recursive in all folders)
372 console.print("\n[bold]Phase 2: Organizing by kind...[/bold]")
373 kind_org = KindOrganizer(
374 mode=OrganizeMode.MOVE,
375 dry_run=dry_run,
376 keep_in_place=list(kind_keep) if kind_keep else None,
377 )
378 kind_stats = kind_org.organize(source_dir, recursive=True, extensions=ext_list)
379 console.print(f" Files moved: {kind_stats.files_moved}")
381 # Phase 3: Language organization (symlinks)
382 console.print("\n[bold]Phase 3: Creating language symlinks...[/bold]")
383 lang_org = LanguageOrganizer(
384 mode=OrganizeMode.SYMLINK,
385 dry_run=dry_run,
386 exclude_languages=list(lang_exclude) if lang_exclude else None,
387 )
388 lang_stats = lang_org.organize(source_dir, recursive=True, extensions=ext_list)
389 console.print(f" Symlinks created: {lang_stats.symlinks_created}")
391 # Display combined results
392 console.print("\n[bold green]Full Organization Complete![/bold green]")
394 table = Table(title="Combined Statistics")
395 table.add_column("Metric", style="cyan")
396 table.add_column("Count", style="magenta", justify="right")
398 total_processed = (
399 region_stats.files_processed + kind_stats.files_processed + lang_stats.files_processed
400 )
401 total_moved = region_stats.files_moved + kind_stats.files_moved
402 total_symlinks = lang_stats.symlinks_created
404 table.add_row("Files Processed", str(total_processed))
405 table.add_row("Files Moved", str(total_moved))
406 table.add_row("Symlinks Created", str(total_symlinks))
407 table.add_row("Errors", str(region_stats.errors + kind_stats.errors + lang_stats.errors))
409 console.print(table)
412@organize_group.command("alphabetical")
413@click.argument("source_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
414@click.option(
415 "--mode",
416 type=click.Choice(["move", "copy", "symlink", "hardlink"], case_sensitive=False),
417 default="move",
418 help="How to organize files (move, copy, symlink, or hardlink)",
419)
420@click.option(
421 "--strategy",
422 type=click.Choice(["per_letter", "balanced", "smart"], case_sensitive=False),
423 default="smart",
424 help="Grouping strategy: per_letter (A/B/..), balanced (A-E/F-M/..), smart (adaptive)",
425)
426@click.option(
427 "--max-per-group",
428 default=50,
429 type=int,
430 help="Maximum files per group (smart strategy only, default 50)",
431)
432@click.option(
433 "--extensions",
434 multiple=True,
435 help="File extensions to process",
436)
437@click.option(
438 "--dry-run",
439 is_flag=True,
440 help="Preview changes without making them",
441)
442def organize_alphabetical(
443 source_dir: Path,
444 mode: str,
445 strategy: str,
446 max_per_group: int,
447 extensions: tuple,
448 dry_run: bool,
449):
450 """
451 Split ROMs into alphabetical subdirectories.
453 Ideal for flashcarts (Everdrive, MiSTer) and low-power systems where
454 browsing hundreds of files in one folder is impractical.
456 Strategies:
457 per_letter: A/, B/, ..., Z/, #/
458 balanced: A-E/, F-M/, N-Z/, #/
459 smart: Adaptive ranges keeping each folder ≤ max-per-group files
461 Examples:
463 # Everdrive-friendly split (50 per folder)
464 romfarmer organize alphabetical /roms/nes --strategy smart
466 # Per-letter split for large collections
467 romfarmer organize alphabetical /roms/snes --strategy per_letter
469 # Hardlink into letter folders (keep originals, zero-cost)
470 romfarmer organize alphabetical /roms/gba --mode hardlink
471 """
472 console.print("\n[bold cyan]Alphabetical Organization[/bold cyan]")
473 console.print(f"Source: {source_dir}")
474 console.print(f"Mode: {mode}, Strategy: {strategy}, Max/group: {max_per_group}")
475 if dry_run:
476 console.print("[yellow]DRY RUN MODE - No changes will be made[/yellow]")
477 console.print()
479 organizer = AlphabeticalOrganizer(
480 mode=OrganizeMode(mode),
481 dry_run=dry_run,
482 strategy=strategy,
483 max_per_group=max_per_group,
484 )
486 stats = organizer.organize(
487 source_dir=source_dir,
488 extensions=list(extensions) if extensions else None,
489 )
491 console.print("\n[bold green]Organization Complete![/bold green]")
492 _display_stats(stats)
495@organize_group.command("genre")
496@click.argument("source_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
497@click.option(
498 "--system",
499 "-s",
500 required=True,
501 help="Platform/system name for metadata lookup (e.g., nes, snes, megadrive)",
502)
503@click.option(
504 "--mode",
505 type=click.Choice(["move", "copy", "symlink", "hardlink"], case_sensitive=False),
506 default="hardlink",
507 help="How to organize files (default: hardlink for zero-cost genre views)",
508)
509@click.option(
510 "--keep-in-place",
511 multiple=True,
512 help="Genres to keep in root directory",
513)
514@click.option(
515 "--exclude",
516 multiple=True,
517 help="Genres to exclude from organization",
518)
519@click.option(
520 "--merge-small",
521 type=int,
522 default=3,
523 help="Merge genres with fewer than N games into 'Other' (0 to disable)",
524)
525@click.option(
526 "--metadata-db",
527 type=click.Path(path_type=Path),
528 default=None,
529 help="Path to metadata DB (default: auto-detect)",
530)
531@click.option(
532 "--extensions",
533 multiple=True,
534 help="File extensions to process",
535)
536@click.option(
537 "--recursive/--no-recursive",
538 default=False,
539 help="Process subdirectories recursively (default: root-level only)",
540)
541@click.option(
542 "--dry-run",
543 is_flag=True,
544 help="Preview changes without making them",
545)
546def organize_genre(
547 source_dir: Path,
548 system: str,
549 mode: str,
550 keep_in_place: tuple,
551 exclude: tuple,
552 merge_small: int,
553 metadata_db: Path | None,
554 extensions: tuple,
555 recursive: bool,
556 dry_run: bool,
557):
558 """
559 Organize ROMs by genre (Action, RPG, Sports, etc.) using metadata DB.
561 Looks up genre information from the ScreenScraper/ARRM metadata database
562 and creates genre-specific subdirectories. Defaults to hardlink mode so
563 games appear in genre folders at zero disk cost.
565 Examples:
567 # Organize NES ROMs by genre (hardlinked)
568 romfarmer organize genre /roms/nes -s nes
570 # Organize arcade ROMs by genre, merge rare genres
571 romfarmer organize genre /roms/mame -s mame --merge-small 5
573 # Preview what would happen
574 romfarmer organize genre /roms/snes -s snes --dry-run
576 # Exclude 'Other' category
577 romfarmer organize genre /roms/psx -s psx --exclude Other
578 """
579 # Resolve metadata DB
580 if metadata_db is None:
581 from ..core.paths import get_paths
583 metadata_db = get_paths().metadata_db
585 if not metadata_db.exists():
586 console.print(f"[red]Metadata DB not found: {metadata_db}[/red]")
587 console.print("Run ARRM import first to populate genre data.")
588 raise click.Abort()
590 console.print("\n[bold cyan]Genre Organization[/bold cyan]")
591 console.print(f"Source: {source_dir}")
592 console.print(f"System: {system}")
593 console.print(f"Mode: {mode}")
594 console.print(
595 f"Merge small genres: {'disabled' if merge_small == 0 else f'< {merge_small} games'}"
596 )
597 if dry_run:
598 console.print("[yellow]DRY RUN MODE - No changes will be made[/yellow]")
599 console.print()
601 organizer = GenreOrganizer(
602 metadata_db=metadata_db,
603 system=system,
604 mode=OrganizeMode(mode),
605 dry_run=dry_run,
606 keep_in_place=list(keep_in_place) if keep_in_place else None,
607 exclude_genres=list(exclude) if exclude else None,
608 merge_small=merge_small,
609 )
611 stats = organizer.organize(
612 source_dir=source_dir,
613 recursive=recursive,
614 extensions=list(extensions) if extensions else None,
615 )
617 console.print("\n[bold green]Genre Organization Complete![/bold green]")
618 _display_stats(stats)
621def _display_stats(stats):
622 """Display organization statistics in a nice table."""
623 table = Table(title="Organization Statistics")
624 table.add_column("Metric", style="cyan")
625 table.add_column("Count", style="magenta", justify="right")
627 table.add_row("Files Processed", str(stats.files_processed))
628 table.add_row("Files Moved", str(stats.files_moved))
629 table.add_row("Files Copied", str(stats.files_copied))
630 table.add_row("Symlinks Created", str(stats.symlinks_created))
631 table.add_row("Directories Created", str(stats.directories_created))
632 table.add_row("Files Skipped", str(stats.skipped))
633 table.add_row("Errors", str(stats.errors))
635 console.print(table)