63 lines
1.7 KiB
Python
63 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
|
|
def load_dotenv_into_environ(dotenv_path: os.PathLike[str] | str, *, override: bool = False) -> bool:
|
|
"""
|
|
Load KEY=VALUE lines from a .env file into os.environ.
|
|
|
|
- Supports lines like: KEY=VALUE, export KEY=VALUE
|
|
- Ignores blank lines and # comments
|
|
- Handles single/double-quoted values
|
|
- Does not expand ${VARS} or handle multiline values
|
|
|
|
Returns True if the file existed and was read.
|
|
"""
|
|
path = Path(dotenv_path)
|
|
if not path.is_file():
|
|
return False
|
|
|
|
content = path.read_text(encoding="utf-8")
|
|
# Remove UTF-8 BOM if present
|
|
if content.startswith("\ufeff"):
|
|
content = content.lstrip("\ufeff")
|
|
|
|
for raw_line in content.splitlines():
|
|
line = raw_line.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
if line.startswith("export "):
|
|
line = line[len("export ") :].lstrip()
|
|
|
|
if "=" not in line:
|
|
continue
|
|
|
|
key, value = line.split("=", 1)
|
|
key = key.strip()
|
|
value = value.strip()
|
|
|
|
if not key:
|
|
continue
|
|
|
|
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
|
|
value = value[1:-1]
|
|
|
|
if not override and key in os.environ:
|
|
continue
|
|
|
|
os.environ[key] = value
|
|
|
|
return True
|
|
|
|
|
|
def load_llm_fsm_dotenv(*, override: bool = False, filename: str = ".env") -> bool:
|
|
"""
|
|
Convenience loader for `.env` next to `scripts/llm_fsm` runner scripts.
|
|
"""
|
|
dotenv_path = Path(__file__).resolve().parent / filename
|
|
return load_dotenv_into_environ(dotenv_path, override=override)
|
|
|