|
| 1 | +import requests |
| 2 | +from pathlib import Path |
| 3 | +from typing import Optional, List, Dict, Any, Tuple |
| 4 | +import logging |
| 5 | + |
| 6 | +logger = logging.getLogger(__name__) |
| 7 | + |
| 8 | +GITHUB_ORG = "CodeGraphContext" |
| 9 | +GITHUB_REPO = "CodeGraphContext" |
| 10 | +REGISTRY_API_URL = f"https://api.github.com/repos/{GITHUB_ORG}/{GITHUB_REPO}/releases" |
| 11 | +MANIFEST_URL = f"https://github.com/{GITHUB_ORG}/{GITHUB_REPO}/releases/download/on-demand-bundles/manifest.json" |
| 12 | + |
| 13 | +class BundleRegistry: |
| 14 | + """ |
| 15 | + Core logic for interacting with the CodeGraphContext bundle registry. |
| 16 | + Handles fetching metadata, searching, and downloading bundles without CLI dependencies. |
| 17 | + """ |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def fetch_available_bundles() -> List[Dict[str, Any]]: |
| 21 | + """ |
| 22 | + Fetch all available bundles from GitHub Releases and the on-demand manifest. |
| 23 | + Returns a list of bundle dictionaries with metadata. |
| 24 | + Preserves all versions - no deduplication. |
| 25 | + """ |
| 26 | + all_bundles = [] |
| 27 | + |
| 28 | + # 1. Fetch on-demand bundles from manifest |
| 29 | + try: |
| 30 | + response = requests.get(MANIFEST_URL, timeout=10) |
| 31 | + if response.status_code == 200: |
| 32 | + manifest = response.json() |
| 33 | + if manifest.get('bundles'): |
| 34 | + for bundle in manifest['bundles']: |
| 35 | + bundle['source'] = 'on-demand' |
| 36 | + # Ensure bundle has a full_name field (with version info) |
| 37 | + if 'bundle_name' in bundle: |
| 38 | + # Extract full name without .cgc extension |
| 39 | + bundle['full_name'] = bundle['bundle_name'].replace('.cgc', '') |
| 40 | + all_bundles.append(bundle) |
| 41 | + except Exception as e: |
| 42 | + logger.warning(f"Could not fetch on-demand bundles from manifest: {e}") |
| 43 | + |
| 44 | + # 2. Fetch weekly pre-indexed bundles |
| 45 | + try: |
| 46 | + response = requests.get(REGISTRY_API_URL, timeout=10) |
| 47 | + if response.status_code == 200: |
| 48 | + releases = response.json() |
| 49 | + |
| 50 | + # Find weekly releases (bundles-YYYYMMDD pattern) |
| 51 | + weekly_releases = [r for r in releases if r['tag_name'].startswith('bundles-') and r['tag_name'] != 'bundles-latest'] |
| 52 | + |
| 53 | + if weekly_releases: |
| 54 | + # Get the most recent weekly release |
| 55 | + latest_weekly = weekly_releases[0] |
| 56 | + |
| 57 | + for asset in latest_weekly.get('assets', []): |
| 58 | + if asset['name'].endswith('.cgc'): |
| 59 | + # Full bundle name without extension |
| 60 | + full_name = asset['name'].replace('.cgc', '') |
| 61 | + |
| 62 | + # Parse bundle name |
| 63 | + name_parts = full_name.split('-') |
| 64 | + bundle = { |
| 65 | + 'name': name_parts[0], # Base package name |
| 66 | + 'full_name': full_name, # Complete name with version |
| 67 | + 'repo': f"{name_parts[0]}/{name_parts[0]}", # Simplified |
| 68 | + 'bundle_name': asset['name'], |
| 69 | + 'version': name_parts[1] if len(name_parts) > 1 else 'latest', |
| 70 | + 'commit': name_parts[2] if len(name_parts) > 2 else 'unknown', |
| 71 | + 'size_bytes': asset.get('size', 0), |
| 72 | + 'size': f"{asset['size'] / 1024 / 1024:.1f}MB", |
| 73 | + 'download_url': asset['browser_download_url'], |
| 74 | + 'generated_at': asset['updated_at'], |
| 75 | + 'source': 'weekly' |
| 76 | + } |
| 77 | + all_bundles.append(bundle) |
| 78 | + except Exception as e: |
| 79 | + logger.warning(f"Could not fetch weekly bundles from GitHub API: {e}") |
| 80 | + |
| 81 | + # Normalize all bundles to have required fields |
| 82 | + for bundle in all_bundles: |
| 83 | + # Ensure 'name' field exists (base package name) |
| 84 | + if 'name' not in bundle: |
| 85 | + repo = bundle.get('repo', '') |
| 86 | + if '/' in repo: |
| 87 | + bundle['name'] = repo.split('/')[-1] |
| 88 | + else: |
| 89 | + # Extract from full_name or bundle_name |
| 90 | + full_name = bundle.get('full_name', bundle.get('bundle_name', 'unknown')) |
| 91 | + bundle['name'] = full_name.split('-')[0] |
| 92 | + |
| 93 | + # Ensure 'full_name' exists |
| 94 | + if 'full_name' not in bundle: |
| 95 | + bundle['full_name'] = bundle.get('bundle_name', bundle.get('name', 'unknown')).replace('.cgc', '') |
| 96 | + |
| 97 | + return all_bundles |
| 98 | + |
| 99 | + @staticmethod |
| 100 | + def find_bundle_download_info(name: str) -> Tuple[Optional[str], Optional[Dict[str, Any]], str]: |
| 101 | + """ |
| 102 | + Find a download URL and metadata for a bundle by name. |
| 103 | + |
| 104 | + Strategies: |
| 105 | + 1. Exact match on full_name (e.g., 'flask-main-abc123') |
| 106 | + 2. Match on base name (e.g., 'flask') - returns most recent version |
| 107 | + |
| 108 | + Returns: |
| 109 | + (download_url, bundle_metadata, error_message) |
| 110 | + """ |
| 111 | + bundles = BundleRegistry.fetch_available_bundles() |
| 112 | + |
| 113 | + if not bundles: |
| 114 | + return None, None, "Could not fetch bundle registry." |
| 115 | + |
| 116 | + name_lower = name.lower() |
| 117 | + |
| 118 | + # Strategy 1: Exact match on full_name |
| 119 | + for b in bundles: |
| 120 | + if b.get('full_name', '').lower() == name_lower: |
| 121 | + url = b.get('download_url') |
| 122 | + if url: |
| 123 | + return url, b, "" |
| 124 | + return None, b, f"No download URL found for bundle '{name}'" |
| 125 | + |
| 126 | + # Strategy 2: Match base package name (most recent) |
| 127 | + matching_bundles = [] |
| 128 | + for b in bundles: |
| 129 | + if b.get('name', '').lower() == name_lower: |
| 130 | + matching_bundles.append(b) |
| 131 | + |
| 132 | + if matching_bundles: |
| 133 | + # Sort by timestamp (newest first) |
| 134 | + matching_bundles.sort(key=lambda x: x.get('generated_at', ''), reverse=True) |
| 135 | + bundle = matching_bundles[0] |
| 136 | + url = bundle.get('download_url') |
| 137 | + if url: |
| 138 | + return url, bundle, "" |
| 139 | + return None, bundle, f"No download URL found for bundle '{name}'" |
| 140 | + |
| 141 | + return None, None, f"Bundle '{name}' not found in registry." |
| 142 | + |
| 143 | + @staticmethod |
| 144 | + def download_file(url: str, output_path: Path, progress_callback=None) -> bool: |
| 145 | + """ |
| 146 | + Download a file from a URL to a local path. |
| 147 | + |
| 148 | + Args: |
| 149 | + url: The URL to download from |
| 150 | + output_path: Local path to save the file |
| 151 | + progress_callback: Optional callable(chunk_size) to report progress |
| 152 | + |
| 153 | + Returns: |
| 154 | + True if successful, raises exception otherwise |
| 155 | + """ |
| 156 | + try: |
| 157 | + response = requests.get(url, stream=True, timeout=30) |
| 158 | + response.raise_for_status() |
| 159 | + |
| 160 | + with open(output_path, 'wb') as f: |
| 161 | + for chunk in response.iter_content(chunk_size=8192): |
| 162 | + if chunk: |
| 163 | + f.write(chunk) |
| 164 | + if progress_callback: |
| 165 | + progress_callback(len(chunk)) |
| 166 | + return True |
| 167 | + except Exception as e: |
| 168 | + # Clean up partial file |
| 169 | + if output_path.exists(): |
| 170 | + output_path.unlink() |
| 171 | + raise e |
0 commit comments