diff options
| author | Christian Breunig <christian@breunig.cc> | 2026-04-28 17:00:07 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-04-28 17:00:07 +0200 |
| commit | 9c8f3d15cd8ba9f3e0ecdfe7081f7f2d13a59453 (patch) | |
| tree | 3ce5f40d490d29566a37efc1defc597e283dcce9 /python | |
| parent | e834a6d51090b2a9261f80464be05d4984cbcce0 (diff) | |
| parent | e8434e64bada81aabed2cfe614d64cd213110984 (diff) | |
| download | vyos-1x-9c8f3d15cd8ba9f3e0ecdfe7081f7f2d13a59453.tar.gz vyos-1x-9c8f3d15cd8ba9f3e0ecdfe7081f7f2d13a59453.zip | |
Merge pull request #5146 from c-po/serial
utils: T8541: add write-config-file-value helper
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 |
