__main__.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. None,
  48. "--log-level",
  49. help="Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL). If omitted, logging is disabled."
  50. )
  51. ) -> None:
  52. """Main CLI application for managing boilerplates."""
  53. # Disable logging by default; only enable when user provides --log-level
  54. if log_level:
  55. # Re-enable logging and configure
  56. logging.disable(logging.NOTSET)
  57. setup_logging(log_level)
  58. else:
  59. # Silence all logging (including third-party) unless user explicitly requests it
  60. logging.disable(logging.CRITICAL)
  61. # Store log level in context for potential use by other commands
  62. ctx.ensure_object(dict)
  63. ctx.obj['log_level'] = log_level
  64. def init_app() -> None:
  65. """Initialize the application by discovering and registering modules.
  66. Raises:
  67. ImportError: If critical module import operations fail
  68. RuntimeError: If application initialization fails
  69. """
  70. logger = logging.getLogger(__name__)
  71. failed_imports = []
  72. failed_registrations = []
  73. try:
  74. # Auto-discover and import all modules
  75. modules_path = Path(cli.modules.__file__).parent
  76. logger.debug(f"Discovering modules in {modules_path}")
  77. for finder, name, ispkg in pkgutil.iter_modules([str(modules_path)]):
  78. if not ispkg and not name.startswith('_') and name != 'base':
  79. try:
  80. logger.debug(f"Importing module: {name}")
  81. importlib.import_module(f"cli.modules.{name}")
  82. except ImportError as e:
  83. error_info = f"Import failed for '{name}': {str(e)}"
  84. failed_imports.append(error_info)
  85. logger.warning(error_info)
  86. except Exception as e:
  87. error_info = f"Unexpected error importing '{name}': {str(e)}"
  88. failed_imports.append(error_info)
  89. logger.error(error_info)
  90. # Register modules with app lazily
  91. module_classes = list(registry.iter_module_classes())
  92. logger.debug(f"Registering {len(module_classes)} discovered modules")
  93. for name, module_cls in module_classes:
  94. try:
  95. logger.debug(f"Registering module class: {module_cls.__name__}")
  96. module_cls.register_cli(app)
  97. except Exception as e:
  98. error_info = f"Registration failed for '{module_cls.__name__}': {str(e)}"
  99. failed_registrations.append(error_info)
  100. # Log warning but don't raise exception for individual module failures
  101. logger.warning(error_info)
  102. console.print(f"[yellow]Warning:[/yellow] {error_info}")
  103. # If we have no modules registered at all, that's a critical error
  104. if not module_classes and not failed_imports:
  105. raise RuntimeError("No modules found to register")
  106. # Log summary
  107. successful_modules = len(module_classes) - len(failed_registrations)
  108. logger.info(f"Application initialized: {successful_modules} modules registered successfully")
  109. if failed_imports:
  110. logger.info(f"Module import failures: {len(failed_imports)}")
  111. if failed_registrations:
  112. logger.info(f"Module registration failures: {len(failed_registrations)}")
  113. except Exception as e:
  114. error_details = []
  115. if failed_imports:
  116. error_details.extend(["Import failures:"] + [f" - {err}" for err in failed_imports])
  117. if failed_registrations:
  118. error_details.extend(["Registration failures:"] + [f" - {err}" for err in failed_registrations])
  119. details = "\n".join(error_details) if error_details else str(e)
  120. raise RuntimeError(f"Application initialization failed: {details}")
  121. def run() -> None:
  122. """Run the CLI application."""
  123. try:
  124. init_app()
  125. app()
  126. except (ValueError, RuntimeError) as e:
  127. # Handle configuration and initialization errors cleanly
  128. console.print(f"[bold red]Error:[/bold red] {e}")
  129. sys.exit(1)
  130. except ImportError as e:
  131. # Handle module import errors with detailed info
  132. console.print(f"[bold red]Module Import Error:[/bold red] {e}")
  133. sys.exit(1)
  134. except KeyboardInterrupt:
  135. # Handle Ctrl+C gracefully
  136. console.print("\n[yellow]Operation cancelled by user[/yellow]")
  137. sys.exit(130)
  138. except Exception as e:
  139. # Handle unexpected errors - show simplified message
  140. console.print(f"[bold red]Unexpected error:[/bold red] {e}")
  141. console.print("[dim]Use --log-level DEBUG for more details[/dim]")
  142. sys.exit(1)
  143. if __name__ == "__main__":
  144. run()