template.py 31 KB

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