"""Sonatype Nexus REST API client using httpx async.""" import hashlib import os import httpx from guarddog_nexus.config import config from guarddog_nexus.logging_setup import log SUPPORTED_EXTENSIONS = (".tar.gz", ".tgz", ".whl", ".zip") def extract_pypi_info(asset_path: str) -> tuple[str, str] | None: """Extract package name and version from a PyPI asset path. Path format: packages/requests/2.31.0/requests-2.31.0.tar.gz """ parts = asset_path.strip("/").split("/") if len(parts) >= 3 and parts[0] == "packages": return parts[1], parts[2] return None async def download_asset(download_url: str, dest_dir: str) -> str | None: """Download an asset from Nexus using async httpx.""" dest_path = os.path.join(dest_dir, os.path.basename(download_url.split("?")[0])) auth = httpx.BasicAuth(config.nexus_username, config.nexus_password) async with httpx.AsyncClient(auth=auth, timeout=120, follow_redirects=True) as client: try: response = await client.get(download_url) response.raise_for_status() with open(dest_path, "wb") as f: f.write(response.content) return dest_path except Exception as e: log.warning("Failed to download %s: %s", download_url, e) return None async def nexus_get(path: str) -> httpx.Response: """Make an authenticated GET request to Nexus REST API.""" auth = httpx.BasicAuth(config.nexus_username, config.nexus_password) async with httpx.AsyncClient(auth=auth, timeout=30) as client: return await client.get(f"{config.nexus_url.rstrip('/')}{path}") def compute_sha256(filepath: str) -> str: h = hashlib.sha256() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): h.update(chunk) return h.hexdigest()