base_commands.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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. # Reset disabled bool variables to False to prevent confusion
  186. reset_vars = template.variables.reset_disabled_bool_variables()
  187. if reset_vars:
  188. logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
  189. # Display template header
  190. module_instance.display.templates.render_template_header(template, id)
  191. # Display file tree
  192. module_instance.display.templates.render_file_tree(template)
  193. # Display variables table
  194. module_instance.display.variables.render_variables_table(template)
  195. def check_output_directory(
  196. output_dir: Path,
  197. rendered_files: dict[str, str],
  198. interactive: bool,
  199. display: DisplayManager,
  200. ) -> list[Path] | None:
  201. """Check output directory for conflicts and get user confirmation if needed."""
  202. dir_exists = output_dir.exists()
  203. dir_not_empty = dir_exists and any(output_dir.iterdir())
  204. # Check which files already exist
  205. existing_files = []
  206. if dir_exists:
  207. for file_path in rendered_files:
  208. full_path = output_dir / file_path
  209. if full_path.exists():
  210. existing_files.append(full_path)
  211. # Warn if directory is not empty
  212. if dir_not_empty:
  213. if interactive:
  214. display.text("") # Add newline before warning
  215. # Combine directory warning and file count on same line
  216. warning_msg = f"Directory '{output_dir}' is not empty."
  217. if existing_files:
  218. warning_msg += f" {len(existing_files)} file(s) will be overwritten."
  219. display.warning(warning_msg)
  220. display.text("") # Add newline after warning
  221. input_mgr = InputManager()
  222. if not input_mgr.confirm("Continue?", default=False):
  223. display.info("Generation cancelled")
  224. return None
  225. else:
  226. # Non-interactive mode: show warning but continue
  227. logger.warning(f"Directory '{output_dir}' is not empty")
  228. if existing_files:
  229. logger.warning(f"{len(existing_files)} file(s) will be overwritten")
  230. return existing_files
  231. def get_generation_confirmation(_ctx: ConfirmationContext) -> bool:
  232. """Display file generation confirmation and get user approval."""
  233. # No confirmation needed - either non-interactive, dry-run, or already confirmed during directory check
  234. return True
  235. def _collect_subdirectories(rendered_files: dict[str, str]) -> set[Path]:
  236. """Collect unique subdirectories from file paths."""
  237. subdirs = set()
  238. for file_path in rendered_files:
  239. parts = Path(file_path).parts
  240. for i in range(1, len(parts)):
  241. subdirs.add(Path(*parts[:i]))
  242. return subdirs
  243. def _analyze_file_operations(
  244. output_dir: Path, rendered_files: dict[str, str]
  245. ) -> tuple[list[tuple[str, int, str]], int, int, int]:
  246. """Analyze file operations and return statistics."""
  247. total_size = 0
  248. new_files = 0
  249. overwrite_files = 0
  250. file_operations = []
  251. for file_path, content in sorted(rendered_files.items()):
  252. full_path = output_dir / file_path
  253. file_size = len(content.encode("utf-8"))
  254. total_size += file_size
  255. if full_path.exists():
  256. status = "Overwrite"
  257. overwrite_files += 1
  258. else:
  259. status = "Create"
  260. new_files += 1
  261. file_operations.append((file_path, file_size, status))
  262. return file_operations, total_size, new_files, overwrite_files
  263. def _format_size(total_size: int) -> str:
  264. """Format byte size into human-readable string."""
  265. if total_size < BYTES_PER_KB:
  266. return f"{total_size}B"
  267. if total_size < BYTES_PER_MB:
  268. return f"{total_size / BYTES_PER_KB:.1f}KB"
  269. return f"{total_size / BYTES_PER_MB:.1f}MB"
  270. def execute_dry_run(
  271. id: str,
  272. output_dir: Path,
  273. rendered_files: dict[str, str],
  274. show_files: bool,
  275. display: DisplayManager,
  276. ) -> tuple[int, int, str]:
  277. """Execute dry run mode - preview files without writing.
  278. Returns:
  279. Tuple of (total_files, overwrite_files, size_str) for summary display
  280. """
  281. _file_operations, total_size, _new_files, overwrite_files = _analyze_file_operations(output_dir, rendered_files)
  282. size_str = _format_size(total_size)
  283. # Show file contents if requested
  284. if show_files:
  285. display.text("")
  286. display.heading("File Contents")
  287. for file_path, content in sorted(rendered_files.items()):
  288. display.text(f"\n[cyan]{file_path}[/cyan]")
  289. display.text(f"{'─' * 80}")
  290. display.text(content)
  291. display.text("")
  292. logger.info(f"Dry run completed for template '{id}' - {len(rendered_files)} files, {total_size} bytes")
  293. return len(rendered_files), overwrite_files, size_str
  294. def write_rendered_files(
  295. output_dir: Path,
  296. rendered_files: dict[str, str],
  297. _quiet: bool,
  298. _display: DisplayManager,
  299. ) -> None:
  300. """Write rendered files to the output directory."""
  301. output_dir.mkdir(parents=True, exist_ok=True)
  302. for file_path, content in rendered_files.items():
  303. full_path = output_dir / file_path
  304. full_path.parent.mkdir(parents=True, exist_ok=True)
  305. with full_path.open("w", encoding="utf-8") as f:
  306. f.write(content)
  307. logger.info(f"Template written to directory: {output_dir}")
  308. def _prepare_template(
  309. module_instance,
  310. id: str,
  311. var_file: str | None,
  312. var: list[str] | None,
  313. display: DisplayManager,
  314. ):
  315. """Load template and apply all defaults/overrides."""
  316. template = module_instance._load_template_by_id(id)
  317. config = ConfigManager()
  318. apply_variable_defaults(template, config, module_instance.name)
  319. apply_var_file(template, var_file, display)
  320. apply_cli_overrides(template, var)
  321. if template.variables:
  322. reset_vars = template.variables.reset_disabled_bool_variables()
  323. if reset_vars:
  324. logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
  325. return template
  326. def _render_template(template, id: str, display: DisplayManager, interactive: bool):
  327. """Validate, render template and collect variable values."""
  328. variable_values = collect_variable_values(template, interactive)
  329. if template.variables:
  330. template.variables.validate_all()
  331. debug_mode = logger.isEnabledFor(logging.DEBUG)
  332. rendered_files, variable_values = template.render(template.variables, debug=debug_mode)
  333. if not rendered_files:
  334. display.error(
  335. "Template rendering returned no files",
  336. context="template generation",
  337. )
  338. raise Exit(code=1)
  339. logger.info(f"Successfully rendered template '{id}'")
  340. return rendered_files, variable_values
  341. def _determine_output_dir(directory: str | None, output: str | None, id: str) -> tuple[Path, bool]:
  342. """Determine and normalize output directory path.
  343. Returns:
  344. Tuple of (output_dir, used_deprecated_arg) where used_deprecated_arg indicates
  345. if the deprecated positional directory argument was used.
  346. """
  347. used_deprecated_arg = False
  348. # Priority: --output flag > positional directory argument > template ID
  349. if output:
  350. output_dir = Path(output)
  351. elif directory:
  352. output_dir = Path(directory)
  353. used_deprecated_arg = True
  354. logger.debug(f"Using deprecated positional directory argument: {directory}")
  355. else:
  356. output_dir = Path(id)
  357. # Normalize paths that look like absolute paths but are relative
  358. if not output_dir.is_absolute() and str(output_dir).startswith(("Users/", "home/", "usr/", "opt/", "var/", "tmp/")):
  359. output_dir = Path("/") / output_dir
  360. logger.debug(f"Normalized relative-looking absolute path to: {output_dir}")
  361. return output_dir, used_deprecated_arg
  362. def _display_template_error(display: DisplayManager, template_id: str, error: TemplateRenderError) -> None:
  363. """Display template rendering error with clean formatting."""
  364. display.text("")
  365. display.text("─" * 80, style="dim")
  366. display.text("")
  367. # Build details if available
  368. details = None
  369. if error.file_path:
  370. details = error.file_path
  371. if error.line_number:
  372. details += f":line {error.line_number}"
  373. # Display error with details
  374. display.error(f"Failed to generate boilerplate from template '{template_id}'", details=details)
  375. def _display_generic_error(display: DisplayManager, template_id: str, error: Exception) -> None:
  376. """Display generic error with clean formatting."""
  377. display.text("")
  378. display.text("─" * 80, style="dim")
  379. display.text("")
  380. # Truncate long error messages
  381. max_error_length = 100
  382. error_msg = str(error)
  383. if len(error_msg) > max_error_length:
  384. error_msg = f"{error_msg[:max_error_length]}..."
  385. # Display error with details
  386. display.error(f"Failed to generate boilerplate from template '{template_id}'", details=error_msg)
  387. def generate_template(module_instance, config: GenerationConfig) -> None: # noqa: PLR0912, PLR0915
  388. """Generate from template."""
  389. logger.info(f"Starting generation for template '{config.id}' from module '{module_instance.name}'")
  390. display = DisplayManager(quiet=config.quiet) if config.quiet else module_instance.display
  391. template = _prepare_template(module_instance, config.id, config.var_file, config.var, display)
  392. # Determine output directory early to check for deprecated argument usage
  393. output_dir, used_deprecated_arg = _determine_output_dir(config.directory, config.output, config.id)
  394. if not config.quiet:
  395. # Display template header
  396. module_instance.display.templates.render_template_header(template, config.id)
  397. # Display file tree
  398. module_instance.display.templates.render_file_tree(template)
  399. # Display variables table
  400. module_instance.display.variables.render_variables_table(template)
  401. module_instance.display.text("")
  402. # Show deprecation warning BEFORE any user interaction
  403. if used_deprecated_arg:
  404. module_instance.display.warning(
  405. "Using positional argument for output directory is deprecated and will be removed in v0.2.0",
  406. details="Use --output/-o flag instead",
  407. )
  408. module_instance.display.text("")
  409. try:
  410. rendered_files, variable_values = _render_template(template, config.id, display, config.interactive)
  411. # Check for conflicts and get confirmation (skip in quiet mode)
  412. if not config.quiet:
  413. existing_files = check_output_directory(output_dir, rendered_files, config.interactive, display)
  414. if existing_files is None:
  415. return # User cancelled
  416. dir_not_empty = output_dir.exists() and any(output_dir.iterdir())
  417. ctx = ConfirmationContext(
  418. output_dir=output_dir,
  419. rendered_files=rendered_files,
  420. existing_files=existing_files,
  421. dir_not_empty=dir_not_empty,
  422. dry_run=config.dry_run,
  423. interactive=config.interactive,
  424. display=display,
  425. )
  426. if not get_generation_confirmation(ctx):
  427. return # User cancelled
  428. # Execute generation (dry run or actual)
  429. dry_run_stats = None
  430. if config.dry_run:
  431. if not config.quiet:
  432. dry_run_stats = execute_dry_run(config.id, output_dir, rendered_files, config.show_files, display)
  433. else:
  434. write_rendered_files(output_dir, rendered_files, config.quiet, display)
  435. # Display next steps (not in quiet mode)
  436. if template.metadata.next_steps and not config.quiet:
  437. display.text("")
  438. display.heading("Next Steps")
  439. try:
  440. next_steps_template = Jinja2Template(template.metadata.next_steps)
  441. rendered_next_steps = next_steps_template.render(variable_values)
  442. display.status.markdown(rendered_next_steps)
  443. except Exception as e:
  444. logger.warning(f"Failed to render next_steps as template: {e}")
  445. # Fallback to plain text if rendering fails
  446. display.status.markdown(template.metadata.next_steps)
  447. # Display final status message at the end
  448. if not config.quiet:
  449. display.text("")
  450. display.text("─" * 80, style="dim")
  451. if config.dry_run and dry_run_stats:
  452. total_files, overwrite_files, size_str = dry_run_stats
  453. if overwrite_files > 0:
  454. display.warning(
  455. f"Dry run complete: {total_files} files ({size_str}) would be written to '{output_dir}' "
  456. f"({overwrite_files} would be overwritten)"
  457. )
  458. else:
  459. display.success(
  460. f"Dry run complete: {total_files} files ({size_str}) would be written to '{output_dir}'"
  461. )
  462. else:
  463. # Actual generation completed
  464. display.success(f"Boilerplate generated successfully in '{output_dir}'")
  465. except TemplateRenderError as e:
  466. _display_template_error(display, config.id, e)
  467. raise Exit(code=1) from None
  468. except Exception as e:
  469. _display_generic_error(display, config.id, e)
  470. raise Exit(code=1) from None
  471. def validate_templates(
  472. module_instance,
  473. template_id: str,
  474. path: str | None,
  475. verbose: bool,
  476. semantic: bool,
  477. ) -> None:
  478. """Validate templates for Jinja2 syntax, undefined variables, and semantic correctness."""
  479. # Load template based on input
  480. template = _load_template_for_validation(module_instance, template_id, path)
  481. if template:
  482. _validate_single_template(module_instance, template, template_id, verbose, semantic)
  483. else:
  484. _validate_all_templates(module_instance, verbose)
  485. def _load_template_for_validation(module_instance, template_id: str, path: str | None):
  486. """Load a template from path or ID for validation."""
  487. if path:
  488. template_path = Path(path).resolve()
  489. if not template_path.exists():
  490. module_instance.display.error(f"Path does not exist: {path}")
  491. raise Exit(code=1) from None
  492. if not template_path.is_dir():
  493. module_instance.display.error(f"Path is not a directory: {path}")
  494. raise Exit(code=1) from None
  495. module_instance.display.info(f"[bold]Validating template from path:[/bold] [cyan]{template_path}[/cyan]")
  496. try:
  497. return Template(template_path, library_name="local")
  498. except Exception as e:
  499. module_instance.display.error(f"Failed to load template from path '{path}': {e}")
  500. raise Exit(code=1) from None
  501. if template_id:
  502. try:
  503. template = module_instance._load_template_by_id(template_id)
  504. module_instance.display.info(f"Validating template: {template_id}")
  505. return template
  506. except Exception as e:
  507. module_instance.display.error(f"Failed to load template '{template_id}': {e}")
  508. raise Exit(code=1) from None
  509. return None
  510. def _validate_single_template(module_instance, template, template_id: str, verbose: bool, semantic: bool) -> None:
  511. """Validate a single template."""
  512. try:
  513. # Jinja2 validation
  514. _ = template.used_variables
  515. _ = template.variables
  516. module_instance.display.success("Jinja2 validation passed")
  517. # Semantic validation
  518. if semantic:
  519. _run_semantic_validation(module_instance, template, verbose)
  520. # Verbose output
  521. if verbose:
  522. _display_validation_details(module_instance, template, semantic)
  523. except TemplateRenderError as e:
  524. module_instance.display.error(str(e), context=f"template '{template_id}'")
  525. raise Exit(code=1) from None
  526. except (TemplateSyntaxError, TemplateValidationError, ValueError) as e:
  527. module_instance.display.error(f"Validation failed for '{template_id}':")
  528. module_instance.display.info(f"\n{e}")
  529. raise Exit(code=1) from None
  530. except Exception as e:
  531. module_instance.display.error(f"Unexpected error validating '{template_id}': {e}")
  532. raise Exit(code=1) from None
  533. def _run_semantic_validation(module_instance, template, verbose: bool) -> None:
  534. """Run semantic validation on rendered template files."""
  535. module_instance.display.info("")
  536. module_instance.display.info("Running semantic validation...")
  537. registry = get_validator_registry()
  538. debug_mode = logger.isEnabledFor(logging.DEBUG)
  539. rendered_files, _ = template.render(template.variables, debug=debug_mode)
  540. has_semantic_errors = False
  541. for file_path, content in rendered_files.items():
  542. result = registry.validate_file(content, file_path)
  543. if result.errors or result.warnings or (verbose and result.info):
  544. module_instance.display.info(f"\nFile: {file_path}")
  545. result.display(f"{file_path}")
  546. if result.errors:
  547. has_semantic_errors = True
  548. if has_semantic_errors:
  549. module_instance.display.error("Semantic validation found errors")
  550. raise Exit(code=1) from None
  551. module_instance.display.success("Semantic validation passed")
  552. def _display_validation_details(module_instance, template, semantic: bool) -> None:
  553. """Display verbose validation details."""
  554. module_instance.display.info(f"\nTemplate path: {template.template_dir}")
  555. module_instance.display.info(f"Found {len(template.used_variables)} variables")
  556. if semantic:
  557. debug_mode = logger.isEnabledFor(logging.DEBUG)
  558. rendered_files, _ = template.render(template.variables, debug=debug_mode)
  559. module_instance.display.info(f"Generated {len(rendered_files)} files")
  560. def _validate_all_templates(module_instance, verbose: bool) -> None:
  561. """Validate all templates in the module."""
  562. module_instance.display.info(f"Validating all {module_instance.name} templates...")
  563. valid_count = 0
  564. invalid_count = 0
  565. errors = []
  566. all_templates = module_instance._load_all_templates()
  567. total = len(all_templates)
  568. for template in all_templates:
  569. try:
  570. _ = template.used_variables
  571. _ = template.variables
  572. valid_count += 1
  573. if verbose:
  574. module_instance.display.success(template.id)
  575. except ValueError as e:
  576. invalid_count += 1
  577. errors.append((template.id, str(e)))
  578. if verbose:
  579. module_instance.display.error(template.id)
  580. except Exception as e:
  581. invalid_count += 1
  582. errors.append((template.id, f"Load error: {e}"))
  583. if verbose:
  584. module_instance.display.warning(template.id)
  585. # Display summary
  586. module_instance.display.info("")
  587. module_instance.display.info(f"Total templates: {total}")
  588. module_instance.display.info(f"Valid: {valid_count}")
  589. module_instance.display.info(f"Invalid: {invalid_count}")
  590. if errors:
  591. module_instance.display.info("")
  592. for template_id, error_msg in errors:
  593. module_instance.display.error(f"{template_id}: {error_msg}")
  594. raise Exit(code=1)
  595. if total > 0:
  596. module_instance.display.info("")
  597. module_instance.display.success("All templates are valid")