check.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Validation of dependencies of packages
  2. """
  3. import logging
  4. from collections import namedtuple
  5. from pip._vendor.packaging.utils import canonicalize_name
  6. from pip._vendor.pkg_resources import RequirementParseError
  7. from pip._internal.distributions import make_distribution_for_install_requirement
  8. from pip._internal.utils.misc import get_installed_distributions
  9. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  10. logger = logging.getLogger(__name__)
  11. if MYPY_CHECK_RUNNING:
  12. from typing import Any, Callable, Dict, List, Optional, Set, Tuple
  13. from pip._internal.req.req_install import InstallRequirement
  14. # Shorthands
  15. PackageSet = Dict[str, 'PackageDetails']
  16. Missing = Tuple[str, Any]
  17. Conflicting = Tuple[str, str, Any]
  18. MissingDict = Dict[str, List[Missing]]
  19. ConflictingDict = Dict[str, List[Conflicting]]
  20. CheckResult = Tuple[MissingDict, ConflictingDict]
  21. ConflictDetails = Tuple[PackageSet, CheckResult]
  22. PackageDetails = namedtuple('PackageDetails', ['version', 'requires'])
  23. def create_package_set_from_installed(**kwargs):
  24. # type: (**Any) -> Tuple[PackageSet, bool]
  25. """Converts a list of distributions into a PackageSet.
  26. """
  27. # Default to using all packages installed on the system
  28. if kwargs == {}:
  29. kwargs = {"local_only": False, "skip": ()}
  30. package_set = {}
  31. problems = False
  32. for dist in get_installed_distributions(**kwargs):
  33. name = canonicalize_name(dist.project_name)
  34. try:
  35. package_set[name] = PackageDetails(dist.version, dist.requires())
  36. except (OSError, RequirementParseError) as e:
  37. # Don't crash on unreadable or broken metadata
  38. logger.warning("Error parsing requirements for %s: %s", name, e)
  39. problems = True
  40. return package_set, problems
  41. def check_package_set(package_set, should_ignore=None):
  42. # type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult
  43. """Check if a package set is consistent
  44. If should_ignore is passed, it should be a callable that takes a
  45. package name and returns a boolean.
  46. """
  47. missing = {}
  48. conflicting = {}
  49. for package_name in package_set:
  50. # Info about dependencies of package_name
  51. missing_deps = set() # type: Set[Missing]
  52. conflicting_deps = set() # type: Set[Conflicting]
  53. if should_ignore and should_ignore(package_name):
  54. continue
  55. for req in package_set[package_name].requires:
  56. name = canonicalize_name(req.project_name) # type: str
  57. # Check if it's missing
  58. if name not in package_set:
  59. missed = True
  60. if req.marker is not None:
  61. missed = req.marker.evaluate()
  62. if missed:
  63. missing_deps.add((name, req))
  64. continue
  65. # Check if there's a conflict
  66. version = package_set[name].version # type: str
  67. if not req.specifier.contains(version, prereleases=True):
  68. conflicting_deps.add((name, version, req))
  69. if missing_deps:
  70. missing[package_name] = sorted(missing_deps, key=str)
  71. if conflicting_deps:
  72. conflicting[package_name] = sorted(conflicting_deps, key=str)
  73. return missing, conflicting
  74. def check_install_conflicts(to_install):
  75. # type: (List[InstallRequirement]) -> ConflictDetails
  76. """For checking if the dependency graph would be consistent after \
  77. installing given requirements
  78. """
  79. # Start from the current state
  80. package_set, _ = create_package_set_from_installed()
  81. # Install packages
  82. would_be_installed = _simulate_installation_of(to_install, package_set)
  83. # Only warn about directly-dependent packages; create a whitelist of them
  84. whitelist = _create_whitelist(would_be_installed, package_set)
  85. return (
  86. package_set,
  87. check_package_set(
  88. package_set, should_ignore=lambda name: name not in whitelist
  89. )
  90. )
  91. def _simulate_installation_of(to_install, package_set):
  92. # type: (List[InstallRequirement], PackageSet) -> Set[str]
  93. """Computes the version of packages after installing to_install.
  94. """
  95. # Keep track of packages that were installed
  96. installed = set()
  97. # Modify it as installing requirement_set would (assuming no errors)
  98. for inst_req in to_install:
  99. abstract_dist = make_distribution_for_install_requirement(inst_req)
  100. dist = abstract_dist.get_pkg_resources_distribution()
  101. assert dist is not None
  102. name = canonicalize_name(dist.key)
  103. package_set[name] = PackageDetails(dist.version, dist.requires())
  104. installed.add(name)
  105. return installed
  106. def _create_whitelist(would_be_installed, package_set):
  107. # type: (Set[str], PackageSet) -> Set[str]
  108. packages_affected = set(would_be_installed)
  109. for package_name in package_set:
  110. if package_name in packages_affected:
  111. continue
  112. for req in package_set[package_name].requires:
  113. if canonicalize_name(req.name) in packages_affected:
  114. packages_affected.add(package_name)
  115. break
  116. return packages_affected