packaging.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from __future__ import absolute_import
  2. from email.parser import FeedParser
  3. import logging
  4. import sys
  5. from pip._vendor.packaging import specifiers
  6. from pip._vendor.packaging import version
  7. from pip._vendor import pkg_resources
  8. from pip import exceptions
  9. logger = logging.getLogger(__name__)
  10. def check_requires_python(requires_python):
  11. """
  12. Check if the python version in use match the `requires_python` specifier.
  13. Returns `True` if the version of python in use matches the requirement.
  14. Returns `False` if the version of python in use does not matches the
  15. requirement.
  16. Raises an InvalidSpecifier if `requires_python` have an invalid format.
  17. """
  18. if requires_python is None:
  19. # The package provides no information
  20. return True
  21. requires_python_specifier = specifiers.SpecifierSet(requires_python)
  22. # We only use major.minor.micro
  23. python_version = version.parse('.'.join(map(str, sys.version_info[:3])))
  24. return python_version in requires_python_specifier
  25. def get_metadata(dist):
  26. if (isinstance(dist, pkg_resources.DistInfoDistribution) and
  27. dist.has_metadata('METADATA')):
  28. return dist.get_metadata('METADATA')
  29. elif dist.has_metadata('PKG-INFO'):
  30. return dist.get_metadata('PKG-INFO')
  31. def check_dist_requires_python(dist):
  32. metadata = get_metadata(dist)
  33. feed_parser = FeedParser()
  34. feed_parser.feed(metadata)
  35. pkg_info_dict = feed_parser.close()
  36. requires_python = pkg_info_dict.get('Requires-Python')
  37. try:
  38. if not check_requires_python(requires_python):
  39. raise exceptions.UnsupportedPythonVersion(
  40. "%s requires Python '%s' but the running Python is %s" % (
  41. dist.project_name,
  42. requires_python,
  43. '.'.join(map(str, sys.version_info[:3])),)
  44. )
  45. except specifiers.InvalidSpecifier as e:
  46. logger.warning(
  47. "Package %s has an invalid Requires-Python entry %s - %s" % (
  48. dist.project_name, requires_python, e))
  49. return