base_commands.py 28 KB

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