__main__.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #!/usr/bin/env python3
  2. """
  3. Main entry point for the Boilerplates CLI application.
  4. This file serves as the primary executable when running the CLI.
  5. """
  6. from __future__ import annotations
  7. import importlib
  8. import logging
  9. import pkgutil
  10. import sys
  11. from pathlib import Path
  12. from typing import Optional
  13. from typer import Typer, Option
  14. from rich.console import Console
  15. import cli.modules
  16. from cli.core.registry import registry
  17. from cli.core import repo
  18. from cli import __version__
  19. # Using standard Python exceptions instead of custom ones
  20. app = Typer(
  21. help="CLI tool for managing infrastructure boilerplates.\n\n[dim]Easily generate, customize, and deploy templates for Docker Compose, Terraform, Kubernetes, and more.\n\n [white]Made with 💜 by [bold]Christian Lempa[/bold]",
  22. add_completion=True,
  23. rich_markup_mode="rich",
  24. )
  25. console = Console()
  26. def setup_logging(log_level: str = "WARNING") -> None:
  27. """Configure the logging system with the specified log level.
  28. Args:
  29. log_level: The logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  30. Raises:
  31. ValueError: If the log level is invalid
  32. RuntimeError: If logging configuration fails
  33. """
  34. numeric_level = getattr(logging, log_level.upper(), None)
  35. if not isinstance(numeric_level, int):
  36. raise ValueError(
  37. f"Invalid log level '{log_level}'. Valid levels: DEBUG, INFO, WARNING, ERROR, CRITICAL"
  38. )
  39. try:
  40. logging.basicConfig(
  41. level=numeric_level,
  42. format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  43. datefmt="%Y-%m-%d %H:%M:%S",
  44. )
  45. logger = logging.getLogger(__name__)
  46. logger.setLevel(numeric_level)
  47. except Exception as e:
  48. raise RuntimeError(f"Failed to configure logging: {e}")
  49. @app.callback(invoke_without_command=True)
  50. def main(
  51. version: Optional[bool] = Option(
  52. None,
  53. "--version",
  54. "-v",
  55. help="Show the application version and exit.",
  56. is_flag=True,
  57. callback=lambda v: console.print(f"boilerplates version {__version__}")
  58. or sys.exit(0)
  59. if v
  60. else None,
  61. is_eager=True,
  62. ),
  63. log_level: Optional[str] = Option(
  64. None,
  65. "--log-level",
  66. help="Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL). If omitted, logging is disabled.",
  67. ),
  68. ) -> None:
  69. """CLI tool for managing infrastructure boilerplates."""
  70. # Disable logging by default; only enable when user provides --log-level
  71. if log_level:
  72. # Re-enable logging and configure
  73. logging.disable(logging.NOTSET)
  74. setup_logging(log_level)
  75. else:
  76. # Silence all logging (including third-party) unless user explicitly requests it
  77. logging.disable(logging.CRITICAL)
  78. # Get context without type annotation (compatible with all Typer versions)
  79. import click
  80. ctx = click.get_current_context()
  81. # Store log level in context for potential use by other commands
  82. ctx.ensure_object(dict)
  83. ctx.obj["log_level"] = log_level
  84. # If no subcommand is provided, show help and friendly intro
  85. if ctx.invoked_subcommand is None:
  86. console.print(ctx.get_help())
  87. sys.exit(0)
  88. def init_app() -> None:
  89. """Initialize the application by discovering and registering modules.
  90. Raises:
  91. ImportError: If critical module import operations fail
  92. RuntimeError: If application initialization fails
  93. """
  94. logger = logging.getLogger(__name__)
  95. failed_imports = []
  96. failed_registrations = []
  97. try:
  98. # Auto-discover and import all modules
  99. modules_path = Path(cli.modules.__file__).parent
  100. logger.debug(f"Discovering modules in {modules_path}")
  101. for finder, name, ispkg in pkgutil.iter_modules([str(modules_path)]):
  102. # Import both module files and packages (for multi-schema modules)
  103. if not name.startswith("_") and name != "base":
  104. try:
  105. logger.debug(
  106. f"Importing module: {name} ({'package' if ispkg else 'file'})"
  107. )
  108. importlib.import_module(f"cli.modules.{name}")
  109. except ImportError as e:
  110. error_info = f"Import failed for '{name}': {str(e)}"
  111. failed_imports.append(error_info)
  112. logger.warning(error_info)
  113. except Exception as e:
  114. error_info = f"Unexpected error importing '{name}': {str(e)}"
  115. failed_imports.append(error_info)
  116. logger.error(error_info)
  117. # Register core repo command
  118. try:
  119. logger.debug("Registering repo command")
  120. repo.register_cli(app)
  121. except Exception as e:
  122. error_info = f"Repo command registration failed: {str(e)}"
  123. failed_registrations.append(error_info)
  124. logger.warning(error_info)
  125. # Register template-based modules with app
  126. module_classes = list(registry.iter_module_classes())
  127. logger.debug(f"Registering {len(module_classes)} template-based modules")
  128. for name, module_cls in module_classes:
  129. try:
  130. logger.debug(f"Registering module class: {module_cls.__name__}")
  131. module_cls.register_cli(app)
  132. except Exception as e:
  133. error_info = (
  134. f"Registration failed for '{module_cls.__name__}': {str(e)}"
  135. )
  136. failed_registrations.append(error_info)
  137. # Log warning but don't raise exception for individual module failures
  138. logger.warning(error_info)
  139. console.print(f"[yellow]Warning:[/yellow] {error_info}")
  140. # If we have no modules registered at all, that's a critical error
  141. if not module_classes and not failed_imports:
  142. raise RuntimeError("No modules found to register")
  143. # Log summary
  144. successful_modules = len(module_classes) - len(failed_registrations)
  145. logger.info(
  146. f"Application initialized: {successful_modules} modules registered successfully"
  147. )
  148. if failed_imports:
  149. logger.info(f"Module import failures: {len(failed_imports)}")
  150. if failed_registrations:
  151. logger.info(f"Module registration failures: {len(failed_registrations)}")
  152. except Exception as e:
  153. error_details = []
  154. if failed_imports:
  155. error_details.extend(
  156. ["Import failures:"] + [f" - {err}" for err in failed_imports]
  157. )
  158. if failed_registrations:
  159. error_details.extend(
  160. ["Registration failures:"]
  161. + [f" - {err}" for err in failed_registrations]
  162. )
  163. details = "\n".join(error_details) if error_details else str(e)
  164. raise RuntimeError(f"Application initialization failed: {details}")
  165. def run() -> None:
  166. """Run the CLI application."""
  167. try:
  168. init_app()
  169. app()
  170. except (ValueError, RuntimeError) as e:
  171. # Handle configuration and initialization errors cleanly
  172. console.print(f"[bold red]Error:[/bold red] {e}")
  173. sys.exit(1)
  174. except ImportError as e:
  175. # Handle module import errors with detailed info
  176. console.print(f"[bold red]Module Import Error:[/bold red] {e}")
  177. sys.exit(1)
  178. except KeyboardInterrupt:
  179. # Handle Ctrl+C gracefully
  180. console.print("\n[yellow]Operation cancelled by user[/yellow]")
  181. sys.exit(130)
  182. except Exception as e:
  183. # Handle unexpected errors - show simplified message
  184. console.print(f"[bold red]Unexpected error:[/bold red] {e}")
  185. console.print("[dim]Use --log-level DEBUG for more details[/dim]")
  186. sys.exit(1)
  187. if __name__ == "__main__":
  188. run()