__main__.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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="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]",
  27. add_completion=True,
  28. rich_markup_mode="rich",
  29. pretty_exceptions_enable=False,
  30. no_args_is_help=True,
  31. cls=OrderedGroup,
  32. )
  33. console = Console()
  34. display = DisplayManager()
  35. def setup_logging(log_level: str = "WARNING") -> None:
  36. """Configure the logging system with the specified log level.
  37. Args:
  38. log_level: The logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  39. Raises:
  40. ValueError: If the log level is invalid
  41. RuntimeError: If logging configuration fails
  42. """
  43. numeric_level = getattr(logging, log_level.upper(), None)
  44. if not isinstance(numeric_level, int):
  45. raise ValueError(
  46. f"Invalid log level '{log_level}'. Valid levels: DEBUG, INFO, WARNING, ERROR, CRITICAL"
  47. )
  48. try:
  49. logging.basicConfig(
  50. level=numeric_level,
  51. format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  52. datefmt="%Y-%m-%d %H:%M:%S",
  53. )
  54. logger = logging.getLogger(__name__)
  55. logger.setLevel(numeric_level)
  56. except Exception as e:
  57. raise RuntimeError(f"Failed to configure logging: {e}") from e
  58. @app.callback(invoke_without_command=True)
  59. def main(
  60. version: bool | None = Option(
  61. None,
  62. "--version",
  63. "-v",
  64. help="Show the application version and exit.",
  65. is_flag=True,
  66. callback=lambda v: console.print(f"boilerplates version {__version__}")
  67. or sys.exit(0)
  68. if v
  69. 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(
  103. f"Importing module: {name} ({'package' if ispkg else 'file'})"
  104. )
  105. importlib.import_module(f"cli.modules.{name}")
  106. except ImportError as e:
  107. error_info = f"Import failed for '{name}': {e!s}"
  108. failed_imports.append(error_info)
  109. logger.warning(error_info)
  110. except Exception as e:
  111. error_info = f"Unexpected error importing '{name}': {e!s}"
  112. failed_imports.append(error_info)
  113. logger.error(error_info)
  114. return failed_imports
  115. def _register_repo_command(logger: logging.Logger) -> list[str]:
  116. """Register repo command and return list of failures."""
  117. failed = []
  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: {e!s}"
  123. failed.append(error_info)
  124. logger.warning(error_info)
  125. return failed
  126. def _register_module_classes(logger: logging.Logger) -> tuple[list, list[str]]:
  127. """Register template-based modules and return (module_classes, failures)."""
  128. failed_registrations = []
  129. module_classes = list(registry.iter_module_classes())
  130. logger.debug(f"Registering {len(module_classes)} template-based modules")
  131. for _name, module_cls in module_classes:
  132. try:
  133. logger.debug(f"Registering module class: {module_cls.__name__}")
  134. module_cls.register_cli(app)
  135. except Exception as e:
  136. error_info = f"Registration failed for '{module_cls.__name__}': {e!s}"
  137. failed_registrations.append(error_info)
  138. logger.warning(error_info)
  139. display.warning(error_info)
  140. return module_classes, failed_registrations
  141. def _build_error_details(
  142. failed_imports: list[str], failed_registrations: list[str]
  143. ) -> str:
  144. """Build detailed error message from failures."""
  145. error_details = []
  146. if failed_imports:
  147. error_details.extend(
  148. ["Import failures:"] + [f" - {err}" for err in failed_imports]
  149. )
  150. if failed_registrations:
  151. error_details.extend(
  152. ["Registration failures:"] + [f" - {err}" for err in failed_registrations]
  153. )
  154. return "\n".join(error_details) if error_details else ""
  155. def init_app() -> None:
  156. """Initialize the application by discovering and registering modules.
  157. Raises:
  158. ImportError: If critical module import operations fail
  159. RuntimeError: If application initialization fails
  160. """
  161. logger = logging.getLogger(__name__)
  162. failed_imports = []
  163. failed_registrations = []
  164. try:
  165. # Auto-discover and import all modules
  166. modules_path = Path(cli.modules.__file__).parent
  167. logger.debug(f"Discovering modules in {modules_path}")
  168. failed_imports = _import_modules(modules_path, logger)
  169. # Register core repo command
  170. repo_failures = _register_repo_command(logger)
  171. # Register template-based modules
  172. module_classes, failed_registrations = _register_module_classes(logger)
  173. failed_registrations.extend(repo_failures)
  174. # Validate we have modules
  175. if not module_classes and not failed_imports:
  176. raise RuntimeError("No modules found to register")
  177. # Log summary
  178. successful_modules = len(module_classes) - len(failed_registrations)
  179. logger.info(
  180. f"Application initialized: {successful_modules} modules registered successfully"
  181. )
  182. if failed_imports:
  183. logger.info(f"Module import failures: {len(failed_imports)}")
  184. if failed_registrations:
  185. logger.info(f"Module registration failures: {len(failed_registrations)}")
  186. except Exception as e:
  187. details = _build_error_details(failed_imports, failed_registrations) or str(e)
  188. raise RuntimeError(f"Application initialization failed: {details}") from e
  189. def run() -> None:
  190. """Run the CLI application."""
  191. # Configure logging early if --log-level is provided
  192. if "--log-level" in sys.argv:
  193. try:
  194. log_level_index = sys.argv.index("--log-level") + 1
  195. if log_level_index < len(sys.argv):
  196. log_level = sys.argv[log_level_index]
  197. logging.disable(logging.NOTSET)
  198. setup_logging(log_level)
  199. except (ValueError, IndexError):
  200. pass # Let Typer handle argument parsing errors
  201. try:
  202. init_app()
  203. app()
  204. except (ValueError, RuntimeError) as e:
  205. # Handle configuration and initialization errors cleanly
  206. display.error(str(e))
  207. sys.exit(1)
  208. except ImportError as e:
  209. # Handle module import errors with detailed info
  210. display.error(f"Module Import Error: {e}")
  211. sys.exit(1)
  212. except KeyboardInterrupt:
  213. # Handle Ctrl+C gracefully
  214. display.warning("Operation cancelled by user")
  215. sys.exit(130)
  216. except Exception as e:
  217. # Handle unexpected errors - show simplified message
  218. display.error(str(e))
  219. display.info("Use --log-level DEBUG for more details")
  220. sys.exit(1)
  221. if __name__ == "__main__":
  222. run()