template.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. self._schema_deprecation_warned: bool = False # Track if deprecation warning shown
  273. try:
  274. # Find and parse the main template file (template.yaml or template.yml)
  275. main_template_path = self._find_main_template_file()
  276. with main_template_path.open(encoding="utf-8") as f:
  277. # Load all YAML documents (handles templates with empty lines before ---)
  278. documents = list(yaml.safe_load_all(f))
  279. # Filter out None/empty documents and get the first non-empty one
  280. valid_docs = [doc for doc in documents if doc is not None]
  281. if not valid_docs:
  282. raise ValueError("Template file contains no valid YAML data")
  283. if len(valid_docs) > 1:
  284. logger.warning("Template file contains multiple YAML documents, using the first one")
  285. self._template_data = valid_docs[0]
  286. # Validate template data
  287. if not isinstance(self._template_data, dict):
  288. raise ValueError("Template file must contain a valid YAML dictionary")
  289. # Load metadata (always needed)
  290. self.metadata = TemplateMetadata(self._template_data, library_name, library_type)
  291. logger.debug(f"Loaded metadata: {self.metadata}")
  292. # Validate 'kind' field (always needed)
  293. self._validate_kind(self._template_data)
  294. # Extract schema version (default to 1.0 for backward compatibility)
  295. self.schema_version = str(self._template_data.get("schema", "1.0"))
  296. logger.debug(f"Template schema version: {self.schema_version}")
  297. # Note: Schema version validation is done by the module when loading templates
  298. # NOTE: File collection is now lazy-loaded via the template_files property
  299. # This significantly improves performance when listing many templates
  300. logger.info(f"Loaded template '{self.id}' (v{self.metadata.version})")
  301. except (ValueError, FileNotFoundError) as e:
  302. logger.error(f"Error loading template from {template_dir}: {e}")
  303. raise TemplateLoadError(f"Error loading template from {template_dir}: {e}") from e
  304. except yaml.YAMLError as e:
  305. logger.error(f"YAML parsing error in template {template_dir}: {e}")
  306. raise YAMLParseError(str(template_dir / "template.y*ml"), e) from e
  307. except OSError as e:
  308. logger.error(f"File I/O error loading template {template_dir}: {e}")
  309. raise TemplateLoadError(f"File I/O error loading template from {template_dir}: {e}") from e
  310. def set_qualified_id(self, library_name: str | None = None) -> None:
  311. """Set a qualified ID for this template (used when duplicates exist across libraries).
  312. Args:
  313. library_name: Name of the library to qualify with. If None, uses self.library_name
  314. """
  315. lib_name = library_name or self.library_name
  316. self.id = f"{self.original_id}.{lib_name}"
  317. logger.debug(f"Template ID qualified: {self.original_id} -> {self.id}")
  318. def _find_main_template_file(self) -> Path:
  319. """Find the main template file (template.yaml or template.yml)."""
  320. for filename in ["template.yaml", "template.yml"]:
  321. path = self.template_dir / filename
  322. if path.exists():
  323. return path
  324. raise FileNotFoundError(f"Main template file (template.yaml or template.yml) not found in {self.template_dir}")
  325. @staticmethod
  326. @lru_cache(maxsize=32)
  327. def _load_module_specs_for_schema(kind: str, schema_version: str) -> dict:
  328. """Load specifications from the corresponding module for a specific schema version.
  329. DEPRECATION NOTICE (v0.1.3): Module schemas are being deprecated. Templates should define
  330. all variables in their template.yaml spec section. In future versions, this method will
  331. return an empty dict and templates will need to be self-contained.
  332. Uses LRU cache to avoid re-loading the same module spec multiple times.
  333. This significantly improves performance when listing many templates of the same kind.
  334. Args:
  335. kind: The module kind (e.g., 'compose', 'terraform')
  336. schema_version: The schema version to load (e.g., '1.0', '1.1')
  337. Returns:
  338. Dictionary containing the module's spec for the requested schema version,
  339. or empty dict if kind is empty
  340. Raises:
  341. ValueError: If module cannot be loaded or spec is invalid
  342. """
  343. if not kind:
  344. return {}
  345. # Log cache statistics for performance monitoring
  346. cache_info = Template._load_module_specs_for_schema.cache_info()
  347. logger.debug(
  348. f"Loading module spec: kind='{kind}', schema={schema_version} "
  349. f"(cache: hits={cache_info.hits}, misses={cache_info.misses}, size={cache_info.currsize})"
  350. )
  351. try:
  352. module = importlib.import_module(f"cli.modules.{kind}")
  353. # Check if module has schema-specific specs (multi-schema support)
  354. # Try SCHEMAS constant first (uppercase), then schemas attribute
  355. schemas = getattr(module, "SCHEMAS", None) or getattr(module, "schemas", None)
  356. if schemas and schema_version in schemas:
  357. spec = schemas[schema_version]
  358. logger.debug(f"Loaded and cached module spec for kind '{kind}' schema {schema_version}")
  359. else:
  360. # Fallback to default spec if schema mapping not available
  361. spec = getattr(module, "spec", {})
  362. logger.debug(f"Loaded and cached module spec for kind '{kind}' (default/no schema mapping)")
  363. return spec
  364. except Exception as e:
  365. raise ValueError(f"Error loading module specifications for kind '{kind}': {e}") from e
  366. def _merge_specs(self, module_specs: dict, template_specs: dict) -> dict:
  367. """Deep merge template specs with module specs using VariableCollection.
  368. Uses VariableCollection's native merge() method for consistent merging logic.
  369. Module specs are base, template specs override with origin tracking.
  370. """
  371. # Create VariableCollection from module specs (base)
  372. module_collection = VariableCollection(module_specs) if module_specs else VariableCollection({})
  373. # Set origin for module variables
  374. for section in module_collection.get_sections().values():
  375. for variable in section.variables.values():
  376. if not variable.origin:
  377. variable.origin = "module"
  378. # Merge template specs into module specs (template overrides)
  379. if template_specs:
  380. merged_collection = module_collection.merge(template_specs, origin="template")
  381. else:
  382. merged_collection = module_collection
  383. # Convert back to dict format
  384. merged_spec = {}
  385. for section_key, section in merged_collection.get_sections().items():
  386. merged_spec[section_key] = section.to_dict()
  387. return merged_spec
  388. def _warn_about_inherited_variables(self, module_specs: dict, template_specs: dict) -> None:
  389. """Warn about variables inherited from module schemas (deprecation warning).
  390. DEPRECATION (v0.1.3): Templates should define all variables explicitly in template.yaml.
  391. This method detects variables that are used in template files but come from module schemas,
  392. and warns users to add them to the template spec.
  393. Args:
  394. module_specs: Variables defined in module schema
  395. template_specs: Variables defined in template.yaml
  396. """
  397. # Skip if no module specs (already self-contained)
  398. if not module_specs:
  399. return
  400. # Collect variables from module specs
  401. module_vars = set()
  402. for section_data in module_specs.values():
  403. if isinstance(section_data, dict) and "vars" in section_data:
  404. module_vars.update(section_data["vars"].keys())
  405. # Collect variables explicitly defined in template
  406. template_vars = set()
  407. for section_data in (template_specs or {}).values():
  408. if isinstance(section_data, dict) and "vars" in section_data:
  409. template_vars.update(section_data["vars"].keys())
  410. # Get variables actually used in template files
  411. used_vars = self.used_variables
  412. # Find variables that are:
  413. # 1. Used in template files AND defined in module schema (inherited variables)
  414. # 2. NOT explicitly defined in template.yaml (missing definitions)
  415. # These are the problematic ones - the template relies on schema
  416. inherited_vars = used_vars & module_vars
  417. missing_definitions = inherited_vars - template_vars
  418. # Only warn once per template (use a flag to avoid repeated warnings)
  419. if missing_definitions and not self._schema_deprecation_warned:
  420. self._schema_deprecation_warned = True
  421. # Show first N variables in warning, full list in debug
  422. max_shown_vars = 10
  423. shown_vars = sorted(list(missing_definitions)[:max_shown_vars])
  424. ellipsis = "..." if len(missing_definitions) > max_shown_vars else ""
  425. logger.warning(
  426. f"DEPRECATION WARNING: Template '{self.id}' uses {len(missing_definitions)} "
  427. f"variable(s) from module schema without defining them in template.yaml. "
  428. f"In future versions, all used variables must be defined in template.yaml. "
  429. f"Missing definitions: {', '.join(shown_vars)}{ellipsis}"
  430. )
  431. logger.debug(
  432. f"Template '{self.id}' should add these variable definitions to template.yaml spec: "
  433. f"{sorted(missing_definitions)}"
  434. )
  435. def _collect_template_files(self) -> None:
  436. """Collects all TemplateFile objects in the template directory."""
  437. template_files: list[TemplateFile] = []
  438. for root, _, files in os.walk(self.template_dir):
  439. for filename in files:
  440. file_path = Path(root) / filename
  441. relative_path = file_path.relative_to(self.template_dir)
  442. # Skip the main template file
  443. if filename in ["template.yaml", "template.yml"]:
  444. continue
  445. if filename.endswith(".j2"):
  446. file_type: Literal["j2", "static"] = "j2"
  447. output_path = relative_path.with_suffix("") # Remove .j2 suffix
  448. else:
  449. file_type = "static"
  450. output_path = relative_path # Static files keep their name
  451. template_files.append(
  452. TemplateFile(
  453. relative_path=relative_path,
  454. file_type=file_type,
  455. output_path=output_path,
  456. )
  457. )
  458. self.__template_files = template_files
  459. def _extract_all_used_variables(self) -> set[str]:
  460. """Extract all undeclared variables from all .j2 files in the template directory.
  461. Raises:
  462. ValueError: If any Jinja2 template has syntax errors
  463. """
  464. used_variables: set[str] = set()
  465. syntax_errors = []
  466. # Track which file uses which variable (for debugging)
  467. self._variable_usage_map: dict[str, list[str]] = {}
  468. for template_file in self.template_files: # Iterate over TemplateFile objects
  469. if template_file.file_type == "j2":
  470. file_path = self.template_dir / template_file.relative_path
  471. try:
  472. with file_path.open(encoding="utf-8") as f:
  473. content = f.read()
  474. ast = self.jinja_env.parse(content) # Use lazy-loaded jinja_env
  475. file_vars = meta.find_undeclared_variables(ast)
  476. used_variables.update(file_vars)
  477. # Track which file uses each variable
  478. for var in file_vars:
  479. if var not in self._variable_usage_map:
  480. self._variable_usage_map[var] = []
  481. self._variable_usage_map[var].append(str(template_file.relative_path))
  482. except OSError as e:
  483. relative_path = file_path.relative_to(self.template_dir)
  484. syntax_errors.append(f" - {relative_path}: File I/O error: {e}")
  485. except Exception as e:
  486. # Collect syntax errors for Jinja2 issues
  487. relative_path = file_path.relative_to(self.template_dir)
  488. syntax_errors.append(f" - {relative_path}: {e}")
  489. # Raise error if any syntax errors were found
  490. if syntax_errors:
  491. logger.error(f"Jinja2 syntax errors found in template '{self.id}'")
  492. raise TemplateSyntaxError(self.id, syntax_errors)
  493. return used_variables
  494. def _filter_specs_to_used(
  495. self,
  496. used_variables: set,
  497. merged_specs: dict,
  498. _module_specs: dict,
  499. template_specs: dict,
  500. ) -> dict:
  501. """Filter specs to only include variables used in templates using VariableCollection.
  502. Uses VariableCollection's native filter_to_used() method.
  503. Keeps sensitive variables only if they're defined in the template spec or actually used.
  504. """
  505. # Build set of variables explicitly defined in template spec
  506. template_defined_vars = set()
  507. for section_data in (template_specs or {}).values():
  508. if isinstance(section_data, dict) and "vars" in section_data:
  509. template_defined_vars.update(section_data["vars"].keys())
  510. # Create VariableCollection from merged specs
  511. merged_collection = VariableCollection(merged_specs)
  512. # Filter to only used variables (and sensitive ones that are template-defined)
  513. # We keep sensitive variables that are either:
  514. # 1. Actually used in template files, OR
  515. # 2. Explicitly defined in the template spec (even if not yet used)
  516. variables_to_keep = used_variables | template_defined_vars
  517. filtered_collection = merged_collection.filter_to_used(variables_to_keep, keep_sensitive=False)
  518. # Convert back to dict format
  519. filtered_specs = {}
  520. for section_key, section in filtered_collection.get_sections().items():
  521. filtered_specs[section_key] = section.to_dict()
  522. return filtered_specs
  523. def _validate_schema_version(self, module_schema: str, module_name: str) -> None:
  524. """Validate that template schema version is supported by the module.
  525. Args:
  526. module_schema: Schema version supported by the module
  527. module_name: Name of the module (for error messages)
  528. Raises:
  529. IncompatibleSchemaVersionError: If template schema > module schema
  530. """
  531. template_schema = self.schema_version
  532. # Compare schema versions
  533. if not is_compatible(module_schema, template_schema):
  534. logger.error(
  535. f"Template '{self.id}' uses schema version {template_schema}, "
  536. f"but module '{module_name}' only supports up to {module_schema}"
  537. )
  538. raise IncompatibleSchemaVersionError(
  539. template_id=self.id,
  540. template_schema=template_schema,
  541. module_schema=module_schema,
  542. module_name=module_name,
  543. )
  544. logger.debug(
  545. f"Template '{self.id}' schema version compatible: "
  546. f"template uses {template_schema}, module supports {module_schema}"
  547. )
  548. @staticmethod
  549. def _validate_kind(template_data: dict) -> None:
  550. """Validate that template has required 'kind' field.
  551. Args:
  552. template_data: Parsed YAML data from template.yaml
  553. Raises:
  554. ValueError: If 'kind' field is missing
  555. """
  556. if not template_data.get("kind"):
  557. raise TemplateValidationError("Template format error: missing 'kind' field")
  558. def _validate_variable_definitions(self, used_variables: set[str], merged_specs: dict[str, Any]) -> None:
  559. """Validate that all variables used in Jinja2 content are defined in the spec."""
  560. defined_variables = set()
  561. for section_data in merged_specs.values():
  562. if "vars" in section_data and isinstance(section_data["vars"], dict):
  563. defined_variables.update(section_data["vars"].keys())
  564. undefined_variables = used_variables - defined_variables
  565. if undefined_variables:
  566. undefined_list = sorted(undefined_variables)
  567. # Build file location info for each undefined variable
  568. file_locations = []
  569. for var_name in undefined_list:
  570. if hasattr(self, "_variable_usage_map") and var_name in self._variable_usage_map:
  571. files = self._variable_usage_map[var_name]
  572. file_locations.append(f" • {var_name}: {', '.join(files)}")
  573. error_msg = (
  574. f"Template validation error in '{self.id}': "
  575. f"Variables used in template content but not defined in spec:\n"
  576. )
  577. if file_locations:
  578. error_msg += "\n".join(file_locations) + "\n"
  579. else:
  580. error_msg += f"{undefined_list}\n"
  581. error_msg += (
  582. "\nPlease add these variables to your template's template.yaml spec. "
  583. "Each variable must have a default value.\n\n"
  584. "Example:\n"
  585. "spec:\n"
  586. " general:\n"
  587. " vars:\n"
  588. )
  589. for var_name in undefined_list:
  590. error_msg += (
  591. f" {var_name}:\n"
  592. f" type: str\n"
  593. f" description: Description for {var_name}\n"
  594. f" default: <your_default_value_here>\n"
  595. )
  596. # Only log at DEBUG level - the exception will be displayed to user
  597. logger.debug(error_msg)
  598. raise TemplateValidationError(error_msg)
  599. @staticmethod
  600. def _create_jinja_env(searchpath: Path) -> Environment:
  601. """Create sandboxed Jinja2 environment for secure template processing.
  602. Uses SandboxedEnvironment to prevent code injection vulnerabilities
  603. when processing untrusted templates. This restricts access to dangerous
  604. operations while still allowing safe template rendering.
  605. Returns:
  606. SandboxedEnvironment configured for template processing.
  607. """
  608. # NOTE Use SandboxedEnvironment for security - prevents arbitrary code execution
  609. return SandboxedEnvironment(
  610. loader=FileSystemLoader(searchpath),
  611. trim_blocks=True,
  612. lstrip_blocks=True,
  613. keep_trailing_newline=False,
  614. )
  615. def _generate_autogenerated_values(self, variables: VariableCollection, variable_values: dict) -> None:
  616. """Generate values for autogenerated variables that are empty.
  617. Supports both plain and base64-encoded autogenerated values based on
  618. the autogenerated_base64 flag. Base64 encoding generates random bytes
  619. and encodes them, which is more suitable for cryptographic keys.
  620. """
  621. for section in variables.get_sections().values():
  622. for var_name, variable in section.variables.items():
  623. if variable.autogenerated and (variable.value is None or variable.value == ""):
  624. length = getattr(variable, "autogenerated_length", 32)
  625. use_base64 = getattr(variable, "autogenerated_base64", False)
  626. if use_base64:
  627. # Generate random bytes and base64 encode
  628. # Note: length refers to number of random bytes, not base64 string length
  629. random_bytes = secrets.token_bytes(length)
  630. generated_value = base64.b64encode(random_bytes).decode("utf-8")
  631. logger.debug(
  632. f"Auto-generated base64 value for variable '{var_name}' "
  633. f"(bytes: {length}, encoded length: {len(generated_value)})"
  634. )
  635. else:
  636. # Generate alphanumeric string
  637. alphabet = string.ascii_letters + string.digits
  638. generated_value = "".join(secrets.choice(alphabet) for _ in range(length))
  639. logger.debug(f"Auto-generated value for variable '{var_name}' (length: {length})")
  640. variable_values[var_name] = generated_value
  641. def _log_render_start(self, debug: bool, variable_values: dict) -> None:
  642. """Log rendering start information."""
  643. if debug:
  644. logger.info(f"Rendering template '{self.id}' in debug mode")
  645. logger.info(f"Available variables: {sorted(variable_values.keys())}")
  646. logger.info(f"Variable values: {variable_values}")
  647. else:
  648. logger.debug(f"Rendering template '{self.id}' with variables: {variable_values}")
  649. def _render_jinja2_file(self, template_file, variable_values: dict, _available_vars: set, debug: bool) -> str:
  650. """Render a single Jinja2 template file."""
  651. if debug:
  652. logger.info(f"Rendering Jinja2 template: {template_file.relative_path}")
  653. template = self.jinja_env.get_template(str(template_file.relative_path))
  654. rendered_content = template.render(**variable_values)
  655. rendered_content = self._sanitize_content(rendered_content, template_file.output_path)
  656. if debug:
  657. logger.info(f"Successfully rendered: {template_file.relative_path} -> {template_file.output_path}")
  658. return rendered_content
  659. def _handle_jinja2_error(
  660. self,
  661. e: Exception,
  662. template_file,
  663. available_vars: set,
  664. variable_values: dict,
  665. debug: bool,
  666. ) -> None:
  667. """Handle Jinja2 rendering errors."""
  668. error_msg, line_num, col, context_lines, suggestions = TemplateErrorHandler.parse_jinja_error(
  669. e, template_file, self.template_dir, available_vars
  670. )
  671. logger.error(f"Error rendering template file {template_file.relative_path}: {error_msg}")
  672. context = RenderErrorContext(
  673. file_path=str(template_file.relative_path),
  674. line_number=line_num,
  675. column=col,
  676. context_lines=context_lines,
  677. variable_context={k: str(v) for k, v in variable_values.items()} if debug else {},
  678. suggestions=suggestions,
  679. original_error=e,
  680. )
  681. raise TemplateRenderError(message=error_msg, context=context) from e
  682. def _render_static_file(self, template_file, debug: bool) -> str:
  683. """Read and return content of a static file."""
  684. file_path = self.template_dir / template_file.relative_path
  685. if debug:
  686. logger.info(f"Copying static file: {template_file.relative_path}")
  687. try:
  688. with file_path.open(encoding="utf-8") as f:
  689. return f.read()
  690. except OSError as e:
  691. logger.error(f"Error reading static file {file_path}: {e}")
  692. context = RenderErrorContext(
  693. file_path=str(template_file.relative_path),
  694. suggestions=["Check that the file exists and has read permissions"],
  695. original_error=e,
  696. )
  697. raise TemplateRenderError(
  698. message=f"Error reading static file: {e}",
  699. context=context,
  700. ) from e
  701. def render(self, variables: VariableCollection, debug: bool = False) -> tuple[dict[str, str], dict[str, Any]]:
  702. """Render all .j2 files in the template directory.
  703. Args:
  704. variables: VariableCollection with values to use for rendering
  705. debug: Enable debug mode with verbose output
  706. Returns:
  707. Tuple of (rendered_files, variable_values) where variable_values includes autogenerated values.
  708. Empty files (files with only whitespace) are excluded from the returned dict.
  709. """
  710. variable_values = variables.get_satisfied_values()
  711. self._generate_autogenerated_values(variables, variable_values)
  712. self._log_render_start(debug, variable_values)
  713. rendered_files = {}
  714. skipped_files = []
  715. available_vars = set(variable_values.keys())
  716. for template_file in self.template_files:
  717. if template_file.file_type == "j2":
  718. try:
  719. content = self._render_jinja2_file(template_file, variable_values, available_vars, debug)
  720. # Skip empty files (only whitespace, empty string, or just YAML document separator)
  721. stripped = content.strip()
  722. if stripped and stripped != "---":
  723. rendered_files[str(template_file.output_path)] = content
  724. else:
  725. skipped_files.append(str(template_file.output_path))
  726. if debug:
  727. logger.info(f"Skipping empty file: {template_file.output_path}")
  728. except (
  729. UndefinedError,
  730. Jinja2TemplateSyntaxError,
  731. Jinja2TemplateNotFound,
  732. Jinja2TemplateError,
  733. ) as e:
  734. self._handle_jinja2_error(e, template_file, available_vars, variable_values, debug)
  735. except Exception as e:
  736. logger.error(f"Unexpected error rendering template file {template_file.relative_path}: {e}")
  737. context = RenderErrorContext(
  738. file_path=str(template_file.relative_path),
  739. suggestions=["This is an unexpected error. Please check the template for issues."],
  740. original_error=e,
  741. )
  742. raise TemplateRenderError(
  743. message=f"Unexpected rendering error: {e}",
  744. context=context,
  745. ) from e
  746. elif template_file.file_type == "static":
  747. content = self._render_static_file(template_file, debug)
  748. # Static files are always included, even if empty
  749. rendered_files[str(template_file.output_path)] = content
  750. if skipped_files:
  751. logger.debug(f"Skipped {len(skipped_files)} empty file(s): {', '.join(skipped_files)}")
  752. return rendered_files, variable_values
  753. def _sanitize_content(self, content: str, _file_path: Path) -> str:
  754. """Sanitize rendered content by removing excessive blank lines and trailing whitespace."""
  755. if not content:
  756. return content
  757. lines = [line.rstrip() for line in content.split("\n")]
  758. sanitized = []
  759. prev_blank = False
  760. for line in lines:
  761. is_blank = not line
  762. if is_blank and prev_blank:
  763. continue # Skip consecutive blank lines
  764. sanitized.append(line)
  765. prev_blank = is_blank
  766. # Remove leading blanks and ensure single trailing newline
  767. return "\n".join(sanitized).lstrip("\n").rstrip("\n") + "\n"
  768. @property
  769. def template_files(self) -> list[TemplateFile]:
  770. if self.__template_files is None:
  771. self._collect_template_files() # Populate self.__template_files
  772. return self.__template_files
  773. @property
  774. def template_specs(self) -> dict:
  775. """Get the spec section from template YAML data."""
  776. return self._template_data.get("spec", {})
  777. @property
  778. def module_specs(self) -> dict:
  779. """Get the spec from the module definition for this template's schema version."""
  780. if self.__module_specs is None:
  781. kind = self._template_data.get("kind")
  782. self.__module_specs = self._load_module_specs_for_schema(kind, self.schema_version)
  783. return self.__module_specs
  784. @property
  785. def merged_specs(self) -> dict:
  786. if self.__merged_specs is None:
  787. # Warn about inherited variables (deprecation)
  788. self._warn_about_inherited_variables(self.module_specs, self.template_specs)
  789. self.__merged_specs = self._merge_specs(self.module_specs, self.template_specs)
  790. return self.__merged_specs
  791. @property
  792. def jinja_env(self) -> Environment:
  793. if self.__jinja_env is None:
  794. self.__jinja_env = self._create_jinja_env(self.template_dir)
  795. return self.__jinja_env
  796. @property
  797. def used_variables(self) -> set[str]:
  798. if self.__used_variables is None:
  799. self.__used_variables = self._extract_all_used_variables()
  800. return self.__used_variables
  801. @property
  802. def variables(self) -> VariableCollection:
  803. if self.__variables is None:
  804. # Validate that all used variables are defined
  805. self._validate_variable_definitions(self.used_variables, self.merged_specs)
  806. # Filter specs to only used variables
  807. filtered_specs = self._filter_specs_to_used(
  808. self.used_variables,
  809. self.merged_specs,
  810. self.module_specs,
  811. self.template_specs,
  812. )
  813. self.__variables = VariableCollection(filtered_specs)
  814. # Sort sections: required first, then enabled, then disabled
  815. self.__variables.sort_sections()
  816. return self.__variables
  817. @property
  818. def status(self) -> str:
  819. """Get the status of the template.
  820. Returns:
  821. Status string: 'published' or 'draft'
  822. Note:
  823. The 'invalid' status is reserved for future use when template validation
  824. is implemented without impacting list command performance.
  825. """
  826. # Check if template is marked as draft in metadata
  827. if self.metadata.draft:
  828. return TEMPLATE_STATUS_DRAFT
  829. # Template is published (valid and not draft)
  830. return TEMPLATE_STATUS_PUBLISHED