Coverage for src/romfarmer/farmhand/config.py: 0%
71 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"""Farm-Hand target configuration loader.
3Reads YAML connection profiles from config/farmhand/targets/ and
4manages scan profiles in config/farmhand/profiles/.
6Target configs (YAML) contain:
7 - Connection details (host, port, user, password/key)
8 - System identity (frontend, device, target build config)
9 - Volume hints (pinned platforms, reserve space)
11Scan profiles (JSON) contain:
12 - Full TargetProfile from the analyzer
13 - Auto-populated on each scan; stale data gets refreshed
14"""
16from __future__ import annotations
18import json
19import logging
20from pathlib import Path
21from typing import Any
23import yaml
25from romfarmer.farmhand.models import TargetProfile
27logger = logging.getLogger(__name__)
30class TargetConfigError(Exception):
31 """Invalid target configuration."""
34def get_farmhand_config_dir(workspace_root: Path) -> Path:
35 """Return the farmhand config root (config/farmhand/)."""
36 return workspace_root / "config" / "farmhand"
39def get_targets_dir(workspace_root: Path) -> Path:
40 """Return the targets config directory."""
41 return get_farmhand_config_dir(workspace_root) / "targets"
44def get_profiles_dir(workspace_root: Path) -> Path:
45 """Return the scan profiles directory."""
46 return get_farmhand_config_dir(workspace_root) / "profiles"
49# ---------------------------------------------------------------------------
50# Target config loading (YAML)
51# ---------------------------------------------------------------------------
54def list_targets(workspace_root: Path) -> list[str]:
55 """List available target config names (without extension)."""
56 targets_dir = get_targets_dir(workspace_root)
57 if not targets_dir.exists():
58 return []
59 return sorted(p.stem for p in targets_dir.glob("*.yaml") if not p.name.startswith("."))
62def load_target_config(workspace_root: Path, name: str) -> dict[str, Any]:
63 """Load a target config YAML by name.
65 Args:
66 workspace_root: Project root path.
67 name: Target name (e.g., "batocera-nuc") — matches filename without .yaml.
69 Returns:
70 Parsed YAML as dict.
72 Raises:
73 TargetConfigError: If config doesn't exist or is invalid.
74 """
75 config_path = get_targets_dir(workspace_root) / f"{name}.yaml"
76 if not config_path.exists():
77 available = list_targets(workspace_root)
78 raise TargetConfigError(
79 f"Target config '{name}' not found at {config_path}. "
80 f"Available targets: {available or 'none'}"
81 )
83 try:
84 data = yaml.safe_load(config_path.read_text())
85 except yaml.YAMLError as exc:
86 raise TargetConfigError(f"Invalid YAML in {config_path}: {exc}") from exc
88 if not isinstance(data, dict):
89 raise TargetConfigError(f"Target config must be a YAML mapping, got {type(data)}")
91 # Validate required fields
92 for field in ("name", "host"):
93 if field not in data:
94 raise TargetConfigError(f"Target config missing required field: {field}")
96 return data
99def target_config_to_ssh_kwargs(config: dict[str, Any]) -> dict[str, Any]:
100 """Extract SSH connection kwargs from a target config dict.
102 Returns dict suitable for SSHClient(**kwargs).
103 """
104 kwargs: dict[str, Any] = {
105 "host": config["host"],
106 "port": config.get("port", 22),
107 "user": config.get("user", "root"),
108 }
109 if config.get("password"):
110 kwargs["password"] = config["password"]
111 if config.get("key_file"):
112 kwargs["key_file"] = config["key_file"]
113 return kwargs
116# ---------------------------------------------------------------------------
117# Profile persistence (JSON)
118# ---------------------------------------------------------------------------
121def save_profile(workspace_root: Path, profile: TargetProfile) -> Path:
122 """Save a TargetProfile to the profiles directory as JSON.
124 Returns the path where it was saved.
125 """
126 profiles_dir = get_profiles_dir(workspace_root)
127 profiles_dir.mkdir(parents=True, exist_ok=True)
129 profile_path = profiles_dir / f"{profile.name}.json"
130 profile_path.write_text(profile.model_dump_json(indent=2))
131 logger.info("Saved profile to %s", profile_path)
132 return profile_path
135def load_profile(workspace_root: Path, name: str) -> TargetProfile | None:
136 """Load a saved scan profile by target name.
138 Returns None if not found.
139 """
140 profile_path = get_profiles_dir(workspace_root) / f"{name}.json"
141 if not profile_path.exists():
142 # Also check legacy location (config/farmhand/<name>.json)
143 legacy_path = get_farmhand_config_dir(workspace_root) / f"{name}.json"
144 if legacy_path.exists():
145 profile_path = legacy_path
146 else:
147 return None
149 try:
150 data = json.loads(profile_path.read_text())
151 return TargetProfile.model_validate(data)
152 except Exception as exc:
153 logger.warning("Failed to load profile %s: %s", profile_path, exc)
154 return None
157def list_profiles(workspace_root: Path) -> list[str]:
158 """List available scan profile names."""
159 profiles_dir = get_profiles_dir(workspace_root)
160 names = []
161 if profiles_dir.exists():
162 names.extend(p.stem for p in profiles_dir.glob("*.json"))
163 # Also check legacy location
164 legacy_dir = get_farmhand_config_dir(workspace_root)
165 if legacy_dir.exists():
166 names.extend(p.stem for p in legacy_dir.glob("*.json") if p.stem not in names)
167 return sorted(names)