Coverage for src/romfarmer/cli/cache.py: 0%

155 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""Cache management CLI commands.""" 

2 

3import click 

4from rich.console import Console 

5from rich.table import Table 

6 

7from romfarmer.cache import CacheConfig, CacheManager 

8 

9 

10@click.group(name="cache") 

11def cache_group() -> None: 

12 """Manage ROM build cache. 

13 

14 The cache stores compressed ROMs (CHD, RVZ, etc.) to avoid rebuilding 

15 the same files. Uses hardlinks by default to save disk space. 

16 """ 

17 pass 

18 

19 

20@cache_group.command("status") 

21@click.option("--verbose", "-v", is_flag=True, help="Show detailed statistics") 

22@click.pass_context 

23def cache_status(ctx: click.Context, verbose: bool) -> None: 

24 """Display cache statistics and status.""" 

25 console = Console() 

26 

27 try: 

28 config = CacheConfig.from_env() 

29 manager = CacheManager(config) 

30 stats = manager.get_stats() 

31 

32 console.print("\n[bold cyan]ROM Build Cache Status[/bold cyan]\n") 

33 

34 # Status table 

35 table = Table(show_header=False, box=None) 

36 table.add_column("Property", style="dim") 

37 table.add_column("Value", style="green") 

38 

39 table.add_row("Enabled", "✓ Yes" if config.enabled else "✗ No") 

40 table.add_row("Cache Directory", str(config.cache_dir)) 

41 table.add_row("Link Mode", config.link_mode.value) 

42 table.add_row("Verify Level", config.verify_level.value) 

43 table.add_row("Check Tool Version", "✓ Yes" if config.check_tool_version else "✗ No") 

44 

45 console.print(table) 

46 console.print() 

47 

48 # Stats table 

49 stats_table = Table(show_header=True, header_style="bold cyan", title="Cache Statistics") 

50 stats_table.add_column("Metric", style="dim") 

51 stats_table.add_column("Value", justify="right", style="green") 

52 

53 stats_table.add_row("Total Entries", f"{stats['total_entries']:,}") 

54 stats_table.add_row("Total Size", _format_size(stats["total_size"])) 

55 stats_table.add_row("CHD Files", f"{stats.get('chd_count', 0):,}") 

56 stats_table.add_row("RVZ Files", f"{stats.get('rvz_count', 0):,}") 

57 stats_table.add_row("7z Files", f"{stats.get('7z_count', 0):,}") 

58 

59 if verbose and stats.get("tool_versions"): 

60 stats_table.add_row("", "") # Spacer 

61 for tool, version in stats["tool_versions"].items(): 

62 stats_table.add_row(f" {tool} version", version) 

63 

64 console.print(stats_table) 

65 

66 # Space savings estimate 

67 if stats["total_entries"] > 0: 

68 console.print( 

69 f"\n[dim]Estimated space saved by hardlinks: {_format_size(stats['total_size'])}[/dim]" 

70 ) 

71 

72 except Exception as e: 

73 console.print(f"[red]Error:[/red] {e}") 

74 raise click.Abort() from e 

75 

76 

77@cache_group.command("verify") 

78@click.option("--fix", is_flag=True, help="Remove invalid entries") 

79@click.pass_context 

80def cache_verify(ctx: click.Context, fix: bool) -> None: 

81 """Verify cache integrity. 

82 

83 Checks that all cached files exist and optionally validates checksums. 

84 """ 

85 console = Console() 

86 

87 try: 

88 config = CacheConfig.from_env() 

89 manager = CacheManager(config) 

90 

91 console.print("\n[bold cyan]Verifying ROM Build Cache...[/bold cyan]\n") 

92 

93 results = manager.verify_all() 

94 

95 valid = results["valid"] 

96 invalid = results["invalid"] 

97 missing = results["missing"] 

98 

99 # Results table 

100 table = Table(show_header=True, header_style="bold cyan") 

101 table.add_column("Status", style="dim") 

102 table.add_column("Count", justify="right") 

103 

104 table.add_row("[green]Valid[/green]", str(len(valid))) 

105 table.add_row("[yellow]Missing Files[/yellow]", str(len(missing))) 

106 table.add_row("[red]Invalid[/red]", str(len(invalid))) 

107 

108 console.print(table) 

109 

110 if missing: 

111 console.print("\n[yellow]Missing files:[/yellow]") 

112 for entry in missing[:10]: # Show first 10 

113 console.print(f" • {entry}") 

114 if len(missing) > 10: 

115 console.print(f" ... and {len(missing) - 10} more") 

116 

117 if invalid: 

118 console.print("\n[red]Invalid entries:[/red]") 

119 for entry in invalid[:10]: # Show first 10 

120 console.print(f" • {entry}") 

121 if len(invalid) > 10: 

122 console.print(f" ... and {len(invalid) - 10} more") 

123 

124 if fix and (missing or invalid): 

125 console.print("\n[bold]Removing invalid entries...[/bold]") 

126 removed = manager.remove_orphans() 

127 console.print(f"[green]Removed {removed} invalid entries.[/green]") 

128 elif missing or invalid: 

129 console.print("\n[dim]Run with --fix to remove invalid entries.[/dim]") 

130 else: 

131 console.print("\n[green]✓ All cache entries are valid![/green]") 

132 

133 except Exception as e: 

134 console.print(f"[red]Error:[/red] {e}") 

135 raise click.Abort() from e 

136 

137 

138@cache_group.command("clear") 

139@click.option( 

140 "--format", 

141 "file_format", 

142 type=click.Choice(["chd", "rvz", "7z", "all"]), 

143 default="all", 

144 help="Format to clear", 

145) 

146@click.option("--force", "-f", is_flag=True, help="Skip confirmation") 

147@click.pass_context 

148def cache_clear(ctx: click.Context, file_format: str, force: bool) -> None: 

149 """Clear the cache. 

