diff options
Diffstat (limited to 'python')
| -rw-r--r-- | python/vyos/utils/config.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/python/vyos/utils/config.py b/python/vyos/utils/config.py index 1f067e91e..1032e22dc 100644 --- a/python/vyos/utils/config.py +++ b/python/vyos/utils/config.py @@ -44,6 +44,37 @@ def read_saved_value(path: list): return ' '.join(res) return res +def write_saved_value(path: list, value=None, config_path: str=config_file): + """Write or replace a node in a saved configuration. + + - If value is None, the node is treated as valueless. + - Tag nodes in the path are detected via XML reference tree and marked on + the ConfigTree prior to setting the node. + """ + if not isinstance(path, list) or not path: + raise ValueError('path must be a non-empty list') + + from vyos.configtree import ConfigTree + from vyos.utils.file import read_file + from vyos.utils.file import write_file + + config_string = read_file(config_path) + ct = ConfigTree(config_string) + + # ConfigTree.set_tag() requires the node to exist. + # Create missing nodes along the path so tag marking works even when + # writing a completely new subtree into config.boot. + for target in flag(path): + if not ct.exists(target): + ct.create_node(target) + + set_tags(ct, path) + + ct.set(path, value=value, replace=True) + set_leaf(ct, path) + + write_file(config_path, ct.to_string()) + def flag(l: list) -> list: res = [l[0:i] for i,_ in enumerate(l, start=1)] return res @@ -63,6 +94,11 @@ def set_tags(ct: 'ConfigTree', path: list) -> None: if condition: ct.set_tag(target) +def set_leaf(ct: 'ConfigTree', path: list) -> None: + from vyos.xml_ref import is_leaf + if is_leaf(path): + ct.set_leaf(path, True) + def parse_commands(cmds: str) -> dict: from re import split as re_split from shlex import split as shlex_split |
