flow
This commit is contained in:
38
core/variables.py
Normal file
38
core/variables.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Variable substitution for $VAR/${VAR} and {{var}} templates."""
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def substitute(text: str, variables: Dict[str, str]) -> str:
|
||||
"""Replace $VAR and ${VAR} with values from variables dict or env."""
|
||||
if not isinstance(text, str):
|
||||
return text
|
||||
|
||||
pattern = re.compile(r"\$(\w+)|\$\{([^}]+)\}")
|
||||
|
||||
def _replace(match: re.Match[str]) -> str:
|
||||
key = match.group(1) or match.group(2) or ""
|
||||
if key in variables:
|
||||
return str(variables[key])
|
||||
if key == "HOME":
|
||||
return str(Path.home())
|
||||
if key in os.environ:
|
||||
return os.environ[key]
|
||||
return match.group(0)
|
||||
|
||||
return pattern.sub(_replace, text)
|
||||
|
||||
|
||||
def substitute_template(text: str, context: Dict[str, str]) -> str:
|
||||
"""Replace {{key}} placeholders with values from context dict."""
|
||||
if not isinstance(text, str):
|
||||
return text
|
||||
|
||||
def _replace(match: re.Match[str]) -> str:
|
||||
key = match.group(1).strip()
|
||||
return context.get(key, match.group(0))
|
||||
|
||||
return re.sub(r"\{\{(\w+)\}\}", _replace, text)
|
||||
Reference in New Issue
Block a user