mirror of
https://github.com/jrnl-org/jrnl.git
synced 2025-05-20 04:58:32 +02:00
refactor recursive code
This commit is contained in:
parent
d348dbd55e
commit
9540d34964
2 changed files with 21 additions and 8 deletions
|
@ -10,7 +10,7 @@ def apply_overrides(overrides: dict, base_config: dict) -> dict:
|
|||
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
|
||||
Credit to iJames on SO: https://stackoverflow.com/a/47276490 for algorithm
|
||||
|
||||
Args:
|
||||
config (dict): loaded configuration from YAML
|
||||
|
@ -18,11 +18,18 @@ def recursively_apply(config: dict, nodes: list, override_value) -> dict:
|
|||
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
|
||||
)
|
||||
)
|
||||
if len(nodes) == 1:
|
||||
config[key] = override_value
|
||||
else:
|
||||
next_key = nodes[1:]
|
||||
_recursively_apply(_get_config_node(config, key), next_key, override_value)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def _get_config_node(config: dict, key: str):
|
||||
if key in config:
|
||||
pass
|
||||
else:
|
||||
config[key] = None
|
||||
return config[key]
|
||||
|
|
|
@ -32,3 +32,9 @@ def test_recursive_override(minimal_config):
|
|||
cfg = {"colors": {"body": "red", "title": "green"}}
|
||||
cfg = recursively_apply(cfg, ["colors", "body"], "blue")
|
||||
assert cfg["colors"]["body"] == "blue"
|
||||
|
||||
|
||||
def test_get_config_node(minimal_config):
|
||||
assert len(minimal_config.keys()) == 3
|
||||
assert _get_config_node(minimal_config, "editor") == "vim"
|
||||
assert _get_config_node(minimal_config, "display_format") == None
|
||||
|
|
Loading…
Add table
Reference in a new issue