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