display.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. from __future__ import annotations
  2. import logging
  3. from pathlib import Path
  4. from typing import TYPE_CHECKING
  5. from rich.console import Console
  6. from rich.table import Table
  7. from rich.tree import Tree
  8. if TYPE_CHECKING:
  9. from .exceptions import TemplateRenderError
  10. from .template import Template
  11. logger = logging.getLogger(__name__)
  12. console = Console()
  13. console_err = Console(stderr=True)
  14. class IconManager:
  15. """Centralized icon management system for consistent CLI display.
  16. This class provides standardized icons for file types, status indicators,
  17. and UI elements. Icons use Nerd Font glyphs for consistent display.
  18. Categories:
  19. - File types: .yaml, .j2, .json, .md, etc.
  20. - Status: success, warning, error, info, skipped
  21. - UI elements: folders, config, locks, etc.
  22. """
  23. # File Type Icons
  24. FILE_FOLDER = "\uf07b" #
  25. FILE_DEFAULT = "\uf15b" #
  26. FILE_YAML = "\uf15c" #
  27. FILE_JSON = "\ue60b" #
  28. FILE_MARKDOWN = "\uf48a" #
  29. FILE_JINJA2 = "\ue235" #
  30. FILE_DOCKER = "\uf308" #
  31. FILE_COMPOSE = "\uf308" #
  32. FILE_SHELL = "\uf489" #
  33. FILE_PYTHON = "\ue73c" #
  34. FILE_TEXT = "\uf15c" #
  35. # Status Indicators
  36. STATUS_SUCCESS = "\uf00c" # (check)
  37. STATUS_ERROR = "\uf00d" # (times/x)
  38. STATUS_WARNING = "\uf071" # (exclamation-triangle)
  39. STATUS_INFO = "\uf05a" # (info-circle)
  40. STATUS_SKIPPED = "\uf05e" # (ban/circle-slash)
  41. # UI Elements
  42. UI_CONFIG = "\ue5fc" #
  43. UI_LOCK = "\uf084" #
  44. UI_SETTINGS = "\uf013" #
  45. UI_ARROW_RIGHT = "\uf061" # (arrow-right)
  46. UI_BULLET = "\uf111" # (circle)
  47. UI_LIBRARY_GIT = "\uf418" # (git icon)
  48. UI_LIBRARY_STATIC = "\uf07c" # (folder icon)
  49. @classmethod
  50. def get_file_icon(cls, file_path: str | Path) -> str:
  51. """Get the appropriate icon for a file based on its extension or name.
  52. Args:
  53. file_path: Path to the file (can be string or Path object)
  54. Returns:
  55. Unicode icon character for the file type
  56. Examples:
  57. >>> IconManager.get_file_icon("config.yaml")
  58. '\uf15c'
  59. >>> IconManager.get_file_icon("template.j2")
  60. '\ue235'
  61. """
  62. if isinstance(file_path, str):
  63. file_path = Path(file_path)
  64. file_name = file_path.name.lower()
  65. suffix = file_path.suffix.lower()
  66. # Check for Docker Compose files
  67. compose_names = {
  68. "docker-compose.yml",
  69. "docker-compose.yaml",
  70. "compose.yml",
  71. "compose.yaml",
  72. }
  73. if file_name in compose_names or file_name.startswith("docker-compose"):
  74. return cls.FILE_DOCKER
  75. # Check by extension
  76. extension_map = {
  77. ".yaml": cls.FILE_YAML,
  78. ".yml": cls.FILE_YAML,
  79. ".json": cls.FILE_JSON,
  80. ".md": cls.FILE_MARKDOWN,
  81. ".j2": cls.FILE_JINJA2,
  82. ".sh": cls.FILE_SHELL,
  83. ".py": cls.FILE_PYTHON,
  84. ".txt": cls.FILE_TEXT,
  85. }
  86. return extension_map.get(suffix, cls.FILE_DEFAULT)
  87. @classmethod
  88. def get_status_icon(cls, status: str) -> str:
  89. """Get the appropriate icon for a status indicator.
  90. Args:
  91. status: Status type (success, error, warning, info, skipped)
  92. Returns:
  93. Unicode icon character for the status
  94. Examples:
  95. >>> IconManager.get_status_icon("success")
  96. '✓'
  97. >>> IconManager.get_status_icon("warning")
  98. '⚠'
  99. """
  100. status_map = {
  101. "success": cls.STATUS_SUCCESS,
  102. "error": cls.STATUS_ERROR,
  103. "warning": cls.STATUS_WARNING,
  104. "info": cls.STATUS_INFO,
  105. "skipped": cls.STATUS_SKIPPED,
  106. }
  107. return status_map.get(status.lower(), cls.STATUS_INFO)
  108. @classmethod
  109. def folder(cls) -> str:
  110. """Get the folder icon."""
  111. return cls.FILE_FOLDER
  112. @classmethod
  113. def config(cls) -> str:
  114. """Get the config icon."""
  115. return cls.UI_CONFIG
  116. @classmethod
  117. def lock(cls) -> str:
  118. """Get the lock icon (for sensitive variables)."""
  119. return cls.UI_LOCK
  120. @classmethod
  121. def arrow_right(cls) -> str:
  122. """Get the right arrow icon (for showing transitions/changes)."""
  123. return cls.UI_ARROW_RIGHT
  124. class DisplayManager:
  125. """Handles all rich rendering for the CLI.
  126. This class is responsible for ALL display output in the CLI, including:
  127. - Status messages (success, error, warning, info)
  128. - Tables (templates, summaries, results)
  129. - Trees (file structures, configurations)
  130. - Confirmation dialogs and prompts
  131. - Headers and sections
  132. Design Principles:
  133. - All display logic should go through DisplayManager methods
  134. - IconManager is ONLY used internally by DisplayManager
  135. - External code should never directly call IconManager or console.print
  136. - Consistent formatting across all display types
  137. """
  138. def __init__(self, quiet: bool = False):
  139. """Initialize DisplayManager.
  140. Args:
  141. quiet: If True, suppress all non-error output
  142. """
  143. self.quiet = quiet
  144. def display_templates_table(
  145. self, templates: list, module_name: str, title: str
  146. ) -> None:
  147. """Display a table of templates with library type indicators.
  148. Args:
  149. templates: List of Template objects
  150. module_name: Name of the module
  151. title: Title for the table
  152. """
  153. if not templates:
  154. logger.info(f"No templates found for module '{module_name}'")
  155. return
  156. logger.info(f"Listing {len(templates)} templates for module '{module_name}'")
  157. table = Table(title=title)
  158. table.add_column("ID", style="bold", no_wrap=True)
  159. table.add_column("Name")
  160. table.add_column("Tags")
  161. table.add_column("Version", no_wrap=True)
  162. table.add_column("Library", no_wrap=True)
  163. for template in templates:
  164. name = template.metadata.name or "Unnamed Template"
  165. tags_list = template.metadata.tags or []
  166. tags = ", ".join(tags_list) if tags_list else "-"
  167. version = (
  168. str(template.metadata.version) if template.metadata.version else ""
  169. )
  170. # Show library with type indicator and color
  171. library_name = template.metadata.library or ""
  172. library_type = template.metadata.library_type or "git"
  173. if library_type == "static":
  174. # Static libraries: yellow/amber color with folder icon
  175. library_display = (
  176. f"[yellow]{IconManager.UI_LIBRARY_STATIC} {library_name}[/yellow]"
  177. )
  178. else:
  179. # Git libraries: blue color with git icon
  180. library_display = (
  181. f"[blue]{IconManager.UI_LIBRARY_GIT} {library_name}[/blue]"
  182. )
  183. # Display qualified ID if present (e.g., "alloy.default")
  184. display_id = template.id
  185. table.add_row(display_id, name, tags, version, library_display)
  186. console.print(table)
  187. def display_template_details(
  188. self, template: Template, template_id: str
  189. ) -> None:
  190. """Display template information panel and variables table.
  191. Args:
  192. template: Template instance to display
  193. template_id: ID of the template
  194. """
  195. self._display_template_header(template, template_id)
  196. self._display_file_tree(template)
  197. self._display_variables_table(template)
  198. def display_section_header(self, title: str, description: str | None) -> None:
  199. """Display a section header."""
  200. if description:
  201. console.print(
  202. f"\n[bold cyan]{title}[/bold cyan] [dim]- {description}[/dim]"
  203. )
  204. else:
  205. console.print(f"\n[bold cyan]{title}[/bold cyan]")
  206. console.print("─" * 40, style="dim")
  207. def display_validation_error(self, message: str) -> None:
  208. """Display a validation error message."""
  209. self.display_message("error", message)
  210. def display_message(
  211. self, level: str, message: str, context: str | None = None
  212. ) -> None:
  213. """Display a message with consistent formatting.
  214. Args:
  215. level: Message level (error, warning, success, info)
  216. message: The message to display
  217. context: Optional context information
  218. """
  219. # Errors and warnings always go to stderr, even in quiet mode
  220. # Success and info respect quiet mode and go to stdout
  221. if level in ("error", "warning"):
  222. output_console = console_err
  223. should_print = True
  224. else:
  225. output_console = console
  226. should_print = not self.quiet
  227. if not should_print:
  228. return
  229. icon = IconManager.get_status_icon(level)
  230. colors = {
  231. "error": "red",
  232. "warning": "yellow",
  233. "success": "green",
  234. "info": "blue",
  235. }
  236. color = colors.get(level, "white")
  237. # Format message based on context
  238. if context:
  239. text = (
  240. f"{level.capitalize()} in {context}: {message}"
  241. if level == "error" or level == "warning"
  242. else f"{context}: {message}"
  243. )
  244. else:
  245. text = (
  246. f"{level.capitalize()}: {message}"
  247. if level == "error" or level == "warning"
  248. else message
  249. )
  250. output_console.print(f"[{color}]{icon} {text}[/{color}]")
  251. # Log appropriately
  252. log_message = f"{context}: {message}" if context else message
  253. log_methods = {
  254. "error": logger.error,
  255. "warning": logger.warning,
  256. "success": logger.info,
  257. "info": logger.info,
  258. }
  259. log_methods.get(level, logger.info)(log_message)
  260. def display_error(self, message: str, context: str | None = None) -> None:
  261. """Display an error message."""
  262. self.display_message("error", message, context)
  263. def display_warning(self, message: str, context: str | None = None) -> None:
  264. """Display a warning message."""
  265. self.display_message("warning", message, context)
  266. def display_success(self, message: str, context: str | None = None) -> None:
  267. """Display a success message."""
  268. self.display_message("success", message, context)
  269. def display_info(self, message: str, context: str | None = None) -> None:
  270. """Display an informational message."""
  271. self.display_message("info", message, context)
  272. def display_version_incompatibility(
  273. self, template_id: str, required_version: str, current_version: str
  274. ) -> None:
  275. """Display a version incompatibility error with upgrade instructions.
  276. Args:
  277. template_id: ID of the incompatible template
  278. required_version: Minimum CLI version required by template
  279. current_version: Current CLI version
  280. """
  281. console_err.print()
  282. console_err.print(
  283. f"[bold red]{IconManager.STATUS_ERROR} Version Incompatibility[/bold red]"
  284. )
  285. console_err.print()
  286. console_err.print(
  287. f"Template '[cyan]{template_id}[/cyan]' requires CLI version [green]{required_version}[/green] or higher."
  288. )
  289. console_err.print(f"Current CLI version: [yellow]{current_version}[/yellow]")
  290. console_err.print()
  291. console_err.print("[bold]Upgrade Instructions:[/bold]")
  292. console_err.print(
  293. f" {IconManager.UI_ARROW_RIGHT} Run: [cyan]pip install --upgrade boilerplates[/cyan]"
  294. )
  295. console_err.print(
  296. f" {IconManager.UI_ARROW_RIGHT} Or install specific version: [cyan]pip install boilerplates=={required_version}[/cyan]"
  297. )
  298. console_err.print()
  299. logger.error(
  300. f"Template '{template_id}' requires CLI version {required_version}, "
  301. f"current version is {current_version}"
  302. )
  303. def _display_template_header(self, template: Template, template_id: str) -> None:
  304. """Display the header for a template with library information."""
  305. template_name = template.metadata.name or "Unnamed Template"
  306. version = (
  307. str(template.metadata.version)
  308. if template.metadata.version
  309. else "Not specified"
  310. )
  311. description = template.metadata.description or "No description available"
  312. # Get library information
  313. library_name = template.metadata.library or ""
  314. library_type = template.metadata.library_type or "git"
  315. # Format library display with icon and color
  316. if library_type == "static":
  317. library_display = (
  318. f"[yellow]{IconManager.UI_LIBRARY_STATIC} {library_name}[/yellow]"
  319. )
  320. else:
  321. library_display = (
  322. f"[blue]{IconManager.UI_LIBRARY_GIT} {library_name}[/blue]"
  323. )
  324. console.print(
  325. f"[bold blue]{template_name} ({template_id} - [cyan]{version}[/cyan]) {library_display}[/bold blue]"
  326. )
  327. console.print(description)
  328. def _build_file_tree(
  329. self, root_label: str, files: list, get_file_info: callable
  330. ) -> Tree:
  331. """Build a file tree structure.
  332. Args:
  333. root_label: Label for root node
  334. files: List of files to display
  335. get_file_info: Function that takes a file and returns (path, display_name, color, extra_text)
  336. Returns:
  337. Tree object ready for display
  338. """
  339. file_tree = Tree(root_label)
  340. tree_nodes = {Path("."): file_tree}
  341. for file_item in sorted(files, key=lambda f: get_file_info(f)[0]):
  342. path, display_name, color, extra_text = get_file_info(file_item)
  343. parts = path.parts
  344. current_path = Path(".")
  345. current_node = file_tree
  346. # Build directory structure
  347. for part in parts[:-1]:
  348. current_path = current_path / part
  349. if current_path not in tree_nodes:
  350. new_node = current_node.add(
  351. f"{IconManager.folder()} [white]{part}[/white]"
  352. )
  353. tree_nodes[current_path] = new_node
  354. current_node = tree_nodes[current_path]
  355. # Add file
  356. icon = IconManager.get_file_icon(display_name)
  357. file_label = f"{icon} [{color}]{display_name}[/{color}]"
  358. if extra_text:
  359. file_label += f" {extra_text}"
  360. current_node.add(file_label)
  361. return file_tree
  362. def _display_file_tree(self, template: Template) -> None:
  363. """Display the file structure of a template."""
  364. console.print()
  365. console.print("[bold blue]Template File Structure:[/bold blue]")
  366. def get_template_file_info(template_file):
  367. display_name = (
  368. template_file.output_path.name
  369. if hasattr(template_file, "output_path")
  370. else template_file.relative_path.name
  371. )
  372. return (template_file.relative_path, display_name, "white", None)
  373. file_tree = self._build_file_tree(
  374. f"{IconManager.folder()} [white]{template.id}[/white]",
  375. template.template_files,
  376. get_template_file_info,
  377. )
  378. if file_tree.children:
  379. console.print(file_tree)
  380. def _display_variables_table(
  381. self, template: Template
  382. ) -> None:
  383. """Display a table of variables for a template.
  384. All variables and sections are always shown. Disabled sections/variables
  385. are displayed with dimmed styling.
  386. Args:
  387. template: Template instance
  388. """
  389. if not (template.variables and template.variables.has_sections()):
  390. return
  391. console.print()
  392. console.print("[bold blue]Template Variables:[/bold blue]")
  393. variables_table = Table(show_header=True, header_style="bold blue")
  394. variables_table.add_column("Variable", style="white", no_wrap=True)
  395. variables_table.add_column("Type", style="magenta")
  396. variables_table.add_column("Default", style="green")
  397. variables_table.add_column("Description", style="white")
  398. first_section = True
  399. for section in template.variables.get_sections().values():
  400. if not section.variables:
  401. continue
  402. if not first_section:
  403. variables_table.add_row("", "", "", "", style="bright_black")
  404. first_section = False
  405. # Check if section is enabled AND dependencies are satisfied
  406. is_enabled = section.is_enabled()
  407. dependencies_satisfied = template.variables.is_section_satisfied(
  408. section.key
  409. )
  410. is_dimmed = not (is_enabled and dependencies_satisfied)
  411. # Only show (disabled) if section has no dependencies (dependencies make it obvious)
  412. # Empty list means no dependencies (same as None)
  413. has_dependencies = section.needs and len(section.needs) > 0
  414. disabled_text = (
  415. " (disabled)" if (is_dimmed and not has_dependencies) else ""
  416. )
  417. # For disabled sections, make entire heading bold and dim (don't include colored markup inside)
  418. if is_dimmed:
  419. # Build text without internal markup, then wrap entire thing in bold bright_black (dimmed appearance)
  420. required_part = " (required)" if section.required else ""
  421. header_text = f"[bold bright_black]{section.title}{required_part}{disabled_text}[/bold bright_black]"
  422. else:
  423. # For enabled sections, include the colored markup
  424. required_text = (
  425. " [yellow](required)[/yellow]" if section.required else ""
  426. )
  427. header_text = (
  428. f"[bold]{section.title}{required_text}{disabled_text}[/bold]"
  429. )
  430. variables_table.add_row(header_text, "", "", "")
  431. for var_name, variable in section.variables.items():
  432. # Skip toggle variable in required sections (always enabled, no need to show)
  433. if section.required and section.toggle and var_name == section.toggle:
  434. continue
  435. # Check if variable's needs are satisfied
  436. var_satisfied = template.variables.is_variable_satisfied(var_name)
  437. # Dim the variable if section is dimmed OR variable needs are not satisfied
  438. row_style = "bright_black" if (is_dimmed or not var_satisfied) else None
  439. # Build default value display
  440. # Special case: disabled bool variables show as "original → False"
  441. if (is_dimmed or not var_satisfied) and variable.type == "bool":
  442. # Show that disabled bool variables are forced to False
  443. if hasattr(variable, "_original_disabled") and variable._original_disabled is not False:
  444. orig_val = str(variable._original_disabled)
  445. default_val = f"{orig_val} {IconManager.arrow_right()} False"
  446. else:
  447. default_val = "False"
  448. # If origin is 'config' and original value differs from current, show: original → config_value
  449. # BUT only for enabled variables (don't show arrow for disabled ones)
  450. elif (
  451. not (is_dimmed or not var_satisfied)
  452. and variable.origin == "config"
  453. and hasattr(variable, "_original_stored")
  454. and variable.original_value != variable.value
  455. ):
  456. # Format original value (use same display logic, but shorter)
  457. if variable.sensitive:
  458. orig_display = "********"
  459. elif (
  460. variable.original_value is None or variable.original_value == ""
  461. ):
  462. orig_display = "[dim](none)[/dim]"
  463. else:
  464. orig_val_str = str(variable.original_value)
  465. orig_display = (
  466. orig_val_str[:15] + "..."
  467. if len(orig_val_str) > 15
  468. else orig_val_str
  469. )
  470. # Get current (config) value display (without showing "(none)" since we have the arrow)
  471. config_display = variable.get_display_value(
  472. mask_sensitive=True, max_length=15, show_none=False
  473. )
  474. if (
  475. not config_display
  476. ): # If still empty after show_none=False, show actual value
  477. config_display = (
  478. str(variable.value) if variable.value else "(empty)"
  479. )
  480. # Highlight the arrow and config value in bold yellow to show it's a custom override
  481. default_val = f"{orig_display} [bold yellow]{IconManager.arrow_right()} {config_display}[/bold yellow]"
  482. else:
  483. # Use variable's native get_display_value() method (shows "(none)" for empty)
  484. default_val = variable.get_display_value(
  485. mask_sensitive=True, max_length=30, show_none=True
  486. )
  487. # Add lock icon for sensitive variables
  488. sensitive_icon = f" {IconManager.lock()}" if variable.sensitive else ""
  489. # Add required indicator for required variables
  490. required_indicator = (
  491. " [yellow](required)[/yellow]" if variable.required else ""
  492. )
  493. var_display = f" {var_name}{sensitive_icon}{required_indicator}"
  494. variables_table.add_row(
  495. var_display,
  496. variable.type or "str",
  497. default_val,
  498. variable.description or "",
  499. style=row_style,
  500. )
  501. console.print(variables_table)
  502. def display_file_generation_confirmation(
  503. self,
  504. output_dir: Path,
  505. files: dict[str, str],
  506. existing_files: list[Path] | None = None,
  507. ) -> None:
  508. """Display files to be generated with confirmation prompt."""
  509. console.print()
  510. console.print("[bold]Files to be generated:[/bold]")
  511. def get_file_generation_info(file_path_str):
  512. file_path = Path(file_path_str)
  513. file_name = file_path.parts[-1] if file_path.parts else file_path.name
  514. full_path = output_dir / file_path
  515. if existing_files and full_path in existing_files:
  516. return (file_path, file_name, "yellow", "[red](will overwrite)[/red]")
  517. else:
  518. return (file_path, file_name, "green", None)
  519. file_tree = self._build_file_tree(
  520. f"{IconManager.folder()} [cyan]{output_dir.resolve()}[/cyan]",
  521. files.keys(),
  522. get_file_generation_info,
  523. )
  524. console.print(file_tree)
  525. console.print()
  526. def display_config_tree(
  527. self, spec: dict, module_name: str, show_all: bool = False
  528. ) -> None:
  529. """Display configuration spec as a tree view.
  530. Args:
  531. spec: The configuration spec dictionary
  532. module_name: Name of the module
  533. show_all: If True, show all details including descriptions
  534. """
  535. if not spec:
  536. console.print(
  537. f"[yellow]No configuration found for module '{module_name}'[/yellow]"
  538. )
  539. return
  540. # Create root tree node
  541. tree = Tree(
  542. f"[bold blue]{IconManager.config()} {str.capitalize(module_name)} Configuration[/bold blue]"
  543. )
  544. for section_name, section_data in spec.items():
  545. if not isinstance(section_data, dict):
  546. continue
  547. # Determine if this is a section with variables
  548. # Guard against None from empty YAML sections
  549. section_vars = section_data.get("vars") or {}
  550. section_desc = section_data.get("description", "")
  551. section_required = section_data.get("required", False)
  552. section_toggle = section_data.get("toggle", None)
  553. section_needs = section_data.get("needs", None)
  554. # Build section label
  555. section_label = f"[cyan]{section_name}[/cyan]"
  556. if section_required:
  557. section_label += " [yellow](required)[/yellow]"
  558. if section_toggle:
  559. section_label += f" [dim](toggle: {section_toggle})[/dim]"
  560. if section_needs:
  561. needs_str = (
  562. ", ".join(section_needs)
  563. if isinstance(section_needs, list)
  564. else section_needs
  565. )
  566. section_label += f" [dim](needs: {needs_str})[/dim]"
  567. if show_all and section_desc:
  568. section_label += f"\n [dim]{section_desc}[/dim]"
  569. section_node = tree.add(section_label)
  570. # Add variables
  571. if section_vars:
  572. for var_name, var_data in section_vars.items():
  573. if isinstance(var_data, dict):
  574. var_type = var_data.get("type", "string")
  575. var_default = var_data.get("default", "")
  576. var_desc = var_data.get("description", "")
  577. var_sensitive = var_data.get("sensitive", False)
  578. # Build variable label
  579. var_label = f"[green]{var_name}[/green] [dim]({var_type})[/dim]"
  580. if var_default is not None and var_default != "":
  581. display_val = (
  582. "********" if var_sensitive else str(var_default)
  583. )
  584. if not var_sensitive and len(display_val) > 30:
  585. display_val = display_val[:27] + "..."
  586. var_label += f" = [yellow]{display_val}[/yellow]"
  587. if show_all and var_desc:
  588. var_label += f"\n [dim]{var_desc}[/dim]"
  589. section_node.add(var_label)
  590. else:
  591. # Simple key-value pair
  592. section_node.add(
  593. f"[green]{var_name}[/green] = [yellow]{var_data}[/yellow]"
  594. )
  595. console.print(tree)
  596. def display_next_steps(self, next_steps: str, variable_values: dict) -> None:
  597. """Display next steps after template generation, rendering them as a Jinja2 template.
  598. Args:
  599. next_steps: The next_steps string from template metadata (may contain Jinja2 syntax)
  600. variable_values: Dictionary of variable values to use for rendering
  601. """
  602. if not next_steps:
  603. return
  604. console.print("\n[bold cyan]Next Steps:[/bold cyan]")
  605. try:
  606. from jinja2 import Template as Jinja2Template
  607. next_steps_template = Jinja2Template(next_steps)
  608. rendered_next_steps = next_steps_template.render(variable_values)
  609. console.print(rendered_next_steps)
  610. except Exception as e:
  611. logger.warning(f"Failed to render next_steps as template: {e}")
  612. # Fallback to plain text if rendering fails
  613. console.print(next_steps)
  614. def display_status_table(
  615. self,
  616. title: str,
  617. rows: list[tuple[str, str, bool]],
  618. columns: tuple[str, str] = ("Item", "Status"),
  619. ) -> None:
  620. """Display a status table with success/error indicators.
  621. Args:
  622. title: Table title
  623. rows: List of tuples (name, message, success_bool)
  624. columns: Column headers (name_header, status_header)
  625. """
  626. table = Table(title=title, show_header=True)
  627. table.add_column(columns[0], style="cyan", no_wrap=True)
  628. table.add_column(columns[1])
  629. for name, message, success in rows:
  630. status_style = "green" if success else "red"
  631. status_icon = IconManager.get_status_icon("success" if success else "error")
  632. table.add_row(
  633. name, f"[{status_style}]{status_icon} {message}[/{status_style}]"
  634. )
  635. console.print(table)
  636. def display_summary_table(self, title: str, items: dict[str, str]) -> None:
  637. """Display a simple two-column summary table.
  638. Args:
  639. title: Table title
  640. items: Dictionary of key-value pairs to display
  641. """
  642. table = Table(title=title, show_header=False, box=None, padding=(0, 2))
  643. table.add_column(style="bold")
  644. table.add_column()
  645. for key, value in items.items():
  646. table.add_row(key, value)
  647. console.print(table)
  648. def display_file_operation_table(self, files: list[tuple[str, int, str]]) -> None:
  649. """Display a table of file operations with sizes and statuses.
  650. Args:
  651. files: List of tuples (file_path, size_bytes, status)
  652. """
  653. table = Table(
  654. show_header=True, header_style="bold cyan", box=None, padding=(0, 1)
  655. )
  656. table.add_column("File", style="white", no_wrap=False)
  657. table.add_column("Size", justify="right", style="dim")
  658. table.add_column("Status", style="yellow")
  659. for file_path, size_bytes, status in files:
  660. # Format size
  661. if size_bytes < 1024:
  662. size_str = f"{size_bytes}B"
  663. elif size_bytes < 1024 * 1024:
  664. size_str = f"{size_bytes / 1024:.1f}KB"
  665. else:
  666. size_str = f"{size_bytes / (1024 * 1024):.1f}MB"
  667. table.add_row(str(file_path), size_str, status)
  668. console.print(table)
  669. def display_heading(
  670. self, text: str, icon_type: str | None = None, style: str = "bold"
  671. ) -> None:
  672. """Display a heading with optional icon.
  673. Args:
  674. text: Heading text
  675. icon_type: Type of icon to display (e.g., 'folder', 'file', 'config')
  676. style: Rich style to apply
  677. """
  678. if icon_type:
  679. icon = self._get_icon_by_type(icon_type)
  680. console.print(f"[{style}]{icon} {text}[/{style}]")
  681. else:
  682. console.print(f"[{style}]{text}[/{style}]")
  683. def display_warning_with_confirmation(
  684. self, message: str, details: list[str] | None = None, default: bool = False
  685. ) -> bool:
  686. """Display a warning message with optional details and get confirmation.
  687. Args:
  688. message: Warning message to display
  689. details: Optional list of detail lines to show
  690. default: Default value for confirmation
  691. Returns:
  692. True if user confirms, False otherwise
  693. """
  694. icon = IconManager.get_status_icon("warning")
  695. console.print(f"\n[yellow]{icon} {message}[/yellow]")
  696. if details:
  697. for detail in details:
  698. console.print(f"[yellow] {detail}[/yellow]")
  699. from rich.prompt import Confirm
  700. return Confirm.ask("Continue?", default=default)
  701. def display_skipped(self, message: str, reason: str | None = None) -> None:
  702. """Display a skipped/disabled message.
  703. Args:
  704. message: The main message to display
  705. reason: Optional reason why it was skipped
  706. """
  707. icon = IconManager.get_status_icon("skipped")
  708. if reason:
  709. console.print(f"\n[dim]{icon} {message} (skipped - {reason})[/dim]")
  710. else:
  711. console.print(f"\n[dim]{icon} {message} (skipped)[/dim]")
  712. def get_lock_icon(self) -> str:
  713. """Get the lock icon for sensitive variables.
  714. Returns:
  715. Lock icon unicode character
  716. """
  717. return IconManager.lock()
  718. def _get_icon_by_type(self, icon_type: str) -> str:
  719. """Get icon by semantic type name.
  720. Args:
  721. icon_type: Type of icon (e.g., 'folder', 'file', 'config', 'lock')
  722. Returns:
  723. Icon unicode character
  724. """
  725. icon_map = {
  726. "folder": IconManager.folder(),
  727. "file": IconManager.FILE_DEFAULT,
  728. "config": IconManager.config(),
  729. "lock": IconManager.lock(),
  730. "arrow": IconManager.arrow_right(),
  731. }
  732. return icon_map.get(icon_type, "")
  733. def display_template_render_error(
  734. self, error: "TemplateRenderError", context: str | None = None
  735. ) -> None:
  736. """Display a detailed template rendering error with context and suggestions.
  737. Args:
  738. error: TemplateRenderError exception with detailed error information
  739. context: Optional context information (e.g., template ID)
  740. """
  741. from rich.panel import Panel
  742. from rich.syntax import Syntax
  743. # Always display errors to stderr
  744. # Display main error header
  745. icon = IconManager.get_status_icon("error")
  746. if context:
  747. console_err.print(
  748. f"\n[red bold]{icon} Template Rendering Error[/red bold] [dim]({context})[/dim]"
  749. )
  750. else:
  751. console_err.print(f"\n[red bold]{icon} Template Rendering Error[/red bold]")
  752. console_err.print()
  753. # Display error message
  754. if error.file_path:
  755. console_err.print(
  756. f"[red]Error in file:[/red] [cyan]{error.file_path}[/cyan]"
  757. )
  758. if error.line_number:
  759. location = f"Line {error.line_number}"
  760. if error.column:
  761. location += f", Column {error.column}"
  762. console_err.print(f"[red]Location:[/red] {location}")
  763. console_err.print(
  764. f"[red]Message:[/red] {str(error.original_error) if error.original_error else str(error)}"
  765. )
  766. console_err.print()
  767. # Display code context if available
  768. if error.context_lines:
  769. console_err.print("[bold cyan]Code Context:[/bold cyan]")
  770. # Build the context text
  771. context_text = "\n".join(error.context_lines)
  772. # Display in a panel with syntax highlighting if possible
  773. file_ext = Path(error.file_path).suffix if error.file_path else ""
  774. if file_ext == ".j2":
  775. # Remove .j2 to get base extension for syntax highlighting
  776. base_name = Path(error.file_path).stem
  777. base_ext = Path(base_name).suffix
  778. lexer = "jinja2" if not base_ext else None
  779. else:
  780. lexer = None
  781. try:
  782. if lexer:
  783. syntax = Syntax(
  784. context_text, lexer, line_numbers=False, theme="monokai"
  785. )
  786. console_err.print(Panel(syntax, border_style="red", padding=(1, 2)))
  787. else:
  788. console_err.print(
  789. Panel(context_text, border_style="red", padding=(1, 2))
  790. )
  791. except Exception:
  792. # Fallback to plain panel if syntax highlighting fails
  793. console_err.print(
  794. Panel(context_text, border_style="red", padding=(1, 2))
  795. )
  796. console_err.print()
  797. # Display suggestions if available
  798. if error.suggestions:
  799. console_err.print("[bold yellow]Suggestions:[/bold yellow]")
  800. for i, suggestion in enumerate(error.suggestions, 1):
  801. bullet = IconManager.UI_BULLET
  802. console_err.print(f" [yellow]{bullet}[/yellow] {suggestion}")
  803. console_err.print()
  804. # Display variable context in debug mode
  805. if error.variable_context:
  806. console_err.print("[bold blue]Available Variables (Debug):[/bold blue]")
  807. var_list = ", ".join(sorted(error.variable_context.keys()))
  808. console_err.print(f"[dim]{var_list}[/dim]")
  809. console_err.print()