base_commands.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. """Base commands for module: list, search, show, validate, generate."""
  2. from __future__ import annotations
  3. import logging
  4. from dataclasses import dataclass, replace
  5. from pathlib import Path
  6. from typer import Exit
  7. from ..config import ConfigManager
  8. from ..display import DisplayManager, IconManager
  9. from ..exceptions import (
  10. TemplateRenderError,
  11. TemplateSyntaxError,
  12. TemplateValidationError,
  13. )
  14. from ..input import InputManager
  15. from ..template import Template
  16. from ..validation import DependencyMatrixBuilder, MatrixOptions, ValidationRunner
  17. from .generation_destination import (
  18. GenerationDestination,
  19. format_remote_destination,
  20. prompt_generation_destination,
  21. resolve_cli_destination,
  22. write_rendered_files_remote,
  23. )
  24. from .helpers import (
  25. apply_cli_overrides,
  26. apply_var_file,
  27. apply_variable_defaults,
  28. collect_variable_values,
  29. )
  30. logger = logging.getLogger(__name__)
  31. # File size thresholds for display formatting
  32. BYTES_PER_KB = 1024
  33. BYTES_PER_MB = 1024 * 1024
  34. @dataclass
  35. class GenerationConfig:
  36. """Configuration for template generation."""
  37. id: str
  38. output: str | None = None
  39. remote: str | None = None
  40. remote_path: str | None = None
  41. interactive: bool = True
  42. var: list[str] | None = None
  43. var_file: str | None = None
  44. dry_run: bool = False
  45. show_files: bool = False
  46. quiet: bool = False
  47. name: str | None = None
  48. @dataclass
  49. class ValidationConfig:
  50. """Configuration for template validation."""
  51. verbose: bool
  52. semantic: bool = False
  53. kind: bool = False
  54. all_templates: bool = False
  55. matrix_max_combinations: int = 100
  56. kind_validator: object | None = None
  57. quiet_success: bool = False
  58. def list_templates(module_instance, raw: bool = False) -> list:
  59. """List all templates."""
  60. logger.debug(f"Listing templates for module '{module_instance.name}'")
  61. # Load all templates using centralized helper
  62. filtered_templates = module_instance._load_all_templates()
  63. if filtered_templates:
  64. if raw:
  65. # Output raw format (tab-separated values for easy filtering with awk/sed/cut)
  66. # Format: ID\tNAME\tTAGS\tVERSION\tLIBRARY
  67. for template in filtered_templates:
  68. name = template.metadata.name or "Unnamed Template"
  69. tags_list = template.metadata.tags or []
  70. tags = ",".join(tags_list) if tags_list else "-"
  71. version = template.metadata.version.name if template.metadata.version else "-"
  72. library = template.metadata.library or "-"
  73. module_instance.display.text("\t".join([template.id, name, tags, version, library]))
  74. else:
  75. # Output rich table format
  76. def format_template_row(template):
  77. name = template.metadata.name or "Unnamed Template"
  78. tags_list = template.metadata.tags or []
  79. tags = ", ".join(tags_list) if tags_list else "-"
  80. version = template.metadata.version.name if template.metadata.version else ""
  81. library_name = template.metadata.library or ""
  82. library_type = template.metadata.library_type or "git"
  83. # Format library with icon and color
  84. icon = IconManager.UI_LIBRARY_STATIC if library_type == "static" else IconManager.UI_LIBRARY_GIT
  85. color = "yellow" if library_type == "static" else "blue"
  86. library_display = f"[{color}]{icon} {library_name}[/{color}]"
  87. return (template.id, name, tags, version, library_display)
  88. module_instance.display.data_table(
  89. columns=[
  90. {"name": "ID", "style": "bold", "no_wrap": True},
  91. {"name": "Name"},
  92. {"name": "Tags"},
  93. {"name": "Version", "no_wrap": True},
  94. {"name": "Library", "no_wrap": True},
  95. ],
  96. rows=filtered_templates,
  97. row_formatter=format_template_row,
  98. )
  99. else:
  100. logger.info(f"No templates found for module '{module_instance.name}'")
  101. module_instance.display.info(
  102. f"No templates found for module '{module_instance.name}'",
  103. context="Use 'bp repo update' to update libraries or check library configuration",
  104. )
  105. return filtered_templates
  106. def search_templates(module_instance, query: str) -> list:
  107. """Search for templates by ID containing the search string."""
  108. logger.debug(f"Searching templates for module '{module_instance.name}' with query='{query}'")
  109. # Load templates with search filter using centralized helper
  110. filtered_templates = module_instance._load_all_templates(lambda t: query.lower() in t.id.lower())
  111. if filtered_templates:
  112. logger.info(f"Found {len(filtered_templates)} templates matching '{query}' for module '{module_instance.name}'")
  113. def format_template_row(template):
  114. name = template.metadata.name or "Unnamed Template"
  115. tags_list = template.metadata.tags or []
  116. tags = ", ".join(tags_list) if tags_list else "-"
  117. version = template.metadata.version.name if template.metadata.version else ""
  118. library_name = template.metadata.library or ""
  119. library_type = template.metadata.library_type or "git"
  120. # Format library with icon and color
  121. icon = IconManager.UI_LIBRARY_STATIC if library_type == "static" else IconManager.UI_LIBRARY_GIT
  122. color = "yellow" if library_type == "static" else "blue"
  123. library_display = f"[{color}]{icon} {library_name}[/{color}]"
  124. return (template.id, name, tags, version, library_display)
  125. module_instance.display.data_table(
  126. columns=[
  127. {"name": "ID", "style": "bold", "no_wrap": True},
  128. {"name": "Name"},
  129. {"name": "Tags"},
  130. {"name": "Version", "no_wrap": True},
  131. {"name": "Library", "no_wrap": True},
  132. ],
  133. rows=filtered_templates,
  134. row_formatter=format_template_row,
  135. )
  136. else:
  137. logger.info(f"No templates found matching '{query}' for module '{module_instance.name}'")
  138. module_instance.display.warning(
  139. f"No templates found matching '{query}'",
  140. context=f"module '{module_instance.name}'",
  141. )
  142. return filtered_templates
  143. def show_template(module_instance, id: str, var: list[str] | None = None, var_file: str | None = None) -> None:
  144. """Show template details with optional variable overrides."""
  145. logger.debug(f"Showing template '{id}' from module '{module_instance.name}'")
  146. template = module_instance._load_template_by_id(id)
  147. if not template:
  148. module_instance.display.error(f"Template '{id}' not found", context=f"module '{module_instance.name}'")
  149. return
  150. # Apply defaults and overrides (same precedence as generate command)
  151. if template.variables:
  152. config = ConfigManager()
  153. apply_variable_defaults(template, config, module_instance.name)
  154. apply_var_file(template, var_file, module_instance.display)
  155. apply_cli_overrides(template, var)
  156. # Re-sort sections after applying overrides (toggle values may have changed)
  157. template.variables.sort_sections()
  158. # Reset disabled bool variables to False to prevent confusion
  159. reset_vars = template.variables.reset_disabled_bool_variables()
  160. if reset_vars:
  161. logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
  162. # Display template header
  163. module_instance.display.templates.render_template_header(template, id)
  164. # Display file tree
  165. module_instance.display.templates.render_file_tree(template)
  166. # Display variables table
  167. module_instance.display.variables.render_variables_table(template)
  168. def check_output_directory(
  169. output_dir: Path,
  170. rendered_files: dict[str, str],
  171. interactive: bool,
  172. display: DisplayManager,
  173. ) -> list[Path] | None:
  174. """Check output directory for conflicts and get user confirmation if needed."""
  175. dir_exists = output_dir.exists()
  176. dir_not_empty = dir_exists and any(output_dir.iterdir())
  177. # Check which files already exist
  178. existing_files = []
  179. if dir_exists:
  180. for file_path in rendered_files:
  181. full_path = output_dir / file_path
  182. if full_path.exists():
  183. existing_files.append(full_path)
  184. # Warn if directory is not empty
  185. if dir_not_empty:
  186. if interactive:
  187. display.text("") # Add newline before warning
  188. # Combine directory warning and file count on same line
  189. warning_msg = f"Directory '{output_dir}' is not empty."
  190. if existing_files:
  191. warning_msg += f" {len(existing_files)} file(s) will be overwritten."
  192. display.warning(warning_msg)
  193. display.text("") # Add newline after warning
  194. input_mgr = InputManager()
  195. if not input_mgr.confirm("Continue?", default=False):
  196. display.info("Generation cancelled")
  197. return None
  198. else:
  199. # Non-interactive mode: show warning but continue
  200. logger.warning(f"Directory '{output_dir}' is not empty")
  201. if existing_files:
  202. logger.warning(f"{len(existing_files)} file(s) will be overwritten")
  203. return existing_files
  204. def _analyze_file_operations(
  205. output_dir: Path, rendered_files: dict[str, str]
  206. ) -> tuple[list[tuple[str, int, str]], int, int, int]:
  207. """Analyze file operations and return statistics."""
  208. total_size = 0
  209. new_files = 0
  210. overwrite_files = 0
  211. file_operations = []
  212. for file_path, content in sorted(rendered_files.items()):
  213. full_path = output_dir / file_path
  214. file_size = len(content.encode("utf-8"))
  215. total_size += file_size
  216. if full_path.exists():
  217. status = "Overwrite"
  218. overwrite_files += 1
  219. else:
  220. status = "Create"
  221. new_files += 1
  222. file_operations.append((file_path, file_size, status))
  223. return file_operations, total_size, new_files, overwrite_files
  224. def _format_size(total_size: int) -> str:
  225. """Format byte size into human-readable string."""
  226. if total_size < BYTES_PER_KB:
  227. return f"{total_size}B"
  228. if total_size < BYTES_PER_MB:
  229. return f"{total_size / BYTES_PER_KB:.1f}KB"
  230. return f"{total_size / BYTES_PER_MB:.1f}MB"
  231. def _get_rendered_file_stats(rendered_files: dict[str, str]) -> tuple[int, int, str]:
  232. """Return file count, total size, and formatted size for rendered output."""
  233. total_size = sum(len(content.encode("utf-8")) for content in rendered_files.values())
  234. return len(rendered_files), total_size, _format_size(total_size)
  235. def _display_rendered_file_contents(rendered_files: dict[str, str], display: DisplayManager) -> None:
  236. """Display rendered file contents for dry-run mode."""
  237. display.text("")
  238. display.heading("File Contents")
  239. for file_path, content in sorted(rendered_files.items()):
  240. display.text(f"\n[cyan]{file_path}[/cyan]")
  241. display.text(f"{'─' * 80}")
  242. display.text(content)
  243. display.text("")
  244. def execute_dry_run(
  245. id: str,
  246. output_dir: Path,
  247. rendered_files: dict[str, str],
  248. show_files: bool,
  249. display: DisplayManager,
  250. ) -> tuple[int, int, str]:
  251. """Execute dry run mode - preview files without writing.
  252. Returns:
  253. Tuple of (total_files, overwrite_files, size_str) for summary display
  254. """
  255. _file_operations, total_size, _new_files, overwrite_files = _analyze_file_operations(output_dir, rendered_files)
  256. size_str = _format_size(total_size)
  257. if show_files:
  258. _display_rendered_file_contents(rendered_files, display)
  259. logger.info(f"Dry run completed for template '{id}' - {len(rendered_files)} files, {total_size} bytes")
  260. return len(rendered_files), overwrite_files, size_str
  261. def execute_remote_dry_run(
  262. remote_host: str,
  263. remote_path: str,
  264. rendered_files: dict[str, str],
  265. show_files: bool,
  266. display: DisplayManager,
  267. ) -> tuple[int, str]:
  268. """Preview a remote upload without writing files."""
  269. total_files, _total_size, size_str = _get_rendered_file_stats(rendered_files)
  270. if show_files:
  271. _display_rendered_file_contents(rendered_files, display)
  272. logger.info(
  273. "Dry run completed for remote destination '%s' - %s files",
  274. format_remote_destination(remote_host, remote_path),
  275. total_files,
  276. )
  277. return total_files, size_str
  278. def _validate_output_name(name: str) -> str:
  279. """Validate and normalize a generated output name."""
  280. normalized_name = name.strip()
  281. if not normalized_name:
  282. raise ValueError("--name cannot be empty")
  283. if "/" in normalized_name or "\\" in normalized_name:
  284. raise ValueError("--name must be a file name, not a path")
  285. if normalized_name in {".", ".."}:
  286. raise ValueError("--name cannot be '.' or '..'")
  287. return normalized_name
  288. def _prefix_path_part(name: str, part: str) -> str:
  289. """Prefix one top-level path part with the generated output name."""
  290. path = Path(part)
  291. if path.stem == "main" and path.suffix:
  292. return f"{name}{path.suffix}"
  293. return f"{name}_{part}"
  294. def apply_output_name(rendered_files: dict[str, str], name: str | None) -> dict[str, str]:
  295. """Rename top-level generated paths with a user-provided output name.
  296. The top-level entrypoint file named ``main.<ext>`` becomes ``<name>.<ext>``.
  297. All other top-level files or directories receive ``<name>_`` as a prefix.
  298. Nested path segments are preserved unchanged.
  299. """
  300. if name is None:
  301. return rendered_files
  302. normalized_name = _validate_output_name(name)
  303. renamed_files: dict[str, str] = {}
  304. for file_path, content in rendered_files.items():
  305. path = Path(file_path)
  306. parts = path.parts
  307. if not parts:
  308. continue
  309. renamed_top_level = _prefix_path_part(normalized_name, parts[0])
  310. renamed_path = Path(renamed_top_level, *parts[1:]).as_posix()
  311. if renamed_path in renamed_files:
  312. raise ValueError(f"--name creates duplicate generated path: {renamed_path}")
  313. renamed_files[renamed_path] = content
  314. return renamed_files
  315. def write_rendered_files(output_dir: Path, rendered_files: dict[str, str]) -> None:
  316. """Write rendered files to the output directory."""
  317. output_dir.mkdir(parents=True, exist_ok=True)
  318. for file_path, content in rendered_files.items():
  319. full_path = output_dir / file_path
  320. full_path.parent.mkdir(parents=True, exist_ok=True)
  321. with full_path.open("w", encoding="utf-8") as f:
  322. f.write(content)
  323. logger.info(f"Template written to directory: {output_dir}")
  324. def _prepare_template(
  325. module_instance,
  326. id: str,
  327. var_file: str | None,
  328. var: list[str] | None,
  329. display: DisplayManager,
  330. ):
  331. """Load template and apply all defaults/overrides."""
  332. template = module_instance._load_template_by_id(id)
  333. config = ConfigManager()
  334. apply_variable_defaults(template, config, module_instance.name)
  335. apply_var_file(template, var_file, display)
  336. apply_cli_overrides(template, var)
  337. if template.variables:
  338. template.variables.sort_sections()
  339. reset_vars = template.variables.reset_disabled_bool_variables()
  340. if reset_vars:
  341. logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
  342. return template
  343. def _render_template(template, id: str, display: DisplayManager, interactive: bool):
  344. """Validate, render template and collect variable values."""
  345. variable_values = collect_variable_values(template, interactive)
  346. if template.variables:
  347. template.variables.validate_all()
  348. debug_mode = logger.isEnabledFor(logging.DEBUG)
  349. rendered_files, variable_values = template.render(template.variables, debug=debug_mode)
  350. if not rendered_files:
  351. display.error(
  352. "Template rendering returned no files",
  353. context="template generation",
  354. )
  355. raise Exit(code=1)
  356. logger.info(f"Successfully rendered template '{id}'")
  357. return rendered_files, variable_values
  358. def _display_template_error(display: DisplayManager, template_id: str, error: TemplateRenderError) -> None:
  359. """Display template rendering error with clean formatting."""
  360. display.text("")
  361. display.text("─" * 80, style="dim")
  362. display.text("")
  363. # Build details if available
  364. details = None
  365. if error.file_path:
  366. details = error.file_path
  367. if error.line_number:
  368. details += f":line {error.line_number}"
  369. # Display error with details
  370. display.error(f"Failed to generate boilerplate from template '{template_id}'", details=details)
  371. def _display_generic_error(display: DisplayManager, template_id: str, error: Exception) -> None:
  372. """Display generic error with clean formatting."""
  373. display.text("")
  374. display.text("─" * 80, style="dim")
  375. display.text("")
  376. # Truncate long error messages
  377. max_error_length = 100
  378. error_msg = str(error)
  379. if len(error_msg) > max_error_length:
  380. error_msg = f"{error_msg[:max_error_length]}..."
  381. # Display error with details
  382. display.error(f"Failed to generate boilerplate from template '{template_id}'", details=error_msg)
  383. def generate_template(module_instance, config: GenerationConfig) -> None: # noqa: PLR0912, PLR0915
  384. """Generate from template."""
  385. logger.info(f"Starting generation for template '{config.id}' from module '{module_instance.name}'")
  386. display = DisplayManager(quiet=config.quiet) if config.quiet else module_instance.display
  387. template = _prepare_template(module_instance, config.id, config.var_file, config.var, display)
  388. slug = getattr(template, "slug", template.id)
  389. used_implicit_dry_run_destination = False
  390. try:
  391. destination = resolve_cli_destination(config.output, config.remote, config.remote_path, slug)
  392. except ValueError as e:
  393. display.error(str(e), context="template generation")
  394. raise Exit(code=1) from None
  395. if not config.quiet:
  396. # Display template header
  397. module_instance.display.templates.render_template_header(template, config.id)
  398. # Display file tree
  399. module_instance.display.templates.render_file_tree(template)
  400. # Display variables table
  401. module_instance.display.variables.render_variables_table(template)
  402. module_instance.display.text("")
  403. try:
  404. rendered_files, _variable_values = _render_template(template, config.id, display, config.interactive)
  405. rendered_files = apply_output_name(rendered_files, config.name)
  406. if destination is None:
  407. if config.dry_run:
  408. destination = GenerationDestination(mode="local", local_output_dir=Path.cwd() / slug)
  409. used_implicit_dry_run_destination = True
  410. elif config.interactive:
  411. destination = prompt_generation_destination(slug)
  412. else:
  413. destination = GenerationDestination(mode="local", local_output_dir=Path.cwd() / slug)
  414. if not destination.is_remote:
  415. output_dir = destination.local_output_dir or (Path.cwd() / slug)
  416. if (
  417. not config.dry_run
  418. and not config.quiet
  419. and check_output_directory(output_dir, rendered_files, config.interactive, display) is None
  420. ):
  421. return
  422. # Execute generation (dry run or actual)
  423. dry_run_stats = None
  424. if destination.is_remote:
  425. remote_host = destination.remote_host or ""
  426. remote_path = destination.remote_path or f"~/{slug}"
  427. if config.dry_run:
  428. if not config.quiet:
  429. dry_run_stats = execute_remote_dry_run(
  430. remote_host,
  431. remote_path,
  432. rendered_files,
  433. config.show_files,
  434. display,
  435. )
  436. else:
  437. write_rendered_files_remote(remote_host, remote_path, rendered_files)
  438. else:
  439. output_dir = destination.local_output_dir or (Path.cwd() / slug)
  440. if config.dry_run:
  441. if not config.quiet:
  442. dry_run_stats = execute_dry_run(config.id, output_dir, rendered_files, config.show_files, display)
  443. else:
  444. write_rendered_files(output_dir, rendered_files)
  445. # Display final status message at the end
  446. if not config.quiet:
  447. display.text("")
  448. display.text("─" * 80, style="dim")
  449. if destination.is_remote:
  450. remote_host = destination.remote_host or ""
  451. remote_path = destination.remote_path or f"~/{slug}"
  452. remote_target = format_remote_destination(remote_host, remote_path)
  453. if config.dry_run and dry_run_stats:
  454. total_files, size_str = dry_run_stats
  455. display.success(
  456. f"Dry run complete: {total_files} files ({size_str}) would be uploaded to '{remote_target}'"
  457. )
  458. else:
  459. display.success(f"Boilerplate uploaded successfully to '{remote_target}'")
  460. elif config.dry_run and dry_run_stats:
  461. total_files, overwrite_files, size_str = dry_run_stats
  462. if used_implicit_dry_run_destination:
  463. display.success(
  464. "Dry run complete: boilerplate rendered successfully "
  465. f"({total_files} files, {size_str}, preview only)"
  466. )
  467. elif overwrite_files > 0:
  468. display.warning(
  469. f"Dry run complete: {total_files} files ({size_str}) would be written to '{output_dir}' "
  470. f"({overwrite_files} would be overwritten)"
  471. )
  472. else:
  473. display.success(
  474. f"Dry run complete: {total_files} files ({size_str}) would be written to '{output_dir}'"
  475. )
  476. else:
  477. display.success(f"Boilerplate generated successfully in '{output_dir}'")
  478. except TemplateRenderError as e:
  479. _display_template_error(display, config.id, e)
  480. raise Exit(code=1) from None
  481. except Exception as e:
  482. _display_generic_error(display, config.id, e)
  483. raise Exit(code=1) from None
  484. def validate_templates(
  485. module_instance,
  486. template_id: str,
  487. path: str | None,
  488. config: ValidationConfig,
  489. ) -> None:
  490. """Validate templates for Jinja2 syntax, undefined variables, and semantic correctness."""
  491. # Load template based on input
  492. if config.all_templates and (template_id or path):
  493. module_instance.display.error("--all cannot be combined with a template ID or --path")
  494. raise Exit(code=1) from None
  495. if not config.all_templates and not template_id and not path:
  496. module_instance.display.error("Provide a template ID, --path, or --all")
  497. raise Exit(code=1) from None
  498. template = _load_template_for_validation(module_instance, template_id, path)
  499. if template:
  500. _validate_single_template(module_instance, template, template_id or template.id, config)
  501. else:
  502. _validate_all_templates(module_instance, config)
  503. def _load_template_for_validation(module_instance, template_id: str, path: str | None):
  504. """Load a template from path or ID for validation."""
  505. if path:
  506. template_path = Path(path).resolve()
  507. if not template_path.exists():
  508. module_instance.display.error(f"Path does not exist: {path}")
  509. raise Exit(code=1) from None
  510. if not template_path.is_dir():
  511. module_instance.display.error(f"Path is not a directory: {path}")
  512. raise Exit(code=1) from None
  513. module_instance.display.info(f"[bold]Validating template from path:[/bold] [cyan]{template_path}[/cyan]")
  514. try:
  515. return Template(template_path, library_name="local")
  516. except Exception as e:
  517. module_instance.display.error(f"Failed to load template from path '{path}': {e}")
  518. raise Exit(code=1) from None
  519. if template_id:
  520. try:
  521. template = module_instance._load_template_by_id(template_id)
  522. module_instance.display.info(f"Validating template: {template_id}")
  523. return template
  524. except Exception as e:
  525. module_instance.display.error(f"Failed to load template '{template_id}': {e}")
  526. raise Exit(code=1) from None
  527. return None
  528. def _validate_single_template(
  529. module_instance,
  530. template,
  531. template_id: str,
  532. config: ValidationConfig,
  533. ) -> None:
  534. """Validate a single template."""
  535. try:
  536. # Jinja2 validation
  537. _ = template.used_variables
  538. _ = template.variables
  539. if not config.quiet_success:
  540. module_instance.display.success("Jinja2 validation passed")
  541. if config.semantic or config.kind:
  542. _run_matrix_validation(module_instance, template, config)
  543. return
  544. # Verbose output
  545. if config.verbose:
  546. _display_validation_details(module_instance, template)
  547. except TemplateRenderError as e:
  548. module_instance.display.error(str(e), context=f"template '{template_id}'")
  549. raise Exit(code=1) from None
  550. except (TemplateSyntaxError, TemplateValidationError, ValueError) as e:
  551. module_instance.display.error(f"Validation failed for '{template_id}':")
  552. module_instance.display.info(f"\n{e}")
  553. raise Exit(code=1) from None
  554. except Exit:
  555. raise
  556. except Exception as e:
  557. module_instance.display.error(f"Unexpected error validating '{template_id}': {e}")
  558. raise Exit(code=1) from None
  559. def _run_matrix_validation(
  560. module_instance,
  561. template,
  562. config: ValidationConfig,
  563. ) -> None:
  564. """Run dependency matrix validation for one template."""
  565. module_instance.display.info("")
  566. module_instance.display.info("Running dependency matrix validation...")
  567. options = MatrixOptions(max_combinations=config.matrix_max_combinations)
  568. cases = DependencyMatrixBuilder(template, options).build()
  569. runner = ValidationRunner(
  570. template,
  571. cases,
  572. semantic=config.semantic,
  573. kind_validator=config.kind_validator,
  574. )
  575. summary = runner.run()
  576. module_instance.display.data_table(
  577. columns=[
  578. {"name": "Case", "style": "cyan", "no_wrap": False},
  579. {"name": "Tpl", "justify": "center"},
  580. {"name": "Sem", "justify": "center"},
  581. {"name": "Kind", "justify": "center"},
  582. ],
  583. rows=_build_matrix_result_rows(
  584. cases,
  585. summary.failures,
  586. kind_requested=config.kind,
  587. kind_available=config.kind_validator is not None,
  588. kind_skipped_cases=summary.kind_skipped_cases,
  589. ),
  590. title=f"Dependency Matrix ({len(cases)} cases)",
  591. )
  592. if config.kind and config.kind_validator is None:
  593. module_instance.display.warning(f"No kind-specific validator available for '{module_instance.name}'")
  594. elif summary.kind_skipped_cases:
  595. module_instance.display.warning("Kind-specific validation skipped for one or more cases")
  596. if summary.failures:
  597. module_instance.display.info("")
  598. for failure in summary.failures:
  599. location = f" [{failure.file_path}]" if failure.file_path else ""
  600. validator = f" ({failure.validator})" if failure.validator else ""
  601. module_instance.display.error(
  602. f"{failure.case_name}: {failure.stage}{location}{validator}: {failure.message}"
  603. )
  604. raise Exit(code=1) from None
  605. module_instance.display.success(f"Dependency matrix validation passed ({summary.total_cases} case(s))")
  606. def _build_matrix_result_rows(
  607. cases,
  608. failures,
  609. kind_requested: bool,
  610. kind_available: bool,
  611. kind_skipped_cases: set[str],
  612. ) -> list[tuple[str, str, str, str]]:
  613. """Build display rows for matrix validation results."""
  614. failures_by_case: dict[str, dict[str, set[str]]] = {}
  615. for failure in failures:
  616. case_failures = failures_by_case.setdefault(failure.case_name, {})
  617. case_failures.setdefault(failure.stage, set()).add(failure.message)
  618. rows = []
  619. for case in cases:
  620. failed_stages = failures_by_case.get(case.name, {})
  621. rows.append(
  622. (
  623. case.name,
  624. "fail" if "tpl" in failed_stages else "pass",
  625. "fail" if "sem" in failed_stages else "pass",
  626. _matrix_stage_status(
  627. failed_stages,
  628. "kind",
  629. requested=kind_requested,
  630. available=kind_available,
  631. skipped=case.name in kind_skipped_cases,
  632. ),
  633. )
  634. )
  635. return rows
  636. def _matrix_stage_status(
  637. failed_stages: dict[str, set[str]],
  638. stage: str,
  639. *,
  640. requested: bool = True,
  641. available: bool = True,
  642. skipped: bool = False,
  643. ) -> str:
  644. if not requested:
  645. return "skip"
  646. if not available:
  647. return "missing"
  648. if any("not available" in message or "unavailable" in message for message in failed_stages.get(stage, set())):
  649. return "missing"
  650. if stage in failed_stages:
  651. return "fail"
  652. if skipped:
  653. return "skip"
  654. return "pass"
  655. def _display_validation_details(module_instance, template) -> None:
  656. """Display verbose validation details."""
  657. module_instance.display.info(f"\nTemplate path: {template.template_dir}")
  658. module_instance.display.info(f"Found {len(template.used_variables)} variables")
  659. def _validate_all_templates(module_instance, config: ValidationConfig) -> None:
  660. """Validate all templates in the module."""
  661. module_instance.display.info(f"Validating all {module_instance.name} templates...")
  662. valid_count = 0
  663. invalid_count = 0
  664. errors = []
  665. all_templates = module_instance._load_all_templates()
  666. total = len(all_templates)
  667. child_config = replace(config, quiet_success=not config.verbose)
  668. for template in all_templates:
  669. try:
  670. _validate_single_template(module_instance, template, template.id, child_config)
  671. valid_count += 1
  672. if config.verbose:
  673. module_instance.display.success(template.id)
  674. except Exit:
  675. invalid_count += 1
  676. errors.append((template.id, "Validation failed"))
  677. if config.verbose:
  678. module_instance.display.error(template.id)
  679. except ValueError as e:
  680. invalid_count += 1
  681. errors.append((template.id, str(e)))
  682. if config.verbose:
  683. module_instance.display.error(template.id)
  684. except Exception as e:
  685. invalid_count += 1
  686. errors.append((template.id, f"Load error: {e}"))
  687. if config.verbose:
  688. module_instance.display.warning(template.id)
  689. # Display summary
  690. module_instance.display.info("")
  691. module_instance.display.info(f"Total templates: {total}")
  692. module_instance.display.info(f"Valid: {valid_count}")
  693. module_instance.display.info(f"Invalid: {invalid_count}")
  694. if errors:
  695. module_instance.display.info("")
  696. for template_id, error_msg in errors:
  697. module_instance.display.error(f"{template_id}: {error_msg}")
  698. raise Exit(code=1)
  699. if total > 0:
  700. module_instance.display.info("")
  701. module_instance.display.success("All templates are valid")