From: Christian Herdtweck Date: Tue, 3 Mar 2026 14:24:50 +0000 (+0100) Subject: Allow children in cnfvar templates X-Git-Tag: v1.7.5~3 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=d2e31cef8f7770c27614534292592269f528eea5;p=pyi2ncommon Allow children in cnfvar templates Some templates are not just lists of cnfvars, but contain elements that required child cnfvars (e.g. the upcomping VPNCONN_WG_LOCAL_NET). However, a CnfVar's "children" attribute cannot be set in the CnfVar constructor, nor are there mechanisms to do that in other functions that create CnfVars. Add functionality for this special case of creating CnfVars from templates, where values are very-well controlled. Use dicts to specify the children. Also warn if naive users specify overwrite parameters including the "name" like "VPNCONN_PROTO" (should only be "proto=...") --- diff --git a/src/cnfvar/templates.py b/src/cnfvar/templates.py index 5154a03..4c157fa 100644 --- a/src/cnfvar/templates.py +++ b/src/cnfvar/templates.py @@ -219,13 +219,25 @@ def template(name, value, instance=-1, defaults=None, **kwargs): :rtype: :py:class:`Cnf` All additional keyword arguments will be used to overwrite the defaults. + They cannot add new variables, not present in defaults. """ log.info(f"Generating a template {name} cnfvar") cnf = Cnf(name, value=value, instance=instance) defaults = {} if defaults is None else defaults - cnf.add_children(*[(key, value) for key, value in defaults.items()]) + for key, value in defaults.items(): + if isinstance(value, dict): + sub_children = value.pop("children") + new_child = Cnf(name=key, **value) + new_child.add_children(*sub_children) + cnf.add_child(new_child) + else: + cnf.add_child(key, value) + prefix = name.lower() + "_" for key in kwargs.keys(): - cnf.children.single_with_name(f"{name}_{key}").value = kwargs[key] + if key.lower().startswith(prefix): + log.warning(f"For overwriting template params, omit the leading name " + f"(here: {name}_) from keys (here: {key})") + cnf.children.single_with_name(f"{prefix}{key}").value = kwargs[key] return cnf