base_commands.py 26 KB

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