base_commands.py 29 KB

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