Coverage for src/romfarmer/driver/sources.py: 91%
56 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"""Named source roots — the machine-specific half of a portable Spec.
3A Spec never embeds an absolute path. It names a root alias from
4``config/sources.yaml`` (``roots:`` map, ``${ENV}``-expanded, so each host
5maps ``myrient_redump`` to wherever its mirror is mounted) plus a subpath.
6Resolution happens here, inside RESOLVE — the layer whose job is
7machine-specific facts — so the same Spec hashes identically on every host
8and after every remount.
9"""
11from __future__ import annotations
13import os
14import re
15from pathlib import Path
17import yaml
19# Importing core.paths loads the workspace .env (ROMFARMER_SOURCE_ROOT …) exactly
20# once; sources.yaml is ${ENV}-expanded and would otherwise resolve to '/Redump'
21# in a process that never touched the CLI.
22import romfarmer.core.paths # noqa: F401
23from romfarmer.ir.spec import SpecError, SpecSource
25_UNEXPANDED = re.compile(r"\$\{?[A-Za-z_][A-Za-z0-9_]*\}?")
28def _load_workspace_env(config_dir: Path) -> None:
29 """Load ``<workspace>/.env`` (never overriding a real environment).
31 ``core.paths`` loads the .env next to the *installed package*, which is the
32 repo checkout in development and nothing at all elsewhere. RESOLVE must
33 not depend on that: the workspace being resolved carries its own .env.
34 """
35 env_path = config_dir.parent / ".env"
36 if not env_path.exists():
37 return
38 try:
39 from dotenv import load_dotenv
41 load_dotenv(env_path, override=False)
42 except ImportError: # pragma: no cover — python-dotenv is a hard dependency
43 pass
46def load_source_roots(config_dir: Path) -> dict[str, Path]:
47 """``{alias: absolute path}`` from ``config/sources.yaml`` (env vars expanded).
49 Loud: a root whose ``${VAR}`` is still unexpanded after loading the
50 workspace ``.env`` is an error naming the variable — not a path under ``/``.
51 """
52 path = config_dir / "sources.yaml"
53 if not path.exists():
54 return {}
55 _load_workspace_env(config_dir)
56 try:
57 raw = yaml.safe_load(os.path.expandvars(path.read_text())) or {}
58 except yaml.YAMLError as exc:
59 raise SpecError(f"{path} is not valid YAML: {exc}") from exc
60 roots = raw.get("roots") or {}
61 if not isinstance(roots, dict):
62 raise SpecError(f"{path}: 'roots' must be a mapping of alias → path")
63 out: dict[str, Path] = {}
64 for k, v in roots.items():
65 text = str(v)
66 m = _UNEXPANDED.search(text)
67 if m:
68 raise SpecError(
69 f"{path}: root {k!r} = {text!r} — {m.group(0)} is not set. Define it in "
70 f"{config_dir.parent / '.env'} or the environment."
71 )
72 out[str(k)] = Path(text)
73 return out
76def resolve_source(src: SpecSource, roots: dict[str, Path], where: str = "source") -> Path:
77 """Absolute directory for *src*; loud when the alias is unknown."""
78 root = roots.get(src.root)
79 if root is None:
80 raise SpecError(
81 f"{where}: unknown source root {src.root!r} — add it to config/sources.yaml "
82 f"(known: {sorted(roots)})"
83 )
84 return root / src.subpath if src.subpath else root
87def alias_path(path: Path, roots: dict[str, Path], *, recursive: bool = False) -> SpecSource | None:
88 """Reverse map: the longest root that is a prefix of *path* → ``SpecSource``."""
89 best: tuple[int, str, Path] | None = None
90 resolved = Path(os.path.abspath(path))
91 for alias, root in roots.items():
92 r = Path(os.path.abspath(root))
93 try:
94 rel = resolved.relative_to(r)
95 except ValueError:
96 continue
97 depth = len(r.parts)
98 if best is None or depth > best[0]:
99 best = (depth, alias, rel)
100 if best is None:
101 return None
102 _, alias, rel = best
103 return SpecSource(
104 root=alias, subpath=rel.as_posix() if str(rel) != "." else "", recursive=recursive
105 )