render.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. Core rendering functionality for handling template output and display.
  3. Provides consistent rendering and output handling across different module types.
  4. """
  5. import logging
  6. from pathlib import Path
  7. from typing import Optional, Union
  8. from rich.console import Console
  9. from rich.syntax import Syntax
  10. logger = logging.getLogger(__name__)
  11. class RenderOutput:
  12. """Handles the output of rendered templates."""
  13. def __init__(self, console: Optional[Console] = None):
  14. self.console = console or Console()
  15. def write_to_file(self, content: str, output_path: Path) -> None:
  16. """
  17. Write rendered content to a file.
  18. Args:
  19. content: Content to write
  20. output_path: Path to write the content to
  21. Raises:
  22. Exception: If writing fails
  23. """
  24. try:
  25. # Ensure parent directory exists
  26. output_parent = output_path.parent
  27. if not output_parent.exists():
  28. output_parent.mkdir(parents=True, exist_ok=True)
  29. output_path.write_text(content, encoding="utf-8")
  30. self.console.print(f"[green]Rendered content written to {output_path}[/green]")
  31. except Exception as e:
  32. raise Exception(f"Failed to write output to {output_path}: {e}")
  33. def print_to_console(self, content: str, syntax: str = "yaml",
  34. template_name: Optional[str] = None) -> None:
  35. """
  36. Print rendered content to the console with syntax highlighting.
  37. Args:
  38. content: Content to print
  39. syntax: Syntax highlighting to use (default: yaml)
  40. template_name: Optional template name to show in header
  41. """
  42. if template_name:
  43. self.console.print(f"\n\nGenerated Content for [bold cyan]{template_name}[/bold cyan]\n")
  44. syntax_output = Syntax(
  45. content,
  46. syntax,
  47. theme="monokai",
  48. line_numbers=False,
  49. word_wrap=True
  50. )
  51. self.console.print(syntax_output)
  52. def output_rendered_content(self, content: str, output_target: Optional[Union[str, Path]],
  53. syntax: str = "yaml", template_name: Optional[str] = None) -> None:
  54. """
  55. Output rendered content either to a file or console.
  56. Args:
  57. content: Content to output
  58. output_target: Path to output file or None for console output
  59. syntax: Syntax highlighting to use for console output
  60. template_name: Optional template name for console output header
  61. Raises:
  62. Exception: If writing to file fails
  63. """
  64. if output_target:
  65. if isinstance(output_target, str):
  66. output_target = Path(output_target)
  67. self.write_to_file(content, output_target)
  68. else:
  69. self.print_to_console(content, syntax, template_name)