base_commands.py 26 KB

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