-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathtemplate.py
More file actions
62 lines (48 loc) · 1.6 KB
/
Copy pathtemplate.py
File metadata and controls
62 lines (48 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""Template rendering for fuzzer crash reports using Jinja2."""
import os
from pathlib import Path
from jinja2 import BaseLoader, Environment, Undefined
class _NotSetUndefined(Undefined):
"""Jinja2 undefined that renders as '(not set)' and is falsy."""
def __str__(self):
return "(not set)"
def __bool__(self):
return False
def render_template(
template_path: str | Path,
variables: dict[str, str] | None = None,
use_env: bool = True,
) -> str:
"""
Render a Jinja2 template with the given variables.
Variables are resolved in order: explicit variables > environment variables.
Undefined variables render as "(not set)".
Args:
template_path: Path to the template file
variables: Dictionary of variables to substitute
use_env: If True, also look up variables from environment
Returns:
Rendered template content
"""
template_content = Path(template_path).read_text()
merged = {}
if use_env:
merged.update(os.environ)
if variables:
merged.update(variables)
env = Environment(
loader=BaseLoader(),
keep_trailing_newline=True,
undefined=_NotSetUndefined,
)
template = env.from_string(template_content)
return template.render(merged)
def render_template_to_file(
template_path: str | Path,
output_path: str | Path,
variables: dict[str, str] | None = None,
use_env: bool = True,
) -> None:
"""Render template and write to output file."""
content = render_template(template_path, variables, use_env)
Path(output_path).write_text(content)