display.py 32 KB

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