From f3d8ed2e45bc4500996e6c82395347efe5eb4219 Mon Sep 17 00:00:00 2001 From: Suhas Date: Sun, 24 Jan 2021 11:08:47 -0500 Subject: [PATCH] implement recursive config overrides --- jrnl/args.py | 10 +++++----- jrnl/override.py | 25 +++++++++++++++++++++---- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/jrnl/args.py b/jrnl/args.py index d991783f..99489b74 100644 --- a/jrnl/args.py +++ b/jrnl/args.py @@ -330,11 +330,11 @@ def parse_args(args=[]): help=""" Override configured key-value pairs with CONFIG_KV_PAIR for this command invocation only. - Examples: - - Use a different editor for this jrnl entry, call: - jrnl --config-override '{"editor": "nano"}' - - Override color selections - jrnl --config-override '{"colors.body":"blue", "colors.title": "green"} + Examples: \n + \t - Use a different editor for this jrnl entry, call: \n + \t jrnl --config-override '{"editor": "nano"}' \n + \t - Override color selections\n + \t jrnl --config-override '{"colors.body":"blue", "colors.title": "green"} """, ) diff --git a/jrnl/override.py b/jrnl/override.py index 09de4258..8da034f9 100644 --- a/jrnl/override.py +++ b/jrnl/override.py @@ -1,8 +1,25 @@ -import logging +# import logging def apply_overrides(overrides: dict, base_config: dict) -> dict: config = base_config.copy() - for k in overrides: - logging.debug("Overriding %s from %s to %s" % (k, config[k], overrides[k])) - config[k] = overrides[k] + for k in overrides: + nodes = k.split('.') + 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 \ No newline at end of file