__main__.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. import click
  13. from rich.console import Console
  14. from typer import Option, Typer
  15. from typer.core import TyperGroup
  16. import cli.modules
  17. from cli import __version__
  18. from cli.core import repo
  19. from cli.core.display import DisplayManager
  20. from cli.core.registry import registry
  21. class OrderedGroup(TyperGroup):
  22. """Typer Group that lists commands in alphabetical order."""
  23. def list_commands(self, ctx: click.Context) -> list[str]:
  24. return sorted(super().list_commands(ctx))
  25. app = Typer(
  26. help=(
  27. "CLI tool for managing infrastructure boilerplates.\n\n"
  28. "[dim]Easily generate, customize, and deploy templates for Docker Compose, "
  29. "Terraform, Kubernetes, and more.\n\n "
  30. "[white]Made with 💜 by [bold]Christian Lempa[/bold]"
  31. ),
  32. add_completion=True,
  33. rich_markup_mode="rich",
  34. pretty_exceptions_enable=False,
  35. no_args_is_help=True,
  36. cls=OrderedGroup,
  37. )
  38. console = Console()
  39. display = DisplayManager()
  40. def setup_logging(log_level: str = "WARNING") -> None:
  41. """Configure the logging system with the specified log level.
  42. Args:
  43. log_level: The logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  44. Raises:
  45. ValueError: If the log level is invalid
  46. RuntimeError: If logging configuration fails
  47. """
  48. numeric_level = getattr(logging, log_level.upper(), None)
  49. if not isinstance(numeric_level, int):
  50. raise ValueError(f"Invalid log level '{log_level}'. Valid levels: DEBUG, INFO, WARNING, ERROR, CRITICAL")
  51. try:
  52. logging.basicConfig(
  53. level=numeric_level,
  54. format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  55. datefmt="%Y-%m-%d %H:%M:%S",
  56. )
  57. logger = logging.getLogger(__name__)
  58. logger.setLevel(numeric_level)
  59. except Exception as e:
  60. raise RuntimeError(f"Failed to configure logging: {e}") from e
  61. @app.callback(invoke_without_command=True)
  62. def main(
  63. _version: bool | None = Option(
  64. None,
  65. "--version",
  66. "-v",
  67. help="Show the application version and exit.",
  68. is_flag=True,
  69. callback=lambda v: console.print(f"boilerplates version {__version__}") or sys.exit(0) if v else None,
  70. is_eager=True,
  71. ),
  72. log_level: str | None = Option(
  73. None,
  74. "--log-level",
  75. help=("Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL). If omitted, logging is disabled."),
  76. ),
  77. ) -> None:
  78. """CLI tool for managing infrastructure boilerplates."""
  79. # Disable logging by default; only enable when user provides --log-level
  80. if log_level:
  81. # Re-enable logging and configure
  82. logging.disable(logging.NOTSET)
  83. setup_logging(log_level)
  84. else:
  85. # Silence all logging (including third-party) unless user explicitly requests it
  86. logging.disable(logging.CRITICAL)
  87. # Get context without type annotation (compatible with all Typer versions)
  88. ctx = click.get_current_context()
  89. # Store log level in context for potential use by other commands
  90. ctx.ensure_object(dict)
  91. ctx.obj["log_level"] = log_level
  92. # If no subcommand is provided, show help and friendly intro
  93. if ctx.invoked_subcommand is None:
  94. console.print(ctx.get_help())
  95. sys.exit(0)
  96. def _import_modules(modules_path: Path, logger: logging.Logger) -> list[str]:
  97. """Import all modules and return list of failures."""
  98. failed_imports = []
  99. for _finder, name, ispkg in pkgutil.iter_modules([str(modules_path)]):
  100. if not name.startswith("_") and name != "base":
  101. try:
  102. logger.debug(f"Importing module: {name} ({'package' if ispkg else 'file'})")
  103. importlib.import_module(f"cli.modules.{name}")
  104. except ImportError as e:
  105. error_info = f"Import failed for '{name}': {e!s}"
  106. failed_imports.append(error_info)
  107. logger.warning(error_info)
  108. except Exception as e:
  109. error_info = f"Unexpected error importing '{name}': {e!s}"
  110. failed_imports.append(error_info)
  111. logger.error(error_info)
  112. return failed_imports
  113. def _register_repo_command(logger: logging.Logger) -> list[str]:
  114. """Register repo command and return list of failures."""
  115. failed = []
  116. try:
  117. logger.debug("Registering repo command")
  118. repo.register_cli(app)
  119. except Exception as e:
  120. error_info = f"Repo command registration failed: {e!s}"
  121. failed.append(error_info)
  122. logger.warning(error_info)
  123. return failed
  124. def _register_module_classes(logger: logging.Logger) -> tuple[list, list[str]]:
  125. """Register template-based modules and return (module_classes, failures)."""
  126. failed_registrations = []
  127. module_classes = list(registry.iter_module_classes())
  128. logger.debug(f"Registering {len(module_classes)} template-based modules")
  129. for _name, module_cls in module_classes:
  130. try:
  131. logger.debug(f"Registering module class: {module_cls.__name__}")
  132. module_cls.register_cli(app)
  133. except Exception as e:
  134. error_info = f"Registration failed for '{module_cls.__name__}': {e!s}"
  135. failed_registrations.append(error_info)
  136. logger.warning(error_info)
  137. display.warning(error_info)
  138. return module_classes, failed_registrations
  139. def _build_error_details(failed_imports: list[str], failed_registrations: list[str]) -> str:
  140. """Build detailed error message from failures."""
  141. error_details = []
  142. if failed_imports:
  143. error_details.extend(["Import failures:"] + [f" - {err}" for err in failed_imports])
  144. if failed_registrations:
  145. error_details.extend(["Registration failures:"] + [f" - {err}" for err in failed_registrations])
  146. return "\n".join(error_details) if error_details else ""
  147. def init_app() -> None:
  148. """Initialize the application by discovering and registering modules.
  149. Raises:
  150. ImportError: If critical module import operations fail
  151. RuntimeError: If application initialization fails
  152. """
  153. logger = logging.getLogger(__name__)
  154. failed_imports = []
  155. failed_registrations = []
  156. try:
  157. # Auto-discover and import all modules
  158. modules_path = Path(cli.modules.__file__).parent
  159. logger.debug(f"Discovering modules in {modules_path}")
  160. failed_imports = _import_modules(modules_path, logger)
  161. # Register core repo command
  162. repo_failures = _register_repo_command(logger)
  163. # Register template-based modules
  164. module_classes, failed_registrations = _register_module_classes(logger)
  165. failed_registrations.extend(repo_failures)
  166. # Validate we have modules
  167. if not module_classes and not failed_imports:
  168. raise RuntimeError("No modules found to register")
  169. # Log summary
  170. successful_modules = len(module_classes) - len(failed_registrations)
  171. logger.info(f"Application initialized: {successful_modules} modules registered successfully")
  172. if failed_imports:
  173. logger.info(f"Module import failures: {len(failed_imports)}")
  174. if failed_registrations:
  175. logger.info(f"Module registration failures: {len(failed_registrations)}")
  176. except Exception as e:
  177. details = _build_error_details(failed_imports, failed_registrations) or str(e)
  178. raise RuntimeError(f"Application initialization failed: {details}") from e
  179. def run() -> None:
  180. """Run the CLI application."""
  181. # Configure logging early if --log-level is provided
  182. if "--log-level" in sys.argv:
  183. try:
  184. log_level_index = sys.argv.index("--log-level") + 1
  185. if log_level_index < len(sys.argv):
  186. log_level = sys.argv[log_level_index]
  187. logging.disable(logging.NOTSET)
  188. setup_logging(log_level)
  189. except (ValueError, IndexError):
  190. pass # Let Typer handle argument parsing errors
  191. try:
  192. init_app()
  193. app()
  194. except (ValueError, RuntimeError) as e:
  195. # Handle configuration and initialization errors cleanly
  196. display.error(str(e))
  197. sys.exit(1)
  198. except ImportError as e:
  199. # Handle module import errors with detailed info
  200. display.error(f"Module Import Error: {e}")
  201. sys.exit(1)
  202. except KeyboardInterrupt:
  203. # Handle Ctrl+C gracefully
  204. display.warning("Operation cancelled by user")
  205. sys.exit(130)
  206. except Exception as e:
  207. # Handle unexpected errors - show simplified message
  208. display.error(str(e))
  209. display.info("Use --log-level DEBUG for more details")
  210. sys.exit(1)
  211. if __name__ == "__main__":
  212. run()