base_commands.py 26 KB

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