Coverage for src/romfarmer/cli/__init__.py: 0%
248 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
1"""Command-line interface for ROM Farmer."""
3from pathlib import Path
5import click
6from rich.console import Console
7from rich.table import Table
9from romfarmer.core.config import RomGroomerConfig
10from romfarmer.core.logger import get_logger
12from .build import build_group
13from .cache import cache_group
14from .cas import cas_group
15from .dat import dat_group
16from .doctor import doctor
17from .farmhand import farmhand_group
18from .generation import generation_group
19from .lists import lists_group
20from .metadata_commands import metadata_group
21from .organize import organize_group
22from .plan import plan_group
23from .quick import quick
24from .scan import scan_group
25from .scores import scores_group
26from .spec import spec_group
29@click.group()
30@click.option("--config", type=click.Path(exists=True), help="Config file path")
31@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
32@click.option("--quiet", "-q", is_flag=True, help="Quiet output")
33@click.pass_context
34def cli(ctx: click.Context, config: str, verbose: bool, quiet: bool) -> None:
35 """
36 ROM Farmer - Enterprise-grade ROM collection management.
38 Organize, validate, and manage your ROM collections with database-backed
39 cataloging and intelligent organization.
40 """
41 # Initialize context
42 ctx.ensure_object(dict)
44 # Load configuration
45 config_path = Path(config) if config else None
46 ctx.obj["config"] = RomGroomerConfig.load(config_path)
48 # Setup logging
49 import logging
51 if verbose:
52 level = logging.DEBUG
53 elif quiet:
54 level = logging.WARNING
55 else:
56 level = logging.INFO
58 ctx.obj["logger"] = get_logger(level=level)
59 ctx.obj["console"] = Console()
62@cli.command()
63@click.pass_context
64def init(ctx: click.Context) -> None:
65 """Initialize ROM Farmer configuration."""
66 logger = ctx.obj["logger"]
67 console = ctx.obj["console"]
69 logger.section("Initializing ROM Farmer")
71 # Create default configuration
72 config = RomGroomerConfig.create_default_config()
74 # Save configuration
75 config_path = Path.home() / ".config" / "romfarmer" / "config.yaml"
76 config.save(config_path)
78 logger.success(f"Configuration saved to [path]{config_path}[/path]")
80 # Create database directory
81 db_path = config.database.path
82 db_path.parent.mkdir(parents=True, exist_ok=True)
84 logger.success(f"Database directory created at [path]{db_path.parent}[/path]")
86 # Display profiles
87 console.print("\n[bold]Available Profiles:[/bold]")
88 table = Table(show_header=True, header_style="bold cyan")
89 table.add_column("Profile", style="green")
90 table.add_column("Regions")
91 table.add_column("Languages")
92 table.add_column("Exclude Regions")
94 for name, profile in config.profiles.items():
95 table.add_row(
96 name,
97 ", ".join(profile.regions),
98 "Yes" if profile.organize_languages else "No",
99 ", ".join(profile.exclude_language_regions),
100 )
102 console.print(table)
103 console.print("\n[dim]Edit ~/.config/romfarmer/config.yaml to customize profiles[/dim]")
106@cli.group()
107def catalog() -> None:
108 """Manage ROM catalog database."""
109 pass
112@catalog.command("stats")
113@click.pass_context
114def catalog_stats(ctx: click.Context) -> None:
115 """Display catalog statistics."""
116 from romfarmer.catalog.database import RomGroomerDatabase
118 config = ctx.obj["config"]
119 console = ctx.obj["console"]
121 db = RomGroomerDatabase(str(config.database.path))
123 with db.get_session() as session:
124 stats = db.get_statistics(session)
126 db.close()
128 console.print("\n[bold]Catalog Statistics[/bold]\n")
130 table = Table(show_header=False, box=None)
131 table.add_column("Metric", style="cyan")
132 table.add_column("Value", style="green", justify="right")
134 table.add_row("DAT Files", str(stats["total_dat_files"]))
135 table.add_row("DAT Games", str(stats["total_dat_games"]))
136 table.add_row("ROM Files", str(stats["total_rom_files"]))
137 table.add_row("Verified ROMs", str(stats["verified_roms"]))
138 table.add_row("Total Operations", str(stats["total_operations"]))
140 console.print(table)
141 console.print()
144@cli.command()
145@click.argument("source", type=click.Path(exists=True))
146@click.option("--profile", "-p", help="Organization profile to use")
147@click.option("--dest", "-d", type=click.Path(), help="Destination directory")
148@click.option("--dry-run", is_flag=True, help="Simulate without making changes")
149@click.pass_context
150def organize(
151 ctx: click.Context,
152 source: str,
153 profile: str,
154 dest: str,
155 dry_run: bool,
156) -> None:
157 """
158 Organize ROMs according to profile settings.
160 For specific organization modes, use the subcommands instead:
161 romfarmer organize region /roms/nes --keep-in-place USA
162 romfarmer organize kind /roms/nes
163 romfarmer organize language /roms/nes --mode hardlink
164 romfarmer organize alphabetical /roms/nes --strategy smart
165 romfarmer organize all /roms/nes --region-keep USA
167 Example:
168 romfarmer organize ~/roms/nes --profile nes-usa --dest ~/organized/nes
169 """
170 logger = ctx.obj["logger"]
171 config = ctx.obj["config"]
173 logger.section(f"Organizing ROMs from {source}")
175 if profile:
176 org_profile = config.get_profile(profile)
177 if not org_profile:
178 logger.error(f"Profile '{profile}' not found")
179 raise click.Abort()
181 logger.info(f"Using profile: [highlight]{profile}[/highlight]")
182 else:
183 logger.warning("No profile specified. Use a subcommand for direct organization:")
184 logger.info(" romfarmer organize region <dir>")
185 logger.info(" romfarmer organize kind <dir>")
186 logger.info(" romfarmer organize language <dir>")
187 logger.info(" romfarmer organize alphabetical <dir>")
188 logger.info(" romfarmer organize all <dir>")
189 return
192@cli.command()
193@click.argument("source", type=click.Path(exists=True))
194@click.option("--dat", type=click.Path(exists=True), help="DAT file for validation")
195@click.option("--check-size", is_flag=True, help="Flag zero-size files")
196@click.option("--check-m3u", is_flag=True, help="Verify M3U playlists reference existing files")
197@click.pass_context
198def validate(ctx: click.Context, source: str, dat: str, check_size: bool, check_m3u: bool) -> None:
199 """
200 Validate ROM collection against DAT file.
202 Example:
203 romfarmer validate ~/roms/nes --dat ~/dats/nes.dat
204 romfarmer validate ~/roms/saturn --check-size --check-m3u
205 """
206 from romfarmer.dat_parser.parser import DATParser
208 logger = ctx.obj["logger"]
209 console = ctx.obj["console"]
210 source_path = Path(source)
212 logger.section(f"Validating ROMs in {source}")
214 # Collect all files in source directory
215 all_files = sorted(f for f in source_path.rglob("*") if f.is_file())
217 if not all_files:
218 logger.error("No files found in source directory")
219 return
221 logger.info(f"Found {len(all_files)} files")
223 errors = 0
224 warnings = 0
226 # Basic checks (always run)
227 zero_files = [f for f in all_files if f.stat().st_size == 0]
228 if zero_files:
229 errors += len(zero_files)
230 logger.error(f"{len(zero_files)} zero-size file(s):")
231 for zf in zero_files[:10]:
232 logger.error(f" {zf.relative_to(source_path)}")
233 if len(zero_files) > 10:
234 logger.error(f" ... and {len(zero_files) - 10} more")
236 # M3U validation
237 if check_m3u:
238 m3u_files = [f for f in all_files if f.suffix.lower() == ".m3u"]
239 if m3u_files:
240 logger.info(f"Checking {len(m3u_files)} M3U playlists...")
241 for m3u in m3u_files:
242 try:
243 with open(m3u, encoding="utf-8", errors="ignore") as fh:
244 for line in fh:
245 line = line.strip()
246 if not line or line.startswith("#"):
247 continue
248 ref = m3u.parent / line
249 if not ref.exists():
250 logger.error(f" {m3u.name}: missing reference -> {line}")
251 errors += 1
252 except Exception as e:
253 logger.warning(f" Could not read {m3u.name}: {e}")
254 warnings += 1
256 # DAT validation
257 if dat:
258 dat_path = Path(dat)
259 logger.info(f"Parsing DAT: {dat_path.name}")
261 parser = DATParser()
262 dat_file = parser.parse(dat_path)
263 logger.info(
264 f"DAT contains {dat_file.get_game_count()} games, {dat_file.get_rom_count()} ROMs"
265 )
267 # Build set of ROM names from DAT (stem only for comparison)
268 dat_stems = {Path(rom.name).stem for game in dat_file.games for rom in game.roms}
270 # Build set of file stems we have
271 file_stems = {
272 f.stem for f in all_files if f.suffix.lower() not in {".m3u", ".xml", ".txt", ".cfg"}
273 }
275 # Files we have that aren't in DAT
276 extra = file_stems - dat_stems
277 if extra:
278 warnings += len(extra)
279 logger.warning(f"{len(extra)} file(s) not in DAT (extras/transforms OK):")
280 for name in sorted(extra)[:10]:
281 logger.warning(f" + {name}")
282 if len(extra) > 10:
283 logger.warning(f" ... and {len(extra) - 10} more")
285 # DAT entries we're missing
286 missing = dat_stems - file_stems
287 if missing:
288 logger.info(
289 f"{len(missing)} DAT entries not found on disk (normal for filtered builds):"
290 )
291 for name in sorted(missing)[:10]:
292 logger.info(f" - {name}")
293 if len(missing) > 10:
294 logger.info(f" ... and {len(missing) - 10} more")
296 matched = dat_stems & file_stems
297 logger.info(
298 f"DAT match: {len(matched)}/{len(dat_stems)} ({100 * len(matched) / max(len(dat_stems), 1):.0f}%)"
299 )
301 # Summary
302 table = Table(title="Validation Summary")
303 table.add_column("Check", style="cyan")
304 table.add_column("Result", style="green")
305 table.add_row("Total files", str(len(all_files)))
306 table.add_row("Zero-size files", f"[red]{len(zero_files)}[/red]" if zero_files else "0")
307 if dat:
308 table.add_row("DAT matched", str(len(matched)))
309 table.add_row("DAT missing", str(len(missing)))
310 table.add_row("Extra files", str(len(extra)))
311 table.add_row("Errors", f"[red]{errors}[/red]" if errors else "[green]0[/green]")
312 table.add_row("Warnings", f"[yellow]{warnings}[/yellow]" if warnings else "0")
313 console.print(table)
315 if errors > 0:
316 logger.error(f"Validation FAILED with {errors} error(s)")
317 else:
318 logger.success("Validation PASSED")
321@cli.group()
322def profile() -> None:
323 """Manage organization profiles."""
324 pass
327@profile.command("list")
328@click.pass_context
329def profile_list(ctx: click.Context) -> None:
330 """List all organization profiles."""
331 config = ctx.obj["config"]
332 console = ctx.obj["console"]
334 table = Table(show_header=True, header_style="bold cyan", title="Organization Profiles")
335 table.add_column("Profile", style="green")
336 table.add_column("Regions")
337 table.add_column("Languages")
338 table.add_column("Exclude Regions")
339 table.add_column("Kinds")
341 for name, prof in config.profiles.items():
342 table.add_row(
343 name,
344 ", ".join(prof.regions[:3]) + ("..." if len(prof.regions) > 3 else ""),
345 "✓" if prof.organize_languages else "✗",
346 ", ".join(prof.exclude_language_regions),
347 "✓" if prof.organize_kinds else "✗",
348 )
350 console.print(table)
353# ── Web UI Command ───────────────────────────────────────────────────────────
356@cli.command()
357@click.option("--host", default="0.0.0.0", help="Bind address")
358@click.option("--port", "-p", default=8420, type=int, help="Port number")
359@click.option(
360 "--config-dir", type=click.Path(exists=True), help="Config directory (default: ./config)"
361)
362@click.option("--reload", "live_reload", is_flag=True, help="Enable auto-reload for development")
363def web(host: str, port: int, config_dir: str, live_reload: bool) -> None:
364 """Launch the ROM Farmer web UI.
366 Starts a local web server for managing configs and builds
367 through a browser interface.
369 Example:
370 romfarmer web
371 romfarmer web --port 9000
372 romfarmer web --config-dir /path/to/config
373 """
374 try:
375 import uvicorn
376 except ImportError:
377 click.echo(
378 "Error: uvicorn is required. Install with: pip install 'romfarmer[web]'", err=True
379 )
380 raise click.Abort() from None
382 from pathlib import Path as _Path
384 config_root = _Path(config_dir) if config_dir else _Path.cwd() / "config"
385 if not config_root.exists():
386 click.echo(f"Config directory not found: {config_root}", err=True)
387 raise click.Abort()
389 click.echo(f"🎮 ROM Farmer Web UI — http://{host}:{port}")
390 click.echo(f" Config: {config_root}")
392 # Set config root via env so the app factory can pick it up
393 import os
395 os.environ["ROMFARMER_CONFIG_ROOT"] = str(config_root)
397 uvicorn.run(
398 "romfarmer.web.app:create_app",
399 factory=True,
400 host=host,
401 port=port,
402 reload=live_reload,
403 log_level="info",
404 )
407# Add command groups
408cli.add_command(quick)
409cli.add_command(build_group)
410cli.add_command(organize_group)
411cli.add_command(dat_group)
412cli.add_command(scan_group)
413cli.add_command(metadata_group)
414cli.add_command(lists_group)
415cli.add_command(cache_group)
416cli.add_command(cas_group)
417cli.add_command(farmhand_group)
418cli.add_command(generation_group)
419cli.add_command(spec_group)
420cli.add_command(scores_group)
421cli.add_command(plan_group, name="plan")
422cli.add_command(doctor)
425if __name__ == "__main__":
426 cli()