template.py 36 KB

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