|
| 1 | +"""Cache command handler for my-unicorn CLI. |
| 2 | +
|
| 3 | +Handles cache management operations for the CLI, including clearing cache entries |
| 4 | +and displaying cache statistics. |
| 5 | +""" |
| 6 | + |
| 7 | +import sys |
| 8 | +from argparse import Namespace |
| 9 | + |
| 10 | +from ..logger import get_logger |
| 11 | +from ..services.cache import get_cache_manager |
| 12 | +from .base import BaseCommandHandler |
| 13 | + |
| 14 | +logger = get_logger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class CacheHandler(BaseCommandHandler): |
| 18 | + """Handler for cache command operations. |
| 19 | +
|
| 20 | + Provides cache management functionality: |
| 21 | + - Clearing cache entries |
| 22 | + - Displaying cache statistics |
| 23 | +
|
| 24 | + Note: |
| 25 | + Cache refresh is handled by the update command (--refresh-cache flag). |
| 26 | + """ |
| 27 | + |
| 28 | + async def execute(self, args: Namespace) -> None: |
| 29 | + """Execute the cache command based on subcommand. |
| 30 | +
|
| 31 | + Args: |
| 32 | + args: Parsed command-line arguments containing cache parameters. |
| 33 | +
|
| 34 | + Raises: |
| 35 | + SystemExit: On unknown action or error. |
| 36 | + """ |
| 37 | + try: |
| 38 | + if args.cache_action == "clear": |
| 39 | + await self._handle_clear(args) |
| 40 | + elif args.cache_action == "stats": |
| 41 | + await self._handle_stats(args) |
| 42 | + else: |
| 43 | + logger.error("Unknown cache action: %s", args.cache_action) |
| 44 | + sys.exit(1) |
| 45 | + except KeyboardInterrupt: |
| 46 | + logger.info("Cache operation interrupted by user") |
| 47 | + sys.exit(130) |
| 48 | + except Exception as e: |
| 49 | + logger.error("Cache operation failed: %s", e) |
| 50 | + sys.exit(1) |
| 51 | + |
| 52 | + async def _handle_clear(self, args: Namespace) -> None: |
| 53 | + """Clear cache entries based on arguments. |
| 54 | +
|
| 55 | + Args: |
| 56 | + args: Parsed command-line arguments. |
| 57 | +
|
| 58 | + Raises: |
| 59 | + SystemExit: If neither --all nor app name is specified. |
| 60 | + """ |
| 61 | + cache_manager = get_cache_manager() |
| 62 | + if args.all: |
| 63 | + await cache_manager.clear_cache() |
| 64 | + logger.info("✅ Cleared all cache entries") |
| 65 | + elif args.app_name: |
| 66 | + # Parse owner/repo from app name |
| 67 | + owner, repo = self._parse_app_name(args.app_name) |
| 68 | + await cache_manager.clear_cache(owner, repo) |
| 69 | + logger.info("✅ Cleared cache for %s/%s", owner, repo) |
| 70 | + else: |
| 71 | + logger.error("Please specify either --all or an app name to clear") |
| 72 | + sys.exit(1) |
| 73 | + |
| 74 | + async def _handle_stats(self, args: Namespace) -> None: |
| 75 | + """Display cache statistics. |
| 76 | +
|
| 77 | + Args: |
| 78 | + args: Parsed command-line arguments. |
| 79 | +
|
| 80 | + Raises: |
| 81 | + SystemExit: On error. |
| 82 | + """ |
| 83 | + cache_manager = get_cache_manager() |
| 84 | + try: |
| 85 | + stats = await cache_manager.get_cache_stats() |
| 86 | + logger.info("📁 Cache Directory: %s", stats["cache_directory"]) |
| 87 | + logger.info("Total Entries: %d", stats["total_entries"]) |
| 88 | + logger.info("TTL Hours: %d", stats["ttl_hours"]) |
| 89 | + |
| 90 | + total_entries = stats["total_entries"] |
| 91 | + if isinstance(total_entries, int) and total_entries > 0: |
| 92 | + print(f"✅ Fresh Entries: {stats['fresh_entries']}") |
| 93 | + print(f"⏰ Expired Entries: {stats['expired_entries']}") |
| 94 | + corrupted = stats["corrupted_entries"] |
| 95 | + if isinstance(corrupted, int) and corrupted > 0: |
| 96 | + print(f"❌ Corrupted Entries: {corrupted}") |
| 97 | + else: |
| 98 | + print("📭 No cache entries found") |
| 99 | + |
| 100 | + if "error" in stats: |
| 101 | + print(f"⚠️ Error getting stats: {stats['error']}") |
| 102 | + except Exception as e: |
| 103 | + print(f"❌ Failed to get cache stats: {e}") |
| 104 | + sys.exit(1) |
| 105 | + |
| 106 | + def _parse_app_name(self, app_name: str) -> tuple[str, str]: |
| 107 | + """Parse app name to (owner, repo). |
| 108 | +
|
| 109 | + Args: |
| 110 | + app_name: App name, either 'owner/repo' or just 'appname'. |
| 111 | +
|
| 112 | + Returns: |
| 113 | + Tuple[str, str]: (owner, repo). |
| 114 | +
|
| 115 | + Raises: |
| 116 | + SystemExit: If app config not found. |
| 117 | + """ |
| 118 | + if "/" in app_name: |
| 119 | + owner, repo = app_name.split("/", 1) |
| 120 | + return owner, repo |
| 121 | + |
| 122 | + # Lookup owner/repo from installed app config |
| 123 | + app_config = self.config_manager.load_app_config(app_name) |
| 124 | + if not app_config: |
| 125 | + logger.error("App %s not found", app_name) |
| 126 | + sys.exit(1) |
| 127 | + return app_config["owner"], app_config["repo"] |
0 commit comments