Debian Codegraph @

scripts/make

raw
1 #!/usr/bin/env python3
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 textwrap import dedent
11 from typing import TYPE_CHECKING, Any
12
13 if TYPE_CHECKING:
14 from collections.abc import Iterator
15
16
17 PYTHON_VERSIONS = os.getenv("PYTHON_VERSIONS", "3.10 3.11 3.12 3.13 3.14 3.15").split()
18 PYTHON_DEV = "3.15"
19
20
21 def shell(cmd: str, *, capture_output: bool = False, **kwargs: Any) -> str | None:
22 """Run a shell command."""
23 if capture_output:
24 return subprocess.check_output(cmd, shell=True, text=True, **kwargs) # noqa: S602
25 subprocess.run(cmd, shell=True, check=True, stderr=subprocess.STDOUT, **kwargs) # noqa: S602
26 return None
27
28
29 @contextmanager
30 def environ(**kwargs: str) -> Iterator[None]:
31 """Temporarily set environment variables."""
32 original = dict(os.environ)
33 os.environ.update(kwargs)
34 try:
35 yield
36 finally:
37 os.environ.clear()
38 os.environ.update(original)
39
40
41 def uv_install(venv: Path) -> None:
42 """Install dependencies using uv."""
43 with environ(UV_PROJECT_ENVIRONMENT=str(venv), PYO3_USE_ABI3_FORWARD_COMPATIBILITY="1"):
44 if "CI" in os.environ:
45 shell("uv sync --no-editable")
46 else:
47 shell("uv sync")
48
49
50 def setup() -> None:
51 """Setup the project."""
52 if not shutil.which("uv"):
53 raise ValueError("make: setup: uv must be installed, see https://github.com/astral-sh/uv")
54
55 print("Installing dependencies (default environment)")
56 default_venv = Path(".venv")
57 if not default_venv.exists():
58 shell("uv venv")
59 uv_install(default_venv)
60
61 if PYTHON_VERSIONS:
62 for version in PYTHON_VERSIONS:
63 print(f"\nInstalling dependencies (python{version})")
64 venv_path = Path(f".venvs/{version}")
65 if not venv_path.exists():
66 shell(f"uv venv --python {version} {venv_path}")
67 with environ(UV_PROJECT_ENVIRONMENT=str(venv_path.resolve())):
68 uv_install(venv_path)
69
70
71 class _RunError(subprocess.CalledProcessError):
72 def __init__(self, *args: Any, python_version: str, **kwargs: Any):
73 super().__init__(*args, **kwargs)
74 self.python_version = python_version
75
76
77 def run(version: str, cmd: str, *args: str, **kwargs: Any) -> None:
78 """Run a command in a virtual environment."""
79 kwargs = {"check": True, **kwargs}
80 uv_run = ["uv", "run", "--no-sync"]
81 try:
82 if version == "default":
83 with environ(UV_PROJECT_ENVIRONMENT=".venv"):
84 subprocess.run([*uv_run, cmd, *args], **kwargs) # noqa: S603, PLW1510
85 else:
86 with environ(UV_PROJECT_ENVIRONMENT=f".venvs/{version}", MULTIRUN="1"):
87 subprocess.run([*uv_run, cmd, *args], **kwargs) # noqa: S603, PLW1510
88 except subprocess.CalledProcessError as process:
89 raise _RunError(
90 returncode=process.returncode,
91 python_version=version,
92 cmd=process.cmd,
93 output=process.output,
94 stderr=process.stderr,
95 ) from process
96
97
98 def multirun(cmd: str, *args: str, **kwargs: Any) -> None:
99 """Run a command for all configured Python versions."""
100 if PYTHON_VERSIONS:
101 for version in PYTHON_VERSIONS:
102 run(version, cmd, *args, **kwargs)
103 else:
104 run("default", cmd, *args, **kwargs)
105
106
107 def allrun(cmd: str, *args: str, **kwargs: Any) -> None:
108 """Run a command in all virtual environments."""
109 run("default", cmd, *args, **kwargs)
110 if PYTHON_VERSIONS:
111 multirun(cmd, *args, **kwargs)
112
113
114 def clean() -> None:
115 """Delete build artifacts and cache files."""
116 paths_to_clean = ["build", "dist", "htmlcov", "site", ".coverage*", ".pdm-build"]
117 for path in paths_to_clean:
118 shutil.rmtree(path, ignore_errors=True)
119
120 cache_dirs = {".cache", ".pytest_cache", ".ruff_cache", "__pycache__"}
121 for dirpath in Path().rglob("*/"):
122 if dirpath.parts[0] not in (".venv", ".venvs") and dirpath.name in cache_dirs:
123 shutil.rmtree(dirpath, ignore_errors=True)
124
125
126 def vscode() -> None:
127 """Configure VSCode to work on this project."""
128 shutil.copytree("config/vscode", ".vscode", dirs_exist_ok=True)
129
130
131 def main() -> int:
132 """Main entry point."""
133 args = list(sys.argv[1:])
134 if not args or args[0] == "help":
135 if len(args) > 1:
136 run("default", "duty", "--help", args[1])
137 else:
138 print(
139 dedent(
140 """
141 Available commands
142 help Print this help. Add task name to print help.
143 setup Setup all virtual environments (install dependencies).
144 run Run a command in the default virtual environment.
145 multirun Run a command for all configured Python versions.
146 allrun Run a command in all virtual environments.
147 3.x Run a command in the virtual environment for Python 3.x.
148 clean Delete build artifacts and cache files.
149 vscode Configure VSCode to work on this project.
150 """,
151 ),
152 flush=True,
153 )
154 if Path(".venv").exists():
155 print("\nAvailable tasks", flush=True)
156 run("default", "duty", "--list")
157 return 0
158
159 while args:
160 cmd = args.pop(0)
161
162 if cmd == "run":
163 if not args:
164 print("make: run: missing command", file=sys.stderr)
165 return 1
166 run("default", *args)
167 return 0
168
169 if cmd == "multirun":
170 if not args:
171 print("make: run: missing command", file=sys.stderr)
172 return 1
173 multirun(*args)
174 return 0
175
176 if cmd == "allrun":
177 if not args:
178 print("make: run: missing command", file=sys.stderr)
179 return 1
180 allrun(*args)
181 return 0
182
183 if cmd.startswith("3."):
184 if not args:
185 print("make: run: missing command", file=sys.stderr)
186 return 1
187 run(cmd, *args)
188 return 0
189
190 opts = []
191 while args and (args[0].startswith("-") or "=" in args[0]):
192 opts.append(args.pop(0))
193
194 if cmd == "clean":
195 clean()
196 elif cmd == "setup":
197 setup()
198 elif cmd == "vscode":
199 vscode()
200 elif cmd == "check":
201 multirun("duty", "check-quality", "check-types", "check-docs")
202 run("default", "duty", "check-api")
203 elif cmd in {"check-quality", "check-docs", "check-types", "test"}:
204 multirun("duty", cmd, *opts)
205 else:
206 run("default", "duty", cmd, *opts)
207
208 return 0
209
210
211 if __name__ == "__main__":
212 try:
213 sys.exit(main())
214 except _RunError as process:
215 if process.output:
216 print(process.output, file=sys.stderr)
217 if (code := process.returncode) == 139: # noqa: PLR2004
218 print(
219 f"✗ (python{process.python_version}) '{' '.join(process.cmd)}' failed with return code {code} (segfault)",
220 file=sys.stderr,
221 )
222 if process.python_version == PYTHON_DEV:
223 code = 0
224 sys.exit(code)