mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-06 02:54:26 +00:00
* tests/integration/meta/env/test_dotenv_generator.py picks up a module-level `STATIC_READS` tuple on every dynamic handler module under utils/env/handlers/, in addition to PASSTHROUGH_STATIC_KEYS and GHA_STATIC_KEYS. So a handler that pulls its fallback from `ctx.static[KEY]` (e.g. infinito_outer_network_mtu) can declare the key it reads without flipping the drift detector. * utils/env/handlers/infinito_outer_network_mtu.py exports `STATIC_READS = (KEY,)` accordingly and marks the two live system reads (`/proc/net/route`, `/sys/class/net/<iface>/mtu`) with `# nocheck: cache-read` since the cached-read lint forbids uncached `Path.read_text` calls inside utils/. * utils/env/loader.py marks the `INFINITO_ENV_LOADED` sentinel with `# nocheck: env-loader-internal-guard` so the registry-drift lint does not treat the idempotency flag as a missing config key. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
"""Idempotent ``.env`` loader for Python CLI entry-points."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from utils.env.parser import parse_static_env
|
|
|
|
_LOADED_FLAG = "INFINITO_ENV_LOADED" # nocheck: env-loader-internal-guard
|
|
_DOTENV_NAME = ".env"
|
|
|
|
|
|
def _find_dotenv(start: Path) -> Path | None:
|
|
for candidate in (start, *start.parents):
|
|
path = candidate / _DOTENV_NAME
|
|
if path.is_file():
|
|
return path
|
|
return None
|
|
|
|
|
|
def load_dotenv_once(start: Path | None = None) -> Path | None:
|
|
"""Source ``.env`` into ``os.environ`` exactly once per process.
|
|
|
|
Mirrors the bash ``scripts/meta/env/load.sh`` semantics:
|
|
|
|
* Honours ``INFINITO_ENV_LOADED=1`` and returns immediately when set.
|
|
* Caller-set values win over ``.env`` defaults (``setdefault``).
|
|
* Walks up from ``start`` (default: current working directory) until a
|
|
``.env`` is found; returns ``None`` if none exists in any parent.
|
|
"""
|
|
if os.environ.get(_LOADED_FLAG) == "1":
|
|
return None
|
|
|
|
dotenv = _find_dotenv((start or Path.cwd()).resolve())
|
|
if dotenv is None:
|
|
return None
|
|
|
|
for key, value in parse_static_env(dotenv).items():
|
|
os.environ.setdefault(key, value)
|
|
|
|
os.environ[_LOADED_FLAG] = "1"
|
|
return dotenv
|