__main__.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. # Using standard Python exceptions instead of custom ones
  18. app = Typer(no_args_is_help=True)
  19. console = Console()
  20. def setup_logging(log_level: str = "WARNING") -> None:
  21. """Configure the logging system with the specified log level.
  22. Args:
  23. log_level: The logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  24. Raises:
  25. ValueError: If the log level is invalid
  26. RuntimeError: If logging configuration fails
  27. """
  28. numeric_level = getattr(logging, log_level.upper(), None)
  29. if not isinstance(numeric_level, int):
  30. raise ValueError(
  31. f"Invalid log level '{log_level}'. Valid levels: DEBUG, INFO, WARNING, ERROR, CRITICAL"
  32. )
  33. try:
  34. logging.basicConfig(
  35. level=numeric_level,
  36. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  37. datefmt='%Y-%m-%d %H:%M:%S'
  38. )
  39. logger = logging.getLogger(__name__)
  40. logger.setLevel(numeric_level)
  41. except Exception as e:
  42. raise RuntimeError(f"Failed to configure logging: {e}")
  43. @app.callback()
  44. def main(
  45. ctx: Context,
  46. log_level: Optional[str] = Option(
  47. "WARNING",
  48. "--log-level",
  49. help="Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)"
  50. )
  51. ) -> None:
  52. """Main CLI application for managing boilerplates."""
  53. # Configure logging based on the provided log level
  54. setup_logging(log_level)
  55. # Store log level in context for potential use by other commands
  56. ctx.ensure_object(dict)
  57. ctx.obj['log_level'] = log_level
  58. def init_app() -> None:
  59. """Initialize the application by discovering and registering modules.
  60. Raises:
  61. ImportError: If critical module import operations fail
  62. RuntimeError: If application initialization fails
  63. """
  64. logger = logging.getLogger(__name__)
  65. failed_imports = []
  66. failed_registrations = []
  67. try:
  68. # Auto-discover and import all modules
  69. modules_path = Path(cli.modules.__file__).parent
  70. logger.debug(f"Discovering modules in {modules_path}")
  71. for finder, name, ispkg in pkgutil.iter_modules([str(modules_path)]):
  72. if not ispkg and not name.startswith('_') and name != 'base':
  73. try:
  74. logger.debug(f"Importing module: {name}")
  75. importlib.import_module(f"cli.modules.{name}")
  76. except ImportError as e:
  77. error_info = f"Import failed for '{name}': {str(e)}"
  78. failed_imports.append(error_info)
  79. logger.warning(error_info)
  80. except Exception as e:
  81. error_info = f"Unexpected error importing '{name}': {str(e)}"
  82. failed_imports.append(error_info)
  83. logger.error(error_info)
  84. # Register modules with app lazily
  85. module_classes = list(registry.iter_module_classes())
  86. logger.debug(f"Registering {len(module_classes)} discovered modules")
  87. for name, module_cls in module_classes:
  88. try:
  89. logger.debug(f"Registering module class: {module_cls.__name__}")
  90. module_cls.register_cli(app)
  91. except Exception as e:
  92. error_info = f"Registration failed for '{module_cls.__name__}': {str(e)}"
  93. failed_registrations.append(error_info)
  94. # Log warning but don't raise exception for individual module failures
  95. logger.warning(error_info)
  96. console.print(f"[yellow]Warning:[/yellow] {error_info}")
  97. # If we have no modules registered at all, that's a critical error
  98. if not module_classes and not failed_imports:
  99. raise RuntimeError("No modules found to register")
  100. # Log summary
  101. successful_modules = len(module_classes) - len(failed_registrations)
  102. logger.info(f"Application initialized: {successful_modules} modules registered successfully")
  103. if failed_imports:
  104. logger.info(f"Module import failures: {len(failed_imports)}")
  105. if failed_registrations:
  106. logger.info(f"Module registration failures: {len(failed_registrations)}")
  107. except Exception as e:
  108. error_details = []
  109. if failed_imports:
  110. error_details.extend(["Import failures:"] + [f" - {err}" for err in failed_imports])
  111. if failed_registrations:
  112. error_details.extend(["Registration failures:"] + [f" - {err}" for err in failed_registrations])
  113. details = "\n".join(error_details) if error_details else str(e)
  114. raise RuntimeError(f"Application initialization failed: {details}")
  115. def run() -> None:
  116. """Run the CLI application."""
  117. try:
  118. init_app()
  119. app()
  120. except (ValueError, RuntimeError) as e:
  121. # Handle configuration and initialization errors cleanly
  122. console.print(f"[bold red]Error:[/bold red] {e}")
  123. sys.exit(1)
  124. except ImportError as e:
  125. # Handle module import errors with detailed info
  126. console.print(f"[bold red]Module Import Error:[/bold red] {e}")
  127. sys.exit(1)
  128. except KeyboardInterrupt:
  129. # Handle Ctrl+C gracefully
  130. console.print("\n[yellow]Operation cancelled by user[/yellow]")
  131. sys.exit(130)
  132. except Exception as e:
  133. # Handle unexpected errors - show simplified message
  134. console.print(f"[bold red]Unexpected error:[/bold red] {e}")
  135. console.print("[dim]Use --log-level DEBUG for more details[/dim]")
  136. sys.exit(1)
  137. if __name__ == "__main__":
  138. run()