Coverage for src/romfarmer/cli/quick.py: 0%
201 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"""Quick build command - interactive wizard for creating and running builds."""
3from pathlib import Path
5import click
6import yaml
7from rich.console import Console
8from rich.panel import Panel
9from rich.prompt import Confirm, Prompt
10from rich.table import Table
12console = Console()
15def discover_platforms(config_root: Path = None) -> list[dict]:
16 """Discover available platform configurations."""
17 if config_root is None:
18 config_root = Path("config")
20 platforms_dir = config_root / "platforms"
21 if not platforms_dir.exists():
22 return []
24 platforms = []
25 for yaml_file in platforms_dir.glob("*.yaml"):
26 try:
27 with open(yaml_file) as f:
28 config = yaml.safe_load(f)
29 platforms.append(
30 {
31 "file": yaml_file.stem,
32 "name": config.get("name", yaml_file.stem),
33 "description": config.get("description", ""),
34 "dat_count": config.get("dat", {}).get("expected_count", "?"),
35 "enabled": config.get("enabled", True),
36 }
37 )
38 except Exception as e:
39 console.print(f"[yellow]Warning: Could not load {yaml_file.name}: {e}[/yellow]")
41 return sorted(platforms, key=lambda x: x["name"])
44def discover_selections(config_root: Path = None) -> list[dict]:
45 """Discover available selection configurations."""
46 if config_root is None:
47 config_root = Path("config")
49 selections_dir = config_root / "selections"
50 if not selections_dir.exists():
51 return []
53 selections = []
54 for yaml_file in selections_dir.glob("*.yaml"):
55 try:
56 with open(yaml_file) as f:
57 config = yaml.safe_load(f)
58 selections.append(
59 {
60 "file": yaml_file.stem,
61 "name": config.get("name", yaml_file.stem),
62 "description": config.get("description", ""),
63 "strategy": config.get("strategy", "unknown"),
64 "limit": config.get("limit", None),
65 "max_size_gb": config.get("max_size_gb", None),
66 }
67 )
68 except Exception as e:
69 console.print(f"[yellow]Warning: Could not load {yaml_file.name}: {e}[/yellow]")
71 return sorted(selections, key=lambda x: x["name"])
74def discover_builds(config_root: Path = None) -> list[dict]:
75 """Discover existing build configurations."""
76 if config_root is None:
77 config_root = Path("config")
79 builds_dir = config_root / "builds"
80 if not builds_dir.exists():
81 return []
83 builds = []
84 for yaml_file in builds_dir.glob("*.yaml"):
85 if yaml_file.stem.startswith("."): # Skip hidden files
86 continue
87 try:
88 with open(yaml_file) as f:
89 config = yaml.safe_load(f)
90 builds.append(
91 {
92 "file": yaml_file.stem,
93 "name": config.get("name", yaml_file.stem),
94 "description": config.get("description", ""),
95 "platforms": config.get("platforms", []),
96 }
97 )
98 except Exception as e:
99 console.print(f"[yellow]Warning: Could not load {yaml_file.name}: {e}[/yellow]")
101 return sorted(builds, key=lambda x: x["name"])
104def display_platforms(platforms: list[dict]) -> None:
105 """Display platforms in a nice table."""
106 table = Table(title="Available Platforms", show_header=True, header_style="bold cyan")
107 table.add_column("#", style="dim", width=3)
108 table.add_column("Platform", style="green")
109 table.add_column("Games", justify="right")
110 table.add_column("Description")
112 for i, platform in enumerate(platforms, 1):
113 table.add_row(
114 str(i), platform["name"], str(platform["dat_count"]), platform["description"] or "—"
115 )
117 console.print(table)
120def display_selections(selections: list[dict]) -> None:
121 """Display selections in a nice table."""
122 table = Table(
123 title="Available Selection Strategies", show_header=True, header_style="bold cyan"
124 )
125 table.add_column("#", style="dim", width=3)
126 table.add_column("Name", style="green")
127 table.add_column("Strategy")
128 table.add_column("Limit")
129 table.add_column("Description")
131 for i, sel in enumerate(selections, 1):
132 limit_str = str(sel["limit"]) if sel["limit"] else "—"
133 if sel["max_size_gb"]:
134 limit_str += f" ({sel['max_size_gb']}GB)"
136 table.add_row(str(i), sel["name"], sel["strategy"], limit_str, sel["description"] or "—")
138 console.print(table)
141def display_builds(builds: list[dict]) -> None:
142 """Display existing builds in a nice table."""
143 table = Table(title="Existing Build Configurations", show_header=True, header_style="bold cyan")
144 table.add_column("#", style="dim", width=3)
145 table.add_column("Build Name", style="green")
146 table.add_column("Platforms")
147 table.add_column("Description")
149 for i, build in enumerate(builds, 1):
150 platforms_str = ", ".join(build["platforms"][:3])
151 if len(build["platforms"]) > 3:
152 platforms_str += f" +{len(build['platforms']) - 3} more"
154 table.add_row(str(i), build["name"], platforms_str, build["description"] or "—")
156 console.print(table)
159def select_from_list(items: list[dict], prompt: str, allow_none: bool = False) -> dict | None:
160 """Interactive selection from a list."""
161 if not items:
162 console.print("[yellow]No options available.[/yellow]")
163 return None
165 none_option = " (or 0 for none)" if allow_none else ""
166 choice = Prompt.ask(f"{prompt} (1-{len(items)}{none_option})", default="1")
168 try:
169 idx = int(choice)
170 if allow_none and idx == 0:
171 return None
172 if 1 <= idx <= len(items):
173 return items[idx - 1]
174 except ValueError:
175 pass
177 console.print("[red]Invalid choice[/red]")
178 return None
181@click.command()
182@click.option("--interactive", "-i", is_flag=True, help="Interactive mode")
183@click.option("--platform", "-p", help="Platform name (skip interactive)")
184@click.option("--selection", "-s", help="Selection name (skip interactive)")
185@click.option("--config-root", type=click.Path(exists=True), help="Config root directory")
186def quick(interactive: bool, platform: str, selection: str, config_root: str):
187 """
188 Quick build wizard - create and run builds interactively.
190 Examples:
192 # Interactive mode
193 romfarmer quick --interactive
195 # Direct command (skips prompts)
196 romfarmer quick --platform saturn --selection usa-10
197 """
198 config_path = Path(config_root) if config_root else Path("config")
200 # Banner
201 console.print()
202 console.print(
203 Panel.fit(
204 "[bold cyan]🎮 ROM Farmer Quick Build[/bold cyan]\n"
205 "Interactive wizard for building ROM collections",
206 border_style="cyan",
207 )
208 )
209 console.print()
211 # Discover available resources
212 console.print("[cyan]Discovering available configurations...[/cyan]")
213 platforms = discover_platforms(config_path)
214 selections = discover_selections(config_path)
215 builds = discover_builds(config_path)
217 console.print(f" ✓ Found {len(platforms)} platforms")
218 console.print(f" ✓ Found {len(selections)} selections")
219 console.print(f" ✓ Found {len(builds)} existing builds")
220 console.print()
222 if not platforms:
223 console.print("[red]No platforms found! Check your config/platforms/ directory.[/red]")
224 return
226 # Step 1: Use existing build or create new?
227 if builds and interactive:
228 console.print("[bold]Step 1: Build Configuration[/bold]")
229 console.print("Would you like to use an existing build or create a new one?")
230 console.print(" 1. Create new build (guided)")
231 console.print(" 2. Use existing build")
232 console.print()
234 choice = Prompt.ask("Choice", choices=["1", "2"], default="1")
236 if choice == "2":
237 display_builds(builds)
238 build = select_from_list(builds, "Select build")
239 if build:
240 # Run existing build
241 import subprocess
243 cmd = f"python3 -m romfarmer build run {build['name']}"
244 console.print()
245 console.print(f"[cyan]Running:[/cyan] {cmd}")
246 console.print()
247 subprocess.run(cmd, shell=True)
248 return
250 # Step 2: Select platform
251 console.print("[bold]Step 2: Select Platform[/bold]")
252 display_platforms(platforms)
254 if platform:
255 selected_platform = next(
256 (p for p in platforms if p["name"] == platform or p["file"] == platform), None
257 )
258 if not selected_platform:
259 console.print(f"[red]Platform '{platform}' not found[/red]")
260 return
261 else:
262 selected_platform = select_from_list(platforms, "Select platform")
263 if not selected_platform:
264 return
266 console.print(f"[green]✓ Selected:[/green] {selected_platform['name']}")
267 console.print()
269 # Step 3: Select selection strategy
270 console.print("[bold]Step 3: Select Strategy[/bold]")
271 console.print("How many games do you want to process?")
273 if selections:
274 display_selections(selections)
276 if selection:
277 selected_selection = next(
278 (s for s in selections if s["name"] == selection or s["file"] == selection), None
279 )
280 else:
281 selected_selection = select_from_list(selections, "Select strategy", allow_none=True)
282 else:
283 selected_selection = None
285 if selected_selection:
286 console.print(f"[green]✓ Selected:[/green] {selected_selection['name']}")
287 else:
288 console.print("[green]✓ Selected:[/green] All games (no filtering)")
289 console.print()
291 # Step 4: Summary and confirmation
292 console.print(
293 Panel.fit(
294 f"[bold]Build Summary[/bold]\n\n"
295 f"Platform: [cyan]{selected_platform['name']}[/cyan]\n"
296 f"Selection: [cyan]{selected_selection['name'] if selected_selection else 'All games'}[/cyan]\n"
297 f"Games: [cyan]{selected_platform['dat_count']} available[/cyan]",
298 title="Review",
299 border_style="green",
300 )
301 )
302 console.print()
304 if not Confirm.ask("Proceed with build?", default=True):
305 console.print("[yellow]Build cancelled[/yellow]")
306 return
308 # Step 5: Check if matching build exists
309 platform_file = selected_platform["file"]
311 # Look for existing build that uses this platform
312 matching_build = None
313 for build in builds:
314 if platform_file in build["platforms"]:
315 matching_build = build
316 break
318 if matching_build:
319 console.print(f"[green]Found existing build:[/green] {matching_build['name']}")
320 build_name = matching_build["name"]
321 else:
322 console.print("[yellow]No existing build found with this configuration.[/yellow]")
323 console.print("[yellow]Please create a build config or use an existing one.[/yellow]")
324 console.print()
325 console.print(f"[cyan]Hint:[/cyan] Create config/builds/{platform_file}-test.yaml with:")
326 console.print(f" name: {platform_file}-test")
327 console.print(f" platforms: [{platform_file}]")
328 return
330 # Step 6: Run the build
331 import subprocess
333 cmd = f"python3 -m romfarmer build run {build_name}"
335 console.print()
336 console.print(Panel.fit(f"[cyan]{cmd}[/cyan]", title="Executing", border_style="cyan"))
337 console.print()
339 subprocess.run(cmd, shell=True)
342@click.group(name="quick")
343def quick_group():
344 """Quick build commands."""
345 pass
348quick_group.add_command(quick, name="build")
351if __name__ == "__main__":
352 quick()