Coverage for src/romfarmer/cli/cas.py: 0%
194 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"""CAS (Content-Addressable Store) CLI commands.
3Provides tools for bulk-ingesting existing folder outputs into the CAS
4and tree cache, e.g. PS3 JB folders that were built before rom-farmer
5tracked them.
6"""
8import hashlib
9import time
10from pathlib import Path
12import click
13from rich.console import Console
14from rich.progress import (
15 BarColumn,
16 MofNCompleteColumn,
17 Progress,
18 SpinnerColumn,
19 TextColumn,
20 TimeElapsedColumn,
21 TimeRemainingColumn,
22)
23from rich.table import Table
25from romfarmer.cache import CacheConfig, CacheManager
26from romfarmer.cas import ContentStore, TreeStore
29@click.group(name="cas")
30def cas_group() -> None:
31 """Content-Addressable Store operations.
33 Manage the CAS blob store and tree manifests.
34 Ingest existing folder builds into the cache for future deduplication.
35 """
36 pass
39@cas_group.command("ingest")
40@click.argument(
41 "source_dir",
42 type=click.Path(exists=True, file_okay=False, resolve_path=True),
43)
44@click.option(
45 "--platform",
46 default="ps3",
47 help="Platform identifier (default: ps3)",
48)
49@click.option(
50 "--format",
51 "output_format",
52 default="ps3-jb",
53 help="Output format (default: ps3-jb)",
54)
55@click.option(
56 "--suffix",
57 default=".ps3",
58 help="Folder suffix to match (default: .ps3)",
59)
60@click.option(
61 "--myrient-dir",
62 type=click.Path(exists=True, file_okay=False, resolve_path=True),
63 help="Myrient source directory for ZIP matching (optional)",
64)
65@click.option(
66 "--store-dir",
67 type=click.Path(resolve_path=True),
68 default=None,
69 help="CAS store directory (default: ./store)",
70)
71@click.option(
72 "--hash-sources",
73 is_flag=True,
74 default=False,
75 help="Compute MD5 of Myrient source ZIPs (slow, ~hours for full set)",
76)
77@click.option(
78 "--dry-run",
79 is_flag=True,
80 default=False,
81 help="Show what would be ingested without doing it",
82)
83@click.option(
84 "--limit",
85 type=int,
86 default=0,
87 help="Limit number of folders to ingest (0=all)",
88)
89@click.option(
90 "--skip-existing",
91 is_flag=True,
92 default=True,
93 help="Skip folders already in tree cache (default: True)",
94)
95def cas_ingest(
96 source_dir: str,
97 platform: str,
98 output_format: str,
99 suffix: str,
100 myrient_dir: str | None,
101 store_dir: str | None,
102 hash_sources: bool,
103 dry_run: bool,
104 limit: int,
105 skip_existing: bool,
106) -> None:
107 """Ingest existing folder builds into the CAS via hardlinks.
109 Walks SOURCE_DIR for folders matching --suffix (default: .ps3),
110 ingests each into the CAS tree store using hardlinks (zero-copy
111 on the same filesystem), and records tree cache entries.
113 Examples:
115 # Ingest all PS3 JB folders
116 romfarmer cas ingest /path/to/ps3netsrv/GAMES/
118 # With Myrient source matching
119 romfarmer cas ingest /path/to/ps3netsrv/GAMES/ \\
120 --myrient-dir "/path/to/myrient/Redump/Sony - PlayStation 3"
122 # Dry run first
123 romfarmer cas ingest /path/to/ps3netsrv/GAMES/ --dry-run
125 # Ingest just one folder for testing
126 romfarmer cas ingest /path/to/ps3netsrv/GAMES/ --limit 1
127 """
128 console = Console()
129 source_path = Path(source_dir)
130 myrient_path = Path(myrient_dir) if myrient_dir else None
132 # Default store_dir to ./store relative to cwd
133 cas_dir = Path(store_dir) if store_dir else Path.cwd() / "store"
135 # ── Discover folders ──────────────────────────────────────────────
136 folders = sorted([d for d in source_path.iterdir() if d.is_dir() and d.name.endswith(suffix)])
138 if not folders:
139 console.print(f"[yellow]No folders matching *{suffix} found in {source_dir}[/yellow]")
140 return
142 console.print("\n[bold cyan]CAS Batch Ingest[/bold cyan]")
143 console.print(f" Source: {source_dir}")
144 console.print(f" Platform: {platform}")
145 console.print(f" Format: {output_format}")
146 console.print(f" Suffix: {suffix}")
147 console.print(f" CAS dir: {cas_dir}")
148 if myrient_path:
149 console.print(f" Myrient: {myrient_path}")
150 console.print(f" Folders: {len(folders)}")
151 console.print()
153 # ── Build Myrient source lookup ───────────────────────────────────
154 myrient_zips: dict[str, Path] = {}
155 if myrient_path:
156 for zf in myrient_path.iterdir():
157 if zf.is_file() and zf.suffix == ".zip":
158 # Key: stem matches folder name without .ps3
159 myrient_zips[zf.stem] = zf
160 console.print(f" Myrient ZIPs indexed: {len(myrient_zips)}")
162 # ── Initialize CAS + Cache ────────────────────────────────────────
163 store = ContentStore(cas_dir)
164 tree_store = TreeStore(store)
166 config = CacheConfig.from_env()
167 cache_manager = CacheManager(config)
169 # ── Check existing entries ────────────────────────────────────────
170 existing_folders: set[str] = set()
171 if skip_existing:
172 try:
173 from romfarmer.cache.models import TreeCache
175 existing = (
176 cache_manager.session.query(TreeCache.folder_name)
177 .filter_by(
178 format=output_format,
179 )
180 .all()
181 )
182 existing_folders = {row[0] for row in existing}
183 if existing_folders:
184 console.print(f" Already cached: {len(existing_folders)} (will skip)")
185 except Exception:
186 pass # Table may not exist yet
188 # ── Filter ────────────────────────────────────────────────────────
189 to_ingest = []
190 skipped = 0
191 for folder in folders:
192 if skip_existing and folder.name in existing_folders:
193 skipped += 1
194 continue
195 to_ingest.append(folder)
197 if limit > 0:
198 to_ingest = to_ingest[:limit]
200 if skipped:
201 console.print(f" Skipping: {skipped} already in cache")
202 console.print(f" To ingest: {len(to_ingest)}")
203 console.print()
205 # ── Dry run ───────────────────────────────────────────────────────
206 if dry_run:
207 console.print("[bold yellow]DRY RUN — no changes will be made[/bold yellow]\n")
208 table = Table(title="Folders to Ingest", show_lines=False)
209 table.add_column("#", style="dim", width=5)
210 table.add_column("Folder", style="green")
211 table.add_column("Source ZIP", style="cyan")
212 for i, folder in enumerate(to_ingest, 1):
213 base = folder.stem # e.g., "Terraria (USA) (En,Fr,Es)"
214 source_zip = myrient_zips.get(base)
215 table.add_row(str(i), folder.name, source_zip.name if source_zip else "—")
216 if i >= 50:
217 table.add_row("...", f"(+{len(to_ingest) - 50} more)", "")
218 break
219 console.print(table)
220 return
222 if not to_ingest:
223 console.print("[green]Nothing to ingest — all folders already cached.[/green]")
224 return
226 # ── Ingest loop ───────────────────────────────────────────────────
227 results = {"success": 0, "error": 0, "files": 0, "bytes": 0}
228 errors: list[tuple[str, str]] = []
229 t0 = time.monotonic()
231 with Progress(
232 SpinnerColumn(),
233 TextColumn("[bold blue]{task.description}[/bold blue]"),
234 BarColumn(),
235 MofNCompleteColumn(),
236 TimeElapsedColumn(),
237 TimeRemainingColumn(),
238 console=console,
239 ) as progress:
240 task = progress.add_task("Ingesting folders", total=len(to_ingest))
242 for folder in to_ingest:
243 folder_name = folder.name
244 base_name = folder.stem # folder name without .ps3
246 progress.update(task, description=f"[bold blue]{folder_name}[/bold blue]")
248 try:
249 # ── Ingest into CAS via hardlinks ─────────────────────
250 manifest = tree_store.ingest(
251 folder,
252 platform=platform,
253 format=output_format,
254 source_name=base_name,
255 tool="batch-ingest",
256 hardlink=True,
257 )
259 # ── Match Myrient source ──────────────────────────────
260 source_zip = myrient_zips.get(base_name)
261 # Generate a deterministic pseudo-MD5 from folder name
262 # so each folder gets a unique cache key. Without this,
263 # all entries share source_md5="0"*32 and overwrite each
264 # other (store_tree upserts on source_md5+format+params).
265 source_md5 = hashlib.md5(folder_name.encode()).hexdigest()
266 source_size = 0
267 source_filename = folder_name
269 if source_zip:
270 source_filename = source_zip.name
271 source_size = source_zip.stat().st_size
272 if hash_sources:
273 source_md5 = _md5_file(source_zip)
275 # ── Record in tree cache ──────────────────────────────
276 cache_manager.store_tree(
277 source_md5=source_md5,
278 tree_hash=manifest.tree_hash,
279 total_files=manifest.total_files,
280 total_size=manifest.total_size,
281 folder_name=folder_name,
282 format=output_format,
283 platform=platform,
284 tool_name="batch-ingest",
285 source_filename=source_filename,
286 source_size=source_size,
287 )
289 results["success"] += 1
290 results["files"] += manifest.total_files
291 results["bytes"] += manifest.total_size
293 except Exception as e:
294 results["error"] += 1
295 errors.append((folder_name, str(e)))
297 progress.advance(task)
299 elapsed = time.monotonic() - t0
301 # ── Summary ───────────────────────────────────────────────────────
302 console.print()
303 console.print("[bold cyan]Ingest Complete[/bold cyan]\n")
305 table = Table(show_header=False, box=None)
306 table.add_column("", style="dim")
307 table.add_column("", style="green")
309 table.add_row("Ingested", f"{results['success']:,} folders")
310 table.add_row("Files", f"{results['files']:,}")
311 table.add_row("Total Size", _format_size(results["bytes"]))
312 table.add_row("Errors", f"[red]{results['error']}[/red]" if results["error"] else "0")
313 table.add_row("Elapsed", f"{elapsed:.1f}s")
315 if results["success"] > 0:
316 rate = results["files"] / elapsed if elapsed > 0 else 0
317 table.add_row("Rate", f"{rate:.0f} files/s")
319 console.print(table)
321 if errors:
322 console.print(f"\n[bold red]Errors ({len(errors)}):[/bold red]")
323 for name, err in errors[:20]:
324 console.print(f" [red]✗[/red] {name}: {err}")
325 if len(errors) > 20:
326 console.print(f" ... and {len(errors) - 20} more")
329@cas_group.command("status")
330def cas_status() -> None:
331 """Show CAS store and tree cache statistics."""
332 console = Console()
333 cas_dir = Path.cwd() / "store"
335 if not cas_dir.exists():
336 console.print("[yellow]CAS store not found at ./store[/yellow]")
337 return
339 store = ContentStore(cas_dir)
340 TreeStore(store)
342 # Blob stats
343 console.print("\n[bold cyan]CAS Store Status[/bold cyan]\n")
344 stats = store.stats()
346 table = Table(show_header=False, box=None)
347 table.add_column("", style="dim")
348 table.add_column("", style="green")
349 table.add_row("Store Dir", str(cas_dir))
350 table.add_row("Total Blobs", f"{stats['total_files']:,}")
351 table.add_row("Total Size", _format_size(stats["total_size"]))
352 table.add_row("Buckets Used", f"{stats['buckets_used']}/256")
353 console.print(table)
355 # Tree cache stats
356 try:
357 config = CacheConfig.from_env()
358 manager = CacheManager(config)
359 tree_stats = manager.get_tree_stats()
361 console.print("\n[bold cyan]Tree Cache[/bold cyan]\n")
362 tree_table = Table(show_header=False, box=None)
363 tree_table.add_column("", style="dim")
364 tree_table.add_column("", style="green")
365 tree_table.add_row("Entries", f"{tree_stats.get('total_entries', 0):,}")
366 tree_table.add_row("Platforms", str(tree_stats.get("platforms", {})))
367 tree_table.add_row("Formats", str(tree_stats.get("formats", {})))
368 console.print(tree_table)
369 except Exception as e:
370 console.print(f"[dim]Tree cache: {e}[/dim]")
373def _md5_file(path: Path, chunk_size: int = 1_048_576) -> str:
374 """Compute MD5 hex digest of a file."""
375 h = hashlib.md5()
376 with open(path, "rb") as f:
377 while True:
378 chunk = f.read(chunk_size)
379 if not chunk:
380 break
381 h.update(chunk)
382 return h.hexdigest()
385def _format_size(size_bytes: int) -> str:
386 """Format bytes as human-readable size."""
387 if size_bytes == 0:
388 return "0 B"
389 units = ["B", "KB", "MB", "GB", "TB"]
390 unit_index = 0
391 size = float(size_bytes)
392 while size >= 1024 and unit_index < len(units) - 1:
393 size /= 1024
394 unit_index += 1
395 return f"{size:.1f} {units[unit_index]}"