111 lines
3.5 KiB
Python
111 lines
3.5 KiB
Python
"""Template variable validation and preview helpers for notification templates.
|
||
|
||
Supported placeholders (exact names, no spaces):
|
||
{{userName}} {{taskName}} {{taskId}} {{dueDate}}
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
ALLOWED_VARIABLES: frozenset[str] = frozenset({"userName", "taskName", "taskId", "dueDate"})
|
||
|
||
# Captures the inner of a well-formed {{...}} pair (no nested braces).
|
||
_VAR_RE = re.compile(r"\{\{([^{}]*)\}\}")
|
||
# Valid identifier: letters then letters/digits (no spaces / punctuation).
|
||
_IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
|
||
|
||
|
||
class TemplateVariableError(ValueError):
|
||
"""Raised when a template contains an invalid / unsupported / unclosed variable."""
|
||
|
||
def __init__(self, message: str) -> None:
|
||
super().__init__(message)
|
||
self.message = message
|
||
|
||
|
||
def validate_template_text(text: str) -> None:
|
||
"""Validate all ``{{var}}`` occurrences in *text*.
|
||
|
||
Raises ``TemplateVariableError`` with a Chinese message pointing at the
|
||
offending variable or position.
|
||
"""
|
||
if not text:
|
||
return
|
||
|
||
i = 0
|
||
while True:
|
||
start = text.find("{{", i)
|
||
if start < 0:
|
||
break
|
||
end = text.find("}}", start + 2)
|
||
if end < 0:
|
||
raise TemplateVariableError(f"未闭合的变量(位置 {start})")
|
||
inner = text[start + 2 : end]
|
||
token = "{{" + inner + "}}"
|
||
if not inner or not _IDENT_RE.fullmatch(inner):
|
||
raise TemplateVariableError(f"变量格式错误:{token}")
|
||
if inner not in ALLOWED_VARIABLES:
|
||
raise TemplateVariableError(f"不支持的变量:{token}")
|
||
i = end + 2
|
||
|
||
|
||
def validate_templates(*texts: str) -> None:
|
||
"""Validate every template string; first error wins."""
|
||
for text in texts:
|
||
validate_template_text(text or "")
|
||
|
||
|
||
def extract_variables(text: str) -> list[str]:
|
||
"""Return ordered unique allowed-looking variable names found in *text*."""
|
||
seen: set[str] = set()
|
||
out: list[str] = []
|
||
for match in _VAR_RE.finditer(text or ""):
|
||
name = match.group(1)
|
||
if name in seen:
|
||
continue
|
||
seen.add(name)
|
||
out.append(name)
|
||
return out
|
||
|
||
|
||
def render_template(text: str, variables: dict[str, str] | None) -> tuple[str, list[str]]:
|
||
"""Replace known placeholders; keep missing ones and report their names.
|
||
|
||
Returns ``(rendered, missing_variables)``. Missing names are unique and
|
||
appear in first-seen order.
|
||
"""
|
||
vars_map = variables or {}
|
||
missing: list[str] = []
|
||
seen_missing: set[str] = set()
|
||
|
||
def _repl(match: re.Match[str]) -> str:
|
||
name = match.group(1)
|
||
if name in vars_map and vars_map[name] is not None:
|
||
return str(vars_map[name])
|
||
if name not in seen_missing:
|
||
seen_missing.add(name)
|
||
missing.append(name)
|
||
return match.group(0)
|
||
|
||
rendered = _VAR_RE.sub(_repl, text or "")
|
||
return rendered, missing
|
||
|
||
|
||
def preview_templates(
|
||
title_template: str,
|
||
content_template: str,
|
||
variables: dict[str, str] | None = None,
|
||
) -> dict[str, object]:
|
||
"""Render title + content; merge missing variable lists (order-preserving)."""
|
||
title, missing_title = render_template(title_template, variables)
|
||
content, missing_content = render_template(content_template, variables)
|
||
seen: set[str] = set()
|
||
missing: list[str] = []
|
||
for name in missing_title + missing_content:
|
||
if name in seen:
|
||
continue
|
||
seen.add(name)
|
||
missing.append(name)
|
||
return {"title": title, "content": content, "missing_variables": missing}
|