|
| 1 | +"""Locate the user's project on disk and read context from it. |
| 2 | +
|
| 3 | +The CLI is shipped inside ``backend/src/cli`` of the boilerplate, but |
| 4 | +when invoked it operates on whichever directory the user is in. These |
| 5 | +helpers resolve the repo root, the backend directory, and read values |
| 6 | +from the project's ``.env`` files without importing the application. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from dataclasses import dataclass |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(frozen=True) |
| 16 | +class ProjectContext: |
| 17 | + """Resolved paths the CLI needs to operate on the user's repo.""" |
| 18 | + |
| 19 | + repo_root: Path |
| 20 | + backend_dir: Path |
| 21 | + |
| 22 | + @property |
| 23 | + def env_file(self) -> Path: |
| 24 | + return self.backend_dir / ".env" |
| 25 | + |
| 26 | + @property |
| 27 | + def env_example(self) -> Path: |
| 28 | + return self.backend_dir / ".env.example" |
| 29 | + |
| 30 | + @property |
| 31 | + def compose_file(self) -> Path: |
| 32 | + return self.repo_root / "docker-compose.yml" |
| 33 | + |
| 34 | + |
| 35 | +def discover_project(start: Path | None = None) -> ProjectContext: |
| 36 | + """Walk up from ``start`` looking for a ``backend/pyproject.toml`` marker. |
| 37 | +
|
| 38 | + Falls back to the current working directory if no marker is found — |
| 39 | + the caller is responsible for deciding whether that's acceptable. |
| 40 | + """ |
| 41 | + current = (start or Path.cwd()).resolve() |
| 42 | + for candidate in [current, *current.parents]: |
| 43 | + if (candidate / "backend" / "pyproject.toml").is_file(): |
| 44 | + return ProjectContext(repo_root=candidate, backend_dir=candidate / "backend") |
| 45 | + if (candidate / "pyproject.toml").is_file() and candidate.name == "backend": |
| 46 | + return ProjectContext(repo_root=candidate.parent, backend_dir=candidate) |
| 47 | + return ProjectContext(repo_root=current, backend_dir=current / "backend") |
| 48 | + |
| 49 | + |
| 50 | +def read_env_value(env_path: Path, key: str) -> str | None: |
| 51 | + """Read a single value from a ``.env``-style file. |
| 52 | +
|
| 53 | + Returns ``None`` if the file is missing or the key isn't set. Quotes |
| 54 | + around the value (single or double) are stripped. Lines beginning |
| 55 | + with ``#`` are skipped. |
| 56 | + """ |
| 57 | + if not env_path.is_file(): |
| 58 | + return None |
| 59 | + for raw in env_path.read_text(encoding="utf-8").splitlines(): |
| 60 | + line = raw.strip() |
| 61 | + if not line or line.startswith("#") or "=" not in line: |
| 62 | + continue |
| 63 | + name, _, value = line.partition("=") |
| 64 | + if name.strip() != key: |
| 65 | + continue |
| 66 | + value = value.strip() |
| 67 | + if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}: |
| 68 | + value = value[1:-1] |
| 69 | + return value |
| 70 | + return None |
0 commit comments