|
1 | | -import os |
2 | | -from typing import Optional |
| 1 | +import os, sys |
| 2 | +from typing import Optional, Callable |
| 3 | +from pathlib import Path |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +import select |
| 7 | +from agentstack import conf |
3 | 8 |
|
4 | | -PACKAGING_CMD = "poetry" |
5 | 9 |
|
| 10 | +DEFAULT_PYTHON_VERSION = "3.12" |
| 11 | +VENV_DIR_NAME: Path = Path(".venv") |
6 | 12 |
|
7 | | -def install(package: str, path: Optional[str] = None): |
8 | | - if path: |
9 | | - os.chdir(path) |
10 | | - os.system(f"{PACKAGING_CMD} add {package}") |
| 13 | +# filter uv output by these words to only show useful progress messages |
| 14 | +RE_UV_PROGRESS = re.compile(r'^(Resolved|Prepared|Installed|Uninstalled|Audited)') |
| 15 | + |
| 16 | + |
| 17 | +# When calling `uv` we explicitly specify the --python executable to use so that |
| 18 | +# the packages are installed into the correct virtual environment. |
| 19 | +# In testing, when this was not set, packages could end up in the pyenv's |
| 20 | +# site-packages directory; it's possible an environemnt variable can control this. |
| 21 | + |
| 22 | + |
| 23 | +def install(package: str): |
| 24 | + """Install a package with `uv` and add it to pyproject.toml.""" |
| 25 | + |
| 26 | + def on_progress(line: str): |
| 27 | + if RE_UV_PROGRESS.match(line): |
| 28 | + print(line.strip()) |
| 29 | + |
| 30 | + def on_error(line: str): |
| 31 | + print(f"uv: [error]\n {line.strip()}") |
| 32 | + |
| 33 | + _wrap_command_with_callbacks( |
| 34 | + [get_uv_bin(), 'add', '--python', '.venv/bin/python', package], |
| 35 | + on_progress=on_progress, |
| 36 | + on_error=on_error, |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +def install_project(): |
| 41 | + """Install all dependencies for the user's project.""" |
| 42 | + |
| 43 | + def on_progress(line: str): |
| 44 | + if RE_UV_PROGRESS.match(line): |
| 45 | + print(line.strip()) |
| 46 | + |
| 47 | + def on_error(line: str): |
| 48 | + print(f"uv: [error]\n {line.strip()}") |
| 49 | + |
| 50 | + _wrap_command_with_callbacks( |
| 51 | + [get_uv_bin(), 'pip', 'install', '--python', '.venv/bin/python', '.'], |
| 52 | + on_progress=on_progress, |
| 53 | + on_error=on_error, |
| 54 | + ) |
11 | 55 |
|
12 | 56 |
|
13 | 57 | def remove(package: str): |
14 | | - os.system(f"{PACKAGING_CMD} remove {package}") |
| 58 | + """Uninstall a package with `uv`.""" |
| 59 | + |
| 60 | + # TODO it may be worth considering removing unused sub-dependencies as well |
| 61 | + def on_progress(line: str): |
| 62 | + if RE_UV_PROGRESS.match(line): |
| 63 | + print(line.strip()) |
| 64 | + |
| 65 | + def on_error(line: str): |
| 66 | + print(f"uv: [error]\n {line.strip()}") |
| 67 | + |
| 68 | + _wrap_command_with_callbacks( |
| 69 | + [get_uv_bin(), 'remove', '--python', '.venv/bin/python', package], |
| 70 | + on_progress=on_progress, |
| 71 | + on_error=on_error, |
| 72 | + ) |
15 | 73 |
|
16 | 74 |
|
17 | 75 | def upgrade(package: str): |
18 | | - os.system(f"{PACKAGING_CMD} add {package}") |
| 76 | + """Upgrade a package with `uv`.""" |
| 77 | + |
| 78 | + # TODO should we try to update the project's pyproject.toml as well? |
| 79 | + def on_progress(line: str): |
| 80 | + if RE_UV_PROGRESS.match(line): |
| 81 | + print(line.strip()) |
| 82 | + |
| 83 | + def on_error(line: str): |
| 84 | + print(f"uv: [error]\n {line.strip()}") |
| 85 | + |
| 86 | + _wrap_command_with_callbacks( |
| 87 | + [get_uv_bin(), 'pip', 'install', '-U', '--python', '.venv/bin/python', package], |
| 88 | + on_progress=on_progress, |
| 89 | + on_error=on_error, |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +def create_venv(python_version: str = DEFAULT_PYTHON_VERSION): |
| 94 | + """Intialize a virtual environment in the project directory of one does not exist.""" |
| 95 | + if os.path.exists(conf.PATH / VENV_DIR_NAME): |
| 96 | + return # venv already exists |
| 97 | + |
| 98 | + RE_VENV_PROGRESS = re.compile(r'^(Using|Creating)') |
| 99 | + |
| 100 | + def on_progress(line: str): |
| 101 | + if RE_VENV_PROGRESS.match(line): |
| 102 | + print(line.strip()) |
| 103 | + |
| 104 | + def on_error(line: str): |
| 105 | + print(f"uv: [error]\n {line.strip()}") |
| 106 | + |
| 107 | + _wrap_command_with_callbacks( |
| 108 | + [get_uv_bin(), 'venv', '--python', python_version], |
| 109 | + on_progress=on_progress, |
| 110 | + on_error=on_error, |
| 111 | + ) |
| 112 | + |
| 113 | + |
| 114 | +def get_uv_bin() -> str: |
| 115 | + """Find the path to the uv binary.""" |
| 116 | + try: |
| 117 | + import uv |
| 118 | + |
| 119 | + return uv.find_uv_bin() |
| 120 | + except ImportError as e: |
| 121 | + raise e |
| 122 | + |
| 123 | + |
| 124 | +def _setup_env() -> dict[str, str]: |
| 125 | + """Copy the current environment and add the virtual environment path for use by a subprocess.""" |
| 126 | + env = os.environ.copy() |
| 127 | + env["VIRTUAL_ENV"] = str(conf.PATH / VENV_DIR_NAME.absolute()) |
| 128 | + env["UV_INTERNAL__PARENT_INTERPRETER"] = sys.executable |
| 129 | + return env |
| 130 | + |
| 131 | + |
| 132 | +def _wrap_command_with_callbacks( |
| 133 | + command: list[str], |
| 134 | + on_progress: Callable[[str], None] = lambda x: None, |
| 135 | + on_complete: Callable[[str], None] = lambda x: None, |
| 136 | + on_error: Callable[[str], None] = lambda x: None, |
| 137 | +) -> None: |
| 138 | + """Run a command with progress callbacks.""" |
| 139 | + try: |
| 140 | + all_lines = '' |
| 141 | + process = subprocess.Popen( |
| 142 | + command, |
| 143 | + cwd=conf.PATH.absolute(), |
| 144 | + env=_setup_env(), |
| 145 | + stdout=subprocess.PIPE, |
| 146 | + stderr=subprocess.PIPE, |
| 147 | + text=True, |
| 148 | + ) |
| 149 | + assert process.stdout and process.stderr # appease type checker |
| 150 | + |
| 151 | + readable = [process.stdout, process.stderr] |
| 152 | + while readable: |
| 153 | + ready, _, _ = select.select(readable, [], []) |
| 154 | + for fd in ready: |
| 155 | + line = fd.readline() |
| 156 | + if not line: |
| 157 | + readable.remove(fd) |
| 158 | + continue |
| 159 | + |
| 160 | + on_progress(line) |
| 161 | + all_lines += line |
| 162 | + |
| 163 | + if process.wait() == 0: # return code: success |
| 164 | + on_complete(all_lines) |
| 165 | + else: |
| 166 | + on_error(all_lines) |
| 167 | + except Exception as e: |
| 168 | + on_error(str(e)) |
| 169 | + finally: |
| 170 | + try: |
| 171 | + process.terminate() |
| 172 | + except: |
| 173 | + pass |
0 commit comments