envfile.py 641 Bytes
from __future__ import annotations

from pathlib import Path


def set_env_value(path: str | Path, key: str, value: str) -> None:
    target = Path(path)
    lines = target.read_text(encoding="utf-8").splitlines() if target.exists() else []
    prefix = f"{key}="
    replacement = f"{key}={value}"
    updated = False
    output: list[str] = []

    for line in lines:
        if line.startswith(prefix):
            output.append(replacement)
            updated = True
        else:
            output.append(line)

    if not updated:
        output.append(replacement)

    target.write_text("\n".join(output) + "\n", encoding="utf-8")