Coverage for src/romfarmer/driver/workspace.py: 82%
39 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"""Workspace — the ONE declared root every path derives from.
3Three bugs of one class (review G4 #8; the ``${ROMFARMER_SOURCE_ROOT}``
4expansion; ``core.paths`` loading ``.env`` from beside the installed package)
5all inferred configuration location and happened to be right in the
6development checkout. The class dies here: a ``Workspace`` is constructed
7from an explicit root or from ``ROMFARMER_WORKSPACE`` — never from the cwd,
8never from where the code lives — loads ``<root>/.env`` exactly once, and
9every other path is a derived field.
10"""
12from __future__ import annotations
14import os
15from dataclasses import dataclass
16from pathlib import Path
18ENV_VAR = "ROMFARMER_WORKSPACE"
19LEGACY_ENV_VAR = "ROMGROOMER_WORKSPACE"
22class WorkspaceError(RuntimeError):
23 """No workspace was declared (or the declared one is not a workspace)."""
26@dataclass(frozen=True)
27class Workspace:
28 root: Path
29 config_dir: Path
30 dats_dir: Path
31 lists_dir: Path
32 artifacts_dir: Path
33 output_dir: Path
34 store_dir: Path
35 cas_dir: Path
36 metadata_db: Path
37 size_data: Path
38 env_file: Path
40 @classmethod
41 def at(cls, root: Path | str, *, require_config: bool = False) -> Workspace:
42 """Declare *root* as the workspace and load its ``.env`` (never overriding the environment)."""
43 r = Path(root).expanduser().resolve()
44 if require_config and not (r / "config").is_dir():
45 raise WorkspaceError(f"{r} is not a ROM Farmer workspace (no config/ directory)")
46 env_file = r / ".env"
47 if env_file.exists():
48 from dotenv import load_dotenv
50 load_dotenv(env_file, override=False)
51 return cls(
52 root=r,
53 config_dir=r / "config",
54 dats_dir=r / "dats",
55 lists_dir=r / "lists",
56 artifacts_dir=r / "artifacts",
57 output_dir=r / "output",
58 store_dir=r / "store",
59 cas_dir=r / "store" / "cas",
60 metadata_db=r / "metadata" / "database" / "romfarmer.db",
61 size_data=r / "config" / "size_data.json",
62 env_file=env_file,
63 )
65 @classmethod
66 def from_env(cls) -> Workspace:
67 """``ROMFARMER_WORKSPACE`` (or legacy ``ROMGROOMER_WORKSPACE``). Loud when unset."""
68 root = os.environ.get(ENV_VAR) or os.environ.get(LEGACY_ENV_VAR)
69 if not root:
70 raise WorkspaceError(
71 f"no workspace declared: set {ENV_VAR}=/path/to/workspace (the directory holding config/)"
72 )
73 return cls.at(root, require_config=True)
75 @classmethod
76 def resolve(cls, explicit: Path | str | None = None) -> Workspace:
77 """Explicit root if given, else the environment variable. Never the cwd."""
78 return cls.at(explicit) if explicit is not None else cls.from_env()