| 1 |
|
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import os |
| 5 |
import shutil |
| 6 |
import subprocess |
| 7 |
import sys |
| 8 |
from contextlib import contextmanager |
| 9 |
from pathlib import Path |
| 10 |
from typing import TYPE_CHECKING, Any |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from collections.abc import Callable, Iterator |
| 14 |
|
| 15 |
|
| 16 |
PYTHON_VERSIONS = os.getenv("PYTHON_VERSIONS", "3.10 3.11 3.12 3.13 3.14 3.15").split() |
| 17 |
PYTHON_DEV = "3.15" |
| 18 |
|
| 19 |
_commands = [] |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
def _shell(cmd: str, *, capture_output: bool = False, **kwargs: Any) -> str | None: |
| 26 |
if capture_output: |
| 27 |
return subprocess.check_output(cmd, shell=True, text=True, **kwargs) |
| 28 |
subprocess.run(cmd, shell=True, check=True, stderr=subprocess.STDOUT, **kwargs) |
| 29 |
return None |
| 30 |
|
| 31 |
|
| 32 |
@contextmanager |
| 33 |
def _environ(**kwargs: str) -> Iterator[None]: |
| 34 |
original = dict(os.environ) |
| 35 |
os.environ.update(kwargs) |
| 36 |
try: |
| 37 |
yield |
| 38 |
finally: |
| 39 |
os.environ.clear() |
| 40 |
os.environ.update(original) |
| 41 |
|
| 42 |
|
| 43 |
def _uv_install(venv: Path) -> None: |
| 44 |
with _environ(UV_PROJECT_ENVIRONMENT=str(venv), PYO3_USE_ABI3_FORWARD_COMPATIBILITY="1"): |
| 45 |
if "CI" in os.environ: |
| 46 |
_shell("uv sync --no-editable") |
| 47 |
else: |
| 48 |
_shell("uv sync") |
| 49 |
|
| 50 |
|
| 51 |
def _run(version: str, cmd: str, *args: str, **kwargs: Any) -> None: |
| 52 |
kwargs = {"check": True, **kwargs} |
| 53 |
uv_run = ["uv", "run", "--no-sync"] |
| 54 |
try: |
| 55 |
if version == "default": |
| 56 |
with _environ(UV_PROJECT_ENVIRONMENT=".venv"): |
| 57 |
subprocess.run([*uv_run, cmd, *args], **kwargs) |
| 58 |
else: |
| 59 |
with _environ(UV_PROJECT_ENVIRONMENT=f".venvs/{version}", MULTIRUN="1"): |
| 60 |
subprocess.run([*uv_run, cmd, *args], **kwargs) |
| 61 |
except subprocess.CalledProcessError as process: |
| 62 |
raise _RunError( |
| 63 |
returncode=process.returncode, |
| 64 |
python_version=version, |
| 65 |
cmd=process.cmd, |
| 66 |
output=process.output, |
| 67 |
stderr=process.stderr, |
| 68 |
) from process |
| 69 |
|
| 70 |
|
| 71 |
def _command(name: str) -> Callable[[Callable[..., None]], Callable[..., None]]: |
| 72 |
def wrapper(func: Callable[..., None]) -> Callable[..., None]: |
| 73 |
func.__cmdname__ = name |
| 74 |
_commands.append(func) |
| 75 |
return func |
| 76 |
|
| 77 |
return wrapper |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
@_command("help") |
| 84 |
def help(*args: str) -> None: |
| 85 |
"""Print this help. Add task name to print help. |
| 86 |
|
| 87 |
```bash |
| 88 |
make help [TASK] |
| 89 |
``` |
| 90 |
|
| 91 |
When the Python dependencies are not installed, |
| 92 |
this command just print the available commands. |
| 93 |
When the Python dependencies are installed, |
| 94 |
[duty](https://github.com/pawamoy/duty) is available |
| 95 |
so the command can also print the available tasks. |
| 96 |
|
| 97 |
If you add a task name after the command, it will print help for this specific task. |
| 98 |
""" |
| 99 |
if len(args) > 1: |
| 100 |
_run("default", "duty", "--help", args[1]) |
| 101 |
else: |
| 102 |
print("Available commands", flush=True) |
| 103 |
for cmd in _commands: |
| 104 |
print(f" {cmd.__cmdname__:21} {cmd.__doc__.splitlines()[0]}", flush=True) |
| 105 |
if Path(".venv").exists(): |
| 106 |
print("\nAvailable tasks", flush=True) |
| 107 |
run("duty", "--list") |
| 108 |
|
| 109 |
|
| 110 |
@_command("setup") |
| 111 |
def setup() -> None: |
| 112 |
"""Setup all virtual environments (install dependencies). |
| 113 |
|
| 114 |
```bash |
| 115 |
make setup |
| 116 |
``` |
| 117 |
|
| 118 |
The `setup` command installs all the Python dependencies required to work on the project. |
| 119 |
Virtual environments and dependencies are managed by [uv](https://github.com/astral-sh/uv). |
| 120 |
Development dependencies are listed in the `devdeps.txt` file. |
| 121 |
|
| 122 |
The command will create a virtual environment in the `.venv` folder, |
| 123 |
as well as one virtual environment per supported Python version in the `.venvs/3.x` folders. |
| 124 |
Supported Python versions are listed in the `scripts/make` file, and can be overridden |
| 125 |
by setting the `PYTHON_VERSIONS` environment variable. |
| 126 |
|
| 127 |
If you cloned the repository on the same file-system as uv's cache, |
| 128 |
everything will be hard linked from the cache, so don't worry about wasting disk space. |
| 129 |
|
| 130 |
Once dependencies are installed, try running `make` or `make help` again, to show additional tasks. |
| 131 |
|
| 132 |
```console exec="1" source="console" id="make-help2" |
| 133 |
$ alias make="$PWD/scripts/make" # markdown-exec: hide |
| 134 |
$ make |
| 135 |
``` |
| 136 |
|
| 137 |
These tasks are written using [duty](https://github.com/pawamoy/duty) (a task runner), |
| 138 |
and located in the `duties.py` module in the repository root. |
| 139 |
|
| 140 |
Some of these tasks will run in the default virtual environment (`.venv`), |
| 141 |
while others will run in all the supported Python version environments (`.venvs/3.x`). |
| 142 |
""" |
| 143 |
if not shutil.which("uv"): |
| 144 |
raise ValueError("make: setup: uv must be installed, see https://github.com/astral-sh/uv") |
| 145 |
|
| 146 |
print("Installing dependencies (default environment)") |
| 147 |
default_venv = Path(".venv") |
| 148 |
if not default_venv.exists(): |
| 149 |
_shell("uv venv --python python") |
| 150 |
_uv_install(default_venv) |
| 151 |
|
| 152 |
if PYTHON_VERSIONS: |
| 153 |
for version in PYTHON_VERSIONS: |
| 154 |
print(f"\nInstalling dependencies (python{version})") |
| 155 |
venv_path = Path(f".venvs/{version}") |
| 156 |
if not venv_path.exists(): |
| 157 |
_shell(f"uv venv --python {version} {venv_path}") |
| 158 |
with _environ(VIRTUAL_ENV=str(venv_path.resolve())): |
| 159 |
_uv_install(venv_path) |
| 160 |
|
| 161 |
|
| 162 |
class _RunError(subprocess.CalledProcessError): |
| 163 |
def __init__(self, *args: Any, python_version: str, **kwargs: Any): |
| 164 |
super().__init__(*args, **kwargs) |
| 165 |
self.python_version = python_version |
| 166 |
|
| 167 |
|
| 168 |
@_command("run") |
| 169 |
def run(cmd: str, *args: str, **kwargs: Any) -> None: |
| 170 |
"""Run a command in the default virtual environment. |
| 171 |
|
| 172 |
```bash |
| 173 |
make run <CMD> [ARG...] |
| 174 |
``` |
| 175 |
|
| 176 |
This command runs an arbitrary command inside the default virtual environment (`.venv`). |
| 177 |
It is especially useful to start a Python interpreter without having to first activate |
| 178 |
the virtual environment: `make run python`. |
| 179 |
""" |
| 180 |
_run("default", cmd, *args, **kwargs) |
| 181 |
|
| 182 |
|
| 183 |
@_command("multirun") |
| 184 |
def multirun(cmd: str, *args: str, **kwargs: Any) -> None: |
| 185 |
"""Run a command for all configured Python versions. |
| 186 |
|
| 187 |
```bash |
| 188 |
make multirun <CMD> [ARG...] |
| 189 |
``` |
| 190 |
|
| 191 |
This command runs an arbitrary command inside the environments |
| 192 |
for all supported Python versions. It is especially useful for running tests. |
| 193 |
""" |
| 194 |
if PYTHON_VERSIONS: |
| 195 |
for version in PYTHON_VERSIONS: |
| 196 |
run3x(version, cmd, *args, **kwargs) |
| 197 |
else: |
| 198 |
run(cmd, *args, **kwargs) |
| 199 |
|
| 200 |
|
| 201 |
@_command("allrun") |
| 202 |
def allrun(cmd: str, *args: str, **kwargs: Any) -> None: |
| 203 |
"""Run a command in all virtual environments. |
| 204 |
|
| 205 |
```bash |
| 206 |
make multirun <CMD> [ARG...] |
| 207 |
``` |
| 208 |
|
| 209 |
This command runs an arbitrary command inside the default environment, |
| 210 |
as well as the environments for all supported Python versions. |
| 211 |
|
| 212 |
This command is especially useful to install, remove or update dependencies |
| 213 |
in all environments at once. For example, if you want to install a dependency |
| 214 |
in editable mode, from a local source: |
| 215 |
|
| 216 |
```bash |
| 217 |
make allrun uv pip install -e ../other-project |
| 218 |
``` |
| 219 |
""" |
| 220 |
run(cmd, *args, **kwargs) |
| 221 |
if PYTHON_VERSIONS: |
| 222 |
multirun(cmd, *args, **kwargs) |
| 223 |
|
| 224 |
|
| 225 |
@_command("3.x") |
| 226 |
def run3x(version: str, cmd: str, *args: str, **kwargs: Any) -> None: |
| 227 |
"""Run a command in the virtual environment for Python 3.x. |
| 228 |
|
| 229 |
```bash |
| 230 |
make 3.x <CMD> [ARG...] |
| 231 |
``` |
| 232 |
|
| 233 |
This command runs an arbitrary command inside the environment of the selected Python version. |
| 234 |
It can be useful if you want to run a task that usually runs in the default environment |
| 235 |
with a different Python version. |
| 236 |
""" |
| 237 |
_run(version, cmd, *args, **kwargs) |
| 238 |
|
| 239 |
|
| 240 |
@_command("clean") |
| 241 |
def clean() -> None: |
| 242 |
"""Delete build artifacts and cache files. |
| 243 |
|
| 244 |
```bash |
| 245 |
make clean |
| 246 |
``` |
| 247 |
|
| 248 |
This command simply deletes build artifacts and cache files and folders |
| 249 |
such as `build/`, `.cache/`, etc.. The virtual environments (`.venv` and `.venvs/*`) |
| 250 |
are not removed by this command. |
| 251 |
""" |
| 252 |
paths_to_clean = ["build", "dist", "htmlcov", "site", ".coverage*", ".pdm-build"] |
| 253 |
for path in paths_to_clean: |
| 254 |
_shell(f"rm -rf {path}") |
| 255 |
|
| 256 |
cache_dirs = {".cache", ".pytest_cache", ".ruff_cache", "__pycache__"} |
| 257 |
for dirpath in Path().rglob("*/"): |
| 258 |
if dirpath.parts[0] not in (".venv", ".venvs") and dirpath.name in cache_dirs: |
| 259 |
shutil.rmtree(dirpath, ignore_errors=True) |
| 260 |
|
| 261 |
|
| 262 |
@_command("vscode") |
| 263 |
def vscode() -> None: |
| 264 |
"""Configure VSCode to work on this project. |
| 265 |
|
| 266 |
```bash |
| 267 |
make vscode |
| 268 |
``` |
| 269 |
|
| 270 |
This command configures the [VSCode editor](https://code.visualstudio.com/) |
| 271 |
by copying the following files into the `.vscode` directory: |
| 272 |
|
| 273 |
- `launch.json`, for run configurations (to run debug sessions) |
| 274 |
- `settings.json`, for various editor settings like linting tools and their configuration |
| 275 |
- `tasks.json`, for running tasks directly from VSCode's interface |
| 276 |
|
| 277 |
Warning: |
| 278 |
These files will be overwritten every time the command is run. |
| 279 |
""" |
| 280 |
Path(".vscode").mkdir(parents=True, exist_ok=True) |
| 281 |
_shell("cp -v config/vscode/* .vscode") |
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
def main(args: list[str]) -> int: |
| 288 |
"""Main entry point.""" |
| 289 |
if not args or args[0] == "help": |
| 290 |
help(*args) |
| 291 |
return 0 |
| 292 |
|
| 293 |
while args: |
| 294 |
cmd = args.pop(0) |
| 295 |
|
| 296 |
if cmd == "run": |
| 297 |
if not args: |
| 298 |
print("make: run: missing command", file=sys.stderr) |
| 299 |
return 1 |
| 300 |
run(*args) |
| 301 |
return 0 |
| 302 |
|
| 303 |
if cmd == "multirun": |
| 304 |
if not args: |
| 305 |
print("make: run: missing command", file=sys.stderr) |
| 306 |
return 1 |
| 307 |
multirun(*args) |
| 308 |
return 0 |
| 309 |
|
| 310 |
if cmd == "allrun": |
| 311 |
if not args: |
| 312 |
print("make: run: missing command", file=sys.stderr) |
| 313 |
return 1 |
| 314 |
allrun(*args) |
| 315 |
return 0 |
| 316 |
|
| 317 |
if cmd.startswith("3."): |
| 318 |
if not args: |
| 319 |
print("make: run: missing command", file=sys.stderr) |
| 320 |
return 1 |
| 321 |
run3x(cmd, *args) |
| 322 |
return 0 |
| 323 |
|
| 324 |
opts = [] |
| 325 |
while args and (args[0].startswith("-") or "=" in args[0]): |
| 326 |
opts.append(args.pop(0)) |
| 327 |
|
| 328 |
if cmd == "clean": |
| 329 |
clean() |
| 330 |
elif cmd == "setup": |
| 331 |
setup() |
| 332 |
elif cmd == "vscode": |
| 333 |
vscode() |
| 334 |
elif cmd == "check": |
| 335 |
multirun("duty", "check-quality", "check-types", "check-docs") |
| 336 |
run("duty", "check-api") |
| 337 |
elif cmd in {"check-quality", "check-docs", "check-types", "test"}: |
| 338 |
multirun("duty", cmd, *opts) |
| 339 |
else: |
| 340 |
run("duty", cmd, *opts) |
| 341 |
|
| 342 |
return 0 |
| 343 |
|
| 344 |
|
| 345 |
if __name__ == "__main__": |
| 346 |
try: |
| 347 |
sys.exit(main(sys.argv[1:])) |
| 348 |
except _RunError as process: |
| 349 |
if process.output: |
| 350 |
print(process.output, file=sys.stderr) |
| 351 |
if (code := process.returncode) == 139: |
| 352 |
print( |
| 353 |
f"✗ (python{process.python_version}) '{' '.join(process.cmd)}' failed with return code {code} (segfault)", |
| 354 |
file=sys.stderr, |
| 355 |
) |
| 356 |
if process.python_version == PYTHON_DEV: |
| 357 |
code = 0 |
| 358 |
sys.exit(code) |