diff --git a/swh/core/config.py b/swh/core/config.py --- a/swh/core/config.py +++ b/swh/core/config.py @@ -9,6 +9,7 @@ import os from typing import Any, Callable, Dict, List, Optional, Tuple +from deprecated import deprecated import yaml logger = logging.getLogger(__name__) @@ -286,6 +287,29 @@ return conf +def load_from_envvar(default_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Load configuration yaml file from the environment variable SWH_CONFIG_FILENAME, + eventually enriched with default configuration key/value from the default_config + dict if provided. + + Returns: + Configuration dict + + Raises: + AssertionError if SWH_CONFIG_FILENAME is undefined + + """ + assert ( + "SWH_CONFIG_FILENAME" in os.environ + ), "SWH_CONFIG_FILENAME environment variable is undefined." + + cfg_path = os.environ["SWH_CONFIG_FILENAME"] + cfg = read_raw_config(config_basepath(cfg_path)) + cfg = merge_configs(default_config or {}, cfg) + return cfg + + +@deprecated(version="0.3.2", reason="Use swh.core.config.load_from_envvar instead") class SWHConfig: """Mixin to add configuration parsing abilities to classes diff --git a/swh/core/tests/test_config.py b/swh/core/tests/test_config.py --- a/swh/core/tests/test_config.py +++ b/swh/core/tests/test_config.py @@ -326,3 +326,39 @@ config.merge_configs({"a": v}, {"a": {}}) with pytest.raises(TypeError): config.merge_configs({"a": {}}, {"a": v}) + + +def test_load_from_envvar_no_environment_var_swh_config_filename_set(): + """Without SWH_CONFIG_FILENAME set, load_from_envvar raises""" + + with pytest.raises(AssertionError, match="SWH_CONFIG_FILENAME environment"): + config.load_from_envvar() + + +def test_load_from_envvar_no_default_config(swh_config, monkeypatch): + config_path = str(swh_config) + monkeypatch.setenv("SWH_CONFIG_FILENAME", config_path) + + actual_config = config.load_from_envvar() + + expected_config = config.read(config_path) + assert actual_config == expected_config + + +def test_load_from_envvar_with_default_config(swh_config, monkeypatch): + default_config = { + "number": 666, + "something-cool": ["something", "cool"], + } + + config_path = str(swh_config) + monkeypatch.setenv("SWH_CONFIG_FILENAME", config_path) + + actual_config = config.load_from_envvar(default_config) + + expected_config = config.read(config_path) + expected_config.update( + {"number": 666, "something-cool": ["something", "cool"],} + ) + + assert actual_config == expected_config