template.py 41 KB

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