"""Variable substitution utilities."""
import re
from typing import Any, Dict
def substitute_variables(text: str, bindings: Dict[str, str]) -> str:
"""
Substitute ${var} patterns in text with values from bindings.
Args:
text: Text containing ${var} patterns
bindings: Dictionary of variable values
Returns:
str: Text with variables substituted
Example:
>>> substitute_variables("Hello ${name}", {"name": "World"})
'Hello World'
"""
if not text:
return text
pattern = re.compile(r"\$\{(\w+)\}")
def replacer(match: re.Match) -> str:
var_name = match.group(1)
return bindings.get(var_name, match.group(0))
return pattern.sub(replacer, text)
def substitute_in_dict(data: Dict[str, Any], bindings: Dict[str, str]) -> Dict[str, Any]:
"""
Recursively substitute variables in dictionary values.
Args:
data: Dictionary to process
bindings: Variable bindings
Returns:
Dict: Dictionary with substituted values
"""
result = {}
for key, value in data.items():
if isinstance(value, str):
result[key] = substitute_variables(value, bindings)
elif isinstance(value, dict):
result[key] = substitute_in_dict(value, bindings)
elif isinstance(value, list):
result[key] = [
substitute_variables(item, bindings)
if isinstance(item, str)
else item
for item in value
]
else:
result[key] = value
return result