| 1 | import os |
| 2 | import re |
| 3 | from typing import Any |
| 4 | |
| 5 | from .files import get_abs_path |
| 6 | from dotenv import load_dotenv as _load_dotenv |
| 7 | |
| 8 | KEY_AUTH_LOGIN = "AUTH_LOGIN" |
| 9 | KEY_AUTH_PASSWORD = "AUTH_PASSWORD" |
| 10 | KEY_RFC_PASSWORD = "RFC_PASSWORD" |
| 11 | KEY_ROOT_PASSWORD = "ROOT_PASSWORD" |
| 12 | |
| 13 | def load_dotenv(): |
| 14 | _load_dotenv(get_dotenv_file_path(), override=True) |
| 15 | |
| 16 | |
| 17 | def get_dotenv_file_path(): |
| 18 | return get_abs_path("usr/.env") |
| 19 | |
| 20 | def get_dotenv_value(key: str, default: Any = None): |
| 21 | # load_dotenv() |
| 22 | return os.getenv(key, default) |
| 23 | |
| 24 | def save_dotenv_value(key: str, value: str, reload_env: bool = True): |
| 25 | if value is None: |
| 26 | value = "" |
| 27 | dotenv_path = get_dotenv_file_path() |
| 28 | if not os.path.isfile(dotenv_path): |
| 29 | with open(dotenv_path, "w") as f: |
| 30 | f.write("") |
| 31 | with open(dotenv_path, "r+") as f: |
| 32 | lines = f.readlines() |
| 33 | found = False |
| 34 | for i, line in enumerate(lines): |
| 35 | if re.match(rf"^\s*{key}\s*=", line): |
| 36 | lines[i] = f"{key}={value}\n" |
| 37 | found = True |
| 38 | if not found: |
| 39 | lines.append(f"\n{key}={value}\n") |
| 40 | f.seek(0) |
| 41 | f.writelines(lines) |
| 42 | f.truncate() |
| 43 | if reload_env: |
| 44 | load_dotenv() |