template.py 39 KB

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