Spaces:
Sleeping
Sleeping
| """Load project-local environment variables from ``.env``.""" | |
| from __future__ import annotations | |
| import os | |
| from pathlib import Path | |
| from chess_tutor.paths import project_root | |
| def _parse_dotenv_line(line: str) -> tuple[str, str] | None: | |
| stripped = line.strip() | |
| if not stripped or stripped.startswith("#"): | |
| return None | |
| if stripped.startswith("export "): | |
| stripped = stripped[len("export ") :].strip() | |
| if "=" not in stripped: | |
| return None | |
| key, _, value = stripped.partition("=") | |
| key = key.strip() | |
| if not key: | |
| return None | |
| value = value.strip() | |
| if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'): | |
| value = value[1:-1] | |
| return key, value | |
| def load_project_dotenv( | |
| path: Path | str | None = None, | |
| *, | |
| override: bool = False, | |
| ) -> bool: | |
| """ | |
| Load ``KEY=VALUE`` pairs from the repo ``.env`` into ``os.environ``. | |
| Returns ``True`` when the file exists and was read. Existing environment | |
| variables are left unchanged unless ``override=True``. | |
| """ | |
| env_path = Path(path) if path is not None else project_root() / ".env" | |
| if not env_path.is_file(): | |
| return False | |
| for raw_line in env_path.read_text(encoding="utf-8").splitlines(): | |
| parsed = _parse_dotenv_line(raw_line) | |
| if parsed is None: | |
| continue | |
| key, value = parsed | |
| if not override and key in os.environ: | |
| continue | |
| os.environ[key] = value | |
| return True | |