implement recursive config overrides

This commit is contained in:
Suhas 2021-01-24 11:08:47 -05:00
parent 9bab1aee87
commit f3d8ed2e45
2 changed files with 26 additions and 9 deletions

View file

@ -330,11 +330,11 @@ def parse_args(args=[]):
help=""" help="""
Override configured key-value pairs with CONFIG_KV_PAIR for this command invocation only. Override configured key-value pairs with CONFIG_KV_PAIR for this command invocation only.
Examples: Examples: \n
- Use a different editor for this jrnl entry, call: \t - Use a different editor for this jrnl entry, call: \n
jrnl --config-override '{"editor": "nano"}' \t jrnl --config-override '{"editor": "nano"}' \n
- Override color selections \t - Override color selections\n
jrnl --config-override '{"colors.body":"blue", "colors.title": "green"} \t jrnl --config-override '{"colors.body":"blue", "colors.title": "green"}
""", """,
) )

View file

@ -1,8 +1,25 @@
import logging # import logging
def apply_overrides(overrides: dict, base_config: dict) -> dict: def apply_overrides(overrides: dict, base_config: dict) -> dict:
config = base_config.copy() config = base_config.copy()
for k in overrides: for k in overrides:
logging.debug("Overriding %s from %s to %s" % (k, config[k], overrides[k])) nodes = k.split('.')
config[k] = overrides[k] config = recursively_apply(config, nodes, overrides[k])
return config
def recursively_apply(config: dict, nodes: list, override_value) -> dict:
"""Recurse through configuration and apply overrides at the leaf of the config tree
See: https://stackoverflow.com/a/47276490 for algorithm
Args:
config (dict): loaded configuration from YAML
nodes (list): vector of override keys; the length of the vector indicates tree depth
override_value (str): runtime override passed from the command-line
"""
key = nodes[0]
config[key] = override_value \
if len(nodes) == 1 \
else \
recursively_apply(config[key] if key in config else {}, nodes[1:], override_value)
return config return config