Quickly sandbox your AI agent.
Python
refactor(cli): delegate `quicksand install` to pip; default-on auto-install
Tyler Paynec383b2a3e21d
diff --git a/packages/quicksand-core/quicksand_core/_auto_install.py b/packages/quicksand-core/quicksand_core/_auto_install.pyindex cfe82a1..0af9de5 100644--- a/packages/quicksand-core/quicksand_core/_auto_install.py+++ b/packages/quicksand-core/quicksand_core/_auto_install.py@@ -1,9 +1,10 @@"""Auto-install images from GitHub releases into site-packages.-When ``QUICKSAND_AUTO_INSTALL`` is set to a truthy value, contrib packages-can call :func:`auto_install_images` to download the fat wheel from GitHub-Releases and extract image files directly into the installed package's-``images/`` directory — no pip reinstall needed.+Contrib packages can call :func:`auto_install_images` to download the fat+wheel from GitHub Releases and extract image files directly into the+installed package's ``images/`` directory — no pip reinstall needed.++Enabled by default; set ``QUICKSAND_AUTO_INSTALL=0`` to opt out."""from __future__ import annotations@@ -21,25 +22,33 @@ from pathlib import Pathlogger = logging.getLogger("quicksand.auto_install")REPO = "microsoft/quicksand"-_TRUTHY = {"1", "true", "yes", "on"}+_FALSY = {"0", "false", "no", "off"}# File extensions and paths that are image artifacts inside a wheel._IMAGE_GLOBS = ("*.qcow2", "*.kernel", "*.initrd", "manifest.json")-def auto_install_images(package_name: str, images_dir: Path) -> bool:+def auto_install_images(+ package_name: str,+ images_dir: Path,+ arch: str | None = None,+) -> bool:"""Download images from the fat wheel on GitHub into *images_dir*.- Only runs when ``QUICKSAND_AUTO_INSTALL`` is set to a truthy value.+ Enabled by default; set ``QUICKSAND_AUTO_INSTALL=0`` to opt out.Returns ``True`` if images were successfully extracted.Args:package_name: PyPI package name (e.g. ``"quicksand-ubuntu"``).images_dir: Destination directory for extracted images(typically the package's ``images/`` folder in site-packages).+ arch: Target arch (``"amd64"``/``"x86_64"``/``"arm64"``/``"aarch64"``).+ When ``None``, picks the wheel matching the host arch and OS.+ When set, picks any wheel for the target arch (cross-arch image+ install — image content is OS-agnostic when extracted)."""val = os.environ.get("QUICKSAND_AUTO_INSTALL", "").strip().lower()- if val not in _TRUTHY:+ if val in _FALSY:return Falsetry:@@ -56,7 +65,7 @@ def auto_install_images(package_name: str, images_dir: Path) -> bool:logger.warning("No GitHub release found for tag %s", tag)return False- wheel_url = _pick_compatible_wheel(assets)+ wheel_url = _pick_compatible_wheel(assets, arch=arch)if not wheel_url:logger.warning("No compatible wheel found in release %s", tag)return False@@ -112,10 +121,28 @@ def _host_os_tag() -> str:return system-def _pick_compatible_wheel(assets: list[dict]) -> str | None:- """Pick the best wheel URL for this platform from release assets."""- arch = _host_arch()- os_tag = _host_os_tag()+_ARCH_ALIASES: dict[str, tuple[str, ...]] = {+ "x86_64": ("x86_64", "amd64"),+ "amd64": ("x86_64", "amd64"),+ "arm64": ("arm64", "aarch64"),+ "aarch64": ("arm64", "aarch64"),+}+++def _pick_compatible_wheel(assets: list[dict], arch: str | None = None) -> str | None:+ """Pick the best wheel URL for the host (or *arch*) from release assets.++ Without *arch*: returns the wheel matching both host arch and host OS.+ With *arch*: returns any non-pure wheel whose name contains the target+ arch tag — image content is OS-agnostic once extracted, so a foreign-OS+ wheel works for cross-arch image installs.+ """+ if arch is None:+ target_archs = (_host_arch(),)+ require_os = _host_os_tag()+ else:+ target_archs = _ARCH_ALIASES.get(arch.lower(), (arch.lower(),))+ require_os = Nonefor asset in assets:name = asset.get("name", "")@@ -123,8 +150,11 @@ def _pick_compatible_wheel(assets: list[dict]) -> str | None:continueif "py3-none-any" in name:continue # skip pure wheels- if arch in name and os_tag in name:- return asset.get("browser_download_url") or asset.get("url")+ if not any(a in name for a in target_archs):+ continue+ if require_os is not None and require_os not in name:+ continue+ return asset.get("browser_download_url") or asset.get("url")return Nonediff --git a/packages/quicksand/quicksand/cli/install.py b/packages/quicksand/quicksand/cli/install.pyindex c282f59..cecbe72 100644--- a/packages/quicksand/quicksand/cli/install.py+++ b/packages/quicksand/quicksand/cli/install.py@@ -1,33 +1,30 @@-"""Install optional quicksand extras from GitHub releases.+"""Install optional quicksand extras from PyPI.-Downloads wheels from public GitHub releases using the REST API — no ``gh``-CLI required. Authentication is optional: set ``GH_TOKEN`` or-``GITHUB_TOKEN`` to avoid rate limits on private repos or heavy usage.+Delegates version resolution and platform-wheel selection to ``pip``: a+package on PyPI under 100 MB ships as a fat wheel with images bundled in;+larger ones ship as a pure ``py3-none-any`` stub that pulls the matching+fat wheel from GitHub Releases on first install (via+:func:`quicksand_core._auto_install.auto_install_images`).Programmatic API::from quicksand import install- install("qemu", "ubuntu") # install specific extras- install("ubuntu", version="0.4.0") # pin a version+ install("qemu", "ubuntu") # install latest from PyPI+ install("[email protected]") # pin a version+ install("ubuntu", arch="amd64") # cross-arch image install"""from __future__ import annotationsimport argparse-import jsonimport platformimport subprocessimport sys-import tempfile-import time-import urllib.request+from importlib.metadata import entry_pointsfrom pathlib import Path-REPO = "microsoft/quicksand"-_GITHUB_API = f"https://api.github.com/repos/{REPO}"--# Short aliases → actual package names on GitHub+# Short aliases → actual package names on PyPIALIASES: dict[str, list[str]] = {"qemu": ["quicksand-qemu"],"ubuntu": ["quicksand-ubuntu"],@@ -54,7 +51,7 @@ def _parse_extra(raw: str) -> tuple[str, str | None]:def _resolve_packages(name: str) -> list[str]:"""Resolve a name to a list of package names.- Aliases (e.g. "ubuntu") expand to their mapped packages.+ Aliases (e.g. ``"ubuntu"``) expand to their mapped packages.All other names are treated as literal package names."""return ALIASES.get(name, [name])@@ -64,31 +61,30 @@ def _resolve_packages(name: str) -> list[str]:def install(*extras: str, arch: str | None = None) -> None:- """Install quicksand extras from GitHub releases.+ """Install quicksand extras from PyPI.- Downloads all wheels for requested packages into a temporary directory,- then uses ``pip install --find-links`` to resolve platform compatibility- and dependencies automatically.+ Uses ``pip install`` so pip's resolver picks the version. Use+ ``"name@version"`` to pin a specific version.- Use ``"name@version"`` to pin a specific version; without ``@`` the- latest release is used.+ For image packages that ship as pure-Python stubs on PyPI (because the+ fat wheel exceeds the 100 MB limit), images are fetched from the+ matching GitHub release after pip install — pass ``arch`` to fetch+ a different architecture's images for use with ``quicksand run --arch``.Args:*extras: One or more extra/package names (e.g. ``"qemu"``, ``"ubuntu"``,- ``"all"``, ``"[email protected]"``, ``"quicksand-agent"``).- arch: Target architecture (e.g. ``"amd64"``, ``"arm64"``).- Downloads cross-platform wheels for use with ``quicksand run --arch``.+ ``"[email protected]"``, ``"quicksand-agent"``).+ arch: Target architecture for cross-arch image installs+ (``"amd64"`` / ``"arm64"``).Raises:- RuntimeError: If no matching wheels are found for the requested- packages.+ RuntimeError: If pip install fails.Examples::from quicksand import installinstall("qemu", "ubuntu")- install("all")install("[email protected]")install("ubuntu", arch="amd64") # cross-arch"""@@ -114,7 +110,7 @@ def register(subparsers: argparse._SubParsersAction) -> None:all_aliases = ", ".join(ALIASES.keys())parser = subparsers.add_parser("install",- help="Install packages from GitHub releases",+ help="Install packages from PyPI",)parser.add_argument("extras",@@ -123,19 +119,19 @@ def register(subparsers: argparse._SubParsersAction) -> None:help=(f"Packages to install (use @version to pin, e.g. [email protected]). "f"Aliases: {all_aliases}. "- "Other names are looked up as package releases on GitHub."+ "Other names are installed directly from PyPI."),)parser.add_argument("--arch",default=None,- help="Install for a specific architecture (e.g. amd64, arm64). "- "Downloads cross-platform wheels for use with quicksand run --arch.",+ help="Install images for a specific architecture (e.g. amd64, arm64). "+ "Fetches cross-platform images from GitHub for use with quicksand run --arch.",)def cmd(args: argparse.Namespace) -> int:- """Install packages from GitHub releases."""+ """Install packages from PyPI."""packages: list[str] = []versions: dict[str, str | None] = {}for raw in args.extras:@@ -151,475 +147,83 @@ def cmd(args: argparse.Namespace) -> int:# ── Implementation ────────────────────────────────────────────────────-def _github_request(url: str) -> urllib.request.Request:- """Build a GitHub API request."""- req = urllib.request.Request(url)- req.add_header("Accept", "application/vnd.github+json")- return req--def _install_packages(packages: list[str],versions: dict[str, str | None],arch: str | None = None,) -> int:- """Download wheels to a temp dir, then pip install --find-links."""+ """Run ``pip install`` then fetch any missing images from GitHub."""print(f"Installing: {', '.join(packages)}")- emulated = _is_platform_emulated()+ print(f"Platform: {platform.system()} {platform.machine()}")if arch:- print(f"Platform: {platform.system()} {platform.machine()} (target arch: {arch})")- elif emulated:- print(- f"Platform: {platform.system()} {platform.machine()} "- f"(Python arch: {_get_pip_arch_tag()}, native: {_get_host_arch_tag()})"- )- else:- print(f"Platform: {platform.system()} {platform.machine()}")- # Resolve compatible versions based on installed quicksand version- quicksand_ver = _get_quicksand_version()- quicksand_date: str | None = None- all_releases: dict[str, str] = {}- if quicksand_ver:- all_releases = _get_all_releases_with_dates()- quicksand_date = all_releases.get(f"quicksand/v{quicksand_ver}")- if quicksand_date:- print(f"Resolving versions compatible with quicksand {quicksand_ver}")- else:- print(f"Warning: no release found for quicksand {quicksand_ver}, using latest versions")+ print(f"Target image arch: {arch}")print()- with tempfile.TemporaryDirectory() as tmp:- wheel_dir = Path(tmp)-- # Download requested packages and their transitive quicksand deps- seen: set[str] = set()- queue = list(packages)- while queue:- pkg_name = queue.pop(0)- if pkg_name in seen:- continue- seen.add(pkg_name)-- ver = versions.get(pkg_name)- if ver:- tag = f"{pkg_name}/v{ver}"- elif quicksand_date:- tag = _resolve_compatible_tag(pkg_name, quicksand_date, all_releases)- else:- tag = _get_latest_release_tag(pkg_name)- if not tag:- if pkg_name in packages:- print(f"Error: No compatible release found for {pkg_name}")- print(f" Check releases: https://github.com/{REPO}/releases")- return 1- continue # not a quicksand package, pip will resolve from PyPI-- resolved_ver = tag.split("/v")[-1]- print(f" {pkg_name} → v{resolved_ver}")-- new_wheels = _download_release_wheels(tag, wheel_dir)- # Scan downloaded wheels for transitive deps that have GH releases- for whl in new_wheels:- for dep in _extract_dep_names(whl):- if dep not in seen:- queue.append(dep)-- if arch:- _retag_wheels_for_arch(wheel_dir)- elif emulated:- print("Retagging image wheels for pip compatibility (emulated platform)")- _retag_wheels_for_arch(wheel_dir)- _cleanup_incompatible_wheels(wheel_dir)-- # Let pip handle platform matching, dep resolution, and conflicts.- # --force-reinstall ensures downloaded wheels overwrite editable installs- # or same-version packages that may shadow the correct entry points.- pip_args = [- sys.executable,- "-m",- "pip",- "install",- "--force-reinstall",- "--find-links",- str(wheel_dir),- ]- pip_args.extend(packages)-- print(f"Running: pip install --find-links {wheel_dir.name} {' '.join(packages)}")- result = subprocess.run(pip_args)- if result.returncode != 0:- print("\nError: pip install failed.")- return 1+ rc = _run_pip_install(packages, versions)+ if rc != 0:+ print("\nError: pip install failed.")+ return rc++ _ensure_images(packages, arch=arch)print(f"\nInstalled {len(packages)} package(s)")return 0-def _is_stable_release_tag(tag: str, pkg_name: str) -> bool:- """True if *tag* is a stable, non-base release for *pkg_name*.-- Excludes pre-releases (PEP 440 ``aN``/``bN``/``rcN``/``.devN``) and the- repo's special ``-base`` / ``-dev`` suffixes.- """- prefix = f"{pkg_name}/v"- if not tag.startswith(prefix):- return False- if tag.endswith("-base") or tag.endswith("-dev"):- return False- version = tag[len(prefix) :]- # Stable PEP 440 release versions contain only digits and dots.- return all(c in "0123456789." for c in version)---def _get_latest_release_tag(pkg_name: str) -> str | None:- """Find the latest per-package release tag (e.g. quicksand-core/v0.3.4)."""- url = f"{_GITHUB_API}/git/matching-refs/tags/{pkg_name}/v"- try:- with urllib.request.urlopen(_github_request(url)) as resp:- refs = json.load(resp)- except Exception:- return None- tags = [- ref["ref"].removeprefix("refs/tags/")- for ref in refs- if _is_stable_release_tag(ref["ref"].removeprefix("refs/tags/"), pkg_name)+def _run_pip_install(packages: list[str], versions: dict[str, str | None]) -> int:+ """Invoke ``pip install`` and let pip resolve versions from PyPI."""+ pip_args = [+ sys.executable,+ "-m",+ "pip",+ "install",+ "--upgrade",+ "--upgrade-strategy",+ "only-if-needed",]- return tags[-1] if tags else None---def _get_quicksand_version() -> str | None:- """Return the installed quicksand version, or ``None`` if unavailable."""- try:- from importlib.metadata import version-- return version("quicksand")- except Exception:- return None---def _version_tuple(ver: str) -> tuple[int, ...]:- """Parse ``'1.2.3'`` into ``(1, 2, 3)`` for comparison."""- parts: list[int] = []- for p in ver.split("."):- try:- parts.append(int(p))- except ValueError:- break- return tuple(parts)---def _get_all_releases_with_dates() -> dict[str, str]:- """Fetch every GitHub release in the repo → ``{tag_name: published_at}``."""- releases: dict[str, str] = {}- page = 1- while True:- url = f"{_GITHUB_API}/releases?per_page=100&page={page}"- try:- with urllib.request.urlopen(_github_request(url)) as resp:- data = json.load(resp)- except Exception:- break- if not data:- break- for rel in data:- releases[rel["tag_name"]] = rel["published_at"]- page += 1- return releases---def _resolve_compatible_tag(- pkg_name: str,- quicksand_date: str,- all_releases: dict[str, str],-) -> str | None:- """Pick the best release tag for *pkg_name* given a quicksand release date.-- 1. Find the latest release published **at or before** *quicksand_date* to- establish a baseline ``major.minor``.- 2. Return the newest ``major.minor.*`` release (patch bumps are always- compatible, even if published after the quicksand release).-- Returns ``None`` if the package has no releases, or none were published- before *quicksand_date*.- """- prefix = f"{pkg_name}/v"- pkg_releases: list[tuple[str, str, str]] = [] # (tag, version, date)- for tag, date in all_releases.items():- if _is_stable_release_tag(tag, pkg_name):- pkg_releases.append((tag, tag[len(prefix) :], date))-- if not pkg_releases:- return None-- pkg_releases.sort(key=lambda x: _version_tuple(x[1]))-- # Baseline: latest version released at or before quicksand- baseline = None- for tag, ver, date in pkg_releases:- if date <= quicksand_date:- baseline = (tag, ver)-- if not baseline:- return None-- parts = baseline[1].split(".")- if len(parts) < 2:- return baseline[0]- major_minor = f"{parts[0]}.{parts[1]}"-- # Newest patch in the same major.minor series- best = baseline[0]- for tag, ver, _date in pkg_releases:- vp = ver.split(".")- if len(vp) >= 2 and f"{vp[0]}.{vp[1]}" == major_minor:- best = tag+ for pkg in packages:+ ver = versions.get(pkg)+ pip_args.append(f"{pkg}=={ver}" if ver else pkg)- return best+ print(f"Running: pip install {' '.join(pip_args[4:])}")+ return subprocess.run(pip_args).returncode-def _get_host_arch_tag() -> str:- """Return the architecture tag substring for the native hardware.+def _ensure_images(packages: list[str], arch: str | None = None) -> None:+ """Fetch images from GitHub for any image-provider package in *packages*.- On Windows, detects the native hardware architecture to prefer- the correct wheel even when Python runs under x86_64 emulation.+ Skipped automatically for packages whose fat wheel was installable from+ PyPI (their ``manifest.json`` already exists). Forced when *arch* is set,+ to overlay images for a different architecture."""- from quicksand_core.host.arch import _detect_architecture-- arch = _detect_architecture()- return "arm64" if arch.image_arch == "arm64" else "x86_64"---def _get_pip_arch_tag() -> str:- """Return the architecture tag that pip will accept on this host.-- Unlike :func:`_get_host_arch_tag` (which reports native hardware),- this returns the arch from Python's perspective — matching what pip- uses for wheel compatibility checks.- """- import sysconfig-- plat = sysconfig.get_platform() # e.g. "win-amd64", "macosx-14.0-arm64"- if "arm64" in plat or "aarch64" in plat:- return "arm64"- return "x86_64"---def _is_platform_emulated() -> bool:- """True when native hardware arch differs from Python's interpreter arch.-- This happens on Windows ARM64 where Python runs under x86_64 emulation.- The native hardware is ARM64 but ``sysconfig.get_platform()`` reports- ``win-amd64``, causing pip to reject ``win_arm64`` wheels.- """- return _get_host_arch_tag() != _get_pip_arch_tag()---def _macos_version_compatible(name: str) -> bool:- """Check if a macosx wheel targets a version this host can run.-- macOS is backwards-compatible: a host running 15.x can install wheels- built for 11.0 through 15.0. Parse the version from the wheel tag- (e.g. ``macosx_14_0_arm64`` → 14) and accept if <= host major version.- """- import re-- match = re.search(r"macosx_(\d+)_", name)- if not match:- return True # not a macosx tag, let other checks handle it- wheel_major = int(match.group(1))- host_major = int(platform.mac_ver()[0].split(".")[0])- return wheel_major <= host_major---def _wheel_compatible_with_host(name: str) -> bool:- """Quick check: could this wheel possibly install on this host?-- Rejects wheels that are clearly for another OS, architecture, or- macOS version. pip does the final precise matching — this just avoids- downloading hundreds of MB of obviously-wrong wheels.-- When platform emulation is detected (e.g. Windows ARM64 with x86_64- Python), accepts wheels for *either* the native arch or the- pip-compatible arch so we can download both arm64 image wheels- (correct VM images) and amd64 binary wheels (pip-installable).- """- if "py3-none-any" in name:- return True-- native_tag = _get_host_arch_tag()- pip_tag = _get_pip_arch_tag()-- if native_tag != pip_tag:- # Emulated: accept wheels matching either architecture- if native_tag not in name and pip_tag not in name:- return False- else:- if native_tag not in name:- return False-- system = platform.system().lower()- if system == "darwin":- return "macosx" in name and _macos_version_compatible(name)- if system == "linux":- return "linux" in name or "manylinux" in name- if system == "windows":- return "win" in name- return False---def _download_release_wheels(tag: str, dest_dir: Path) -> list[Path]:- """Download host-compatible .whl assets from a GitHub release into dest_dir."""- url = f"{_GITHUB_API}/releases/tags/{tag}"- try:- with urllib.request.urlopen(_github_request(url)) as resp:- release = json.load(resp)- except Exception:- return []-- downloaded: list[Path] = []- for asset in release.get("assets", []):- name = asset["name"]- if not name.endswith(".whl"):- continue- if not _wheel_compatible_with_host(name):- continue- dest = dest_dir / name- if dest.exists():+ requested = set(packages)+ providers = _discover_image_providers(requested)+ if not providers:+ return++ from quicksand_core._auto_install import auto_install_images++ for pkg_name, images_dir in providers:+ manifest = images_dir / "manifest.json"+ if manifest.exists() and arch is None:+ continue # fat wheel already on disk for the host+ print(f"Fetching images for {pkg_name} (arch: {arch or 'host'})")+ auto_install_images(pkg_name, images_dir, arch=arch)+++def _discover_image_providers(requested: set[str]) -> list[tuple[str, Path]]:+ """Return ``(pkg_name, images_dir)`` for every ``quicksand.images`` entry+ point whose distribution is in *requested*."""+ found: list[tuple[str, Path]] = []+ for ep in entry_points(group="quicksand.images"):+ dist = ep.dist+ if dist is None or dist.name not in requested:continue- print(f"Downloading {name}")- download_url = asset.get("browser_download_url", asset["url"])- _download_with_progress(download_url, dest, asset["size"])- downloaded.append(dest)- return downloaded---def _extract_dep_names(wheel_path: Path) -> list[str]:- """Extract dependency package names from a wheel's METADATA."""- import zipfile- from email.parser import Parser-- with zipfile.ZipFile(wheel_path) as zf:- metadata_files = [n for n in zf.namelist() if n.endswith(".dist-info/METADATA")]- if not metadata_files:- return []- metadata_text = zf.read(metadata_files[0]).decode("utf-8")-- msg = Parser().parsestr(metadata_text)- requires = msg.get_all("Requires-Dist") or []- names = []- for r in requires:- r = r.split(";")[0] # drop environment markers- for ch in "(<>=!~":- r = r.split(ch)[0] # drop version specifiers- names.append(r.strip().lower().replace("_", "-"))- return names---def _is_image_wheel(wheel_path: Path) -> bool:- """Check if a wheel provides a quicksand.images entry point."""- import zipfile-- with zipfile.ZipFile(wheel_path) as zf:- entry_points_files = [n for n in zf.namelist() if n.endswith(".dist-info/entry_points.txt")]- if not entry_points_files:- return False- content = zf.read(entry_points_files[0]).decode("utf-8")- return "quicksand.images" in content---def _retag_wheels_for_arch(wheel_dir: Path) -> None:- """Retag cross-arch image wheels so pip accepts them on this host.-- Only retags wheels that provide quicksand.images entry points (VM image- packages). Native binary packages (like quicksand-qemu) must not be- retagged — they contain real binaries that only work on their target OS.- """- import sysconfig-- host_tag = sysconfig.get_platform().replace("-", "_").replace(".", "_")- for whl in wheel_dir.glob("*.whl"):- parts = whl.stem.rsplit("-", 1)- if len(parts) != 2:- continue- prefix, old_tag = parts- if old_tag == "any" or host_tag in old_tag:- continue- if not _is_image_wheel(whl):- continue- new_path = whl.parent / f"{prefix}-{host_tag}.whl"- whl.rename(new_path)---def _cleanup_incompatible_wheels(wheel_dir: Path) -> None:- """Remove non-image wheels that pip cannot install on this host.-- After downloading both arch variants (native + pip-compatible) and- retagging image wheels, non-image wheels for the native arch remain.- pip cannot install them, so remove any that have a pip-compatible- counterpart already present in the directory.- """- import sysconfig-- pip_plat = sysconfig.get_platform().replace("-", "_").replace(".", "_")- native_tag = _get_host_arch_tag()-- # Build the native platform tag (e.g. "win_arm64")- if platform.system().lower() == "windows":- native_plat = f"win_{native_tag}"- elif platform.system().lower() == "darwin":- native_plat = native_tag # part of macosx_..._arm64- else:- native_plat = f"linux_{native_tag}"-- for whl in list(wheel_dir.glob("*.whl")):- if native_plat not in whl.name:+ try:+ provider = ep.load()+ except Exception:continue- # Check if a pip-compatible variant exists- pip_name = whl.name.replace(native_plat, pip_plat)- pip_variant = whl.parent / pip_name- if pip_variant.exists() and pip_variant != whl:- whl.unlink()---def _format_size(size_bytes: int) -> str:- """Format size in bytes to human readable string."""- size = float(size_bytes)- for unit in ["B", "KB", "MB", "GB"]:- if size < 1024:- return f"{size:.1f}{unit}"- size /= 1024- return f"{size:.1f}TB"---def _download_with_progress(url: str, dest: Path, size: int) -> None:- """Download a file with progress bar."""- req = _github_request(url)- req.add_header("Accept", "application/octet-stream")-- start_time = time.time()- downloaded = 0-- with urllib.request.urlopen(req) as response, open(dest, "wb") as out_file:- block_size = 8192- while True:- buffer = response.read(block_size)- if not buffer:- break- out_file.write(buffer)- downloaded += len(buffer)-- elapsed = time.time() - start_time- speed = downloaded / elapsed if elapsed > 0 else 0- percent = (downloaded / size * 100) if size > 0 else 0-- bar_width = 30- filled = int(bar_width * downloaded / size) if size > 0 else 0- bar = "#" * filled + "-" * (bar_width - filled)-- sys.stdout.write(- f"\r {bar} {percent:5.1f}% {_format_size(downloaded)}/{_format_size(size)} "- f"({_format_size(int(speed))}/s)"- )- sys.stdout.flush()-- sys.stdout.write("\n")+ images_dir = getattr(provider, "images_dir", None)+ if isinstance(images_dir, Path):+ found.append((dist.name, images_dir))+ return founddiff --git a/tests/unit/test_cli_install.py b/tests/unit/test_cli_install.pyindex a04367b..fea9395 100644--- a/tests/unit/test_cli_install.py+++ b/tests/unit/test_cli_install.py@@ -1,145 +1,212 @@-"""Tests for quicksand.cli.install release-tag filtering."""+"""Tests for quicksand.cli.install (pip-backed installer)."""from __future__ import annotations-import json-from io import BytesIO+import sys+from dataclasses import dataclass+from pathlib import Pathfrom unittest.mock import patch+import pytest+from quicksand.cli import install as install_modfrom quicksand.cli.install import (- _get_latest_release_tag,- _is_stable_release_tag,- _resolve_compatible_tag,+ _ensure_images,+ _install_packages,+ _parse_extra,+ _resolve_packages,+ _run_pip_install,+ install,)-class TestIsStableReleaseTag:- def test_accepts_stable_version(self):- assert _is_stable_release_tag("quicksand-qemu/v0.5.9", "quicksand-qemu")+class TestParseExtra:+ def test_bare_name(self):+ assert _parse_extra("ubuntu") == ("ubuntu", None)- def test_accepts_four_segment_version(self):- assert _is_stable_release_tag("quicksand-qemu/v1.2.3.4", "quicksand-qemu")+ def test_pinned_version(self):+ assert _parse_extra("[email protected]") == ("ubuntu", "0.4.0")- def test_rejects_alpha_prerelease(self):- assert not _is_stable_release_tag("quicksand-qemu/v0.6.0a1", "quicksand-qemu")+ def test_first_at_only(self):+ # Versions can't contain "@", so split once.+ assert _parse_extra("[email protected]@beta") == ("pkg", "1.0@beta")- def test_rejects_beta_prerelease(self):- assert not _is_stable_release_tag("quicksand-qemu/v0.6.0b2", "quicksand-qemu")- def test_rejects_rc_prerelease(self):- assert not _is_stable_release_tag("quicksand-qemu/v0.6.0rc1", "quicksand-qemu")+class TestResolvePackages:+ def test_alias_expands(self):+ assert _resolve_packages("ubuntu") == ["quicksand-ubuntu"]- def test_rejects_dev_version(self):- assert not _is_stable_release_tag("quicksand-qemu/v0.6.0.dev1", "quicksand-qemu")+ def test_dev_alias_expands_to_multiple(self):+ assert _resolve_packages("dev") == [+ "quicksand-image-tools",+ "quicksand-overlay-scaffold",+ "quicksand-base-scaffold",+ ]++ def test_unknown_is_passthrough(self):+ # Treated as a literal PyPI name — pip will resolve or fail.+ assert _resolve_packages("some-random-pkg") == ["some-random-pkg"]- def test_rejects_base_suffix(self):- assert not _is_stable_release_tag("quicksand-qemu/v0.6.0-base", "quicksand-qemu")- def test_rejects_dev_suffix(self):- assert not _is_stable_release_tag("quicksand-qemu/v0.6.0-dev", "quicksand-qemu")+class _DummyCompleted:+ def __init__(self, returncode: int = 0) -> None:+ self.returncode = returncode- def test_rejects_other_package(self):- # Prefix mismatch — tag belongs to a different package name.- assert not _is_stable_release_tag("quicksand-qemu-base/v0.6.0", "quicksand-qemu")- def test_rejects_tag_without_prefix(self):- assert not _is_stable_release_tag("v0.6.0", "quicksand-qemu")+class TestRunPipInstall:+ def test_builds_pip_argv(self):+ captured: dict = {}+ def fake_run(argv, *_args, **_kwargs):+ captured["argv"] = argv+ return _DummyCompleted(0)-def _mock_urlopen(payload: object):- """Return a context manager that yields a response with the given JSON body."""+ with patch("quicksand.cli.install.subprocess.run", side_effect=fake_run):+ rc = _run_pip_install(["quicksand-qemu", "quicksand-cua"], {})- class _Resp:- def __init__(self, body: bytes) -> None:- self._body = body+ assert rc == 0+ assert captured["argv"][:7] == [+ sys.executable,+ "-m",+ "pip",+ "install",+ "--upgrade",+ "--upgrade-strategy",+ "only-if-needed",+ ]+ # Package args appear unpinned and in order.+ assert captured["argv"][7:] == ["quicksand-qemu", "quicksand-cua"]- def read(self) -> bytes:- return self._body+ def test_applies_version_pins(self):+ captured: dict = {}- def __enter__(self):- return BytesIO(self._body)+ def fake_run(argv, *_args, **_kwargs):+ captured["argv"] = argv+ return _DummyCompleted(0)- def __exit__(self, *_):- return False+ with patch("quicksand.cli.install.subprocess.run", side_effect=fake_run):+ _run_pip_install(+ ["quicksand-qemu", "quicksand-ubuntu"],+ {"quicksand-qemu": "0.5.9", "quicksand-ubuntu": None},+ )- return _Resp(json.dumps(payload).encode())+ assert "quicksand-qemu==0.5.9" in captured["argv"]+ assert "quicksand-ubuntu" in captured["argv"]+ assert "quicksand-ubuntu==None" not in captured["argv"]-class TestGetLatestReleaseTag:- def test_picks_latest_stable_skipping_prereleases(self):- # matching-refs returns refs in ascending order; tags[-1] picks the last.- refs = [- {"ref": "refs/tags/quicksand-qemu/v0.5.8"},- {"ref": "refs/tags/quicksand-qemu/v0.5.9"},- {"ref": "refs/tags/quicksand-qemu/v0.6.0a1"},- {"ref": "refs/tags/quicksand-qemu/v0.6.0.dev1"},- {"ref": "refs/tags/quicksand-qemu/v0.5.10.dev0-base"},- ]- with patch(- "quicksand.cli.install.urllib.request.urlopen",- return_value=_mock_urlopen(refs),+@dataclass+class _FakeDist:+ name: str+++class _FakeEntryPoint:+ def __init__(self, dist_name: str, provider):+ self.dist = _FakeDist(dist_name)+ self._provider = provider++ def load(self):+ return self._provider+++class _FakeProvider:+ def __init__(self, images_dir: Path) -> None:+ self.images_dir = images_dir+++class TestEnsureImages:+ def test_skips_packages_not_in_request(self, tmp_path: Path):+ images = tmp_path / "ubuntu-images"+ images.mkdir()+ eps = [_FakeEntryPoint("quicksand-ubuntu", _FakeProvider(images))]++ with (+ patch("quicksand.cli.install.entry_points", return_value=eps),+ patch("quicksand_core._auto_install.auto_install_images") as auto,):- tag = _get_latest_release_tag("quicksand-qemu")- assert tag == "quicksand-qemu/v0.5.9"-- def test_ignores_unrelated_prefix(self):- # GitHub's matching-refs API matches by string prefix on the ref,- # so `quicksand-qemu` could also match `quicksand-qemu-base`. Make- # sure the package filter drops the unrelated one.- refs = [- {"ref": "refs/tags/quicksand-qemu-base/v0.6.0"},- {"ref": "refs/tags/quicksand-qemu/v0.5.9"},- ]- with patch(- "quicksand.cli.install.urllib.request.urlopen",- return_value=_mock_urlopen(refs),+ _ensure_images(packages=["quicksand-qemu"], arch=None)++ auto.assert_not_called()++ def test_skips_when_manifest_present_and_no_arch(self, tmp_path: Path):+ images = tmp_path / "ubuntu-images"+ images.mkdir()+ (images / "manifest.json").write_text("{}")+ eps = [_FakeEntryPoint("quicksand-ubuntu", _FakeProvider(images))]++ with (+ patch("quicksand.cli.install.entry_points", return_value=eps),+ patch("quicksand_core._auto_install.auto_install_images") as auto,):- tag = _get_latest_release_tag("quicksand-qemu")- assert tag == "quicksand-qemu/v0.5.9"+ _ensure_images(packages=["quicksand-ubuntu"], arch=None)- def test_returns_none_when_only_prereleases(self):- refs = [- {"ref": "refs/tags/quicksand-qemu/v0.6.0a1"},- {"ref": "refs/tags/quicksand-qemu/v0.6.0b2"},- ]- with patch(- "quicksand.cli.install.urllib.request.urlopen",- return_value=_mock_urlopen(refs),+ auto.assert_not_called()++ def test_fetches_when_manifest_missing(self, tmp_path: Path):+ images = tmp_path / "ubuntu-images"+ images.mkdir() # empty — pure-wheel install case+ eps = [_FakeEntryPoint("quicksand-ubuntu", _FakeProvider(images))]++ with (+ patch("quicksand.cli.install.entry_points", return_value=eps),+ patch("quicksand_core._auto_install.auto_install_images") as auto,+ ):+ _ensure_images(packages=["quicksand-ubuntu"], arch=None)++ auto.assert_called_once_with("quicksand-ubuntu", images, arch=None)++ def test_fetches_for_cross_arch_even_with_manifest(self, tmp_path: Path):+ # --arch forces a refetch so we can overlay images for a different arch.+ images = tmp_path / "ubuntu-images"+ images.mkdir()+ (images / "manifest.json").write_text("{}")+ eps = [_FakeEntryPoint("quicksand-ubuntu", _FakeProvider(images))]++ with (+ patch("quicksand.cli.install.entry_points", return_value=eps),+ patch("quicksand_core._auto_install.auto_install_images") as auto,):- tag = _get_latest_release_tag("quicksand-qemu")- assert tag is None---class TestResolveCompatibleTag:- def test_skips_prerelease_when_choosing_baseline(self):- # quicksand release on 2026-05-07. 0.6.0a1 was published the day- # before but must be ignored — baseline should fall back to 0.5.9.- all_releases = {- "quicksand-qemu/v0.5.8": "2026-04-20T00:00:00Z",- "quicksand-qemu/v0.5.9": "2026-05-01T00:00:00Z",- "quicksand-qemu/v0.6.0a1": "2026-05-06T00:00:00Z",- "quicksand-qemu/v0.6.0.dev1": "2026-05-05T00:00:00Z",- }- tag = _resolve_compatible_tag("quicksand-qemu", "2026-05-07T00:00:00Z", all_releases)- assert tag == "quicksand-qemu/v0.5.9"-- def test_picks_newest_patch_in_baseline_series(self):- # Patches published after quicksand's release date are still allowed- # as long as they share the baseline's major.minor.- all_releases = {- "quicksand-qemu/v0.5.8": "2026-04-20T00:00:00Z",- "quicksand-qemu/v0.5.9": "2026-05-01T00:00:00Z",- "quicksand-qemu/v0.5.10": "2026-06-01T00:00:00Z",- "quicksand-qemu/v0.6.0a1": "2026-05-15T00:00:00Z",- "quicksand-qemu/v0.6.0": "2026-06-15T00:00:00Z",- }- tag = _resolve_compatible_tag("quicksand-qemu", "2026-05-07T00:00:00Z", all_releases)- assert tag == "quicksand-qemu/v0.5.10"-- def test_returns_none_when_no_stable_releases(self):- all_releases = {- "quicksand-qemu/v0.6.0a1": "2026-05-06T00:00:00Z",- "quicksand-qemu/v0.6.0-base": "2026-05-06T00:00:00Z",- }- tag = _resolve_compatible_tag("quicksand-qemu", "2026-05-07T00:00:00Z", all_releases)- assert tag is None+ _ensure_images(packages=["quicksand-ubuntu"], arch="amd64")++ auto.assert_called_once_with("quicksand-ubuntu", images, arch="amd64")+++class TestInstall:+ def test_pip_failure_raises(self):+ with (+ patch(+ "quicksand.cli.install.subprocess.run",+ return_value=_DummyCompleted(1),+ ),+ pytest.raises(RuntimeError, match="Failed to install"),+ ):+ install("qemu")++ def test_no_extras_raises(self):+ with pytest.raises(ValueError):+ install()++ def test_install_packages_skips_image_fetch_on_pip_failure(self):+ with (+ patch(+ "quicksand.cli.install.subprocess.run",+ return_value=_DummyCompleted(2),+ ),+ patch.object(install_mod, "_ensure_images") as ensure,+ ):+ rc = _install_packages(["quicksand-ubuntu"], {}, arch=None)++ assert rc == 2+ ensure.assert_not_called()++ def test_install_packages_calls_image_fetch_on_success(self):+ with (+ patch(+ "quicksand.cli.install.subprocess.run",+ return_value=_DummyCompleted(0),+ ),+ patch.object(install_mod, "_ensure_images") as ensure,+ ):+ rc = _install_packages(["quicksand-ubuntu"], {"quicksand-ubuntu": None}, arch="amd64")++ assert rc == 0+ ensure.assert_called_once_with(["quicksand-ubuntu"], arch="amd64")