base_commands.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. """Base commands for module: list, search, show, validate, generate."""
  2. from __future__ import annotations
  3. import logging
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. from jinja2 import Template as Jinja2Template
  7. from typer import Exit
  8. from ..config import ConfigManager
  9. from ..display import DisplayManager, IconManager
  10. from ..exceptions import (
  11. TemplateRenderError,
  12. TemplateSyntaxError,
  13. TemplateValidationError,
  14. )
  15. from ..input import InputManager
  16. from ..template import (
  17. TEMPLATE_STATUS_DRAFT,
  18. TEMPLATE_STATUS_PUBLISHED,
  19. Template,
  20. )
  21. from ..validators import get_validator_registry
  22. from .helpers import (
  23. apply_cli_overrides,
  24. apply_var_file,
  25. apply_variable_defaults,
  26. collect_variable_values,
  27. )
  28. logger = logging.getLogger(__name__)
  29. # File size thresholds for display formatting
  30. BYTES_PER_KB = 1024
  31. BYTES_PER_MB = 1024 * 1024
  32. @dataclass
  33. class GenerationConfig:
  34. """Configuration for template generation."""
  35. id: str
  36. directory: str | None = None
  37. output: str | None = None
  38. interactive: bool = True
  39. var: list[str] | None = None
  40. var_file: str | None = None
  41. dry_run: bool = False
  42. show_files: bool = False
  43. quiet: bool = False
  44. @dataclass
  45. class ConfirmationContext:
  46. """Context for file generation confirmation."""
  47. output_dir: Path
  48. rendered_files: dict[str, str]
  49. existing_files: list[Path] | None
  50. dir_not_empty: bool
  51. dry_run: bool
  52. interactive: bool
  53. display: DisplayManager
  54. def list_templates(module_instance, raw: bool = False) -> list:
  55. """List all templates."""
  56. logger.debug(f"Listing templates for module '{module_instance.name}'")
  57. # Load all templates using centralized helper
  58. filtered_templates = module_instance._load_all_templates()
  59. if filtered_templates:
  60. if raw:
  61. # Output raw format (tab-separated values for easy filtering with awk/sed/cut)
  62. # Format: ID\tNAME\tTAGS\tVERSION\tLIBRARY
  63. for template in filtered_templates:
  64. tags_list = template.metadata.tags or []
  65. ",".join(tags_list) if tags_list else "-"
  66. (str(template.metadata.version) if template.metadata.version else "-")
  67. else:
  68. # Output rich table format
  69. def format_template_row(template):
  70. name = template.metadata.name or "Unnamed Template"
  71. tags_list = template.metadata.tags or []
  72. tags = ", ".join(tags_list) if tags_list else "-"
  73. version = str(template.metadata.version) if template.metadata.version else ""
  74. # Get status and format it
  75. status = template.status
  76. if status == TEMPLATE_STATUS_PUBLISHED:
  77. status_display = "[green]Published[/green]"
  78. elif status == TEMPLATE_STATUS_DRAFT:
  79. status_display = "[dim]Draft[/dim]"
  80. else: # TEMPLATE_STATUS_INVALID
  81. status_display = "[red]Invalid[/red]"
  82. library_name = template.metadata.library or ""
  83. library_type = template.metadata.library_type or "git"
  84. # Format library with icon and color
  85. icon = IconManager.UI_LIBRARY_STATIC if library_type == "static" else IconManager.UI_LIBRARY_GIT
  86. color = "yellow" if library_type == "static" else "blue"
  87. library_display = f"[{color}]{icon} {library_name}[/{color}]"
  88. # Apply dimmed style to entire row if draft
  89. if status == TEMPLATE_STATUS_DRAFT:
  90. template_id = f"[dim]{template.id}[/dim]"
  91. name = f"[dim]{name}[/dim]"
  92. tags = f"[dim]{tags}[/dim]"
  93. version = f"[dim]{version}[/dim]"
  94. library_display = f"[dim]{icon} {library_name}[/dim]"
  95. else:
  96. template_id = template.id
  97. return (template_id, name, tags, version, status_display, library_display)
  98. module_instance.display.data_table(
  99. columns=[
  100. {"name": "ID", "style": "bold", "no_wrap": True},
  101. {"name": "Name"},
  102. {"name": "Tags"},
  103. {"name": "Version", "no_wrap": True},
  104. {"name": "Status", "no_wrap": True},
  105. {"name": "Library", "no_wrap": True},
  106. ],
  107. rows=filtered_templates,
  108. row_formatter=format_template_row,
  109. )
  110. else:
  111. logger.info(f"No templates found for module '{module_instance.name}'")
  112. module_instance.display.info(
  113. f"No templates found for module '{module_instance.name}'",
  114. context="Use 'bp repo update' to update libraries or check library configuration",
  115. )
  116. return filtered_templates
  117. def search_templates(module_instance, query: str) -> list:
  118. """Search for templates by ID containing the search string."""
  119. logger.debug(f"Searching templates for module '{module_instance.name}' with query='{query}'")
  120. # Load templates with search filter using centralized helper
  121. filtered_templates = module_instance._load_all_templates(lambda t: query.lower() in t.id.lower())
  122. if filtered_templates:
  123. logger.info(f"Found {len(filtered_templates)} templates matching '{query}' for module '{module_instance.name}'")
  124. def format_template_row(template):
  125. name = template.metadata.name or "Unnamed Template"
  126. tags_list = template.metadata.tags or []
  127. tags = ", ".join(tags_list) if tags_list else "-"
  128. version = str(template.metadata.version) if template.metadata.version else ""
  129. # Get status and format it
  130. status = template.status
  131. if status == TEMPLATE_STATUS_PUBLISHED:
  132. status_display = "[green]Published[/green]"
  133. elif status == TEMPLATE_STATUS_DRAFT:
  134. status_display = "[dim]Draft[/dim]"
  135. else: # TEMPLATE_STATUS_INVALID
  136. status_display = "[red]Invalid[/red]"
  137. library_name = template.metadata.library or ""
  138. library_type = template.metadata.library_type or "git"
  139. # Format library with icon and color
  140. icon = IconManager.UI_LIBRARY_STATIC if library_type == "static" else IconManager.UI_LIBRARY_GIT
  141. color = "yellow" if library_type == "static" else "blue"
  142. library_display = f"[{color}]{icon} {library_name}[/{color}]"
  143. # Apply dimmed style to entire row if draft
  144. if status == TEMPLATE_STATUS_DRAFT:
  145. template_id = f"[dim]{template.id}[/dim]"
  146. name = f"[dim]{name}[/dim]"
  147. tags = f"[dim]{tags}[/dim]"
  148. version = f"[dim]{version}[/dim]"
  149. library_display = f"[dim]{icon} {library_name}[/dim]"
  150. else:
  151. template_id = template.id
  152. return (template_id, name, tags, version, status_display, library_display)
  153. module_instance.display.data_table(
  154. columns=[
  155. {"name": "ID", "style": "bold", "no_wrap": True},
  156. {"name": "Name"},
  157. {"name": "Tags"},
  158. {"name": "Version", "no_wrap": True},
  159. {"name": "Status", "no_wrap": True},
  160. {"name": "Library", "no_wrap": True},
  161. ],
  162. rows=filtered_templates,
  163. row_formatter=format_template_row,
  164. )
  165. else:
  166. logger.info(f"No templates found matching '{query}' for module '{module_instance.name}'")
  167. module_instance.display.warning(
  168. f"No templates found matching '{query}'",
  169. context=f"module '{module_instance.name}'",
  170. )
  171. return filtered_templates
  172. def show_template(module_instance, id: str, var: list[str] | None = None, var_file: str | None = None) -> None:
  173. """Show template details with optional variable overrides."""
  174. logger.debug(f"Showing template '{id}' from module '{module_instance.name}'")
  175. template = module_instance._load_template_by_id(id)
  176. if not template:
  177. module_instance.display.error(f"Template '{id}' not found", context=f"module '{module_instance.name}'")
  178. return
  179. # Apply defaults and overrides (same precedence as generate command)
  180. if template.variables:
  181. config = ConfigManager()
  182. apply_variable_defaults(template, config, module_instance.name)
  183. apply_var_file(template, var_file, module_instance.display)
  184. apply_cli_overrides(template, var)
  185. # Re-sort sections after applying overrides (toggle values may have changed)
  186. template.variables.sort_sections()
  187. # Reset disabled bool variables to False to prevent confusion
  188. reset_vars = template.variables.reset_disabled_bool_variables()
  189. if reset_vars:
  190. logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
  191. # Display template header
  192. module_instance.display.templates.render_template_header(template, id)
  193. # Display file tree
  194. module_instance.display.templates.render_file_tree(template)
  195. # Display variables table
  196. module_instance.display.variables.render_variables_table(template)
  197. def check_output_directory(
  198. output_dir: Path,
  199. rendered_files: dict[str, str],
  200. interactive: bool,
  201. display: DisplayManager,
  202. ) -> list[Path] | None:
  203. """Check output directory for conflicts and get user confirmation if needed."""
  204. dir_exists = output_dir.exists()
  205. dir_not_empty = dir_exists and any(output_dir.iterdir())
  206. # Check which files already exist
  207. existing_files = []
  208. if dir_exists:
  209. for file_path in rendered_files:
  210. full_path = output_dir / file_path
  211. if full_path.exists():
  212. existing_files.append(full_path)
  213. # Warn if directory is not empty
  214. if dir_not_empty:
  215. if interactive:
  216. display.text("") # Add newline before warning
  217. # Combine directory warning and file count on same line
  218. warning_msg = f"Directory '{output_dir}' is not empty."
  219. if existing_files:
  220. warning_msg += f" {len(existing_files)} file(s) will be overwritten."
  221. display.warning(warning_msg)
  222. display.text("") # Add newline after warning
  223. input_mgr = InputManager()
  224. if not input_mgr.confirm("Continue?", default=False):
  225. display.info("Generation cancelled")
  226. return None
  227. else:
  228. # Non-interactive mode: show warning but continue
  229. logger.warning(f"Directory '{output_dir}' is not empty")
  230. if existing_files:
  231. logger.warning(f"{len(existing_files)} file(s) will be overwritten")
  232. return existing_files
  233. def get_generation_confirmation(_ctx: ConfirmationContext) -> bool:
  234. """Display file generation confirmation and get user approval."""
  235. # No confirmation needed - either non-interactive, dry-run, or already confirmed during directory check
  236. return True
  237. def _collect_subdirectories(rendered_files: dict[str, str]) -> set[Path]:
  238. """Collect unique subdirectories from file paths."""
  239. subdirs = set()
  240. for file_path in rendered_files:
  241. parts = Path(file_path).parts
  242. for i in range(1, len(parts)):
  243. subdirs.add(Path(*parts[:i]))
  244. return subdirs
  245. def _analyze_file_operations(
  246. output_dir: Path, rendered_files: dict[str, str]
  247. ) -> tuple[list[tuple[str, int, str]], int, int, int]:
  248. """Analyze file operations and return statistics."""
  249. total_size = 0
  250. new_files = 0
  251. overwrite_files = 0
  252. file_operations = []
  253. for file_path, content in sorted(rendered_files.items()):
  254. full_path = output_dir / file_path
  255. file_size = len(content.encode("utf-8"))
  256. total_size += file_size
  257. if full_path.exists():
  258. status = "Overwrite"
  259. overwrite_files += 1
  260. else:
  261. status = "Create"
  262. new_files += 1
  263. file_operations.append((file_path, file_size, status))
  264. return file_operations, total_size, new_files, overwrite_files
  265. def _format_size(total_size: int) -> str:
  266. """Format byte size into human-readable string."""
  267. if total_size < BYTES_PER_KB:
  268. return f"{total_size}B"
  269. if total_size < BYTES_PER_MB:
  270. return f"{total_size / BYTES_PER_KB:.1f}KB"
  271. return f"{total_size / BYTES_PER_MB:.1f}MB"
  272. def execute_dry_run(
  273. id: str,
  274. output_dir: Path,
  275. rendered_files: dict[str, str],
  276. show_files: bool,
  277. display: DisplayManager,
  278. ) -> tuple[int, int, str]:
  279. """Execute dry run mode - preview files without writing.
  280. Returns:
  281. Tuple of (total_files, overwrite_files, size_str) for summary display
  282. """
  283. _file_operations, total_size, _new_files, overwrite_files = _analyze_file_operations(output_dir, rendered_files)
  284. size_str = _format_size(total_size)
  285. # Show file contents if requested
  286. if show_files:
  287. display.text("")
  288. display.heading("File Contents")
  289. for file_path, content in sorted(rendered_files.items()):
  290. display.text(f"\n[cyan]{file_path}[/cyan]")
  291. display.text(f"{'─' * 80}")
  292. display.text(content)
  293. display.text("")
  294. logger.info(f"Dry run completed for template '{id}' - {len(rendered_files)} files, {total_size} bytes")
  295. return len(rendered_files), overwrite_files, size_str
  296. def write_rendered_files(
  297. output_dir: Path,
  298. rendered_files: dict[str, str],
  299. _quiet: bool,
  300. _display: DisplayManager,
  301. ) -> None:
  302. """Write rendered files to the output directory."""
  303. output_dir.mkdir(parents=True, exist_ok=True)
  304. for file_path, content in rendered_files.items():
  305. full_path = output_dir / file_path
  306. full_path.parent.mkdir(parents=True, exist_ok=True)
  307. with full_path.open("w", encoding="utf-8") as f:
  308. f.write(content)
  309. logger.info(f"Template written to directory: {output_dir}")
  310. def _prepare_template(
  311. module_instance,
  312. id: str,
  313. var_file: str | None,
  314. var: list[str] | None,
  315. display: DisplayManager,
  316. ):
  317. """Load template and apply all defaults/overrides."""
  318. template = module_instance._load_template_by_id(id)
  319. config = ConfigManager()
  320. apply_variable_defaults(template, config, module_instance.name)
  321. apply_var_file(template, var_file, display)
  322. apply_cli_overrides(template, var)
  323. if template.variables:
  324. template.variables.sort_sections()
  325. reset_vars = template.variables.reset_disabled_bool_variables()
  326. if reset_vars:
  327. logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
  328. return template
  329. def _render_template(template, id: str, display: DisplayManager, interactive: bool):
  330. """Validate, render template and collect variable values."""
  331. variable_values = collect_variable_values(template, interactive)
  332. if template.variables:
  333. template.variables.validate_all()
  334. debug_mode = logger.isEnabledFor(logging.DEBUG)
  335. rendered_files, variable_values = template.render(template.variables, debug=debug_mode)
  336. if not rendered_files:
  337. display.error(
  338. "Template rendering returned no files",
  339. context="template generation",
  340. )
  341. raise Exit(code=1)
  342. logger.info(f"Successfully rendered template '{id}'")
  343. return rendered_files, variable_values
  344. def _determine_output_dir(directory: str | None, output: str | None, id: str) -> tuple[Path, bool]:
  345. """Determine and normalize output directory path.
  346. Returns:
  347. Tuple of (output_dir, used_deprecated_arg) where used_deprecated_arg indicates
  348. if the deprecated positional directory argument was used.
  349. """
  350. used_deprecated_arg = False
  351. # Priority: --output flag > positional directory argument > template ID
  352. if output:
  353. output_dir = Path(output)
  354. elif directory:
  355. output_dir = Path(directory)
  356. used_deprecated_arg = True
  357. logger.debug(f"Using deprecated positional directory argument: {directory}")
  358. else:
  359. output_dir = Path(id)
  360. # Normalize paths that look like absolute paths but are relative
  361. if not output_dir.is_absolute() and str(output_dir).startswith(("Users/", "home/", "usr/", "opt/", "var/", "tmp/")):
  362. output_dir = Path("/") / output_dir
  363. logger.debug(f"Normalized relative-looking absolute path to: {output_dir}")
  364. return output_dir, used_deprecated_arg
  365. def _display_template_error(display: DisplayManager, template_id: str, error: TemplateRenderError) -> None:
  366. """Display template rendering error with clean formatting."""
  367. display.text("")
  368. display.text("─" * 80, style="dim")
  369. display.text("")
  370. # Build details if available
  371. details = None
  372. if error.file_path:
  373. details = error.file_path
  374. if error.line_number:
  375. details += f":line {error.line_number}"
  376. # Display error with details
  377. display.error(f"Failed to generate boilerplate from template '{template_id}'", details=details)
  378. def _display_generic_error(display: DisplayManager, template_id: str, error: Exception) -> None:
  379. """Display generic error with clean formatting."""
  380. display.text("")
  381. display.text("─" * 80, style="dim")
  382. display.text("")
  383. # Truncate long error messages
  384. max_error_length = 100
  385. error_msg = str(error)
  386. if len(error_msg) > max_error_length:
  387. error_msg = f"{error_msg[:max_error_length]}..."
  388. # Display error with details
  389. display.error(f"Failed to generate boilerplate from template '{template_id}'", details=error_msg)
  390. def generate_template(module_instance, config: GenerationConfig) -> None: # noqa: PLR0912, PLR0915
  391. """Generate from template."""
  392. logger.info(f"Starting generation for template '{config.id}' from module '{module_instance.name}'")
  393. display = DisplayManager(quiet=config.quiet) if config.quiet else module_instance.display
  394. template = _prepare_template(module_instance, config.id, config.var_file, config.var, display)
  395. # Determine output directory early to check for deprecated argument usage
  396. output_dir, used_deprecated_arg = _determine_output_dir(config.directory, config.output, config.id)
  397. if not config.quiet:
  398. # Display template header
  399. module_instance.display.templates.render_template_header(template, config.id)
  400. # Display file tree
  401. module_instance.display.templates.render_file_tree(template)
  402. # Display variables table
  403. module_instance.display.variables.render_variables_table(template)
  404. module_instance.display.text("")
  405. # Show deprecation warning BEFORE any user interaction
  406. if used_deprecated_arg:
  407. module_instance.display.warning(
  408. "Using positional argument for output directory is deprecated and will be removed in v0.2.0",
  409. details="Use --output/-o flag instead",
  410. )
  411. module_instance.display.text("")
  412. try:
  413. rendered_files, variable_values = _render_template(template, config.id, display, config.interactive)
  414. # Check for conflicts and get confirmation (skip in quiet mode)
  415. if not config.quiet:
  416. existing_files = check_output_directory(output_dir, rendered_files, config.interactive, display)
  417. if existing_files is None:
  418. return # User cancelled
  419. dir_not_empty = output_dir.exists() and any(output_dir.iterdir())
  420. ctx = ConfirmationContext(
  421. output_dir=output_dir,
  422. rendered_files=rendered_files,
  423. existing_files=existing_files,
  424. dir_not_empty=dir_not_empty,
  425. dry_run=config.dry_run,
  426. interactive=config.interactive,
  427. display=display,
  428. )
  429. if not get_generation_confirmation(ctx):
  430. return # User cancelled
  431. # Execute generation (dry run or actual)
  432. dry_run_stats = None
  433. if config.dry_run:
  434. if not config.quiet:
  435. dry_run_stats = execute_dry_run(config.id, output_dir, rendered_files, config.show_files, display)
  436. else:
  437. write_rendered_files(output_dir, rendered_files, config.quiet, display)
  438. # Display next steps (not in quiet mode)
  439. if template.metadata.next_steps and not config.quiet:
  440. display.text("")
  441. display.heading("Next Steps")
  442. try:
  443. next_steps_template = Jinja2Template(template.metadata.next_steps)
  444. rendered_next_steps = next_steps_template.render(variable_values)
  445. display.status.markdown(rendered_next_steps)
  446. except Exception as e:
  447. logger.warning(f"Failed to render next_steps as template: {e}")
  448. # Fallback to plain text if rendering fails
  449. display.status.markdown(template.metadata.next_steps)
  450. # Display final status message at the end
  451. if not config.quiet:
  452. display.text("")
  453. display.text("─" * 80, style="dim")
  454. if config.dry_run and dry_run_stats:
  455. total_files, overwrite_files, size_str = dry_run_stats
  456. if overwrite_files > 0:
  457. display.warning(
  458. f"Dry run complete: {total_files} files ({size_str}) would be written to '{output_dir}' "
  459. f"({overwrite_files} would be overwritten)"
  460. )
  461. else:
  462. display.success(
  463. f"Dry run complete: {total_files} files ({size_str}) would be written to '{output_dir}'"
  464. )
  465. else:
  466. # Actual generation completed
  467. display.success(f"Boilerplate generated successfully in '{output_dir}'")
  468. except TemplateRenderError as e:
  469. _display_template_error(display, config.id, e)
  470. raise Exit(code=1) from None
  471. except Exception as e:
  472. _display_generic_error(display, config.id, e)
  473. raise Exit(code=1) from None
  474. def validate_templates(
  475. module_instance,
  476. template_id: str,
  477. path: str | None,
  478. verbose: bool,
  479. semantic: bool,
  480. ) -> None:
  481. """Validate templates for Jinja2 syntax, undefined variables, and semantic correctness."""
  482. # Load template based on input
  483. template = _load_template_for_validation(module_instance, template_id, path)
  484. if template:
  485. _validate_single_template(module_instance, template, template_id, verbose, semantic)
  486. else:
  487. _validate_all_templates(module_instance, verbose)
  488. def _load_template_for_validation(module_instance, template_id: str, path: str | None):
  489. """Load a template from path or ID for validation."""
  490. if path:
  491. template_path = Path(path).resolve()
  492. if not template_path.exists():
  493. module_instance.display.error(f"Path does not exist: {path}")
  494. raise Exit(code=1) from None
  495. if not template_path.is_dir():
  496. module_instance.display.error(f"Path is not a directory: {path}")
  497. raise Exit(code=1) from None
  498. module_instance.display.info(f"[bold]Validating template from path:[/bold] [cyan]{template_path}[/cyan]")
  499. try:
  500. return Template(template_path, library_name="local")
  501. except Exception as e:
  502. module_instance.display.error(f"Failed to load template from path '{path}': {e}")
  503. raise Exit(code=1) from None
  504. if template_id:
  505. try:
  506. template = module_instance._load_template_by_id(template_id)
  507. module_instance.display.info(f"Validating template: {template_id}")
  508. return template
  509. except Exception as e:
  510. module_instance.display.error(f"Failed to load template '{template_id}': {e}")
  511. raise Exit(code=1) from None
  512. return None
  513. def _validate_single_template(module_instance, template, template_id: str, verbose: bool, semantic: bool) -> None:
  514. """Validate a single template."""
  515. try:
  516. # Jinja2 validation
  517. _ = template.used_variables
  518. _ = template.variables
  519. module_instance.display.success("Jinja2 validation passed")
  520. # Semantic validation
  521. if semantic:
  522. _run_semantic_validation(module_instance, template, verbose)
  523. # Verbose output
  524. if verbose:
  525. _display_validation_details(module_instance, template, semantic)
  526. except TemplateRenderError as e:
  527. module_instance.display.error(str(e), context=f"template '{template_id}'")
  528. raise Exit(code=1) from None
  529. except (TemplateSyntaxError, TemplateValidationError, ValueError) as e:
  530. module_instance.display.error(f"Validation failed for '{template_id}':")
  531. module_instance.display.info(f"\n{e}")
  532. raise Exit(code=1) from None
  533. except Exception as e:
  534. module_instance.display.error(f"Unexpected error validating '{template_id}': {e}")
  535. raise Exit(code=1) from None
  536. def _run_semantic_validation(module_instance, template, verbose: bool) -> None:
  537. """Run semantic validation on rendered template files."""
  538. module_instance.display.info("")
  539. module_instance.display.info("Running semantic validation...")
  540. registry = get_validator_registry()
  541. debug_mode = logger.isEnabledFor(logging.DEBUG)
  542. rendered_files, _ = template.render(template.variables, debug=debug_mode)
  543. has_semantic_errors = False
  544. for file_path, content in rendered_files.items():
  545. result = registry.validate_file(content, file_path)
  546. if result.errors or result.warnings or (verbose and result.info):
  547. module_instance.display.info(f"\nFile: {file_path}")
  548. result.display(f"{file_path}")
  549. if result.errors:
  550. has_semantic_errors = True
  551. if has_semantic_errors:
  552. module_instance.display.error("Semantic validation found errors")
  553. raise Exit(code=1) from None
  554. module_instance.display.success("Semantic validation passed")
  555. def _display_validation_details(module_instance, template, semantic: bool) -> None:
  556. """Display verbose validation details."""
  557. module_instance.display.info(f"\nTemplate path: {template.template_dir}")
  558. module_instance.display.info(f"Found {len(template.used_variables)} variables")
  559. if semantic:
  560. debug_mode = logger.isEnabledFor(logging.DEBUG)
  561. rendered_files, _ = template.render(template.variables, debug=debug_mode)
  562. module_instance.display.info(f"Generated {len(rendered_files)} files")
  563. def _validate_all_templates(module_instance, verbose: bool) -> None:
  564. """Validate all templates in the module."""
  565. module_instance.display.info(f"Validating all {module_instance.name} templates...")
  566. valid_count = 0
  567. invalid_count = 0
  568. errors = []
  569. all_templates = module_instance._load_all_templates()
  570. total = len(all_templates)
  571. for template in all_templates:
  572. try:
  573. _ = template.used_variables
  574. _ = template.variables
  575. valid_count += 1
  576. if verbose:
  577. module_instance.display.success(template.id)
  578. except ValueError as e:
  579. invalid_count += 1
  580. errors.append((template.id, str(e)))
  581. if verbose:
  582. module_instance.display.error(template.id)
  583. except Exception as e:
  584. invalid_count += 1
  585. errors.append((template.id, f"Load error: {e}"))
  586. if verbose:
  587. module_instance.display.warning(template.id)
  588. # Display summary
  589. module_instance.display.info("")
  590. module_instance.display.info(f"Total templates: {total}")
  591. module_instance.display.info(f"Valid: {valid_count}")
  592. module_instance.display.info(f"Invalid: {invalid_count}")
  593. if errors:
  594. module_instance.display.info("")
  595. for template_id, error_msg in errors:
  596. module_instance.display.error(f"{template_id}: {error_msg}")
  597. raise Exit(code=1)
  598. if total > 0:
  599. module_instance.display.info("")
  600. module_instance.display.success("All templates are valid")