| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections |
| 4 |
import copy |
| 5 |
from abc import ABCMeta, abstractmethod |
| 6 |
from functools import partial |
| 7 |
from itertools import chain, count, groupby |
| 8 |
from typing import Any, Container, DefaultDict, Iterable, Iterator |
| 9 |
|
| 10 |
import click |
| 11 |
from pip._internal.exceptions import DistributionNotFound |
| 12 |
from pip._internal.operations.build.build_tracker import ( |
| 13 |
get_build_tracker, |
| 14 |
update_env_context_manager, |
| 15 |
) |
| 16 |
from pip._internal.req import InstallRequirement |
| 17 |
from pip._internal.req.constructors import install_req_from_line |
| 18 |
from pip._internal.resolution.resolvelib.base import Candidate |
| 19 |
from pip._internal.resolution.resolvelib.candidates import ExtrasCandidate |
| 20 |
from pip._internal.resolution.resolvelib.resolver import Resolver |
| 21 |
from pip._internal.utils.logging import indent_log |
| 22 |
from pip._internal.utils.temp_dir import TempDirectory, global_tempdir_manager |
| 23 |
from pip._vendor.packaging.specifiers import SpecifierSet |
| 24 |
from pip._vendor.packaging.utils import canonicalize_name |
| 25 |
from pip._vendor.resolvelib.resolvers import ResolutionImpossible, Result |
| 26 |
|
| 27 |
from piptools.cache import DependencyCache |
| 28 |
from piptools.repositories.base import BaseRepository |
| 29 |
|
| 30 |
from ._compat import create_wheel_cache |
| 31 |
from .exceptions import PipToolsError |
| 32 |
from .logging import log |
| 33 |
from .utils import ( |
| 34 |
UNSAFE_PACKAGES, |
| 35 |
as_tuple, |
| 36 |
copy_install_requirement, |
| 37 |
format_requirement, |
| 38 |
format_specifier, |
| 39 |
is_pinned_requirement, |
| 40 |
is_url_requirement, |
| 41 |
key_from_ireq, |
| 42 |
key_from_req, |
| 43 |
omit_list_value, |
| 44 |
strip_extras, |
| 45 |
) |
| 46 |
|
| 47 |
green = partial(click.style, fg="green") |
| 48 |
magenta = partial(click.style, fg="magenta") |
| 49 |
|
| 50 |
|
| 51 |
class RequirementSummary: |
| 52 |
""" |
| 53 |
Summary of a requirement's properties for comparison purposes. |
| 54 |
""" |
| 55 |
|
| 56 |
def __init__(self, ireq: InstallRequirement) -> None: |
| 57 |
self.req = ireq.req |
| 58 |
self.key = key_from_ireq(ireq) |
| 59 |
self.extras = frozenset(ireq.extras) |
| 60 |
self.specifier = ireq.specifier |
| 61 |
|
| 62 |
def __eq__(self, other: object) -> bool: |
| 63 |
if not isinstance(other, self.__class__): |
| 64 |
return NotImplemented |
| 65 |
|
| 66 |
return ( |
| 67 |
self.key == other.key |
| 68 |
and self.specifier == other.specifier |
| 69 |
and self.extras == other.extras |
| 70 |
) |
| 71 |
|
| 72 |
def __hash__(self) -> int: |
| 73 |
return hash((self.key, self.specifier, self.extras)) |
| 74 |
|
| 75 |
def __str__(self) -> str: |
| 76 |
return repr((self.key, str(self.specifier), sorted(self.extras))) |
| 77 |
|
| 78 |
|
| 79 |
def combine_install_requirements( |
| 80 |
ireqs: Iterable[InstallRequirement], |
| 81 |
) -> InstallRequirement: |
| 82 |
""" |
| 83 |
Return a single install requirement that reflects a combination of |
| 84 |
all the inputs. |
| 85 |
""" |
| 86 |
# We will store the source ireqs in a _source_ireqs attribute; |
| 87 |
# if any of the inputs have this, then use those sources directly. |
| 88 |
source_ireqs: list[InstallRequirement] = [] |
| 89 |
for ireq in ireqs: |
| 90 |
source_ireqs.extend(getattr(ireq, "_source_ireqs", [ireq])) |
| 91 |
|
| 92 |
# Optimization. Don't bother with combination logic. |
| 93 |
if len(source_ireqs) == 1: |
| 94 |
return source_ireqs[0] |
| 95 |
|
| 96 |
link_attrs = { |
| 97 |
attr: getattr(source_ireqs[0], attr) for attr in ("link", "original_link") |
| 98 |
} |
| 99 |
|
| 100 |
constraint = source_ireqs[0].constraint |
| 101 |
extras = set(source_ireqs[0].extras) |
| 102 |
# deepcopy the accumulator req so as to not modify the inputs |
| 103 |
req = copy.deepcopy(source_ireqs[0].req) |
| 104 |
|
| 105 |
for ireq in source_ireqs[1:]: |
| 106 |
# NOTE we may be losing some info on dropped reqs here |
| 107 |
if req is not None and ireq.req is not None: |
| 108 |
req.specifier &= ireq.req.specifier |
| 109 |
|
| 110 |
constraint &= ireq.constraint |
| 111 |
extras |= ireq.extras |
| 112 |
if req is not None: |
| 113 |
req.extras = set(extras) |
| 114 |
|
| 115 |
for attr_name, attr_val in link_attrs.items(): |
| 116 |
link_attrs[attr_name] = attr_val or getattr(ireq, attr_name) |
| 117 |
|
| 118 |
# InstallRequirements objects are assumed to come from only one source, and |
| 119 |
# so they support only a single comes_from entry. This function breaks this |
| 120 |
# model. As a workaround, we deterministically choose a single source for |
| 121 |
# the comes_from entry, and add an extra _source_ireqs attribute to keep |
| 122 |
# track of multiple sources for use within pip-tools. |
| 123 |
if any(ireq.comes_from is None for ireq in source_ireqs): |
| 124 |
# None indicates package was directly specified. |
| 125 |
comes_from = None |
| 126 |
else: |
| 127 |
# Populate the comes_from field from one of the sources. |
| 128 |
# Requirement input order is not stable, so we need to sort: |
| 129 |
# We choose the shortest entry in order to keep the printed |
| 130 |
# representation as concise as possible. |
| 131 |
comes_from = min( |
| 132 |
(ireq.comes_from for ireq in source_ireqs), |
| 133 |
key=lambda x: (len(str(x)), str(x)), |
| 134 |
) |
| 135 |
|
| 136 |
combined_ireq = copy_install_requirement( |
| 137 |
template=source_ireqs[0], |
| 138 |
req=req, |
| 139 |
comes_from=comes_from, |
| 140 |
constraint=constraint, |
| 141 |
extras=extras, |
| 142 |
**link_attrs, |
| 143 |
) |
| 144 |
combined_ireq._source_ireqs = source_ireqs |
| 145 |
|
| 146 |
return combined_ireq |
| 147 |
|
| 148 |
|
| 149 |
class BaseResolver(metaclass=ABCMeta): |
| 150 |
repository: BaseRepository |
| 151 |
unsafe_constraints: set[InstallRequirement] |
| 152 |
|
| 153 |
@abstractmethod |
| 154 |
def resolve(self, max_rounds: int) -> set[InstallRequirement]: |
| 155 |
""" |
| 156 |
Find concrete package versions for all the given InstallRequirements |
| 157 |
and their recursive dependencies and return a set of pinned |
| 158 |
``InstallRequirement``'s. |
| 159 |
""" |
| 160 |
|
| 161 |
def resolve_hashes( |
| 162 |
self, ireqs: set[InstallRequirement] |
| 163 |
) -> dict[InstallRequirement, set[str]]: |
| 164 |
"""Find acceptable hashes for all of the given ``InstallRequirement``s.""" |
| 165 |
log.debug("") |
| 166 |
log.debug("Generating hashes:") |
| 167 |
with self.repository.allow_all_wheels(), log.indentation(): |
| 168 |
return {ireq: self.repository.get_hashes(ireq) for ireq in ireqs} |
| 169 |
|
| 170 |
def _filter_out_unsafe_constraints( |
| 171 |
self, |
| 172 |
ireqs: set[InstallRequirement], |
| 173 |
unsafe_packages: Container[str], |
| 174 |
) -> None: |
| 175 |
""" |
| 176 |
Remove from a given set of ``InstallRequirement``'s unsafe constraints. |
| 177 |
""" |
| 178 |
for req in ireqs.copy(): |
| 179 |
if req.name in unsafe_packages: |
| 180 |
self.unsafe_constraints.add(req) |
| 181 |
ireqs.remove(req) |
| 182 |
|
| 183 |
|
| 184 |
class LegacyResolver(BaseResolver): |
| 185 |
def __init__( |
| 186 |
self, |
| 187 |
constraints: Iterable[InstallRequirement], |
| 188 |
existing_constraints: dict[str, InstallRequirement], |
| 189 |
repository: BaseRepository, |
| 190 |
cache: DependencyCache, |
| 191 |
prereleases: bool | None = False, |
| 192 |
clear_caches: bool = False, |
| 193 |
allow_unsafe: bool = False, |
| 194 |
unsafe_packages: set[str] | None = None, |
| 195 |
) -> None: |
| 196 |
""" |
| 197 |
This class resolves a given set of constraints (a collection of |
| 198 |
InstallRequirement objects) by consulting the given Repository and the |
| 199 |
DependencyCache. |
| 200 |
""" |
| 201 |
self.our_constraints = set(constraints) |
| 202 |
self.their_constraints: set[InstallRequirement] = set() |
| 203 |
self.repository = repository |
| 204 |
self.dependency_cache = cache |
| 205 |
self.prereleases = prereleases |
| 206 |
self.clear_caches = clear_caches |
| 207 |
self.allow_unsafe = allow_unsafe |
| 208 |
self.unsafe_constraints: set[InstallRequirement] = set() |
| 209 |
self.unsafe_packages = unsafe_packages or UNSAFE_PACKAGES |
| 210 |
|
| 211 |
options = self.repository.options |
| 212 |
if "legacy-resolver" not in options.deprecated_features_enabled: |
| 213 |
raise PipToolsError("Legacy resolver deprecated feature must be enabled.") |
| 214 |
|
| 215 |
# Make sure there is no enabled 2020-resolver |
| 216 |
options.features_enabled = omit_list_value( |
| 217 |
options.features_enabled, "2020-resolver" |
| 218 |
) |
| 219 |
|
| 220 |
@property |
| 221 |
def constraints(self) -> set[InstallRequirement]: |
| 222 |
return set( |
| 223 |
self._group_constraints(chain(self.our_constraints, self.their_constraints)) |
| 224 |
) |
| 225 |
|
| 226 |
def resolve(self, max_rounds: int = 10) -> set[InstallRequirement]: |
| 227 |
""" |
| 228 |
Find concrete package versions for all the given InstallRequirements |
| 229 |
and their recursive dependencies and return a set of pinned |
| 230 |
``InstallRequirement``'s. |
| 231 |
|
| 232 |
Resolves constraints one round at a time, until they don't change |
| 233 |
anymore. Protects against infinite loops by breaking out after a max |
| 234 |
number rounds. |
| 235 |
""" |
| 236 |
if self.clear_caches: |
| 237 |
self.dependency_cache.clear() |
| 238 |
self.repository.clear_caches() |
| 239 |
|
| 240 |
# Ignore existing packages |
| 241 |
with update_env_context_manager(PIP_EXISTS_ACTION="i"): |
| 242 |
for current_round in count(start=1): # pragma: no branch |
| 243 |
if current_round > max_rounds: |
| 244 |
raise RuntimeError( |
| 245 |
"No stable configuration of concrete packages " |
| 246 |
"could be found for the given constraints after " |
| 247 |
"{max_rounds} rounds of resolving.\n" |
| 248 |
"This is likely a bug.".format(max_rounds=max_rounds) |
| 249 |
) |
| 250 |
|
| 251 |
log.debug("") |
| 252 |
log.debug(magenta(f"{f'ROUND {current_round}':^60}")) |
| 253 |
has_changed, best_matches = self._resolve_one_round() |
| 254 |
log.debug("-" * 60) |
| 255 |
log.debug( |
| 256 |
"Result of round {}: {}".format( |
| 257 |
current_round, |
| 258 |
"not stable" if has_changed else "stable, done", |
| 259 |
) |
| 260 |
) |
| 261 |
if not has_changed: |
| 262 |
break |
| 263 |
|
| 264 |
# Only include hard requirements and not pip constraints |
| 265 |
results = {req for req in best_matches if not req.constraint} |
| 266 |
|
| 267 |
# Filter out unsafe requirements. |
| 268 |
if not self.allow_unsafe: |
| 269 |
self._filter_out_unsafe_constraints( |
| 270 |
ireqs=results, |
| 271 |
unsafe_packages=self.unsafe_packages, |
| 272 |
) |
| 273 |
|
| 274 |
return results |
| 275 |
|
| 276 |
def _group_constraints( |
| 277 |
self, constraints: Iterable[InstallRequirement] |
| 278 |
) -> Iterator[InstallRequirement]: |
| 279 |
""" |
| 280 |
Groups constraints (remember, InstallRequirements!) by their key name, |
| 281 |
and combining their SpecifierSets into a single InstallRequirement per |
| 282 |
package. For example, given the following constraints: |
| 283 |
|
| 284 |
Django<1.9,>=1.4.2 |
| 285 |
django~=1.5 |
| 286 |
Flask~=0.7 |
| 287 |
|
| 288 |
This will be combined into a single entry per package: |
| 289 |
|
| 290 |
django~=1.5,<1.9,>=1.4.2 |
| 291 |
flask~=0.7 |
| 292 |
|
| 293 |
""" |
| 294 |
constraints = list(constraints) |
| 295 |
|
| 296 |
for ireq in constraints: |
| 297 |
if ireq.name is None: |
| 298 |
# get_dependencies has side-effect of assigning name to ireq |
| 299 |
# (so we can group by the name below). |
| 300 |
self.repository.get_dependencies(ireq) |
| 301 |
|
| 302 |
# Sort first by name, i.e. the groupby key. Then within each group, |
| 303 |
# sort editables first. |
| 304 |
# This way, we don't bother with combining editables, since the first |
| 305 |
# ireq will be editable, if one exists. |
| 306 |
for _, ireqs in groupby( |
| 307 |
sorted(constraints, key=(lambda x: (key_from_ireq(x), not x.editable))), |
| 308 |
key=key_from_ireq, |
| 309 |
): |
| 310 |
yield combine_install_requirements(ireqs) |
| 311 |
|
| 312 |
def _resolve_one_round(self) -> tuple[bool, set[InstallRequirement]]: |
| 313 |
""" |
| 314 |
Resolves one level of the current constraints, by finding the best |
| 315 |
match for each package in the repository and adding all requirements |
| 316 |
for those best package versions. Some of these constraints may be new |
| 317 |
or updated. |
| 318 |
|
| 319 |
Returns whether new constraints appeared in this round. If no |
| 320 |
constraints were added or changed, this indicates a stable |
| 321 |
configuration. |
| 322 |
""" |
| 323 |
# Sort this list for readability of terminal output |
| 324 |
constraints = sorted(self.constraints, key=key_from_ireq) |
| 325 |
|
| 326 |
log.debug("Current constraints:") |
| 327 |
with log.indentation(): |
| 328 |
for constraint in constraints: |
| 329 |
log.debug(str(constraint)) |
| 330 |
|
| 331 |
log.debug("") |
| 332 |
log.debug("Finding the best candidates:") |
| 333 |
with log.indentation(): |
| 334 |
best_matches = {self.get_best_match(ireq) for ireq in constraints} |
| 335 |
|
| 336 |
# Find the new set of secondary dependencies |
| 337 |
log.debug("") |
| 338 |
log.debug("Finding secondary dependencies:") |
| 339 |
|
| 340 |
their_constraints: list[InstallRequirement] = [] |
| 341 |
with log.indentation(): |
| 342 |
for best_match in best_matches: |
| 343 |
their_constraints.extend(self._iter_dependencies(best_match)) |
| 344 |
# Grouping constraints to make clean diff between rounds |
| 345 |
theirs = set(self._group_constraints(their_constraints)) |
| 346 |
|
| 347 |
# NOTE: We need to compare RequirementSummary objects, since |
| 348 |
# InstallRequirement does not define equality |
| 349 |
diff = {RequirementSummary(t) for t in theirs} - { |
| 350 |
RequirementSummary(t) for t in self.their_constraints |
| 351 |
} |
| 352 |
removed = {RequirementSummary(t) for t in self.their_constraints} - { |
| 353 |
RequirementSummary(t) for t in theirs |
| 354 |
} |
| 355 |
|
| 356 |
has_changed = len(diff) > 0 or len(removed) > 0 |
| 357 |
if has_changed: |
| 358 |
log.debug("") |
| 359 |
log.debug("New dependencies found in this round:") |
| 360 |
with log.indentation(): |
| 361 |
for new_dependency in sorted(diff, key=key_from_ireq): |
| 362 |
log.debug(f"adding {new_dependency}") |
| 363 |
log.debug("Removed dependencies in this round:") |
| 364 |
with log.indentation(): |
| 365 |
for removed_dependency in sorted(removed, key=key_from_ireq): |
| 366 |
log.debug(f"removing {removed_dependency}") |
| 367 |
|
| 368 |
# Store the last round's results in the their_constraints |
| 369 |
self.their_constraints = theirs |
| 370 |
return has_changed, best_matches |
| 371 |
|
| 372 |
def get_best_match(self, ireq: InstallRequirement) -> InstallRequirement: |
| 373 |
""" |
| 374 |
Returns a (pinned or editable) InstallRequirement, indicating the best |
| 375 |
match to use for the given InstallRequirement (in the form of an |
| 376 |
InstallRequirement). |
| 377 |
|
| 378 |
Example: |
| 379 |
Given the constraint Flask>=0.10, may return Flask==0.10.1 at |
| 380 |
a certain moment in time. |
| 381 |
|
| 382 |
Pinned requirements will always return themselves, i.e. |
| 383 |
|
| 384 |
Flask==0.10.1 => Flask==0.10.1 |
| 385 |
|
| 386 |
""" |
| 387 |
if ireq.editable or is_url_requirement(ireq): |
| 388 |
# NOTE: it's much quicker to immediately return instead of |
| 389 |
# hitting the index server |
| 390 |
best_match = ireq |
| 391 |
elif is_pinned_requirement(ireq): |
| 392 |
# NOTE: it's much quicker to immediately return instead of |
| 393 |
# hitting the index server |
| 394 |
best_match = ireq |
| 395 |
elif ireq.constraint: |
| 396 |
# NOTE: This is not a requirement (yet) and does not need |
| 397 |
# to be resolved |
| 398 |
best_match = ireq |
| 399 |
else: |
| 400 |
best_match = self.repository.find_best_match( |
| 401 |
ireq, prereleases=self.prereleases |
| 402 |
) |
| 403 |
|
| 404 |
# Format the best match |
| 405 |
log.debug( |
| 406 |
"found candidate {} (constraint was {})".format( |
| 407 |
format_requirement(best_match), format_specifier(ireq) |
| 408 |
) |
| 409 |
) |
| 410 |
best_match.comes_from = ireq.comes_from |
| 411 |
if hasattr(ireq, "_source_ireqs"): |
| 412 |
best_match._source_ireqs = ireq._source_ireqs |
| 413 |
return best_match |
| 414 |
|
| 415 |
def _iter_dependencies( |
| 416 |
self, ireq: InstallRequirement |
| 417 |
) -> Iterator[InstallRequirement]: |
| 418 |
""" |
| 419 |
Given a pinned, url, or editable InstallRequirement, collects all the |
| 420 |
secondary dependencies for them, either by looking them up in a local |
| 421 |
cache, or by reaching out to the repository. |
| 422 |
|
| 423 |
Editable requirements will never be looked up, as they may have |
| 424 |
changed at any time. |
| 425 |
""" |
| 426 |
# Pip does not resolve dependencies of constraints. We skip handling |
| 427 |
# constraints here as well to prevent the cache from being polluted. |
| 428 |
# Constraints that are later determined to be dependencies will be |
| 429 |
# marked as non-constraints in later rounds by |
| 430 |
# `combine_install_requirements`, and will be properly resolved. |
| 431 |
# See https://github.com/pypa/pip/ |
| 432 |
# blob/6896dfcd831330c13e076a74624d95fa55ff53f4/src/pip/_internal/ |
| 433 |
# legacy_resolve.py#L325 |
| 434 |
if ireq.constraint: |
| 435 |
return |
| 436 |
|
| 437 |
if ireq.editable or is_url_requirement(ireq): |
| 438 |
dependencies = self.repository.get_dependencies(ireq) |
| 439 |
# Don't just yield from above. Instead, use the same `markers`-stripping |
| 440 |
# behavior as we have for cached dependencies below. |
| 441 |
dependency_strings = sorted(str(ireq.req) for ireq in dependencies) |
| 442 |
yield from self._ireqs_of_dependencies(ireq, dependency_strings) |
| 443 |
return |
| 444 |
elif not is_pinned_requirement(ireq): |
| 445 |
raise TypeError(f"Expected pinned or editable requirement, got {ireq}") |
| 446 |
|
| 447 |
# Now, either get the dependencies from the dependency cache (for |
| 448 |
# speed), or reach out to the external repository to |
| 449 |
# download and inspect the package version and get dependencies |
| 450 |
# from there |
| 451 |
if ireq not in self.dependency_cache: |
| 452 |
log.debug( |
| 453 |
f"{format_requirement(ireq)} not in cache, need to check index", |
| 454 |
fg="yellow", |
| 455 |
) |
| 456 |
dependencies = self.repository.get_dependencies(ireq) |
| 457 |
self.dependency_cache[ireq] = sorted(str(ireq.req) for ireq in dependencies) |
| 458 |
|
| 459 |
# Example: ['Werkzeug>=0.9', 'Jinja2>=2.4'] |
| 460 |
dependency_strings = self.dependency_cache[ireq] |
| 461 |
yield from self._ireqs_of_dependencies(ireq, dependency_strings) |
| 462 |
|
| 463 |
def _ireqs_of_dependencies( |
| 464 |
self, ireq: InstallRequirement, dependency_strings: list[str] |
| 465 |
) -> Iterator[InstallRequirement]: |
| 466 |
log.debug( |
| 467 |
"{:25} requires {}".format( |
| 468 |
format_requirement(ireq), |
| 469 |
", ".join(sorted(dependency_strings, key=lambda s: s.lower())) or "-", |
| 470 |
) |
| 471 |
) |
| 472 |
# This yields new InstallRequirements that are similar to those that |
| 473 |
# produced the dependency_strings, but they lack `markers` on their |
| 474 |
# underlying Requirements: |
| 475 |
for dependency_string in dependency_strings: |
| 476 |
yield install_req_from_line( |
| 477 |
dependency_string, constraint=ireq.constraint, comes_from=ireq |
| 478 |
) |
| 479 |
|
| 480 |
|
| 481 |
class BacktrackingResolver(BaseResolver): |
| 482 |
"""A wrapper for backtracking resolver.""" |
| 483 |
|
| 484 |
def __init__( |
| 485 |
self, |
| 486 |
constraints: Iterable[InstallRequirement], |
| 487 |
existing_constraints: dict[str, InstallRequirement], |
| 488 |
repository: BaseRepository, |
| 489 |
allow_unsafe: bool = False, |
| 490 |
unsafe_packages: set[str] | None = None, |
| 491 |
**kwargs: Any, |
| 492 |
) -> None: |
| 493 |
self.constraints = list(constraints) |
| 494 |
self.repository = repository |
| 495 |
self.allow_unsafe = allow_unsafe |
| 496 |
self.unsafe_packages = unsafe_packages or UNSAFE_PACKAGES |
| 497 |
|
| 498 |
options = self.options = self.repository.options |
| 499 |
self.session = self.repository.session |
| 500 |
self.finder = self.repository.finder |
| 501 |
self.command = self.repository.command |
| 502 |
self.unsafe_constraints: set[InstallRequirement] = set() |
| 503 |
|
| 504 |
self.existing_constraints = existing_constraints |
| 505 |
|
| 506 |
# Categorize InstallRequirements into sets by key |
| 507 |
constraints_sets: DefaultDict[str, set[InstallRequirement]] = ( |
| 508 |
collections.defaultdict(set) |
| 509 |
) |
| 510 |
for ireq in constraints: |
| 511 |
constraints_sets[key_from_ireq(ireq)].add(ireq) |
| 512 |
# Collapse each set of InstallRequirements using combine_install_requirements |
| 513 |
self._constraints_map = { |
| 514 |
ireq_key: combine_install_requirements(ireqs) |
| 515 |
for ireq_key, ireqs in constraints_sets.items() |
| 516 |
} |
| 517 |
|
| 518 |
# Make sure there is no enabled legacy resolver |
| 519 |
options.deprecated_features_enabled = omit_list_value( |
| 520 |
options.deprecated_features_enabled, "legacy-resolver" |
| 521 |
) |
| 522 |
|
| 523 |
def resolve(self, max_rounds: int = 10) -> set[InstallRequirement]: |
| 524 |
""" |
| 525 |
Find concrete package versions for all the given InstallRequirements |
| 526 |
and their recursive dependencies and return a set of pinned |
| 527 |
``InstallRequirement``'s. |
| 528 |
""" |
| 529 |
with update_env_context_manager( |
| 530 |
PIP_EXISTS_ACTION="i" |
| 531 |
), get_build_tracker() as build_tracker, global_tempdir_manager(), indent_log(): |
| 532 |
# Mark direct/primary/user_supplied packages |
| 533 |
for ireq in self.constraints: |
| 534 |
if ireq.constraint: |
| 535 |
ireq.extras = set() # pip does not support extras in constraints |
| 536 |
ireq.user_supplied = True |
| 537 |
|
| 538 |
# Pass compiled requirements from `requirements.txt` |
| 539 |
# as constraints to resolver |
| 540 |
compatible_existing_constraints: dict[str, InstallRequirement] = {} |
| 541 |
for ireq in self.existing_constraints.values(): |
| 542 |
# Skip if the compiled install requirement conflicts with |
| 543 |
# the primary install requirement. |
| 544 |
primary_ireq = self._constraints_map.get(key_from_ireq(ireq)) |
| 545 |
if primary_ireq is not None: |
| 546 |
_, version, _ = as_tuple(ireq) |
| 547 |
prereleases = ireq.specifier.prereleases |
| 548 |
if not primary_ireq.specifier.contains(version, prereleases): |
| 549 |
continue |
| 550 |
|
| 551 |
ireq.extras = set() |
| 552 |
ireq.constraint = True |
| 553 |
ireq.user_supplied = False |
| 554 |
compatible_existing_constraints[key_from_ireq(ireq)] = ireq |
| 555 |
|
| 556 |
wheel_cache = create_wheel_cache( |
| 557 |
cache_dir=self.options.cache_dir, |
| 558 |
format_control=self.options.format_control, |
| 559 |
) |
| 560 |
|
| 561 |
temp_dir = TempDirectory( |
| 562 |
delete=not self.options.no_clean, |
| 563 |
kind="resolve", |
| 564 |
globally_managed=True, |
| 565 |
) |
| 566 |
|
| 567 |
preparer_kwargs = { |
| 568 |
"temp_build_dir": temp_dir, |
| 569 |
"options": self.options, |
| 570 |
"session": self.session, |
| 571 |
"finder": self.finder, |
| 572 |
"use_user_site": False, |
| 573 |
"build_tracker": build_tracker, |
| 574 |
} |
| 575 |
preparer = self.command.make_requirement_preparer(**preparer_kwargs) |
| 576 |
|
| 577 |
resolver = self.command.make_resolver( |
| 578 |
preparer=preparer, |
| 579 |
finder=self.finder, |
| 580 |
options=self.options, |
| 581 |
wheel_cache=wheel_cache, |
| 582 |
use_user_site=False, |
| 583 |
ignore_installed=True, |
| 584 |
ignore_requires_python=False, |
| 585 |
force_reinstall=False, |
| 586 |
use_pep517=self.options.use_pep517, |
| 587 |
upgrade_strategy="to-satisfy-only", |
| 588 |
) |
| 589 |
|
| 590 |
self.command.trace_basic_info(self.finder) |
| 591 |
|
| 592 |
for current_round in count(start=1): # pragma: no branch |
| 593 |
if current_round > max_rounds: |
| 594 |
raise RuntimeError( |
| 595 |
"No stable configuration of concrete packages " |
| 596 |
"could be found for the given constraints after " |
| 597 |
f"{max_rounds} rounds of resolving.\n" |
| 598 |
"This is likely a bug." |
| 599 |
) |
| 600 |
|
| 601 |
log.debug("") |
| 602 |
log.debug(magenta(f"{f'ROUND {current_round}':^60}")) |
| 603 |
|
| 604 |
is_resolved = self._do_resolve( |
| 605 |
resolver=resolver, |
| 606 |
compatible_existing_constraints=compatible_existing_constraints, |
| 607 |
) |
| 608 |
if is_resolved: |
| 609 |
break |
| 610 |
|
| 611 |
resolver_result = resolver._result |
| 612 |
assert isinstance(resolver_result, Result) |
| 613 |
|
| 614 |
# Prepare set of install requirements from resolver result. |
| 615 |
result_ireqs = self._get_install_requirements(resolver_result=resolver_result) |
| 616 |
|
| 617 |
# Filter out unsafe requirements. |
| 618 |
if not self.allow_unsafe: |
| 619 |
self._filter_out_unsafe_constraints( |
| 620 |
ireqs=result_ireqs, |
| 621 |
unsafe_packages=self.unsafe_packages, |
| 622 |
) |
| 623 |
|
| 624 |
return result_ireqs |
| 625 |
|
| 626 |
def _do_resolve( |
| 627 |
self, |
| 628 |
resolver: Resolver, |
| 629 |
compatible_existing_constraints: dict[str, InstallRequirement], |
| 630 |
) -> bool: |
| 631 |
""" |
| 632 |
Return true on successful resolution, otherwise remove problematic |
| 633 |
requirements from existing constraints and return false. |
| 634 |
""" |
| 635 |
try: |
| 636 |
resolver.resolve( |
| 637 |
root_reqs=self.constraints |
| 638 |
+ list(compatible_existing_constraints.values()), |
| 639 |
check_supported_wheels=not self.options.target_dir, |
| 640 |
) |
| 641 |
except DistributionNotFound as e: |
| 642 |
cause_exc = e.__cause__ |
| 643 |
if cause_exc is None: |
| 644 |
raise |
| 645 |
|
| 646 |
if not isinstance(cause_exc, ResolutionImpossible): |
| 647 |
raise |
| 648 |
|
| 649 |
# Collect all incompatible install requirement names |
| 650 |
cause_ireq_names = { |
| 651 |
strip_extras(key_from_req(cause.requirement)) |
| 652 |
for cause in cause_exc.causes |
| 653 |
} |
| 654 |
|
| 655 |
# Looks like resolution is impossible, try to fix |
| 656 |
for cause_ireq_name in cause_ireq_names: |
| 657 |
# Find the cause requirement in existing requirements, |
| 658 |
# otherwise raise error |
| 659 |
cause_existing_ireq = compatible_existing_constraints.get( |
| 660 |
cause_ireq_name |
| 661 |
) |
| 662 |
if cause_existing_ireq is None: |
| 663 |
raise |
| 664 |
|
| 665 |
# Remove existing incompatible constraint that causes error |
| 666 |
log.warning( |
| 667 |
f"Discarding {cause_existing_ireq} to proceed the resolution" |
| 668 |
) |
| 669 |
del compatible_existing_constraints[cause_ireq_name] |
| 670 |
|
| 671 |
return False |
| 672 |
|
| 673 |
return True |
| 674 |
|
| 675 |
def _get_install_requirements( |
| 676 |
self, resolver_result: Result |
| 677 |
) -> set[InstallRequirement]: |
| 678 |
"""Return a set of install requirements from resolver results.""" |
| 679 |
result_ireqs: dict[str, InstallRequirement] = {} |
| 680 |
|
| 681 |
# Get reverse requirements from the resolver result graph. |
| 682 |
reverse_dependencies = self._get_reverse_dependencies(resolver_result) |
| 683 |
|
| 684 |
# Transform candidates to install requirements |
| 685 |
resolved_candidates = tuple(resolver_result.mapping.values()) |
| 686 |
for candidate in resolved_candidates: |
| 687 |
ireq = self._get_install_requirement_from_candidate( |
| 688 |
candidate=candidate, |
| 689 |
reverse_dependencies=reverse_dependencies, |
| 690 |
) |
| 691 |
if ireq is None: |
| 692 |
continue |
| 693 |
|
| 694 |
project_name = canonicalize_name(candidate.project_name) |
| 695 |
result_ireqs[project_name] = ireq |
| 696 |
|
| 697 |
# Merge extras to install requirements |
| 698 |
extras_candidates = ( |
| 699 |
candidate |
| 700 |
for candidate in resolved_candidates |
| 701 |
if isinstance(candidate, ExtrasCandidate) |
| 702 |
) |
| 703 |
for extras_candidate in extras_candidates: |
| 704 |
project_name = canonicalize_name(extras_candidate.project_name) |
| 705 |
ireq = result_ireqs[project_name] |
| 706 |
ireq.extras |= extras_candidate.extras |
| 707 |
ireq.req.extras |= extras_candidate.extras |
| 708 |
|
| 709 |
return set(result_ireqs.values()) |
| 710 |
|
| 711 |
@staticmethod |
| 712 |
def _get_reverse_dependencies( |
| 713 |
resolver_result: Result, |
| 714 |
) -> dict[str, set[str]]: |
| 715 |
reverse_dependencies: DefaultDict[str, set[str]] = collections.defaultdict(set) |
| 716 |
|
| 717 |
for candidate in resolver_result.mapping.values(): |
| 718 |
stripped_name = strip_extras(canonicalize_name(candidate.name)) |
| 719 |
|
| 720 |
for parent_name in resolver_result.graph.iter_parents(candidate.name): |
| 721 |
# Skip root dependency which is always None |
| 722 |
if parent_name is None: |
| 723 |
continue |
| 724 |
|
| 725 |
# Skip a dependency that equals to the candidate. This could be |
| 726 |
# the dependency with extras. |
| 727 |
stripped_parent_name = strip_extras(canonicalize_name(parent_name)) |
| 728 |
if stripped_name == stripped_parent_name: |
| 729 |
continue |
| 730 |
|
| 731 |
reverse_dependencies[stripped_name].add(stripped_parent_name) |
| 732 |
|
| 733 |
return dict(reverse_dependencies) |
| 734 |
|
| 735 |
def _get_install_requirement_from_candidate( |
| 736 |
self, candidate: Candidate, reverse_dependencies: dict[str, set[str]] |
| 737 |
) -> InstallRequirement | None: |
| 738 |
ireq = candidate.get_install_requirement() |
| 739 |
if ireq is None: |
| 740 |
return None |
| 741 |
|
| 742 |
# Determine a pin operator |
| 743 |
version_pin_operator = "==" |
| 744 |
version_as_str = str(candidate.version) |
| 745 |
for specifier in ireq.specifier: |
| 746 |
if specifier.operator == "===" and specifier.version == version_as_str: |
| 747 |
version_pin_operator = "===" |
| 748 |
break |
| 749 |
|
| 750 |
# Prepare pinned install requirement. Copy it from candidate's install |
| 751 |
# requirement so that it could be mutated later. |
| 752 |
pinned_ireq = copy_install_requirement( |
| 753 |
template=ireq, |
| 754 |
# The link this candidate "originates" from. This is different |
| 755 |
# from ``ireq.link`` when the link is found in the wheel cache. |
| 756 |
# ``ireq.link`` would point to the wheel cache, while this points |
| 757 |
# to the found remote link (e.g. from pypi.org). |
| 758 |
link=candidate.source_link, |
| 759 |
) |
| 760 |
|
| 761 |
# Canonicalize name |
| 762 |
assert ireq.name is not None |
| 763 |
pinned_ireq.req.name = canonicalize_name(ireq.name) |
| 764 |
|
| 765 |
# Pin requirement to a resolved version |
| 766 |
pinned_ireq.req.specifier = SpecifierSet( |
| 767 |
f"{version_pin_operator}{candidate.version}" |
| 768 |
) |
| 769 |
|
| 770 |
# Save reverse dependencies for annotation |
| 771 |
ireq_key = key_from_ireq(ireq) |
| 772 |
pinned_ireq._required_by = reverse_dependencies.get(ireq_key, set()) |
| 773 |
|
| 774 |
# Save sources for annotation |
| 775 |
constraint_ireq = self._constraints_map.get(ireq_key) |
| 776 |
if constraint_ireq is not None: |
| 777 |
if hasattr(constraint_ireq, "_source_ireqs"): |
| 778 |
# If the constraint is combined (has _source_ireqs), use those |
| 779 |
pinned_ireq._source_ireqs = constraint_ireq._source_ireqs |
| 780 |
else: |
| 781 |
# Otherwise (the constraint is not combined) it is the source |
| 782 |
pinned_ireq._source_ireqs = [constraint_ireq] |
| 783 |
|
| 784 |
return pinned_ireq |