template.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. from __future__ import annotations
  2. import importlib
  3. import logging
  4. import os
  5. import re
  6. import secrets
  7. import string
  8. from dataclasses import dataclass, field
  9. from functools import lru_cache
  10. from pathlib import Path
  11. from typing import Any, Literal
  12. import yaml
  13. from jinja2 import Environment, FileSystemLoader, meta
  14. from jinja2.exceptions import (
  15. TemplateError as Jinja2TemplateError,
  16. )
  17. from jinja2.exceptions import (
  18. TemplateNotFound as Jinja2TemplateNotFound,
  19. )
  20. from jinja2.exceptions import (
  21. TemplateSyntaxError as Jinja2TemplateSyntaxError,
  22. )
  23. from jinja2.exceptions import (
  24. UndefinedError,
  25. )
  26. from jinja2.sandbox import SandboxedEnvironment
  27. from ..exceptions import (
  28. IncompatibleSchemaVersionError,
  29. RenderErrorContext,
  30. TemplateLoadError,
  31. TemplateRenderError,
  32. TemplateSyntaxError,
  33. TemplateValidationError,
  34. YAMLParseError,
  35. )
  36. from ..version import is_compatible
  37. from .variable_collection import VariableCollection
  38. logger = logging.getLogger(__name__)
  39. class TemplateErrorHandler:
  40. """Handles parsing and formatting of template rendering errors.
  41. This class provides utilities for:
  42. - Extracting error context from template files
  43. - Generating helpful suggestions based on Jinja2 errors
  44. - Parsing Jinja2 exceptions into structured error information
  45. """
  46. @staticmethod
  47. def extract_error_context(file_path: Path, line_number: int | None, context_size: int = 3) -> list[str]:
  48. """Extract lines of context around an error location.
  49. Args:
  50. file_path: Path to the file with the error
  51. line_number: Line number where error occurred (1-indexed)
  52. context_size: Number of lines to show before and after
  53. Returns:
  54. List of context lines with line numbers
  55. """
  56. if not line_number or not file_path.exists():
  57. return []
  58. try:
  59. with file_path.open(encoding="utf-8") as f:
  60. lines = f.readlines()
  61. start_line = max(0, line_number - context_size - 1)
  62. end_line = min(len(lines), line_number + context_size)
  63. context = []
  64. for i in range(start_line, end_line):
  65. line_num = i + 1
  66. marker = ">>>" if line_num == line_number else " "
  67. context.append(f"{marker} {line_num:4d} | {lines[i].rstrip()}")
  68. return context
  69. except OSError:
  70. return []
  71. @staticmethod
  72. def get_common_jinja_suggestions(error_msg: str, available_vars: set) -> list[str]:
  73. """Generate helpful suggestions based on common Jinja2 errors.
  74. Args:
  75. error_msg: The error message from Jinja2
  76. available_vars: Set of available variable names
  77. Returns:
  78. List of actionable suggestions
  79. """
  80. suggestions = []
  81. error_lower = error_msg.lower()
  82. # Undefined variable errors
  83. if "undefined" in error_lower or "is not defined" in error_lower:
  84. # Try to extract variable name from error message
  85. var_match = re.search(r"'([^']+)'.*is undefined", error_msg)
  86. if not var_match:
  87. var_match = re.search(r"'([^']+)'.*is not defined", error_msg)
  88. if var_match:
  89. undefined_var = var_match.group(1)
  90. suggestions.append(f"Variable '{undefined_var}' is not defined in the template spec")
  91. # Suggest similar variable names (basic fuzzy matching)
  92. similar = [
  93. v
  94. for v in available_vars
  95. if undefined_var.lower() in v.lower() or v.lower() in undefined_var.lower()
  96. ]
  97. if similar:
  98. suggestions.append(f"Did you mean one of these? {', '.join(sorted(similar)[:5])}")
  99. suggestions.append(f"Add '{undefined_var}' to your template.yaml spec with a default value")
  100. suggestions.append("Or use the Jinja2 default filter: {{ " + undefined_var + " | default('value') }}")
  101. else:
  102. suggestions.append("Check that all variables used in templates are defined in template.yaml")
  103. suggestions.append("Use the Jinja2 default filter for optional variables: {{ var | default('value') }}")
  104. # Syntax errors
  105. elif "unexpected" in error_lower or "expected" in error_lower:
  106. suggestions.append("Check for syntax errors in your Jinja2 template")
  107. suggestions.append("Common issues: missing {% endfor %}, {% endif %}, or {% endblock %}")
  108. suggestions.append("Make sure all {{ }} and {% %} tags are properly closed")
  109. # Filter errors
  110. elif "filter" in error_lower:
  111. suggestions.append("Check that the filter name is spelled correctly")
  112. suggestions.append("Verify the filter exists in Jinja2 built-in filters")
  113. suggestions.append("Make sure filter arguments are properly formatted")
  114. # Template not found
  115. elif "not found" in error_lower or "does not exist" in error_lower:
  116. suggestions.append("Check that the included/imported template file exists")
  117. suggestions.append("Verify the template path is relative to the template directory")
  118. suggestions.append("Make sure the file has the .j2 extension if it's a Jinja2 template")
  119. # Type errors
  120. elif "type" in error_lower and ("int" in error_lower or "str" in error_lower or "bool" in error_lower):
  121. suggestions.append("Check that variable values have the correct type")
  122. suggestions.append("Use Jinja2 filters to convert types: {{ var | int }}, {{ var | string }}")
  123. # Add generic helpful tip
  124. if not suggestions:
  125. suggestions.append("Check the Jinja2 template syntax and variable usage")
  126. suggestions.append("Enable --debug mode for more detailed rendering information")
  127. return suggestions
  128. @classmethod
  129. def parse_jinja_error(
  130. cls,
  131. error: Exception,
  132. template_file: TemplateFile,
  133. template_dir: Path,
  134. available_vars: set,
  135. ) -> tuple[str, int | None, int | None, list[str], list[str]]:
  136. """Parse a Jinja2 exception to extract detailed error information.
  137. Args:
  138. error: The Jinja2 exception
  139. template_file: The TemplateFile being rendered
  140. template_dir: Template directory path
  141. available_vars: Set of available variable names
  142. Returns:
  143. Tuple of (error_message, line_number, column, context_lines, suggestions)
  144. """
  145. error_msg = str(error)
  146. line_number = None
  147. column = None
  148. context_lines = []
  149. suggestions = []
  150. # Extract line number from Jinja2 errors
  151. if hasattr(error, "lineno"):
  152. line_number = error.lineno
  153. # Extract file path and get context
  154. file_path = template_dir / template_file.relative_path
  155. if line_number and file_path.exists():
  156. context_lines = cls.extract_error_context(file_path, line_number)
  157. # Generate suggestions based on error type
  158. if isinstance(error, UndefinedError):
  159. error_msg = f"Undefined variable: {error}"
  160. suggestions = cls.get_common_jinja_suggestions(str(error), available_vars)
  161. elif isinstance(error, Jinja2TemplateSyntaxError):
  162. error_msg = f"Template syntax error: {error}"
  163. suggestions = cls.get_common_jinja_suggestions(str(error), available_vars)
  164. elif isinstance(error, Jinja2TemplateNotFound):
  165. error_msg = f"Template file not found: {error}"
  166. suggestions = cls.get_common_jinja_suggestions(str(error), available_vars)
  167. else:
  168. # Generic Jinja2 error
  169. suggestions = cls.get_common_jinja_suggestions(error_msg, available_vars)
  170. return error_msg, line_number, column, context_lines, suggestions
  171. @dataclass
  172. class TemplateFile:
  173. """Represents a single file within a template directory."""
  174. relative_path: Path
  175. file_type: Literal["j2", "static"]
  176. output_path: Path # The path it will have in the output directory
  177. @dataclass
  178. class TemplateMetadata:
  179. """Represents template metadata with proper typing."""
  180. name: str
  181. description: str
  182. author: str
  183. date: str
  184. version: str
  185. module: str = ""
  186. tags: list[str] = field(default_factory=list)
  187. library: str = "unknown"
  188. library_type: str = "git" # Type of library ("git" or "static")
  189. next_steps: str = ""
  190. draft: bool = False
  191. def __init__(
  192. self,
  193. template_data: dict,
  194. library_name: str | None = None,
  195. library_type: str = "git",
  196. ) -> None:
  197. """Initialize TemplateMetadata from parsed YAML template data.
  198. Args:
  199. template_data: Parsed YAML data from template.yaml
  200. library_name: Name of the library this template belongs to
  201. """
  202. # Validate metadata format first
  203. self._validate_metadata(template_data)
  204. # Extract metadata section
  205. metadata_section = template_data.get("metadata", {})
  206. self.name = metadata_section.get("name", "")
  207. # YAML block scalar (|) preserves a trailing newline. Remove only trailing newlines
  208. # while preserving internal newlines/formatting.
  209. raw_description = metadata_section.get("description", "")
  210. # TODO: remove when all templates have been migrated to markdown
  211. description = raw_description.rstrip("\n") if isinstance(raw_description, str) else str(raw_description)
  212. self.description = description or "No description available"
  213. self.author = metadata_section.get("author", "")
  214. self.date = metadata_section.get("date", "")
  215. self.version = metadata_section.get("version", "")
  216. self.module = metadata_section.get("module", "")
  217. self.tags = metadata_section.get("tags", []) or []
  218. self.library = library_name or "unknown"
  219. self.library_type = library_type
  220. self.draft = metadata_section.get("draft", False)
  221. # Extract next_steps (optional)
  222. raw_next_steps = metadata_section.get("next_steps", "")
  223. if isinstance(raw_next_steps, str):
  224. next_steps = raw_next_steps.rstrip("\n")
  225. else:
  226. next_steps = str(raw_next_steps) if raw_next_steps else ""
  227. self.next_steps = next_steps
  228. @staticmethod
  229. def _validate_metadata(template_data: dict) -> None:
  230. """Validate that template has required 'metadata' section with all required fields.
  231. Args:
  232. template_data: Parsed YAML data from template.yaml
  233. Raises:
  234. ValueError: If metadata section is missing or incomplete
  235. """
  236. metadata_section = template_data.get("metadata")
  237. if metadata_section is None:
  238. raise ValueError("Template format error: missing 'metadata' section")
  239. # Validate that metadata section has all required fields
  240. required_fields = ["name", "author", "version", "date", "description"]
  241. missing_fields = [field for field in required_fields if not metadata_section.get(field)]
  242. if missing_fields:
  243. raise ValueError(f"Template format error: missing required metadata fields: {missing_fields}")
  244. @dataclass
  245. class Template:
  246. """Represents a template directory."""
  247. def __init__(self, template_dir: Path, library_name: str, library_type: str = "git") -> None:
  248. """Create a Template instance from a directory path.
  249. Args:
  250. template_dir: Path to the template directory
  251. library_name: Name of the library this template belongs to
  252. library_type: Type of library ("git" or "static"), defaults to "git"
  253. """
  254. logger.debug(f"Loading template from directory: {template_dir}")
  255. self.template_dir = template_dir
  256. self.id = template_dir.name
  257. self.original_id = template_dir.name # Store the original ID
  258. self.library_name = library_name
  259. self.library_type = library_type
  260. # Initialize caches for lazy loading
  261. self.__module_specs: dict | None = None
  262. self.__merged_specs: dict | None = None
  263. self.__jinja_env: Environment | None = None
  264. self.__used_variables: set[str] | None = None
  265. self.__variables: VariableCollection | None = None
  266. self.__template_files: list[TemplateFile] | None = None # New attribute
  267. try:
  268. # Find and parse the main template file (template.yaml or template.yml)
  269. main_template_path = self._find_main_template_file()
  270. with main_template_path.open(encoding="utf-8") as f:
  271. # Load all YAML documents (handles templates with empty lines before ---)
  272. documents = list(yaml.safe_load_all(f))
  273. # Filter out None/empty documents and get the first non-empty one
  274. valid_docs = [doc for doc in documents if doc is not None]
  275. if not valid_docs:
  276. raise ValueError("Template file contains no valid YAML data")
  277. if len(valid_docs) > 1:
  278. logger.warning("Template file contains multiple YAML documents, using the first one")
  279. self._template_data = valid_docs[0]
  280. # Validate template data
  281. if not isinstance(self._template_data, dict):
  282. raise ValueError("Template file must contain a valid YAML dictionary")
  283. # Load metadata (always needed)
  284. self.metadata = TemplateMetadata(self._template_data, library_name, library_type)
  285. logger.debug(f"Loaded metadata: {self.metadata}")
  286. # Validate 'kind' field (always needed)
  287. self._validate_kind(self._template_data)
  288. # Extract schema version (default to 1.0 for backward compatibility)
  289. self.schema_version = str(self._template_data.get("schema", "1.0"))
  290. logger.debug(f"Template schema version: {self.schema_version}")
  291. # Note: Schema version validation is done by the module when loading templates
  292. # NOTE: File collection is now lazy-loaded via the template_files property
  293. # This significantly improves performance when listing many templates
  294. logger.info(f"Loaded template '{self.id}' (v{self.metadata.version})")
  295. except (ValueError, FileNotFoundError) as e:
  296. logger.error(f"Error loading template from {template_dir}: {e}")
  297. raise TemplateLoadError(f"Error loading template from {template_dir}: {e}") from e
  298. except yaml.YAMLError as e:
  299. logger.error(f"YAML parsing error in template {template_dir}: {e}")
  300. raise YAMLParseError(str(template_dir / "template.y*ml"), e) from e
  301. except OSError as e:
  302. logger.error(f"File I/O error loading template {template_dir}: {e}")
  303. raise TemplateLoadError(f"File I/O error loading template from {template_dir}: {e}") from e
  304. def set_qualified_id(self, library_name: str | None = None) -> None:
  305. """Set a qualified ID for this template (used when duplicates exist across libraries).
  306. Args:
  307. library_name: Name of the library to qualify with. If None, uses self.library_name
  308. """
  309. lib_name = library_name or self.library_name
  310. self.id = f"{self.original_id}.{lib_name}"
  311. logger.debug(f"Template ID qualified: {self.original_id} -> {self.id}")
  312. def _find_main_template_file(self) -> Path:
  313. """Find the main template file (template.yaml or template.yml)."""
  314. for filename in ["template.yaml", "template.yml"]:
  315. path = self.template_dir / filename
  316. if path.exists():
  317. return path
  318. raise FileNotFoundError(f"Main template file (template.yaml or template.yml) not found in {self.template_dir}")
  319. @staticmethod
  320. @lru_cache(maxsize=32)
  321. def _load_module_specs_for_schema(kind: str, schema_version: str) -> dict:
  322. """Load specifications from the corresponding module for a specific schema version.
  323. Uses LRU cache to avoid re-loading the same module spec multiple times.
  324. This significantly improves performance when listing many templates of the same kind.
  325. Args:
  326. kind: The module kind (e.g., 'compose', 'terraform')
  327. schema_version: The schema version to load (e.g., '1.0', '1.1')
  328. Returns:
  329. Dictionary containing the module's spec for the requested schema version,
  330. or empty dict if kind is empty
  331. Raises:
  332. ValueError: If module cannot be loaded or spec is invalid
  333. """
  334. if not kind:
  335. return {}
  336. # Log cache statistics for performance monitoring
  337. cache_info = Template._load_module_specs_for_schema.cache_info()
  338. logger.debug(
  339. f"Loading module spec: kind='{kind}', schema={schema_version} "
  340. f"(cache: hits={cache_info.hits}, misses={cache_info.misses}, size={cache_info.currsize})"
  341. )
  342. try:
  343. module = importlib.import_module(f"cli.modules.{kind}")
  344. # Check if module has schema-specific specs (multi-schema support)
  345. # Try SCHEMAS constant first (uppercase), then schemas attribute
  346. schemas = getattr(module, "SCHEMAS", None) or getattr(module, "schemas", None)
  347. if schemas and schema_version in schemas:
  348. spec = schemas[schema_version]
  349. logger.debug(f"Loaded and cached module spec for kind '{kind}' schema {schema_version}")
  350. else:
  351. # Fallback to default spec if schema mapping not available
  352. spec = getattr(module, "spec", {})
  353. logger.debug(f"Loaded and cached module spec for kind '{kind}' (default/no schema mapping)")
  354. return spec
  355. except Exception as e:
  356. raise ValueError(f"Error loading module specifications for kind '{kind}': {e}") from e
  357. def _merge_specs(self, module_specs: dict, template_specs: dict) -> dict:
  358. """Deep merge template specs with module specs using VariableCollection.
  359. Uses VariableCollection's native merge() method for consistent merging logic.
  360. Module specs are base, template specs override with origin tracking.
  361. """
  362. # Create VariableCollection from module specs (base)
  363. module_collection = VariableCollection(module_specs) if module_specs else VariableCollection({})
  364. # Set origin for module variables
  365. for section in module_collection.get_sections().values():
  366. for variable in section.variables.values():
  367. if not variable.origin:
  368. variable.origin = "module"
  369. # Merge template specs into module specs (template overrides)
  370. if template_specs:
  371. merged_collection = module_collection.merge(template_specs, origin="template")
  372. else:
  373. merged_collection = module_collection
  374. # Convert back to dict format
  375. merged_spec = {}
  376. for section_key, section in merged_collection.get_sections().items():
  377. merged_spec[section_key] = section.to_dict()
  378. return merged_spec
  379. def _collect_template_files(self) -> None:
  380. """Collects all TemplateFile objects in the template directory."""
  381. template_files: list[TemplateFile] = []
  382. for root, _, files in os.walk(self.template_dir):
  383. for filename in files:
  384. file_path = Path(root) / filename
  385. relative_path = file_path.relative_to(self.template_dir)
  386. # Skip the main template file
  387. if filename in ["template.yaml", "template.yml"]:
  388. continue
  389. if filename.endswith(".j2"):
  390. file_type: Literal["j2", "static"] = "j2"
  391. output_path = relative_path.with_suffix("") # Remove .j2 suffix
  392. else:
  393. file_type = "static"
  394. output_path = relative_path # Static files keep their name
  395. template_files.append(
  396. TemplateFile(
  397. relative_path=relative_path,
  398. file_type=file_type,
  399. output_path=output_path,
  400. )
  401. )
  402. self.__template_files = template_files
  403. def _extract_all_used_variables(self) -> set[str]:
  404. """Extract all undeclared variables from all .j2 files in the template directory.
  405. Raises:
  406. ValueError: If any Jinja2 template has syntax errors
  407. """
  408. used_variables: set[str] = set()
  409. syntax_errors = []
  410. for template_file in self.template_files: # Iterate over TemplateFile objects
  411. if template_file.file_type == "j2":
  412. file_path = self.template_dir / template_file.relative_path
  413. try:
  414. with file_path.open(encoding="utf-8") as f:
  415. content = f.read()
  416. ast = self.jinja_env.parse(content) # Use lazy-loaded jinja_env
  417. used_variables.update(meta.find_undeclared_variables(ast))
  418. except OSError as e:
  419. relative_path = file_path.relative_to(self.template_dir)
  420. syntax_errors.append(f" - {relative_path}: File I/O error: {e}")
  421. except Exception as e:
  422. # Collect syntax errors for Jinja2 issues
  423. relative_path = file_path.relative_to(self.template_dir)
  424. syntax_errors.append(f" - {relative_path}: {e}")
  425. # Raise error if any syntax errors were found
  426. if syntax_errors:
  427. logger.error(f"Jinja2 syntax errors found in template '{self.id}'")
  428. raise TemplateSyntaxError(self.id, syntax_errors)
  429. return used_variables
  430. def _filter_specs_to_used(
  431. self,
  432. used_variables: set,
  433. merged_specs: dict,
  434. _module_specs: dict,
  435. template_specs: dict,
  436. ) -> dict:
  437. """Filter specs to only include variables used in templates using VariableCollection.
  438. Uses VariableCollection's native filter_to_used() method.
  439. Keeps sensitive variables only if they're defined in the template spec or actually used.
  440. """
  441. # Build set of variables explicitly defined in template spec
  442. template_defined_vars = set()
  443. for section_data in (template_specs or {}).values():
  444. if isinstance(section_data, dict) and "vars" in section_data:
  445. template_defined_vars.update(section_data["vars"].keys())
  446. # Create VariableCollection from merged specs
  447. merged_collection = VariableCollection(merged_specs)
  448. # Filter to only used variables (and sensitive ones that are template-defined)
  449. # We keep sensitive variables that are either:
  450. # 1. Actually used in template files, OR
  451. # 2. Explicitly defined in the template spec (even if not yet used)
  452. variables_to_keep = used_variables | template_defined_vars
  453. filtered_collection = merged_collection.filter_to_used(variables_to_keep, keep_sensitive=False)
  454. # Convert back to dict format
  455. filtered_specs = {}
  456. for section_key, section in filtered_collection.get_sections().items():
  457. filtered_specs[section_key] = section.to_dict()
  458. return filtered_specs
  459. def _validate_schema_version(self, module_schema: str, module_name: str) -> None:
  460. """Validate that template schema version is supported by the module.
  461. Args:
  462. module_schema: Schema version supported by the module
  463. module_name: Name of the module (for error messages)
  464. Raises:
  465. IncompatibleSchemaVersionError: If template schema > module schema
  466. """
  467. template_schema = self.schema_version
  468. # Compare schema versions
  469. if not is_compatible(module_schema, template_schema):
  470. logger.error(
  471. f"Template '{self.id}' uses schema version {template_schema}, "
  472. f"but module '{module_name}' only supports up to {module_schema}"
  473. )
  474. raise IncompatibleSchemaVersionError(
  475. template_id=self.id,
  476. template_schema=template_schema,
  477. module_schema=module_schema,
  478. module_name=module_name,
  479. )
  480. logger.debug(
  481. f"Template '{self.id}' schema version compatible: "
  482. f"template uses {template_schema}, module supports {module_schema}"
  483. )
  484. @staticmethod
  485. def _validate_kind(template_data: dict) -> None:
  486. """Validate that template has required 'kind' field.
  487. Args:
  488. template_data: Parsed YAML data from template.yaml
  489. Raises:
  490. ValueError: If 'kind' field is missing
  491. """
  492. if not template_data.get("kind"):
  493. raise TemplateValidationError("Template format error: missing 'kind' field")
  494. def _validate_variable_definitions(self, used_variables: set[str], merged_specs: dict[str, Any]) -> None:
  495. """Validate that all variables used in Jinja2 content are defined in the spec."""
  496. defined_variables = set()
  497. for section_data in merged_specs.values():
  498. if "vars" in section_data and isinstance(section_data["vars"], dict):
  499. defined_variables.update(section_data["vars"].keys())
  500. undefined_variables = used_variables - defined_variables
  501. if undefined_variables:
  502. undefined_list = sorted(undefined_variables)
  503. error_msg = (
  504. f"Template validation error in '{self.id}': "
  505. f"Variables used in template content but not defined in spec: {undefined_list}\n\n"
  506. f"Please add these variables to your template's template.yaml spec. "
  507. f"Each variable must have a default value.\n\n"
  508. f"Example:\n"
  509. f"spec:\n"
  510. f" general:\n"
  511. f" vars:\n"
  512. )
  513. for var_name in undefined_list:
  514. error_msg += (
  515. f" {var_name}:\n"
  516. f" type: str\n"
  517. f" description: Description for {var_name}\n"
  518. f" default: <your_default_value_here>\n"
  519. )
  520. logger.error(error_msg)
  521. raise TemplateValidationError(error_msg)
  522. @staticmethod
  523. def _create_jinja_env(searchpath: Path) -> Environment:
  524. """Create sandboxed Jinja2 environment for secure template processing.
  525. Uses SandboxedEnvironment to prevent code injection vulnerabilities
  526. when processing untrusted templates. This restricts access to dangerous
  527. operations while still allowing safe template rendering.
  528. Returns:
  529. SandboxedEnvironment configured for template processing.
  530. """
  531. # NOTE Use SandboxedEnvironment for security - prevents arbitrary code execution
  532. return SandboxedEnvironment(
  533. loader=FileSystemLoader(searchpath),
  534. trim_blocks=True,
  535. lstrip_blocks=True,
  536. keep_trailing_newline=False,
  537. )
  538. def _generate_autogenerated_values(self, variables: VariableCollection, variable_values: dict) -> None:
  539. """Generate values for autogenerated variables that are empty."""
  540. for section in variables.get_sections().values():
  541. for var_name, variable in section.variables.items():
  542. if variable.autogenerated and (variable.value is None or variable.value == ""):
  543. alphabet = string.ascii_letters + string.digits
  544. generated_value = "".join(secrets.choice(alphabet) for _ in range(32))
  545. variable_values[var_name] = generated_value
  546. logger.debug(f"Auto-generated value for variable '{var_name}'")
  547. def _log_render_start(self, debug: bool, variable_values: dict) -> None:
  548. """Log rendering start information."""
  549. if debug:
  550. logger.info(f"Rendering template '{self.id}' in debug mode")
  551. logger.info(f"Available variables: {sorted(variable_values.keys())}")
  552. logger.info(f"Variable values: {variable_values}")
  553. else:
  554. logger.debug(f"Rendering template '{self.id}' with variables: {variable_values}")
  555. def _render_jinja2_file(self, template_file, variable_values: dict, _available_vars: set, debug: bool) -> str:
  556. """Render a single Jinja2 template file."""
  557. if debug:
  558. logger.info(f"Rendering Jinja2 template: {template_file.relative_path}")
  559. template = self.jinja_env.get_template(str(template_file.relative_path))
  560. rendered_content = template.render(**variable_values)
  561. rendered_content = self._sanitize_content(rendered_content, template_file.output_path)
  562. if debug:
  563. logger.info(f"Successfully rendered: {template_file.relative_path} -> {template_file.output_path}")
  564. return rendered_content
  565. def _handle_jinja2_error(
  566. self,
  567. e: Exception,
  568. template_file,
  569. available_vars: set,
  570. variable_values: dict,
  571. debug: bool,
  572. ) -> None:
  573. """Handle Jinja2 rendering errors."""
  574. error_msg, line_num, col, context_lines, suggestions = TemplateErrorHandler.parse_jinja_error(
  575. e, template_file, self.template_dir, available_vars
  576. )
  577. logger.error(f"Error rendering template file {template_file.relative_path}: {error_msg}")
  578. context = RenderErrorContext(
  579. file_path=str(template_file.relative_path),
  580. line_number=line_num,
  581. column=col,
  582. context_lines=context_lines,
  583. variable_context={k: str(v) for k, v in variable_values.items()} if debug else {},
  584. suggestions=suggestions,
  585. original_error=e,
  586. )
  587. raise TemplateRenderError(message=error_msg, context=context) from e
  588. def _render_static_file(self, template_file, debug: bool) -> str:
  589. """Read and return content of a static file."""
  590. file_path = self.template_dir / template_file.relative_path
  591. if debug:
  592. logger.info(f"Copying static file: {template_file.relative_path}")
  593. try:
  594. with file_path.open(encoding="utf-8") as f:
  595. return f.read()
  596. except OSError as e:
  597. logger.error(f"Error reading static file {file_path}: {e}")
  598. context = RenderErrorContext(
  599. file_path=str(template_file.relative_path),
  600. suggestions=["Check that the file exists and has read permissions"],
  601. original_error=e,
  602. )
  603. raise TemplateRenderError(
  604. message=f"Error reading static file: {e}",
  605. context=context,
  606. ) from e
  607. def render(self, variables: VariableCollection, debug: bool = False) -> tuple[dict[str, str], dict[str, Any]]:
  608. """Render all .j2 files in the template directory.
  609. Args:
  610. variables: VariableCollection with values to use for rendering
  611. debug: Enable debug mode with verbose output
  612. Returns:
  613. Tuple of (rendered_files, variable_values) where variable_values includes autogenerated values.
  614. Empty files (files with only whitespace) are excluded from the returned dict.
  615. """
  616. variable_values = variables.get_satisfied_values()
  617. self._generate_autogenerated_values(variables, variable_values)
  618. self._log_render_start(debug, variable_values)
  619. rendered_files = {}
  620. skipped_files = []
  621. available_vars = set(variable_values.keys())
  622. for template_file in self.template_files:
  623. if template_file.file_type == "j2":
  624. try:
  625. content = self._render_jinja2_file(template_file, variable_values, available_vars, debug)
  626. # Skip empty files (only whitespace or empty string)
  627. if content.strip():
  628. rendered_files[str(template_file.output_path)] = content
  629. else:
  630. skipped_files.append(str(template_file.output_path))
  631. if debug:
  632. logger.info(f"Skipping empty file: {template_file.output_path}")
  633. except (
  634. UndefinedError,
  635. Jinja2TemplateSyntaxError,
  636. Jinja2TemplateNotFound,
  637. Jinja2TemplateError,
  638. ) as e:
  639. self._handle_jinja2_error(e, template_file, available_vars, variable_values, debug)
  640. except Exception as e:
  641. logger.error(f"Unexpected error rendering template file {template_file.relative_path}: {e}")
  642. context = RenderErrorContext(
  643. file_path=str(template_file.relative_path),
  644. suggestions=["This is an unexpected error. Please check the template for issues."],
  645. original_error=e,
  646. )
  647. raise TemplateRenderError(
  648. message=f"Unexpected rendering error: {e}",
  649. context=context,
  650. ) from e
  651. elif template_file.file_type == "static":
  652. content = self._render_static_file(template_file, debug)
  653. # Static files are always included, even if empty
  654. rendered_files[str(template_file.output_path)] = content
  655. if skipped_files:
  656. logger.debug(f"Skipped {len(skipped_files)} empty file(s): {', '.join(skipped_files)}")
  657. return rendered_files, variable_values
  658. def _sanitize_content(self, content: str, _file_path: Path) -> str:
  659. """Sanitize rendered content by removing excessive blank lines and trailing whitespace."""
  660. if not content:
  661. return content
  662. lines = [line.rstrip() for line in content.split("\n")]
  663. sanitized = []
  664. prev_blank = False
  665. for line in lines:
  666. is_blank = not line
  667. if is_blank and prev_blank:
  668. continue # Skip consecutive blank lines
  669. sanitized.append(line)
  670. prev_blank = is_blank
  671. # Remove leading blanks and ensure single trailing newline
  672. return "\n".join(sanitized).lstrip("\n").rstrip("\n") + "\n"
  673. @property
  674. def template_files(self) -> list[TemplateFile]:
  675. if self.__template_files is None:
  676. self._collect_template_files() # Populate self.__template_files
  677. return self.__template_files
  678. @property
  679. def template_specs(self) -> dict:
  680. """Get the spec section from template YAML data."""
  681. return self._template_data.get("spec", {})
  682. @property
  683. def module_specs(self) -> dict:
  684. """Get the spec from the module definition for this template's schema version."""
  685. if self.__module_specs is None:
  686. kind = self._template_data.get("kind")
  687. self.__module_specs = self._load_module_specs_for_schema(kind, self.schema_version)
  688. return self.__module_specs
  689. @property
  690. def merged_specs(self) -> dict:
  691. if self.__merged_specs is None:
  692. self.__merged_specs = self._merge_specs(self.module_specs, self.template_specs)
  693. return self.__merged_specs
  694. @property
  695. def jinja_env(self) -> Environment:
  696. if self.__jinja_env is None:
  697. self.__jinja_env = self._create_jinja_env(self.template_dir)
  698. return self.__jinja_env
  699. @property
  700. def used_variables(self) -> set[str]:
  701. if self.__used_variables is None:
  702. self.__used_variables = self._extract_all_used_variables()
  703. return self.__used_variables
  704. @property
  705. def variables(self) -> VariableCollection:
  706. if self.__variables is None:
  707. # Validate that all used variables are defined
  708. self._validate_variable_definitions(self.used_variables, self.merged_specs)
  709. # Filter specs to only used variables
  710. filtered_specs = self._filter_specs_to_used(
  711. self.used_variables,
  712. self.merged_specs,
  713. self.module_specs,
  714. self.template_specs,
  715. )
  716. self.__variables = VariableCollection(filtered_specs)
  717. # Sort sections: required first, then enabled, then disabled
  718. self.__variables.sort_sections()
  719. return self.__variables