Coverage for src/romfarmer/web/api/configs.py: 0%
83 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"""Config API routes — list, read, and write ROM Farmer configurations."""
3from __future__ import annotations
5import logging
6from pathlib import Path
7from typing import Any
9import yaml
10from fastapi import APIRouter, HTTPException, Request
12logger = logging.getLogger("romfarmer.web.api.configs")
14router = APIRouter()
17# ── Helpers ──────────────────────────────────────────────────────────────────
20def _config_root(request: Request) -> Path:
21 return request.app.state.config_root
24def _list_yamls(directory: Path) -> list[dict[str, Any]]:
25 """List YAML files in a directory, returning name + metadata."""
26 if not directory.exists():
27 return []
28 results = []
29 for f in sorted(directory.glob("*.yaml")):
30 try:
31 raw = yaml.safe_load(f.read_text())
32 results.append(
33 {
34 "name": f.stem,
35 "file": f.name,
36 "description": raw.get("description", raw.get("name", f.stem)),
37 "raw": raw,
38 }
39 )
40 except Exception as e:
41 results.append(
42 {
43 "name": f.stem,
44 "file": f.name,
45 "description": f"(error: {e})",
46 "raw": {},
47 }
48 )
49 return results
52def _read_yaml(path: Path) -> dict[str, Any]:
53 """Read and parse a YAML file."""
54 if not path.exists():
55 raise HTTPException(status_code=404, detail=f"Config not found: {path.name}")
56 try:
57 return yaml.safe_load(path.read_text())
58 except Exception as e:
59 raise HTTPException(status_code=500, detail=f"Failed to parse: {e}") from e
62def _write_yaml(path: Path, data: dict[str, Any]) -> None:
63 """Write data to a YAML file."""
64 path.parent.mkdir(parents=True, exist_ok=True)
65 path.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
68# ── Platform Configs ─────────────────────────────────────────────────────────
71@router.get("/platforms")
72async def list_platforms(request: Request):
73 """List all platform configurations."""
74 return _list_yamls(_config_root(request) / "platforms")
77@router.get("/platforms/{name}")
78async def get_platform(name: str, request: Request):
79 """Get a specific platform configuration."""
80 return _read_yaml(_config_root(request) / "platforms" / f"{name}.yaml")
83@router.put("/platforms/{name}")
84async def save_platform(name: str, request: Request):
85 """Save/update a platform configuration."""
86 body = await request.json()
87 path = _config_root(request) / "platforms" / f"{name}.yaml"
88 _write_yaml(path, body)
89 return {"status": "saved", "name": name}
92# ── Recipe Configs ───────────────────────────────────────────────────────────
95@router.get("/recipes")
96async def list_recipes(request: Request):
97 """List all recipe configurations."""
98 return _list_yamls(_config_root(request) / "recipes")
101@router.get("/recipes/{name}")
102async def get_recipe(name: str, request: Request):
103 """Get a specific recipe configuration."""
104 return _read_yaml(_config_root(request) / "recipes" / f"{name}.yaml")
107@router.put("/recipes/{name}")
108async def save_recipe(name: str, request: Request):
109 """Save/update a recipe configuration."""
110 body = await request.json()
111 path = _config_root(request) / "recipes" / f"{name}.yaml"
112 _write_yaml(path, body)
113 return {"status": "saved", "name": name}
116# ── Target Configs ───────────────────────────────────────────────────────────
119@router.get("/targets")
120async def list_targets(request: Request):
121 """List all target configurations."""
122 return _list_yamls(_config_root(request) / "targets")
125@router.get("/targets/{name}")
126async def get_target(name: str, request: Request):
127 """Get a specific target configuration."""
128 return _read_yaml(_config_root(request) / "targets" / f"{name}.yaml")
131# ── Frontend Configs ─────────────────────────────────────────────────────────
134@router.get("/frontends")
135async def list_frontends(request: Request):
136 """List all frontend configurations."""
137 return _list_yamls(_config_root(request) / "frontends")
140@router.get("/frontends/{name}")
141async def get_frontend(name: str, request: Request):
142 """Get a specific frontend configuration."""
143 return _read_yaml(_config_root(request) / "frontends" / f"{name}.yaml")
146# ── Device Configs ───────────────────────────────────────────────────────────
149@router.get("/devices")
150async def list_devices(request: Request):
151 """List all device configurations."""
152 return _list_yamls(_config_root(request) / "devices")
155@router.get("/devices/{name}")
156async def get_device(name: str, request: Request):
157 """Get a specific device configuration."""
158 return _read_yaml(_config_root(request) / "devices" / f"{name}.yaml")
161# ── Selection Configs ────────────────────────────────────────────────────────
164@router.get("/selections")
165async def list_selections(request: Request):
166 """List all selection configurations."""
167 return _list_yamls(_config_root(request) / "selections")
170@router.get("/selections/{name}")
171async def get_selection(name: str, request: Request):
172 """Get a specific selection configuration."""
173 return _read_yaml(_config_root(request) / "selections" / f"{name}.yaml")
176# ── Summary ──────────────────────────────────────────────────────────────────
179@router.get("/summary")
180async def config_summary(request: Request):
181 """Get a summary of all config types and counts."""
182 root = _config_root(request)
183 return {
184 "platforms": len(list((root / "platforms").glob("*.yaml")))
185 if (root / "platforms").exists()
186 else 0,
187 "recipes": len(list((root / "recipes").glob("*.yaml")))
188 if (root / "recipes").exists()
189 else 0,
190 "targets": len(list((root / "targets").glob("*.yaml")))
191 if (root / "targets").exists()
192 else 0,
193 "frontends": len(list((root / "frontends").glob("*.yaml")))
194 if (root / "frontends").exists()
195 else 0,
196 "devices": len(list((root / "devices").glob("*.yaml")))
197 if (root / "devices").exists()
198 else 0,
199 "selections": len(list((root / "selections").glob("*.yaml")))
200 if (root / "selections").exists()
201 else 0,
202 "builds_legacy": len(list((root / "builds").glob("*.yaml")))
203 if (root / "builds").exists()
204 else 0,
205 "builds_new": len(list((root / "builds" / "new").glob("*.yaml")))
206 if (root / "builds" / "new").exists()
207 else 0,
208 }