__main__.py 7.0 KB

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