req_set.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import logging
  2. from collections import OrderedDict
  3. from typing import Dict, List
  4. from pip._vendor.packaging.utils import canonicalize_name
  5. from pip._internal.req.req_install import InstallRequirement
  6. logger = logging.getLogger(__name__)
  7. class RequirementSet:
  8. def __init__(self, check_supported_wheels: bool = True) -> None:
  9. """Create a RequirementSet."""
  10. self.requirements: Dict[str, InstallRequirement] = OrderedDict()
  11. self.check_supported_wheels = check_supported_wheels
  12. self.unnamed_requirements: List[InstallRequirement] = []
  13. def __str__(self) -> str:
  14. requirements = sorted(
  15. (req for req in self.requirements.values() if not req.comes_from),
  16. key=lambda req: canonicalize_name(req.name or ""),
  17. )
  18. return " ".join(str(req.req) for req in requirements)
  19. def __repr__(self) -> str:
  20. requirements = sorted(
  21. self.requirements.values(),
  22. key=lambda req: canonicalize_name(req.name or ""),
  23. )
  24. format_string = "<{classname} object; {count} requirement(s): {reqs}>"
  25. return format_string.format(
  26. classname=self.__class__.__name__,
  27. count=len(requirements),
  28. reqs=", ".join(str(req.req) for req in requirements),
  29. )
  30. def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:
  31. assert not install_req.name
  32. self.unnamed_requirements.append(install_req)
  33. def add_named_requirement(self, install_req: InstallRequirement) -> None:
  34. assert install_req.name
  35. project_name = canonicalize_name(install_req.name)
  36. self.requirements[project_name] = install_req
  37. def has_requirement(self, name: str) -> bool:
  38. project_name = canonicalize_name(name)
  39. return (
  40. project_name in self.requirements
  41. and not self.requirements[project_name].constraint
  42. )
  43. def get_requirement(self, name: str) -> InstallRequirement:
  44. project_name = canonicalize_name(name)
  45. if project_name in self.requirements:
  46. return self.requirements[project_name]
  47. raise KeyError(f"No project with the name {name!r}")
  48. @property
  49. def all_requirements(self) -> List[InstallRequirement]:
  50. return self.unnamed_requirements + list(self.requirements.values())
  51. @property
  52. def requirements_to_install(self) -> List[InstallRequirement]:
  53. """Return the list of requirements that need to be installed.
  54. TODO remove this property together with the legacy resolver, since the new
  55. resolver only returns requirements that need to be installed.
  56. """
  57. return [
  58. install_req
  59. for install_req in self.all_requirements
  60. if not install_req.constraint and not install_req.satisfied_by
  61. ]