mirror of
https://github.com/xcat2/confluent.git
synced 2026-01-10 18:12:30 +00:00
Implement .replace() for attribute expressions
Provide an easy to use replace() to allow removing or substiting values during expression evaluation.
This commit is contained in:
@@ -1142,7 +1142,10 @@ class _ExpressionFormat(string.Formatter):
|
||||
# such as 'net.pxe.hwaddr'
|
||||
key = '.' + left.attr + key
|
||||
left = left.value
|
||||
key = left.id + key
|
||||
if isinstance(left, ast.Name):
|
||||
key = left.id + key
|
||||
else:
|
||||
raise ValueError("Invalid AST structure: expected ast.Name at end of attribute chain")
|
||||
if (not key.startswith('custom.') and
|
||||
_get_valid_attrname(key) not in allattributes.node):
|
||||
raise ValueError(
|
||||
@@ -1203,6 +1206,34 @@ class _ExpressionFormat(string.Formatter):
|
||||
return strval[index]
|
||||
elif isinstance(node, ast.Constant):
|
||||
return node.value
|
||||
elif isinstance(node, ast.Call):
|
||||
key = ''
|
||||
if isinstance(node.func, ast.Attribute):
|
||||
fun_name = node.func.attr
|
||||
left = node.func.value
|
||||
while isinstance(left, ast.Attribute):
|
||||
# Loop through, to handle multi dot expressions
|
||||
# such as 'net.pxe.hwaddr'
|
||||
key = '.' + left.attr + key
|
||||
left = left.value
|
||||
if isinstance(left, ast.Name):
|
||||
key = left.id + key
|
||||
else:
|
||||
raise ValueError("Invalid AST structure: expected ast.Name at end of attribute chain")
|
||||
else:
|
||||
raise ValueError(f"Unsupported function in expression")
|
||||
if fun_name == 'replace':
|
||||
if len(node.args) != 2:
|
||||
raise ValueError("Invalid number of arguments to replace")
|
||||
arg1 = self._handle_ast_node(node.args[0])
|
||||
arg2 = self._handle_ast_node(node.args[1])
|
||||
if key in ('node', 'nodename'):
|
||||
keyval = self._nodename
|
||||
else:
|
||||
keyval = self._expand_attribute(key).get('value', '')
|
||||
return keyval.replace(arg1, arg2)
|
||||
else:
|
||||
raise ValueError("Unsupported function in expression")
|
||||
else:
|
||||
raise ValueError("Unrecognized expression syntax")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user