acupedia-ops/acupedia_ops/common/env.py

84 lines
2.1 KiB
Python

from __future__ import annotations
import os
from pathlib import Path
from typing import Mapping
class EnvFileError(ValueError):
"""Raised when a local .env file contains malformed entries."""
def _strip_quotes(value: str) -> str:
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
return value[1:-1]
return value
def parse_env_file(path: Path) -> dict[str, str]:
"""Parse a deliberately small, predictable dotenv subset.
Supported syntax:
NAME=value
export NAME=value
blank lines
# comments
Shell expansion and command substitution are intentionally not supported.
"""
values: dict[str, str] = {}
if not path.exists():
return values
for line_number, raw_line in enumerate(
path.read_text(encoding="utf-8").splitlines(),
start=1,
):
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export "):].lstrip()
if "=" not in line:
raise EnvFileError(
f"Invalid .env entry at {path}:{line_number}: expected NAME=value"
)
key, raw_value = line.split("=", 1)
key = key.strip()
if not key or not key.replace("_", "").isalnum() or key[0].isdigit():
raise EnvFileError(
f"Invalid environment variable name at {path}:{line_number}: {key!r}"
)
values[key] = _strip_quotes(raw_value)
return values
def load_env_file(
path: Path,
*,
override: bool = False,
) -> dict[str, str]:
values = parse_env_file(path)
for key, value in values.items():
if override or key not in os.environ:
os.environ[key] = value
return values
def merged_environment(
*sources: Mapping[str, str] | None,
) -> dict[str, str]:
result = dict(os.environ)
for source in sources:
if source:
result.update({str(k): str(v) for k, v in source.items()})
return result