diff --git a/changelog.md b/changelog.md index 7f3731c..57b8cfd 100644 --- a/changelog.md +++ b/changelog.md @@ -3,7 +3,8 @@ ## [1.1.0] - work in progress ### Added - + - utils.try_load_config + - utils.load_config - Endpoint module move in (from pmworker) ## [1.0.0] - 25 Apr 2020 diff --git a/mglib/utils.py b/mglib/utils.py index 6793cb5..5cc97ee 100644 --- a/mglib/utils.py +++ b/mglib/utils.py @@ -1,5 +1,8 @@ import os import logging +import importlib.machinery +import importlib.util + logger = logging.getLogger(__name__) @@ -84,3 +87,46 @@ def get_assigns_after_delete(total_pages, deleted_pages): page_numbers = range(1, len(pages) + 1) return list(zip(page_numbers, pages)) + + +def load_config(config_file): + + loader_ = importlib.machinery.SourceFileLoader( + "config", + config_file + ) + spec = importlib.util.spec_from_file_location( + "config", config_file, loader=loader_ + ) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + # and stop looking for ther configs. + cfg_papermerge = vars(mod) + cfg_file_found = True + + return cfg_papermerge, cfg_file_found + + +def try_load_config(config_locations, config_env_var_name): + + cfg_file_found = False + cfg_papermerge = {} + + for config_file in config_locations: + if os.path.exists(config_file): + cfg_papermerge, cfg_file_found = load_config(config_file) + if cfg_file_found: + break + + if not cfg_file_found: + config_file = os.environ.get(config_env_var_name, False) + if config_file: + try: + cfg_papermerge, cfg_file_found = load_config(config_file) + except FileNotFoundError: + err_msg = f"Failed attempted to read" +\ + f" configuration file '{config_file}'" +\ + f" pointed by environment variable '{config_env_var_name}'" + raise FileNotFoundError(err_msg) + + return cfg_papermerge diff --git a/setup.py b/setup.py index e7fd420..24b3333 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ with open("README.md", "r") as fh: setup( name="mglib", - version="1.1.0", + version="1.1.1", author="Eugen Ciur", author_email="eugen@papermerge.com", url="https://github.com/papermerge/mglib",