|
| 1 | +from typing import Any, Dict, Optional |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | + |
| 5 | +def load_settings(default_settings: Dict[str, Any]) -> Dict[str, Any]: |
| 6 | + """ |
| 7 | + Load settings by merging default settings with environment variables. |
| 8 | +
|
| 9 | + Args: |
| 10 | + default_settings (Dict[str, Any]): The default settings to use. |
| 11 | +
|
| 12 | + Returns: |
| 13 | + Dict[str, Any]: The merged settings. |
| 14 | + """ |
| 15 | + env_variables = load_env() |
| 16 | + if env_variables: |
| 17 | + return {**default_settings, **env_variables} |
| 18 | + else: |
| 19 | + return default_settings |
| 20 | + |
| 21 | + |
| 22 | +def load_env() -> Optional[Dict[str, Any]]: |
| 23 | + """ |
| 24 | + Loads environment variables from a .env file located in the parent directory of the current file. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + A dictionary containing the loaded environment variables, or None if the .env file does not exist. |
| 28 | + """ |
| 29 | + dirname = Path(__file__).resolve().parent |
| 30 | + env_path = dirname.parent / ".env" |
| 31 | + |
| 32 | + if env_path.exists(): |
| 33 | + return load_env_from_path(str(env_path)) |
| 34 | + else: |
| 35 | + return None |
| 36 | + |
| 37 | + |
| 38 | +def load_env_from_path(file_path: str) -> Dict[str, str]: |
| 39 | + """ |
| 40 | + Load environment variables from a file. |
| 41 | +
|
| 42 | + Args: |
| 43 | + file_path (str): The path to the file containing environment variables. |
| 44 | +
|
| 45 | + Returns: |
| 46 | + dict: A dictionary containing the loaded environment variables, where the keys are the variable names |
| 47 | + and the values are the variable values. |
| 48 | +
|
| 49 | + """ |
| 50 | + env = {} |
| 51 | + with open(file_path, "r", encoding="utf8") as file: |
| 52 | + lines = file.readlines() |
| 53 | + |
| 54 | + for line in lines: |
| 55 | + # Remove comments and trim whitespace |
| 56 | + trimmed_line = line.split("#")[0].strip() |
| 57 | + |
| 58 | + if not trimmed_line: |
| 59 | + continue |
| 60 | + |
| 61 | + key_value = trimmed_line.split("=", 1) |
| 62 | + if len(key_value) != 2: |
| 63 | + continue |
| 64 | + |
| 65 | + key, value = key_value |
| 66 | + value = value.strip() |
| 67 | + |
| 68 | + # Remove surrounding quotes if they exist |
| 69 | + if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")): |
| 70 | + value = value[1:-1] |
| 71 | + |
| 72 | + env[key.strip()] = value |
| 73 | + |
| 74 | + return env # type: ignore |
0 commit comments