mirror of
https://github.com/jrnl-org/jrnl.git
synced 2025-05-20 13:08:31 +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:
|
def recursively_apply(config: dict, nodes: list, override_value) -> dict:
|
||||||
"""Recurse through configuration and apply overrides at the leaf of the config tree
|
"""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:
|
Args:
|
||||||
config (dict): loaded configuration from YAML
|
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
|
override_value (str): runtime override passed from the command-line
|
||||||
"""
|
"""
|
||||||
key = nodes[0]
|
key = nodes[0]
|
||||||
config[key] = (
|
if len(nodes) == 1:
|
||||||
override_value
|
config[key] = override_value
|
||||||
if len(nodes) == 1
|
else:
|
||||||
else recursively_apply(
|
next_key = nodes[1:]
|
||||||
config[key] if key in config else {}, nodes[1:], override_value
|
_recursively_apply(_get_config_node(config, key), next_key, override_value)
|
||||||
)
|
|
||||||
)
|
|
||||||
return config
|
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 = {"colors": {"body": "red", "title": "green"}}
|
||||||
cfg = recursively_apply(cfg, ["colors", "body"], "blue")
|
cfg = recursively_apply(cfg, ["colors", "body"], "blue")
|
||||||
assert 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