Debian Codegraph @

third_party/python/pip_tools/piptools/repositories/pypi.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import hashlib
5 import itertools
6 import optparse
7 import os
8 from contextlib import contextmanager
9 from shutil import rmtree
10 from typing import Any, BinaryIO, ContextManager, Iterator, NamedTuple
11
12 from click import progressbar
13 from pip._internal.cache import WheelCache
14 from pip._internal.commands import create_command
15 from pip._internal.commands.install import InstallCommand
16 from pip._internal.index.package_finder import PackageFinder
17 from pip._internal.models.candidate import InstallationCandidate
18 from pip._internal.models.index import PackageIndex
19 from pip._internal.models.link import Link
20 from pip._internal.models.wheel import Wheel
21 from pip._internal.network.session import PipSession
22 from pip._internal.operations.build.build_tracker import get_build_tracker
23 from pip._internal.req import InstallRequirement, RequirementSet
24 from pip._internal.utils.hashes import FAVORITE_HASH
25 from pip._internal.utils.logging import indent_log, setup_logging
26 from pip._internal.utils.misc import normalize_path
27 from pip._internal.utils.temp_dir import TempDirectory, global_tempdir_manager
28 from pip._internal.utils.urls import path_to_url, url_to_path
29 from pip._vendor.packaging.tags import Tag
30 from pip._vendor.packaging.version import _BaseVersion
31 from pip._vendor.requests import RequestException, Session
32
33 from .._compat import create_wheel_cache
34 from ..exceptions import NoCandidateFound
35 from ..logging import log
36 from ..utils import (
37 as_tuple,
38 is_pinned_requirement,
39 is_url_requirement,
40 lookup_table,
41 make_install_requirement,
42 )
43 from .base import BaseRepository
44
45 FILE_CHUNK_SIZE = 4096
46
47
48 class FileStream(NamedTuple):
49 stream: BinaryIO
50 size: float | None
51
52
53 class PyPIRepository(BaseRepository):
54 HASHABLE_PACKAGE_TYPES = {"bdist_wheel", "sdist"}
55
56 """
57 The PyPIRepository will use the provided Finder instance to lookup
58 packages. Typically, it looks up packages on PyPI (the default implicit
59 config), but any other PyPI mirror can be used if index_urls is
60 changed/configured on the Finder.
61 """
62
63 def __init__(self, pip_args: list[str], cache_dir: str):
64 # Use pip's parser for pip.conf management and defaults.
65 # General options (find_links, index_url, extra_index_url, trusted_host,
66 # and pre) are deferred to pip.
67 self._command: InstallCommand = create_command("install")
68
69 options, _ = self.command.parse_args(pip_args)
70 if options.cache_dir:
71 options.cache_dir = normalize_path(options.cache_dir)
72 options.require_hashes = False
73 options.ignore_dependencies = False
74
75 self._options: optparse.Values = options
76 self._session = self.command._build_session(options)
77 self._finder = self.command._build_package_finder(
78 options=options, session=self.session
79 )
80
81 # Caches
82 # stores project_name => InstallationCandidate mappings for all
83 # versions reported by PyPI, so we only have to ask once for each
84 # project
85 self._available_candidates_cache: dict[str, list[InstallationCandidate]] = {}
86
87 # stores InstallRequirement => list(InstallRequirement) mappings
88 # of all secondary dependencies for the given requirement, so we
89 # only have to go to disk once for each requirement
90 self._dependencies_cache: dict[InstallRequirement, set[InstallRequirement]] = {}
91
92 # Setup file paths
93 self._cache_dir = normalize_path(str(cache_dir))
94 self._download_dir = os.path.join(self._cache_dir, "pkgs")
95
96 # Default pip's logger is noisy, so decrease it's verbosity
97 setup_logging(
98 verbosity=log.verbosity - 1,
99 no_color=self.options.no_color,
100 user_log_file=self.options.log,
101 )
102
103 def clear_caches(self) -> None:
104 rmtree(self._download_dir, ignore_errors=True)
105
106 @property
107 def options(self) -> optparse.Values:
108 return self._options
109
110 @property
111 def session(self) -> PipSession:
112 return self._session
113
114 @property
115 def finder(self) -> PackageFinder:
116 return self._finder
117
118 @property
119 def command(self) -> InstallCommand:
120 """Return an install command instance."""
121 return self._command
122
123 def find_all_candidates(self, req_name: str) -> list[InstallationCandidate]:
124 if req_name not in self._available_candidates_cache:
125 candidates = self.finder.find_all_candidates(req_name)
126 self._available_candidates_cache[req_name] = candidates
127 return self._available_candidates_cache[req_name]
128
129 def find_best_match(
130 self, ireq: InstallRequirement, prereleases: bool | None = None
131 ) -> InstallRequirement:
132 """
133 Returns a pinned InstallRequirement object that indicates the best match
134 for the given InstallRequirement according to the external repository.
135 """
136 if ireq.editable or is_url_requirement(ireq):
137 return ireq # return itself as the best match
138
139 all_candidates = self.find_all_candidates(ireq.name)
140 candidates_by_version = lookup_table(all_candidates, key=candidate_version)
141 matching_versions = ireq.specifier.filter(
142 (candidate.version for candidate in all_candidates), prereleases=prereleases
143 )
144
145 matching_candidates = list(
146 itertools.chain.from_iterable(
147 candidates_by_version[ver] for ver in matching_versions
148 )
149 )
150 if not matching_candidates:
151 raise NoCandidateFound(ireq, all_candidates, self.finder)
152
153 evaluator = self.finder.make_candidate_evaluator(ireq.name)
154 best_candidate_result = evaluator.compute_best_candidate(matching_candidates)
155 best_candidate = best_candidate_result.best_candidate
156
157 # Turn the candidate into a pinned InstallRequirement
158 return make_install_requirement(
159 best_candidate.name,
160 best_candidate.version,
161 ireq,
162 )
163
164 def resolve_reqs(
165 self,
166 download_dir: str | None,
167 ireq: InstallRequirement,
168 wheel_cache: WheelCache,
169 ) -> set[InstallationCandidate]:
170 with get_build_tracker() as build_tracker, TempDirectory(
171 kind="resolver"
172 ) as temp_dir, indent_log():
173 preparer_kwargs = {
174 "temp_build_dir": temp_dir,
175 "options": self.options,
176 "session": self.session,
177 "finder": self.finder,
178 "use_user_site": False,
179 "download_dir": download_dir,
180 "build_tracker": build_tracker,
181 }
182 preparer = self.command.make_requirement_preparer(**preparer_kwargs)
183
184 reqset = RequirementSet()
185 ireq.user_supplied = True
186 if getattr(ireq, "name", None):
187 reqset.add_named_requirement(ireq)
188 else:
189 reqset.add_unnamed_requirement(ireq)
190
191 resolver = self.command.make_resolver(
192 preparer=preparer,
193 finder=self.finder,
194 options=self.options,
195 wheel_cache=wheel_cache,
196 use_user_site=False,
197 ignore_installed=True,
198 ignore_requires_python=False,
199 force_reinstall=False,
200 upgrade_strategy="to-satisfy-only",
201 )
202 results = resolver._resolve_one(reqset, ireq)
203 if not ireq.prepared:
204 # If still not prepared, e.g. a constraint, do enough to assign
205 # the ireq a name:
206 resolver._get_dist_for(ireq)
207
208 return set(results)
209
210 def get_dependencies(self, ireq: InstallRequirement) -> set[InstallRequirement]:
211 """
212 Given a pinned, URL, or editable InstallRequirement, returns a set of
213 dependencies (also InstallRequirements, but not necessarily pinned).
214 They indicate the secondary dependencies for the given requirement.
215 """
216 if not (
217 ireq.editable or is_url_requirement(ireq) or is_pinned_requirement(ireq)
218 ):
219 raise TypeError(
220 f"Expected url, pinned or editable InstallRequirement, got {ireq}"
221 )
222
223 if ireq not in self._dependencies_cache:
224 if ireq.editable and (ireq.source_dir and os.path.exists(ireq.source_dir)):
225 # No download_dir for locally available editable requirements.
226 # If a download_dir is passed, pip will unnecessarily archive
227 # the entire source directory
228 download_dir = None
229 elif ireq.link and ireq.link.is_vcs:
230 # No download_dir for VCS sources. This also works around pip
231 # using git-checkout-index, which gets rid of the .git dir.
232 download_dir = None
233 else:
234 download_dir = self._get_download_path(ireq)
235 os.makedirs(download_dir, exist_ok=True)
236
237 with global_tempdir_manager():
238 wheel_cache = create_wheel_cache(
239 cache_dir=self._cache_dir,
240 format_control=self.options.format_control,
241 )
242 self._dependencies_cache[ireq] = self.resolve_reqs(
243 download_dir, ireq, wheel_cache
244 )
245
246 return self._dependencies_cache[ireq]
247
248 def _get_project(self, ireq: InstallRequirement) -> Any:
249 """
250 Return a dict of a project info from PyPI JSON API for a given
251 InstallRequirement. Return None on HTTP/JSON error or if a package
252 is not found on PyPI server.
253
254 API reference: https://warehouse.readthedocs.io/api-reference/json/
255 """
256 package_indexes = (
257 PackageIndex(url=index_url, file_storage_domain="")
258 for index_url in self.finder.search_scope.index_urls
259 )
260 for package_index in package_indexes:
261 url = f"{package_index.pypi_url}/{ireq.name}/json"
262 try:
263 response = self.session.get(url)
264 except RequestException as e:
265 log.debug(f"Fetch package info from PyPI failed: {url}: {e}")
266 continue
267
268 # Skip this PyPI server, because there is no package
269 # or JSON API might be not supported
270 if response.status_code == 404:
271 continue
272
273 try:
274 data = response.json()
275 except ValueError as e:
276 log.debug(f"Cannot parse JSON response from PyPI: {url}: {e}")
277 continue
278 return data
279 return None
280
281 def _get_download_path(self, ireq: InstallRequirement) -> str:
282 """
283 Determine the download dir location in a way which avoids name
284 collisions.
285 """
286 if ireq.link:
287 salt = hashlib.sha224(ireq.link.url_without_fragment.encode()).hexdigest()
288 # Nest directories to avoid running out of top level dirs on some FS
289 # (see pypi _get_cache_path_parts, which inspired this)
290 return os.path.join(
291 self._download_dir, salt[:2], salt[2:4], salt[4:6], salt[6:]
292 )
293 else:
294 return self._download_dir
295
296 def get_hashes(self, ireq: InstallRequirement) -> set[str]:
297 """
298 Given an InstallRequirement, return a set of hashes that represent all
299 of the files for a given requirement. Unhashable requirements return an
300 empty set. Unpinned requirements raise a TypeError.
301 """
302
303 if ireq.link:
304 link = ireq.link
305
306 if link.is_vcs or (link.is_file and link.is_existing_dir()):
307 # Return empty set for unhashable requirements.
308 # Unhashable logic modeled on pip's
309 # RequirementPreparer.prepare_linked_requirement
310 return set()
311
312 if is_url_requirement(ireq):
313 # Directly hash URL requirements.
314 # URL requirements may have been previously downloaded and cached
315 # locally by self.resolve_reqs()
316 cached_path = os.path.join(self._get_download_path(ireq), link.filename)
317 if os.path.exists(cached_path):
318 cached_link = Link(path_to_url(cached_path))
319 else:
320 cached_link = link
321 return {self._get_file_hash(cached_link)}
322
323 if not is_pinned_requirement(ireq):
324 raise TypeError(f"Expected pinned requirement, got {ireq}")
325
326 log.debug(ireq.name)
327
328 with log.indentation():
329 return self._get_req_hashes(ireq)
330
331 def _get_req_hashes(self, ireq: InstallRequirement) -> set[str]:
332 """
333 Collects the hashes for all candidates satisfying the given InstallRequirement. Computes
334 the hashes for the candidates that don't have one reported by their index.
335 """
336 matching_candidates = self._get_matching_candidates(ireq)
337 pypi_hashes_by_link = self._get_hashes_from_pypi(ireq)
338 pypi_hashes = {
339 pypi_hashes_by_link[candidate.link.url]
340 for candidate in matching_candidates
341 if candidate.link.url in pypi_hashes_by_link
342 }
343 local_hashes = {
344 self._get_file_hash(candidate.link)
345 for candidate in matching_candidates
346 if candidate.link.url not in pypi_hashes_by_link
347 }
348 return pypi_hashes | local_hashes
349
350 def _get_hashes_from_pypi(self, ireq: InstallRequirement) -> dict[str, str]:
351 """
352 Builds a mapping from the release URLs to their hashes as reported by the PyPI JSON API
353 for a given InstallRequirement.
354 """
355 project = self._get_project(ireq)
356 if project is None:
357 return {}
358
359 _, version, _ = as_tuple(ireq)
360
361 try:
362 release_files = project["releases"][version]
363 except KeyError:
364 log.debug("Missing release files on PyPI")
365 return {}
366
367 try:
368 hashes = {
369 file_["url"]: f"{FAVORITE_HASH}:{file_['digests'][FAVORITE_HASH]}"
370 for file_ in release_files
371 if file_["packagetype"] in self.HASHABLE_PACKAGE_TYPES
372 }
373 except KeyError:
374 log.debug("Missing digests of release files on PyPI")
375 return {}
376
377 return hashes
378
379 def _get_matching_candidates(
380 self, ireq: InstallRequirement
381 ) -> set[InstallationCandidate]:
382 """
383 Returns all candidates that satisfy the given InstallRequirement.
384 """
385 # We need to get all of the candidates that match our current version
386 # pin, these will represent all of the files that could possibly
387 # satisfy this constraint.
388 all_candidates = self.find_all_candidates(ireq.name)
389 candidates_by_version = lookup_table(all_candidates, key=candidate_version)
390 matching_versions = list(
391 ireq.specifier.filter(candidate.version for candidate in all_candidates)
392 )
393 return candidates_by_version[matching_versions[0]]
394
395 def _get_file_hash(self, link: Link) -> str:
396 log.debug(f"Hashing {link.show_url}")
397 h = hashlib.new(FAVORITE_HASH)
398 with open_local_or_remote_file(link, self.session) as f:
399 # Chunks to iterate
400 chunks = iter(lambda: f.stream.read(FILE_CHUNK_SIZE), b"")
401
402 # Choose a context manager depending on verbosity
403 context_manager: ContextManager[Iterator[bytes]]
404 if log.verbosity >= 1:
405 iter_length = int(f.size / FILE_CHUNK_SIZE) if f.size else None
406 bar_template = f"{' ' * log.current_indent} |%(bar)s| %(info)s"
407 context_manager = progressbar(
408 chunks,
409 length=iter_length,
410 # Make it look like default pip progress bar
411 fill_char="█",
412 empty_char=" ",
413 bar_template=bar_template,
414 width=32,
415 )
416 else:
417 context_manager = contextlib.nullcontext(chunks)
418
419 # Iterate over the chosen context manager
420 with context_manager as bar:
421 for chunk in bar:
422 h.update(chunk)
423 return ":".join([FAVORITE_HASH, h.hexdigest()])
424
425 @contextmanager
426 def allow_all_wheels(self) -> Iterator[None]:
427 """
428 Monkey patches pip.Wheel to allow wheels from all platforms and Python versions.
429
430 This also saves the candidate cache and set a new one, or else the results from
431 the previous non-patched calls will interfere.
432 """
433
434 def _wheel_supported(self: Wheel, tags: list[Tag]) -> bool:
435 # Ignore current platform. Support everything.
436 return True
437
438 def _wheel_support_index_min(self: Wheel, tags: list[Tag]) -> int:
439 # All wheels are equal priority for sorting.
440 return 0
441
442 original_wheel_supported = Wheel.supported
443 original_support_index_min = Wheel.support_index_min
444 original_cache = self._available_candidates_cache
445
446 Wheel.supported = _wheel_supported
447 Wheel.support_index_min = _wheel_support_index_min
448 self._available_candidates_cache = {}
449
450 # If we don't clear this cache then it can contain results from an
451 # earlier call when allow_all_wheels wasn't active. See GH-1532
452 self.finder.find_all_candidates.cache_clear()
453
454 try:
455 yield
456 finally:
457 Wheel.supported = original_wheel_supported
458 Wheel.support_index_min = original_support_index_min
459 self._available_candidates_cache = original_cache
460
461
462 @contextmanager
463 def open_local_or_remote_file(link: Link, session: Session) -> Iterator[FileStream]:
464 """
465 Open local or remote file for reading.
466
467 :type link: pip.index.Link
468 :type session: requests.Session
469 :raises ValueError: If link points to a local directory.
470 :return: a context manager to a FileStream with the opened file-like object
471 """
472 url = link.url_without_fragment
473
474 if link.is_file:
475 # Local URL
476 local_path = url_to_path(url)
477 if os.path.isdir(local_path):
478 raise ValueError(f"Cannot open directory for read: {url}")
479 else:
480 st = os.stat(local_path)
481 with open(local_path, "rb") as local_file:
482 yield FileStream(stream=local_file, size=st.st_size)
483 else:
484 # Remote URL
485 headers = {"Accept-Encoding": "identity"}
486 response = session.get(url, headers=headers, stream=True)
487
488 # Content length must be int or None
489 content_length: int | None
490 try:
491 content_length = int(response.headers["content-length"])
492 except (ValueError, KeyError, TypeError):
493 content_length = None
494
495 try:
496 yield FileStream(stream=response.raw, size=content_length)
497 finally:
498 response.close()
499
500
501 def candidate_version(candidate: InstallationCandidate) -> _BaseVersion:
502 return candidate.version