You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

check.py 5.0KB

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