template.py 35 KB

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