Created
February 16, 2024 00:34
-
-
Save pingzh/75affcbc0b4b974cc406d9b0dd333691 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
from pathlib import Path | |
from configparser import ConfigParser # type: ignore | |
DEFAULT_CONF_PATH = Path(__file__).parent / "default_conf.cfg" | |
CONFIG_FILE_NAME = "config_name.cfg" | |
class DefaultableConfigParser(ConfigParser): | |
"""Custom Configparser supporting defaults""" | |
def __init__(self, default_config_path: str, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.default_config = ConfigParser(*args, **kwargs) | |
if default_config_path is not None: | |
self.default_config.read(default_config_path) | |
def get(self, section, key, **kwargs): | |
section = str(section).lower() | |
key = str(key).lower() | |
# TODO: support get from environment variable | |
option = self._get_option_from_config_file(section, key, **kwargs) | |
if option is not None: | |
return option | |
return self._get_option_from_default_config(section, key, **kwargs) | |
def _get_option_from_config_file(self, section, key, **kwargs): | |
if super().has_option(section, key): | |
return super().get(section, key, **kwargs) | |
def _get_option_from_default_config(self, section, key, **kwargs): | |
if self.default_config.has_option(section, key): | |
return self.default_config.get(section, key, **kwargs) | |
raise ValueError(f"section/key [{section}/{key}] not found in config") | |
def _config_file_lookup() -> Optional[Path]: | |
""" | |
first check: powertrain_runtime_config.cfg under $HOME | |
then check: /etc/powertrain_runtime_config.cfg | |
""" | |
under_home = Path(f"~/{CONFIG_FILE_NAME}").expanduser() | |
if under_home.is_file(): | |
return under_home | |
under_etc = Path(f"/etc/{CONFIG_FILE_NAME}") | |
if under_etc.is_file(): | |
return under_etc | |
return None | |
def initialize_config(): | |
"""Load the config files.""" | |
conf = DefaultableConfigParser(default_config_path=DEFAULT_CONF_PATH) | |
local_config_path = _config_file_lookup() | |
if local_config_path: | |
conf.read(local_config_path) | |
return conf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment