File size: 2,294 Bytes
a1b343c
f89b1ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1b343c
f89b1ac
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Load local env files without overriding externally injected runtime env vars."""

import logging
import os
from pathlib import Path

from dotenv import dotenv_values, load_dotenv

logger = logging.getLogger(__name__)

_PROJECT_ROOT = Path(__file__).resolve().parent
_RUNTIME_ENV_KEYS = (
    "ENV_FILE",
    "HOST",
    "PORT",
    "DEBUG",
    "ENV_BASE_URL",
    "ADMIN_API_KEY",
    "PUBLIC_GRADER_DETAILS",
    "COOKIE_SECURE",
    "HTTP_SESSION_TIMEOUT_S",
    "CORS_ALLOW_ORIGINS",
    "MAX_HTTP_SESSIONS",
    "MAX_WS_SESSIONS",
    "API_KEY",
    "HF_TOKEN",
    "MODEL_NAME",
    "API_BASE_URL",
)


def _has_external_runtime_config() -> bool:
    return any(bool(os.getenv(key, "").strip()) for key in _RUNTIME_ENV_KEYS)


def _resolve_env_file(env_file_name: str) -> Path:
    env_path = (_PROJECT_ROOT / env_file_name).resolve()
    try:
        env_path.relative_to(_PROJECT_ROOT)
    except ValueError as exc:
        raise ValueError(
            f"ENV_FILE '{env_file_name}' must resolve inside the project root."
        ) from exc
    return env_path


def load_env() -> None:
    """Read repo-root .env to locate the active secondary env file."""
    dot_env = _PROJECT_ROOT / ".env"
    if not dot_env.exists():
        if _has_external_runtime_config():
            logger.debug(
                ".env not found at %s — assuming runtime env vars were injected externally",
                dot_env,
            )
            return
        logger.warning(
            ".env not found at %s — local runs expect it to define ENV_FILE for the active env file",
            dot_env,
        )
        return

    load_dotenv(dot_env, override=False)
    env_file_name = str(
        (dotenv_values(dot_env).get("ENV_FILE") or os.getenv("ENV_FILE") or "")
    ).strip()
    if not env_file_name:
        logger.debug(".env did not specify ENV_FILE — no secondary file loaded")
        return

    try:
        env_file = _resolve_env_file(env_file_name)
    except ValueError as exc:
        logger.warning("%s", exc)
        return

    if not env_file.exists():
        logger.warning("ENV_FILE '%s' not found at %s", env_file_name, env_file)
        return

    load_dotenv(env_file, override=False)
    logger.debug("Loaded environment variables from %s", env_file)