|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# ------------------------------------------------------------------------- |
| 4 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 | +# Licensed under the MIT License. See License.txt in the project root for |
| 6 | +# license information. |
| 7 | +# -------------------------------------------------------------------------- |
| 8 | +"""Package manager utilities for detecting and using pip or uv.""" |
| 9 | + |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +import venv |
| 13 | +from pathlib import Path |
| 14 | +from venvtools import ExtendedEnvBuilder |
| 15 | + |
| 16 | + |
| 17 | +class PackageManagerNotFoundError(Exception): |
| 18 | + """Raised when no suitable package manager is found.""" |
| 19 | + |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +def _check_command_available(command: str) -> bool: |
| 24 | + """Check if a command is available in the environment.""" |
| 25 | + try: |
| 26 | + subprocess.run([command, "--version"], capture_output=True, check=True) |
| 27 | + return True |
| 28 | + except (subprocess.CalledProcessError, FileNotFoundError): |
| 29 | + return False |
| 30 | + |
| 31 | + |
| 32 | +def detect_package_manager() -> str: |
| 33 | + """Detect the best available package manager. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + str: The package manager command ('uv' or 'pip') |
| 37 | +
|
| 38 | + Raises: |
| 39 | + PackageManagerNotFoundError: If no suitable package manager is found |
| 40 | + """ |
| 41 | + # Check for uv first since it's more modern and faster |
| 42 | + if _check_command_available("uv"): |
| 43 | + return "uv" |
| 44 | + |
| 45 | + # Fall back to pip |
| 46 | + if _check_command_available("pip"): |
| 47 | + return "pip" |
| 48 | + |
| 49 | + # As a last resort, try using python -m pip |
| 50 | + try: |
| 51 | + subprocess.run([sys.executable, "-m", "pip", "--version"], capture_output=True, check=True) |
| 52 | + return "python -m pip" |
| 53 | + except (subprocess.CalledProcessError, FileNotFoundError): |
| 54 | + pass |
| 55 | + |
| 56 | + raise PackageManagerNotFoundError("No suitable package manager found. Please install either uv or pip.") |
| 57 | + |
| 58 | + |
| 59 | +def get_install_command(package_manager: str, venv_context=None) -> list: |
| 60 | + """Get the install command for the given package manager. |
| 61 | +
|
| 62 | + Args: |
| 63 | + package_manager: The package manager command ('uv', 'pip', or 'python -m pip') |
| 64 | + venv_context: The virtual environment context (optional, used for pip) |
| 65 | +
|
| 66 | + Returns: |
| 67 | + list: The base install command as a list |
| 68 | + """ |
| 69 | + if package_manager == "uv": |
| 70 | + cmd = ["uv", "pip", "install"] |
| 71 | + if venv_context: |
| 72 | + cmd.extend(["--python", venv_context.env_exe]) |
| 73 | + return cmd |
| 74 | + elif package_manager == "pip": |
| 75 | + if venv_context: |
| 76 | + return [venv_context.env_exe, "-m", "pip", "install"] |
| 77 | + else: |
| 78 | + return ["pip", "install"] |
| 79 | + elif package_manager == "python -m pip": |
| 80 | + if venv_context: |
| 81 | + return [venv_context.env_exe, "-m", "pip", "install"] |
| 82 | + else: |
| 83 | + return [sys.executable, "-m", "pip", "install"] |
| 84 | + else: |
| 85 | + raise ValueError(f"Unknown package manager: {package_manager}") |
| 86 | + |
| 87 | + |
| 88 | +def install_packages(packages: list, venv_context=None, package_manager: str = None) -> None: |
| 89 | + """Install packages using the available package manager. |
| 90 | +
|
| 91 | + Args: |
| 92 | + packages: List of packages to install |
| 93 | + venv_context: Virtual environment context (optional) |
| 94 | + package_manager: Package manager to use (auto-detected if None) |
| 95 | + """ |
| 96 | + if package_manager is None: |
| 97 | + package_manager = detect_package_manager() |
| 98 | + |
| 99 | + install_cmd = get_install_command(package_manager, venv_context) |
| 100 | + |
| 101 | + try: |
| 102 | + subprocess.check_call(install_cmd + packages) |
| 103 | + except subprocess.CalledProcessError as e: |
| 104 | + raise RuntimeError(f"Failed to install packages with {package_manager}: {e}") |
| 105 | + |
| 106 | + |
| 107 | +def create_venv_with_package_manager(venv_path): |
| 108 | + """Create virtual environment using the best available package manager. |
| 109 | +
|
| 110 | + Args: |
| 111 | + venv_path: Path where to create the virtual environment |
| 112 | +
|
| 113 | + Returns: |
| 114 | + venv_context: Virtual environment context object |
| 115 | + """ |
| 116 | + package_manager = detect_package_manager() |
| 117 | + |
| 118 | + if package_manager == "uv": |
| 119 | + # Use uv to create and manage the virtual environment |
| 120 | + if not venv_path.exists(): |
| 121 | + subprocess.check_call(["uv", "venv", str(venv_path)]) |
| 122 | + |
| 123 | + # Create a mock venv_context for compatibility |
| 124 | + class MockVenvContext: |
| 125 | + def __init__(self, venv_path): |
| 126 | + self.env_exe = ( |
| 127 | + str(venv_path / "bin" / "python") |
| 128 | + if sys.platform != "win32" |
| 129 | + else str(venv_path / "Scripts" / "python.exe") |
| 130 | + ) |
| 131 | + |
| 132 | + return MockVenvContext(venv_path) |
| 133 | + else: |
| 134 | + # Use standard venv for pip |
| 135 | + if venv_path.exists(): |
| 136 | + env_builder = venv.EnvBuilder(with_pip=True) |
| 137 | + return env_builder.ensure_directories(venv_path) |
| 138 | + else: |
| 139 | + env_builder = ExtendedEnvBuilder(with_pip=True, upgrade_deps=True) |
| 140 | + env_builder.create(venv_path) |
| 141 | + return env_builder.context |
0 commit comments