Debian Codegraph @

tasks/build_/wheels.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2007 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 Build Tasks
19 ~~~~~~~~~~~
20
21 """
22 from __future__ import print_function
23
24 import itertools as _it
25 import os as _os
26 import platform as _platform
27 import re as _re
28
29 import invoke as _invoke
30
31 from .. import _features
32 from .._inv import tasks as _tasks
33 from . import _container
34
35 NAMESPACE = "build"
36
37
38 @_tasks.optional(None, _features.python_wheels)
39 @_invoke.task()
40 def wheels(ctx, arches=None, pythons=None):
41 """
42 Build wheels
43
44 Parameters:
45 arches (str):
46 Space separated list of architectures. If not supplied it defaults to
47 the current machine type. Except if the current machine type is
48 "x86_64", then if defaults to "x86_64 i686 aarch64" (using
49 binfmt_misc in combination with multiarch/qemu-user-static for the
50 latter).
51
52 pythons (str):
53 Space separated list of pythons (36 37 etc). If omitted, all possible
54 python versions will be built. Only relevant for binary builds.
55 """
56 if ctx.wheels.build == "binary":
57 return _build_binary(ctx, arches=arches, pythons=pythons)
58
59 assert not arches
60 assert ctx.wheels.build in ("universal", "simple")
61 return _build_universal(ctx)
62
63
64 def _build_universal(ctx):
65 """Build universal / simple wheel"""
66 path = ".bdist"
67
68 with ctx.shell.root_dir():
69 ctx.shell.rm_rf(path)
70
71 cmd = ctx.s("pip wheel --no-binary :all: --no-cache --no-deps -w")
72 cmd += [path]
73
74 for package in ctx.shell.files(
75 "dist/", "%s[-_]*.tar.gz" % (ctx.package,)
76 ):
77 ctx.run(ctx.c(cmd + [package]), echo=True)
78 _finalize_bdist(ctx, path)
79
80
81 def _build_binary(ctx, arches=None, pythons=None):
82 """
83 Build binary wheels
84
85 Parameters:
86 arches (str):
87 Space separated list of architectures. If not supplied it defaults to
88 the current machine type. Except if the current machine type is
89 "x86_64", then if defaults to "x86_64 i686 aarch64" (using
90 binfmt_misc in combination with multiarch/qemu-user-static for the
91 latter).
92
93 pythons (str):
94 Space separated list of pythons (36 37 etc). If omitted, all possible
95 python versions will be built. Only relevant for binary builds.
96 """
97 path = ".bdist"
98 arches = _ensure_arches(ctx, arches)
99 build_sh = _os.path.join(_os.path.dirname(__file__), "wheel.sh")
100 wanted_pythons = set(pythons.split()) if pythons else None
101
102 with ctx.shell.root_dir():
103 ctx.shell.rm_rf(path)
104 ctx.shell.mkdir_p(path)
105
106 for package in ctx.shell.files(
107 "dist/", "%s-*.tar.gz" % (ctx.package,)
108 ):
109 for image, cmd, libc, py in _pypa_containers(ctx, arches):
110 pythons = (
111 py
112 if wanted_pythons is None
113 else (set(py) & wanted_pythons)
114 )
115 if not pythons:
116 continue
117
118 name = "wheel-%s" % (_os.path.basename(package),)
119 cmd += [
120 "/io/build.sh",
121 libc,
122 "/io/pkg.tar.gz",
123 " ".join(sorted(pythons)),
124 ]
125
126 with _container.Container(ctx, name, image) as container:
127 container.execute(ctx.s("mkdir /io"))
128 container.cp_in(package, "/io/pkg.tar.gz")
129 container.cp_in(build_sh, "/io/build.sh")
130 container.execute(ctx.s("chmod +x /io/build.sh"))
131 container.execute(cmd)
132 container.cp_out("/io/dist/.", path)
133
134 _finalize_bdist(ctx, path)
135
136
137 def _finalize_bdist(ctx, path):
138 """
139 Finalize wheel names, move files to dist/
140
141 Parameters:
142 path (str):
143 wheel path
144 """
145 # collapse file names
146 multi_sub = _re.compile(r"(?:[.-]manylinux[^.]+)+").sub
147 tomove = []
148 for name in _os.listdir(path):
149 if not name.endswith(".whl"):
150 continue
151 if "manylinux" not in name:
152 continue
153
154 pick = _best_manylinux(name)
155 if pick:
156 tomove.append(
157 (name, multi_sub((lambda _, p=pick: "-" + p), name))
158 )
159 for old, new in tomove:
160 if old == new:
161 continue
162 _os.rename(_os.path.join(path, old), _os.path.join(path, new))
163
164 if path == "dist":
165 return
166
167 # Move to dist/
168 for name in _os.listdir(path):
169 old = "%s/%s" % (path, name)
170 new = "dist/%s" % (name,)
171 print("%s -> %s" % (old, new))
172 _os.rename(ctx.shell.native(old), ctx.shell.native(new))
173
174
175 def _pypa_containers(ctx, arches):
176 """
177 Create a list of containers to execute
178
179 Parameters:
180 arches (list):
181 List of arches to apply
182
183 Yields:
184 tuple: image, command prefix, libc, python list
185 """
186 for arch in arches:
187 spec = ctx.wheels.specs[arch]
188 prefix = "linux32" if arch == "i686" else ""
189 for libc in ("manylinux", "musllinux"):
190 groups = sorted(
191 (
192 (tup[0], tup[1][libc])
193 for tup in spec.items()
194 if libc in tup[1]
195 ),
196 key=lambda x, libc=libc: (x[1], x[0]),
197 )
198 for v, group in _it.groupby(groups, key=lambda x: x[1]):
199 if "_" in v:
200 v = "_" + v
201 if ":" in v:
202 v, tag = v.split(":", 1)
203 else:
204 tag = "latest"
205
206 yield (
207 "quay.io/pypa/%s%s_%s:%s" % (libc, v, arch, tag),
208 [prefix] if prefix else [],
209 libc,
210 sorted(item[0] for item in group),
211 )
212
213
214 def _ensure_arches(ctx, arches):
215 """
216 Install multiarch qemu
217
218 Parameters:
219 arches (str):
220 The desired architectures
221
222 Returns:
223 list: The split architecture strings
224 """
225 machine = _platform.machine()
226 system = _platform.system()
227 if arches is None:
228 if machine == "x86_64":
229 arches = "x86_64 i686 aarch64"
230 else:
231 arches = machine
232 arches = arches.split()
233
234 if system == "Linux":
235 for arch in arches:
236 if machine == arch:
237 continue
238 if machine == "x86_64":
239 if arch == "i686":
240 continue
241
242 ctx.run(
243 ctx.c(
244 _container.DockerCommand(ctx).run(
245 "multiarch/qemu-user-static",
246 command=["--reset", "-p", "yes"],
247 remove=True,
248 privileged=True,
249 )
250 ),
251 echo=True,
252 )
253
254 break
255
256 return arches
257
258
259 def _best_manylinux(name):
260 """
261 Find best manylinux variant produced by auditwheel
262
263 Parameters:
264 name (str):
265 filename (basename) of the package
266
267 Returns:
268 str: The best version, or ``None`` if it couldn't be determined
269 """
270 tag_list_search = _re.compile(r"(?:[.-]manylinux[^.]+)+").search
271
272 tags = tag_list_search(name)
273 if not tags:
274 return None
275 sortable = []
276 for tag in tags.group(0).strip("-.").split("."):
277 assert tag.startswith("manylinux")
278 ver = tag[len("manylinux") :]
279 if ver.startswith(("1_", "2010_", "2014_")):
280 sortable.append(((1, int(ver.split("_")[0])), tag))
281 continue
282 assert ver.startswith("_")
283 ver = tuple(map(int, ver[1:].split("_")[:2]))
284 assert ver[0] > 1
285 sortable.append((ver, tag))
286
287 if not sortable:
288 return None
289
290 return min(sortable)[-1]