Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
keewenaw
GitHub Repository: keewenaw/ethereum-wallet-cracker
Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/wheel_builder.py
4799 views
1
"""Orchestrator for building wheels from InstallRequirements.
2
"""
3
4
import logging
5
import os.path
6
import re
7
import shutil
8
from typing import Any, Callable, Iterable, List, Optional, Tuple
9
10
from pip._vendor.packaging.utils import canonicalize_name, canonicalize_version
11
from pip._vendor.packaging.version import InvalidVersion, Version
12
13
from pip._internal.cache import WheelCache
14
from pip._internal.exceptions import InvalidWheelFilename, UnsupportedWheel
15
from pip._internal.metadata import FilesystemWheel, get_wheel_distribution
16
from pip._internal.models.link import Link
17
from pip._internal.models.wheel import Wheel
18
from pip._internal.operations.build.wheel import build_wheel_pep517
19
from pip._internal.operations.build.wheel_editable import build_wheel_editable
20
from pip._internal.operations.build.wheel_legacy import build_wheel_legacy
21
from pip._internal.req.req_install import InstallRequirement
22
from pip._internal.utils.logging import indent_log
23
from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed
24
from pip._internal.utils.setuptools_build import make_setuptools_clean_args
25
from pip._internal.utils.subprocess import call_subprocess
26
from pip._internal.utils.temp_dir import TempDirectory
27
from pip._internal.utils.urls import path_to_url
28
from pip._internal.vcs import vcs
29
30
logger = logging.getLogger(__name__)
31
32
_egg_info_re = re.compile(r"([a-z0-9_.]+)-([a-z0-9_.!+-]+)", re.IGNORECASE)
33
34
BinaryAllowedPredicate = Callable[[InstallRequirement], bool]
35
BuildResult = Tuple[List[InstallRequirement], List[InstallRequirement]]
36
37
38
def _contains_egg_info(s: str) -> bool:
39
"""Determine whether the string looks like an egg_info.
40
41
:param s: The string to parse. E.g. foo-2.1
42
"""
43
return bool(_egg_info_re.search(s))
44
45
46
def _should_build(
47
req: InstallRequirement,
48
need_wheel: bool,
49
check_binary_allowed: BinaryAllowedPredicate,
50
) -> bool:
51
"""Return whether an InstallRequirement should be built into a wheel."""
52
if req.constraint:
53
# never build requirements that are merely constraints
54
return False
55
if req.is_wheel:
56
if need_wheel:
57
logger.info(
58
"Skipping %s, due to already being wheel.",
59
req.name,
60
)
61
return False
62
63
if need_wheel:
64
# i.e. pip wheel, not pip install
65
return True
66
67
# From this point, this concerns the pip install command only
68
# (need_wheel=False).
69
70
if not req.source_dir:
71
return False
72
73
if req.editable:
74
# we only build PEP 660 editable requirements
75
return req.supports_pyproject_editable()
76
77
if req.use_pep517:
78
return True
79
80
if not check_binary_allowed(req):
81
logger.info(
82
"Skipping wheel build for %s, due to binaries being disabled for it.",
83
req.name,
84
)
85
return False
86
87
if not is_wheel_installed():
88
# we don't build legacy requirements if wheel is not installed
89
logger.info(
90
"Using legacy 'setup.py install' for %s, "
91
"since package 'wheel' is not installed.",
92
req.name,
93
)
94
return False
95
96
return True
97
98
99
def should_build_for_wheel_command(
100
req: InstallRequirement,
101
) -> bool:
102
return _should_build(req, need_wheel=True, check_binary_allowed=_always_true)
103
104
105
def should_build_for_install_command(
106
req: InstallRequirement,
107
check_binary_allowed: BinaryAllowedPredicate,
108
) -> bool:
109
return _should_build(
110
req, need_wheel=False, check_binary_allowed=check_binary_allowed
111
)
112
113
114
def _should_cache(
115
req: InstallRequirement,
116
) -> Optional[bool]:
117
"""
118
Return whether a built InstallRequirement can be stored in the persistent
119
wheel cache, assuming the wheel cache is available, and _should_build()
120
has determined a wheel needs to be built.
121
"""
122
if req.editable or not req.source_dir:
123
# never cache editable requirements
124
return False
125
126
if req.link and req.link.is_vcs:
127
# VCS checkout. Do not cache
128
# unless it points to an immutable commit hash.
129
assert not req.editable
130
assert req.source_dir
131
vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
132
assert vcs_backend
133
if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):
134
return True
135
return False
136
137
assert req.link
138
base, ext = req.link.splitext()
139
if _contains_egg_info(base):
140
return True
141
142
# Otherwise, do not cache.
143
return False
144
145
146
def _get_cache_dir(
147
req: InstallRequirement,
148
wheel_cache: WheelCache,
149
) -> str:
150
"""Return the persistent or temporary cache directory where the built
151
wheel need to be stored.
152
"""
153
cache_available = bool(wheel_cache.cache_dir)
154
assert req.link
155
if cache_available and _should_cache(req):
156
cache_dir = wheel_cache.get_path_for_link(req.link)
157
else:
158
cache_dir = wheel_cache.get_ephem_path_for_link(req.link)
159
return cache_dir
160
161
162
def _always_true(_: Any) -> bool:
163
return True
164
165
166
def _verify_one(req: InstallRequirement, wheel_path: str) -> None:
167
canonical_name = canonicalize_name(req.name or "")
168
w = Wheel(os.path.basename(wheel_path))
169
if canonicalize_name(w.name) != canonical_name:
170
raise InvalidWheelFilename(
171
"Wheel has unexpected file name: expected {!r}, "
172
"got {!r}".format(canonical_name, w.name),
173
)
174
dist = get_wheel_distribution(FilesystemWheel(wheel_path), canonical_name)
175
dist_verstr = str(dist.version)
176
if canonicalize_version(dist_verstr) != canonicalize_version(w.version):
177
raise InvalidWheelFilename(
178
"Wheel has unexpected file name: expected {!r}, "
179
"got {!r}".format(dist_verstr, w.version),
180
)
181
metadata_version_value = dist.metadata_version
182
if metadata_version_value is None:
183
raise UnsupportedWheel("Missing Metadata-Version")
184
try:
185
metadata_version = Version(metadata_version_value)
186
except InvalidVersion:
187
msg = f"Invalid Metadata-Version: {metadata_version_value}"
188
raise UnsupportedWheel(msg)
189
if metadata_version >= Version("1.2") and not isinstance(dist.version, Version):
190
raise UnsupportedWheel(
191
"Metadata 1.2 mandates PEP 440 version, "
192
"but {!r} is not".format(dist_verstr)
193
)
194
195
196
def _build_one(
197
req: InstallRequirement,
198
output_dir: str,
199
verify: bool,
200
build_options: List[str],
201
global_options: List[str],
202
editable: bool,
203
) -> Optional[str]:
204
"""Build one wheel.
205
206
:return: The filename of the built wheel, or None if the build failed.
207
"""
208
artifact = "editable" if editable else "wheel"
209
try:
210
ensure_dir(output_dir)
211
except OSError as e:
212
logger.warning(
213
"Building %s for %s failed: %s",
214
artifact,
215
req.name,
216
e,
217
)
218
return None
219
220
# Install build deps into temporary directory (PEP 518)
221
with req.build_env:
222
wheel_path = _build_one_inside_env(
223
req, output_dir, build_options, global_options, editable
224
)
225
if wheel_path and verify:
226
try:
227
_verify_one(req, wheel_path)
228
except (InvalidWheelFilename, UnsupportedWheel) as e:
229
logger.warning("Built %s for %s is invalid: %s", artifact, req.name, e)
230
return None
231
return wheel_path
232
233
234
def _build_one_inside_env(
235
req: InstallRequirement,
236
output_dir: str,
237
build_options: List[str],
238
global_options: List[str],
239
editable: bool,
240
) -> Optional[str]:
241
with TempDirectory(kind="wheel") as temp_dir:
242
assert req.name
243
if req.use_pep517:
244
assert req.metadata_directory
245
assert req.pep517_backend
246
if global_options:
247
logger.warning(
248
"Ignoring --global-option when building %s using PEP 517", req.name
249
)
250
if build_options:
251
logger.warning(
252
"Ignoring --build-option when building %s using PEP 517", req.name
253
)
254
if editable:
255
wheel_path = build_wheel_editable(
256
name=req.name,
257
backend=req.pep517_backend,
258
metadata_directory=req.metadata_directory,
259
tempd=temp_dir.path,
260
)
261
else:
262
wheel_path = build_wheel_pep517(
263
name=req.name,
264
backend=req.pep517_backend,
265
metadata_directory=req.metadata_directory,
266
tempd=temp_dir.path,
267
)
268
else:
269
wheel_path = build_wheel_legacy(
270
name=req.name,
271
setup_py_path=req.setup_py_path,
272
source_dir=req.unpacked_source_directory,
273
global_options=global_options,
274
build_options=build_options,
275
tempd=temp_dir.path,
276
)
277
278
if wheel_path is not None:
279
wheel_name = os.path.basename(wheel_path)
280
dest_path = os.path.join(output_dir, wheel_name)
281
try:
282
wheel_hash, length = hash_file(wheel_path)
283
shutil.move(wheel_path, dest_path)
284
logger.info(
285
"Created wheel for %s: filename=%s size=%d sha256=%s",
286
req.name,
287
wheel_name,
288
length,
289
wheel_hash.hexdigest(),
290
)
291
logger.info("Stored in directory: %s", output_dir)
292
return dest_path
293
except Exception as e:
294
logger.warning(
295
"Building wheel for %s failed: %s",
296
req.name,
297
e,
298
)
299
# Ignore return, we can't do anything else useful.
300
if not req.use_pep517:
301
_clean_one_legacy(req, global_options)
302
return None
303
304
305
def _clean_one_legacy(req: InstallRequirement, global_options: List[str]) -> bool:
306
clean_args = make_setuptools_clean_args(
307
req.setup_py_path,
308
global_options=global_options,
309
)
310
311
logger.info("Running setup.py clean for %s", req.name)
312
try:
313
call_subprocess(
314
clean_args, command_desc="python setup.py clean", cwd=req.source_dir
315
)
316
return True
317
except Exception:
318
logger.error("Failed cleaning build dir for %s", req.name)
319
return False
320
321
322
def build(
323
requirements: Iterable[InstallRequirement],
324
wheel_cache: WheelCache,
325
verify: bool,
326
build_options: List[str],
327
global_options: List[str],
328
) -> BuildResult:
329
"""Build wheels.
330
331
:return: The list of InstallRequirement that succeeded to build and
332
the list of InstallRequirement that failed to build.
333
"""
334
if not requirements:
335
return [], []
336
337
# Build the wheels.
338
logger.info(
339
"Building wheels for collected packages: %s",
340
", ".join(req.name for req in requirements), # type: ignore
341
)
342
343
with indent_log():
344
build_successes, build_failures = [], []
345
for req in requirements:
346
assert req.name
347
cache_dir = _get_cache_dir(req, wheel_cache)
348
wheel_file = _build_one(
349
req,
350
cache_dir,
351
verify,
352
build_options,
353
global_options,
354
req.editable and req.permit_editable_wheels,
355
)
356
if wheel_file:
357
# Update the link for this.
358
req.link = Link(path_to_url(wheel_file))
359
req.local_file_path = req.link.file_path
360
assert req.link.is_wheel
361
build_successes.append(req)
362
else:
363
build_failures.append(req)
364
365
# notify success/failure
366
if build_successes:
367
logger.info(
368
"Successfully built %s",
369
" ".join([req.name for req in build_successes]), # type: ignore
370
)
371
if build_failures:
372
logger.info(
373
"Failed to build %s",
374
" ".join([req.name for req in build_failures]), # type: ignore
375
)
376
# Return a list of requirements that failed to build
377
return build_successes, build_failures
378
379