54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
# 把本机 .env 补进进程环境,不覆盖已经有值的变量。
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from pathlib import Path
|
||
|
||
|
||
# 按顺序读 .env,只填当前为空的变量。
|
||
#
|
||
# 文件不存在则跳过。已有非空环境变量不覆盖。值两边成对的单双引号会去掉。
|
||
# 多个路径时,先读到的非空值留下。
|
||
def load_env(*paths: Path) -> None:
|
||
for path in paths:
|
||
_fill_env(path)
|
||
|
||
|
||
# 该班次要读的 .env:本包,加购再加选品,最后 rpa_oms。
|
||
def job_env_files(package_dir: Path) -> tuple[Path, ...]:
|
||
repo = package_dir.resolve().parent
|
||
files = [package_dir / ".env"]
|
||
if package_dir.name == "rpa_cart":
|
||
files.append(repo / "rpa_selection" / ".env")
|
||
files.append(repo / "rpa_oms" / ".env")
|
||
return tuple(files)
|
||
|
||
|
||
# 先读班次 .env,空缺再补后面的文件。
|
||
#
|
||
# 默认顺序见 job_env_files。paths 给定时只读这一列,供测试注入。
|
||
# 已有非空环境变量不覆盖。
|
||
def load_job_env(package_dir: Path, paths: list[Path] | None = None) -> None:
|
||
load_env(*(paths if paths is not None else job_env_files(package_dir)))
|
||
|
||
|
||
# 把单个 .env 里尚未占用的键写进 os.environ。
|
||
def _fill_env(path: Path) -> None:
|
||
if not path.is_file():
|
||
return
|
||
for raw in path.read_text(encoding="utf-8").splitlines():
|
||
line = raw.strip()
|
||
if not line or line.startswith("#") or "=" not in line:
|
||
continue
|
||
key, _, value = line.partition("=")
|
||
key = key.strip()
|
||
value = value.strip()
|
||
if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
|
||
value = value[1:-1]
|
||
if not key or not value:
|
||
continue
|
||
current = os.environ.get(key, "")
|
||
if not current:
|
||
os.environ[key] = value
|