150 

151 Removes all cached files and database entries. Use --format to clear 

152 only specific file types. 

153 """ 

154 console = Console() 

155 

156 try: 

157 config = CacheConfig.from_env() 

158 manager = CacheManager(config) 

159 stats = manager.get_stats() 

160 

161 if stats["total_entries"] == 0: 

162 console.print("[yellow]Cache is already empty.[/yellow]") 

163 return 

164 

165 # Confirmation 

166 if not force: 

167 console.print("\n[bold red]Warning:[/bold red] This will delete:") 

168 console.print(f" • {stats['total_entries']:,} cached files") 

169 console.print(f" • {_format_size(stats['total_size'])} of data") 

170 console.print() 

171 

172 if not click.confirm("Are you sure you want to clear the cache?"): 

173 console.print("[dim]Aborted.[/dim]") 

174 return 

175 

176 console.print("\n[bold]Clearing cache...[/bold]") 

177 

178 if file_format == "all": 

179 cleared = manager.clear() 

180 else: 

181 cleared = manager.clear(format=file_format) 

182 

183 console.print(f"[green]✓ Removed {cleared} entries from cache.[/green]") 

184 

185 except Exception as e: 

186 console.print(f"[red]Error:[/red] {e}") 

187 raise click.Abort() from e 

188 

189 

190@cache_group.command("prune") 

191@click.option("--older-than", type=int, default=90, help="Remove entries older than N days") 

192@click.option("--dry-run", is_flag=True, help="Show what would be removed without removing") 

193@click.pass_context 

194def cache_prune(ctx: click.Context, older_than: int, dry_run: bool) -> None: 

195 """Remove old cache entries. 

196 

197 Removes cache entries that haven't been accessed in the specified 

198 number of days. 

199 """ 

200 console = Console() 

201 

202 try: 

203 config = CacheConfig.from_env() 

204 manager = CacheManager(config) 

205 

206 console.print( 

207 f"\n[bold cyan]Pruning cache entries older than {older_than} days...[/bold cyan]\n" 

208 ) 

209 

210 entries = manager.get_old_entries(days=older_than) 

211 

212 if not entries: 

213 console.print("[green]No old entries to prune.[/green]") 

214 return 

215 

216 console.print(f"Found {len(entries)} entries to prune:") 

217 

218 total_size = sum(e.final_file_size or 0 for e in entries) 

219 console.print(f" • Total size: {_format_size(total_size)}") 

220 

221 if dry_run: 

222 console.print("\n[dim]Dry run - no entries removed.[/dim]") 

223 console.print("\n[bold]Entries that would be removed:[/bold]") 

224 for entry in entries[:20]: 

225 console.print(f" • {entry.source_md5[:8]}... ({entry.format})") 

226 if len(entries) > 20: 

227 console.print(f" ... and {len(entries) - 20} more") 

228 else: 

229 removed = manager.prune(days=older_than) 

230 console.print(f"\n[green]✓ Removed {removed} old entries.[/green]") 

231 

232 except Exception as e: 

233 console.print(f"[red]Error:[/red] {e}") 

234 raise click.Abort() from e 

235 

236 

237def _format_size(size_bytes: int) -> str: 

238 """Format bytes as human-readable size.""" 

239 if size_bytes == 0: 

240 return "0 B" 

241 

242 units = ["B", "KB", "MB", "GB", "TB"] 

243 unit_index = 0 

244 size = float(size_bytes) 

245 

246 while size >= 1024 and unit_index < len(units) - 1: 

247 size /= 1024 

248 unit_index += 1 

249 

250 return f"{size:.1f} {units[unit_index]}"