template.py 35 KB

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