Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
454 lines (412 loc) · 15.8 KB
/
Copy pathbuild.py
File metadata and controls
454 lines (412 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# Data Parallel Control (dpctl)
#
# Copyright 2026 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Builds this repository's packages for one Python version.
For the intel-ci.yml GitHub Actions workflow.
This file and ci/matrix.py work out the build system from the files present,
and the Python versions from that build system's own declaration:
rattler-build .conda recipe.yaml or recipe/recipe.yaml, versions in
variants.yaml
conda-build .conda conda-recipe/meta.yaml or meta.yaml, versions in
conda_build_config.yaml
cibuildwheel .whl pyproject.toml, versions from its classifiers
Usage:
python ci/build.py --python 3.14 --output OUT [--system rattler-build]
[--channel conda-forge]
--python must be one of the declared versions; `python ci/matrix.py` lists them.
Packages land directly in OUT, ready for actions/upload-artifact. A conda
recipe's own tests run during the build. Needs only the Python standard library.
rattler-build is used from PATH, or downloaded at a pinned version for Linux or
Windows and checked against its published sha256; conda-build, or cibuildwheel
for wheels, must already be installed for this interpreter, so run it with the
conda base install's Python to build with conda-build.
Wheels build with cibuildwheel, in a manylinux container on Linux, as
pyproject.toml's [tool.cibuildwheel] says. Run-time requirements that
pyproject.toml cannot declare, because the conda package gets them from its
recipe instead, such as MKL's libraries, go in [tool.gh-ci] wheel-requires:
build.py adds them to each wheel's metadata. [tool.gh-ci] pin-compatible maps a
run-time requirement to the build dependency it follows, like conda's
pin_compatible: build.py requires >= the version the build logged for it, < its
next major. The versions come from the list python -m build logs, and from the
same list headed "Installed SDK versions:", which a before-all step can print
for what it installs outside pip.
"""
import argparse
import base64
import hashlib
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import urllib.request
import zipfile
from pathlib import Path
import matrix
ROOT = matrix.ROOT
PACKAGE_SUFFIXES = (".conda", ".tar.bz2", ".whl")
ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
# The headings of the version lists build_versions reads
VERSION_HEADINGS = (
"Installed build dependency versions:",
"Installed SDK versions:",
)
# cibuildwheel's platform part of a build identifier, per system.
WHEEL_PLATFORMS = {
"Linux": "manylinux_x86_64",
"Windows": "win_amd64",
"Darwin": "macosx_x86_64",
}
# The rattler-build release fetched when none is on PATH, per system, with the
# file name it goes under and the sha256 its release publishes.
RATTLER_BUILD_VERSION = "v0.77.0"
RATTLER_BUILD_RELEASES = {
"Linux": (
"rattler-build-x86_64-unknown-linux-musl",
"rattler-build",
"5a5e8150c703b21e88a01f9130ea49a7a680198e9ac9414170c0a293fed7e5af",
),
"Windows": (
"rattler-build-x86_64-pc-windows-msvc.exe",
"rattler-build.exe",
"e144334f782cee9aa23e26eb8d095c143e1696fbbec7ba7534a156663d4abb2c",
),
}
class BuildError(Exception):
"""Raised when the build cannot start or produced nothing."""
def ensure_rattler_build(tools: Path) -> None:
"""
Puts rattler-build on PATH, downloading the pinned release when none is
there.
"""
if shutil.which("rattler-build"):
return
release = RATTLER_BUILD_RELEASES.get(platform.system())
if release is None or platform.machine().lower() not in ("x86_64", "amd64"):
raise BuildError(
"no rattler-build on PATH, and only the Linux and Windows x86_64 "
"releases are pinned here"
)
asset, name, sha256 = release
print(f"build: fetching rattler-build {RATTLER_BUILD_VERSION}", flush=True)
url = (
"https://github.com/prefix-dev/rattler-build/releases/download/"
f"{RATTLER_BUILD_VERSION}/{asset}"
)
with urllib.request.urlopen(url, timeout=300) as reply:
binary = reply.read()
if hashlib.sha256(binary).hexdigest() != sha256:
raise BuildError(
f"rattler-build {RATTLER_BUILD_VERSION} does not match its pinned "
"sha256"
)
tools.mkdir(parents=True, exist_ok=True)
target = tools / name
target.write_bytes(binary)
target.chmod(0o755)
os.environ["PATH"] = f'{tools}{os.pathsep}{os.environ.get("PATH", "")}'
def cibuildwheel_identifier(python: matrix.Python) -> str:
"""The one build cibuildwheel runs, such as cp314t-manylinux_x86_64."""
tag = WHEEL_PLATFORMS.get(platform.system())
if tag is None:
raise BuildError(
f"wheels build on Linux, Windows or macOS, not {platform.system()}"
)
minor, threaded = matrix.version_key(python.version)
return f'cp3{minor}{"t" if threaded else ""}-{tag}'
def wheel_settings() -> tuple[list[str], dict[str, str]]:
"""[tool.gh-ci] wheel-requires and pin-compatible from pyproject.toml."""
if matrix.TOMLLIB is None:
raise BuildError("reading pyproject.toml needs Python 3.11 or newer")
text = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
tool = matrix.TOMLLIB.loads(text).get("tool", {}).get("gh-ci", {})
requires = tool.get("wheel-requires", [])
if not isinstance(requires, list) or not all(
isinstance(r, str) for r in requires
):
raise BuildError("[tool.gh-ci] wheel-requires must be a list of specs")
pins = tool.get("pin-compatible", {})
if not isinstance(pins, dict) or not all(
isinstance(k, str) and isinstance(v, str) for k, v in pins.items()
):
raise BuildError(
"[tool.gh-ci] pin-compatible must map a run-time requirement to "
"a build dependency"
)
return requires, pins
def canonical(name: str) -> str:
"""A distribution name as PEP 503 compares it."""
return re.sub(r"[-_.]+", "-", name).lower()
def build_versions(log: list[str]) -> dict[str, str]:
"""
The version of each build dependency, from the "- name==version" lists
under VERSION_HEADINGS in the build's log.
"""
versions, listing = {}, False
for line in log:
text = ANSI_RE.sub("", line).strip()
if text.endswith(VERSION_HEADINGS):
listing = True
elif listing and (match := re.fullmatch(r"- ([\w.-]+)==(\S+)", text)):
versions[canonical(match[1])] = match[2]
else:
listing = False
return versions
def pinned(pins: dict[str, str], versions: dict[str, str]) -> list[str]:
"""Each pinned run-time requirement: >= its build version, < next major."""
specs = []
for runtime, build in pins.items():
version = versions.get(canonical(build))
major = version.split(".")[0] if version else ""
if not major.isdigit():
raise BuildError(
f"the build logged no installed {build} version, which "
f"[tool.gh-ci] pin-compatible pins {runtime} to"
)
specs.append(f"{runtime} >={version},<{int(major) + 1}")
return specs
def run_logged(command: list[str]) -> list[str]:
"""Runs a command, passing its output through, and returns that output."""
lines = []
sys.stdout.flush()
with subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
) as process:
for line in process.stdout:
sys.stdout.buffer.write(line)
sys.stdout.buffer.flush()
lines.append(line.decode("utf-8", "replace"))
if process.returncode:
raise subprocess.CalledProcessError(process.returncode, command)
return lines
def record_hash(data: bytes) -> str:
"""A file's hash as a wheel's RECORD spells it."""
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest())
return "sha256=" + digest.rstrip(b"=").decode("ascii")
def add_requirements(wheel: Path, requirements: list[str]) -> None:
"""Adds Requires-Dist lines to a built wheel, and updates its RECORD."""
with zipfile.ZipFile(wheel) as source:
members = [(info, source.read(info)) for info in source.infolist()]
names = [info.filename for info, _ in members]
metadata = next(n for n in names if n.endswith(".dist-info/METADATA"))
record = metadata.removesuffix("METADATA") + "RECORD"
for index, (info, data) in enumerate(members):
if info.filename == metadata:
metadata_text = data.decode("utf-8").replace("\r\n", "\n")
head, blank, body = metadata_text.partition("\n\n")
head = head.rstrip("\n") + "".join(
f"\nRequires-Dist: {r}" for r in requirements
)
text = head + ("\n\n" + body if blank else "\n")
new_metadata = text.encode("utf-8")
members[index] = (info, new_metadata)
for index, (info, data) in enumerate(members):
if info.filename == record:
lines = [
(
f"{metadata},{record_hash(new_metadata)},"
f"{len(new_metadata)}"
if line.split(",")[0] == metadata
else line
)
for line in data.decode("utf-8").splitlines()
]
members[index] = (info, ("\n".join(lines) + "\n").encode())
rewritten = wheel.with_suffix(".tmp")
with zipfile.ZipFile(rewritten, "w", zipfile.ZIP_DEFLATED) as target:
for info, data in members:
target.writestr(info, data)
rewritten.replace(wheel)
def commands(
system: str,
selector: Path,
python: matrix.Python,
channels: list[str],
scratch: Path,
) -> list[list[str]]:
"""
The commands that build one Python version's packages into scratch.
Each build system gets the version back exactly as its own file declares it,
and keeps every other variant setting from that file.
"""
channel_args = [arg for channel in channels for arg in ("-c", channel)]
# The commit a conda package came from, in its info/about.json
github = [
os.environ.get(name, "")
for name in ("GITHUB_SERVER_URL", "GITHUB_REPOSITORY", "GITHUB_SHA")
]
extra_meta = (
[
"--extra-meta",
f"remote_url={github[0]}/{github[1]}",
f"sha={github[2]}",
]
if all(github)
else []
)
if system == "rattler-build":
return [
[
"rattler-build",
"build",
"-r",
str(selector),
"--variant",
f"python={python.spec}",
"--output-dir",
str(scratch / "conda"),
*channel_args,
]
]
if system == "conda-build":
# conda runs as a module of this interpreter, so Windows needs no
# conda.bat on PATH.
return [
[
sys.executable,
"-m",
"conda",
"build",
str(selector.parent),
"--python",
python.spec,
"--no-anaconda-upload",
"--output-folder",
str(scratch / "conda"),
*extra_meta,
"--override-channels",
*channel_args,
]
]
return [
[
sys.executable,
"-m",
"cibuildwheel",
"--only",
cibuildwheel_identifier(python),
"--output-dir",
str(scratch / "wheel"),
str(ROOT),
]
]
def collect(scratch: Path, output: Path) -> list[Path]:
"""
Moves built packages into output, flat, and lists the ones it moved.
Two packages of one name are an error: flat, one would overwrite the other.
"""
output.mkdir(parents=True, exist_ok=True)
sources: dict[str, Path] = {}
for package in sorted(scratch.rglob("*")):
if (
package.is_file()
and package.name.endswith(PACKAGE_SUFFIXES)
and "broken" not in package.parts
):
if package.name in sources:
raise BuildError(
f"two packages named {package.name}: "
f"{sources[package.name]} and {package}"
)
sources[package.name] = package
shutil.move(str(package), output / package.name)
built = [output / name for name in sorted(sources)]
if not built:
raise BuildError(f"the build left no package in {output}")
return built
def main(argv: list[str] | None = None) -> int:
"""Builds one Python version."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[1])
parser.add_argument(
"--python", required=True, help="a declared version, such as 3.14t"
)
parser.add_argument(
"--output", required=True, type=Path, help="where the packages go"
)
parser.add_argument(
"--system",
default="",
choices=("", *matrix.SYSTEMS),
help="build system to use instead of the detected one",
)
parser.add_argument(
"--channel",
action="append",
default=None,
help="conda channel to build against, repeatable; default conda-forge",
)
default_tools = (
Path(os.environ.get("RUNNER_TEMP", tempfile.gettempdir())) / "ci-tools"
)
parser.add_argument(
"--tools",
type=Path,
default=default_tools,
help="where a downloaded rattler-build goes",
)
args = parser.parse_args(argv)
system, selector = matrix.detect(ROOT, args.system)
declared = {
python.version: python for python in matrix.declared(system, selector)
}
if args.python not in declared:
raise BuildError(
f"Python {args.python} is not declared for {system}; "
f'declared: {", ".join(declared)}'
)
python = declared[args.python]
print(
f"build: {system} from {selector.relative_to(ROOT)} "
f"for Python {python.version} ({python.spec})",
flush=True,
)
if system == "rattler-build":
ensure_rattler_build(args.tools)
requires, pins = wheel_settings() if system == "wheel" else ([], {})
output = args.output.resolve()
log: list[str] = []
with tempfile.TemporaryDirectory() as scratch:
for command in commands(
system,
selector,
python,
args.channel or ["conda-forge"],
Path(scratch),
):
print(f"+ {shlex.join(command)}", flush=True)
log += run_logged(command)
if system == "wheel":
requires = requires + pinned(pins, build_versions(log))
for wheel in sorted(Path(scratch).rglob("*.whl")) if requires else []:
add_requirements(wheel, requires)
built = collect(Path(scratch), output)
if requires:
print("build: added Requires-Dist " + ", ".join(requires))
print("build: " + ", ".join(path.name for path in built))
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (
BuildError,
matrix.DeclarationError,
subprocess.CalledProcessError,
) as error:
print(f"build: {error}", file=sys.stderr)
sys.exit(1)