Coverage for src/romfarmer/core/paths.py: 65%
155 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""
2Centralized path resolution for ROM Farmer.
4This module provides a single source of truth for all path resolution,
5eliminating hardcoded paths throughout the codebase. Paths can be configured
6via environment variables, configuration files, or defaults.
8Usage:
9 from romfarmer.core.paths import paths
11 # Access paths
12 db_path = paths.metadata_db
13 temp_dir = paths.temp_dir
15 # Or create custom resolver with different workspace
16 custom_paths = PathResolver(workspace_root=Path("/custom/workspace"))
17"""
19import os
20from functools import cached_property
21from pathlib import Path
23import yaml
25# .env is loaded from the RESOLVED workspace root (see PathResolver.__init__),
26# never from beside the installed package — that only worked in the dev checkout.
29def _load_workspace_dotenv(root: Path) -> None:
30 """Load ``<root>/.env`` once (never overriding the real environment)."""
31 env_path = Path(root) / ".env"
32 if not env_path.exists():
33 return
34 try:
35 from dotenv import load_dotenv
37 load_dotenv(env_path, override=False)
38 except ImportError: # pragma: no cover
39 pass
42class PathResolver:
43 """
44 Resolve and manage paths consistently across the application.
46 Paths are resolved in the following priority order:
47 1. Environment variables (ROMGROOMER_*)
48 2. Configuration file (romfarmer.yaml or .romfarmer.yaml)
49 3. Sensible defaults relative to workspace root
51 Attributes:
52 workspace_root: The root directory of the ROM Farmer workspace
53 """
55 # Environment variable prefix
56 ENV_PREFIX = "ROMGROOMER"
58 # Default subdirectory names
59 DEFAULTS = {
60 "config_dir": "config",
61 "logs_dir": "logs",
62 "state_dir": "state",
63 "temp_dir": "temp",
64 "output_dir": "output",
65 "source_dir": "source",
66 "metadata_dir": "metadata/database",
67 "dats_dir": "dats",
68 "lists_dir": "lists",
69 "scripts_dir": "scripts",
70 }
72 def __init__(
73 self,
74 workspace_root: Path | None = None,
75 config_file: Path | None = None,
76 ):
77 """
78 Initialize path resolver.
80 Args:
81 workspace_root: Root directory for the workspace. If not provided,
82 uses ROMGROOMER_WORKSPACE env var or auto-detects.
83 config_file: Optional path to configuration file with path overrides.
84 """
85 self._workspace_root = workspace_root or self._detect_workspace_root()
86 _load_workspace_dotenv(self._workspace_root)
87 self._config = self._load_config(config_file)
88 self._env_overrides = self._load_env_overrides()
90 def _detect_workspace_root(self) -> Path:
91 """
92 Auto-detect workspace root directory.
94 Checks in order:
95 1. ROMGROOMER_WORKSPACE environment variable
96 2. Current working directory if it contains pyproject.toml
97 3. Parent directories looking for pyproject.toml
98 4. Falls back to current directory
99 """
100 # Declared workspace first (ROMFARMER_WORKSPACE; legacy ROMGROOMER_WORKSPACE)
101 env_workspace = os.environ.get("ROMFARMER_WORKSPACE") or os.environ.get(
102 f"{self.ENV_PREFIX}_WORKSPACE"
103 )
104 if env_workspace:
105 return Path(env_workspace)
107 # Check current directory
108 cwd = Path.cwd()
109 if (cwd / "pyproject.toml").exists():
110 return cwd
112 # Walk up looking for pyproject.toml
113 for parent in cwd.parents:
114 if (parent / "pyproject.toml").exists():
115 return parent
116 # Don't go above home directory
117 if parent == Path.home():
118 break
120 # Default to current directory
121 return cwd
123 def _load_config(self, config_file: Path | None) -> dict:
124 """Load configuration from file if present."""
125 if config_file and config_file.exists():
126 with open(config_file) as f:
127 return yaml.safe_load(f) or {}
129 # Try standard locations
130 for name in ["romfarmer.yaml", ".romfarmer.yaml"]:
131 config_path = self._workspace_root / name
132 if config_path.exists():
133 with open(config_path) as f:
134 return yaml.safe_load(f) or {}
136 return {}
138 def _load_env_overrides(self) -> dict:
139 """Load path overrides from environment variables."""
140 overrides = {}
141 for key in self.DEFAULTS:
142 env_key = f"{self.ENV_PREFIX}_{key.upper()}"
143 value = os.environ.get(env_key)
144 if value:
145 overrides[key] = Path(value)
146 return overrides
148 def _resolve_path(self, key: str, default_subdir: str) -> Path:
149 """
150 Resolve a path using the priority chain.
152 Priority: env var > config file > default
153 """
154 # Check environment override
155 if key in self._env_overrides:
156 return self._env_overrides[key]
158 # Check config file
159 paths_config = self._config.get("paths", {})
160 if key in paths_config:
161 path = Path(paths_config[key])
162 if path.is_absolute():
163 return path
164 return self._workspace_root / path
166 # Use default
167 return self._workspace_root / default_subdir
169 # -------------------------------------------------------------------------
170 # Core Directories
171 # -------------------------------------------------------------------------
173 @property
174 def workspace_root(self) -> Path:
175 """Root directory of the ROM Farmer workspace."""
176 return self._workspace_root
178 @cached_property
179 def config_dir(self) -> Path:
180 """Directory containing configuration files."""
181 return self._resolve_path("config_dir", self.DEFAULTS["config_dir"])
183 @cached_property
184 def logs_dir(self) -> Path:
185 """Directory for log files."""
186 path = self._resolve_path("logs_dir", self.DEFAULTS["logs_dir"])
187 path.mkdir(parents=True, exist_ok=True)
188 return path
190 @cached_property
191 def state_dir(self) -> Path:
192 """Directory for build state files (resume capability)."""
193 path = self._resolve_path("state_dir", self.DEFAULTS["state_dir"])
194 path.mkdir(parents=True, exist_ok=True)
195 return path
197 @cached_property
198 def temp_dir(self) -> Path:
199 """Directory for temporary working files."""
200 path = self._resolve_path("temp_dir", self.DEFAULTS["temp_dir"])
201 path.mkdir(parents=True, exist_ok=True)
202 return path
204 @cached_property
205 def output_dir(self) -> Path:
206 """Default directory for build outputs."""
207 path = self._resolve_path("output_dir", self.DEFAULTS["output_dir"])
208 path.mkdir(parents=True, exist_ok=True)
209 return path
211 @cached_property
212 def source_dir(self) -> Path:
213 """Directory containing source ROM files."""
214 return self._resolve_path("source_dir", self.DEFAULTS["source_dir"])
216 @cached_property
217 def metadata_dir(self) -> Path:
218 """Directory for metadata database."""
219 path = self._resolve_path("metadata_dir", self.DEFAULTS["metadata_dir"])
220 path.mkdir(parents=True, exist_ok=True)
221 return path
223 @cached_property
224 def dats_dir(self) -> Path:
225 """Directory containing DAT files."""
226 return self._resolve_path("dats_dir", self.DEFAULTS["dats_dir"])
228 @cached_property
229 def lists_dir(self) -> Path:
230 """Directory containing list files (delete, add, etc.)."""
231 return self._resolve_path("lists_dir", self.DEFAULTS["lists_dir"])
233 @cached_property
234 def scripts_dir(self) -> Path:
235 """Directory for utility scripts."""
236 return self._resolve_path("scripts_dir", self.DEFAULTS["scripts_dir"])
238 # -------------------------------------------------------------------------
239 # Specific Files
240 # -------------------------------------------------------------------------
242 @cached_property
243 def metadata_db(self) -> Path:
244 """Path to the metadata SQLite database."""
245 return self.metadata_dir / "romfarmer.db"
247 # -------------------------------------------------------------------------
248 # Config Subdirectories
249 # -------------------------------------------------------------------------
251 @cached_property
252 def platforms_dir(self) -> Path:
253 """Directory containing platform configuration files."""
254 return self.config_dir / "platforms"
256 @cached_property
257 def builds_dir(self) -> Path:
258 """Directory containing build configuration files."""
259 return self.config_dir / "builds"
261 @cached_property
262 def selections_dir(self) -> Path:
263 """Directory containing selection preset files."""
264 return self.config_dir / "selections"
266 @cached_property
267 def sources_file(self) -> Path:
268 """Path to sources.yaml file."""
269 return self.config_dir / "sources.yaml"
271 # -------------------------------------------------------------------------
272 # Helper Methods
273 # -------------------------------------------------------------------------
275 def build_state_file(self, build_name: str) -> Path:
276 """Get path to build state file for a specific build."""
277 return self.state_dir / f".build_state_{build_name}.yaml"
279 def build_log_file(self, build_name: str) -> Path:
280 """Get path to build log file for a specific build."""
281 return self.logs_dir / f"build_{build_name}.log"
283 def build_report_file(self, build_name: str) -> Path:
284 """Get path to build report file for a specific build."""
285 return self.logs_dir / f"build_report_{build_name}.txt"
287 def platform_config_file(self, platform_name: str) -> Path:
288 """Get path to platform configuration file."""
289 return self.platforms_dir / f"{platform_name}.yaml"
291 def build_config_file(self, build_name: str) -> Path:
292 """Get path to build configuration file."""
293 return self.builds_dir / f"{build_name}.yaml"
295 def platform_temp_dir(self, platform_name: str) -> Path:
296 """Get temporary directory for a specific platform."""
297 path = self.temp_dir / platform_name
298 path.mkdir(parents=True, exist_ok=True)
299 return path
301 def platform_output_dir(
302 self,
303 platform_name: str,
304 target_name: str,
305 dat_variant: str = "1g1r-eng",
306 compression_format: str = "7z",
307 ) -> Path:
308 """
309 Generate output directory path following naming convention.
311 Pattern: {output_dir}/{dat_variant}-{format}-{target}/{platform}
312 Example: /output/1g1r-eng-7z-batocera/nes
313 """
314 folder_name = f"{dat_variant}-{compression_format}-{target_name}"
315 path = self.output_dir / folder_name / platform_name
316 path.mkdir(parents=True, exist_ok=True)
317 return path
319 def ensure_dirs(self) -> None:
320 """Ensure all required directories exist."""
321 for attr in ["logs_dir", "state_dir", "temp_dir", "output_dir", "metadata_dir"]:
322 getattr(self, attr) # Access triggers creation via cached_property
324 def __repr__(self) -> str:
325 return f"PathResolver(workspace_root={self._workspace_root})"
328# -----------------------------------------------------------------------------
329# Module-level singleton for convenience
330# -----------------------------------------------------------------------------
332# Lazy initialization - will be created on first access
333_paths: PathResolver | None = None
336def get_paths() -> PathResolver:
337 """
338 Get the global PathResolver instance.
340 Creates the instance on first call. For custom configuration,
341 use init_paths() before accessing.
342 """
343 global _paths
344 if _paths is None:
345 _paths = PathResolver()
346 return _paths
349def init_paths(
350 workspace_root: Path | None = None,
351 config_file: Path | None = None,
352) -> PathResolver:
353 """
354 Initialize the global PathResolver with custom settings.
356 Call this at application startup if you need non-default paths.
358 Args:
359 workspace_root: Custom workspace root directory
360 config_file: Custom configuration file path
362 Returns:
363 The initialized PathResolver instance
364 """
365 global _paths
366 _paths = PathResolver(workspace_root=workspace_root, config_file=config_file)
367 return _paths
370# Convenience alias
371paths = property(lambda self: get_paths())
374# For direct attribute access without calling get_paths()
375class _PathsProxy:
376 """Proxy class for convenient attribute access to paths."""
378 def __getattr__(self, name):
379 return getattr(get_paths(), name)
382# Export a proxy object for direct access
383paths = _PathsProxy()