template.py 35 KB

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