load_config(): add merge_defaults parameter, fix accidental overwriting of default profile when merging

This commit is contained in:
InsanePrawn 2021-09-01 15:41:18 +02:00
parent 7f153c214c
commit 4cf608eeb6

View file

@ -28,12 +28,16 @@ class ConfigParserException(Exception):
pass pass
def load_config(config_file=None): def load_config(config_file=None, merge_defaults=True):
_conf_file = config_file if config_file != None else CONFIG_DEFAULT_PATH _conf_file = config_file if config_file != None else CONFIG_DEFAULT_PATH
loaded_conf = toml.load(_conf_file) loaded_conf = toml.load(_conf_file)
# Selectively merge known keys in loaded_conf with CONFIG_DEFAULTS if merge_defaults:
parsed = deepcopy(CONFIG_DEFAULTS) # Selectively merge known keys in loaded_conf with CONFIG_DEFAULTS
parsed = deepcopy(CONFIG_DEFAULTS)
else:
parsed = {}
for outer_name, outer_conf in loaded_conf.items(): for outer_name, outer_conf in loaded_conf.items():
# only handle known config sections # only handle known config sections
if outer_name not in CONFIG_DEFAULTS.keys(): if outer_name not in CONFIG_DEFAULTS.keys():
@ -44,8 +48,9 @@ def load_config(config_file=None):
if not isinstance(outer_conf, dict): if not isinstance(outer_conf, dict):
parsed[outer_name] = outer_conf parsed[outer_name] = outer_conf
else: else:
# recurse into inner dict if not merge_defaults:
#parsed[outer_name] = {} # init section
parsed[outer_name] = {}
# profiles need special handling: # profiles need special handling:
# 1. profile names are unknown keys by definition, but we want 'default' to exist # 1. profile names are unknown keys by definition, but we want 'default' to exist
@ -55,7 +60,10 @@ def load_config(config_file=None):
logging.warning('Default profile is not in profiles') logging.warning('Default profile is not in profiles')
for profile_name, profile_conf in outer_conf.items(): for profile_name, profile_conf in outer_conf.items():
parsed[outer_name][profile_name] = {} # init profile; don't accidentally overwrite the default profile when merging
if not (merge_defaults and profile_name == 'default'):
parsed[outer_name][profile_name] = {}
for key, val in profile_conf.items(): for key, val in profile_conf.items():
if key not in PROFILE_DEFAULTS: if key not in PROFILE_DEFAULTS:
logging.warning(f'Skipped unknown config item "{key}" in profile "{profile_name}"') logging.warning(f'Skipped unknown config item "{key}" in profile "{profile_name}"')
@ -63,6 +71,7 @@ def load_config(config_file=None):
parsed[outer_name][profile_name][key] = val parsed[outer_name][profile_name][key] = val
else: else:
# handle generic inner config dict
for inner_name, inner_conf in outer_conf.items(): for inner_name, inner_conf in outer_conf.items():
if inner_name not in CONFIG_DEFAULTS[outer_name].keys(): if inner_name not in CONFIG_DEFAULTS[outer_name].keys():
logging.warning(f'Skipped unknown config item "{key}" in "{inner_name}"') logging.warning(f'Skipped unknown config item "{key}" in "{inner_name}"')