wheel.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. """Wheels support."""
  2. from distutils.util import get_platform
  3. from distutils import log
  4. import email
  5. import itertools
  6. import os
  7. import posixpath
  8. import re
  9. import zipfile
  10. import pkg_resources
  11. import setuptools
  12. from pkg_resources import parse_version
  13. from setuptools.extern.packaging.tags import sys_tags
  14. from setuptools.extern.packaging.utils import canonicalize_name
  15. from setuptools.extern.six import PY3
  16. from setuptools.command.egg_info import write_requirements
  17. __metaclass__ = type
  18. WHEEL_NAME = re.compile(
  19. r"""^(?P<project_name>.+?)-(?P<version>\d.*?)
  20. ((-(?P<build>\d.*?))?-(?P<py_version>.+?)-(?P<abi>.+?)-(?P<platform>.+?)
  21. )\.whl$""",
  22. re.VERBOSE).match
  23. NAMESPACE_PACKAGE_INIT = \
  24. "__import__('pkg_resources').declare_namespace(__name__)\n"
  25. def unpack(src_dir, dst_dir):
  26. '''Move everything under `src_dir` to `dst_dir`, and delete the former.'''
  27. for dirpath, dirnames, filenames in os.walk(src_dir):
  28. subdir = os.path.relpath(dirpath, src_dir)
  29. for f in filenames:
  30. src = os.path.join(dirpath, f)
  31. dst = os.path.join(dst_dir, subdir, f)
  32. os.renames(src, dst)
  33. for n, d in reversed(list(enumerate(dirnames))):
  34. src = os.path.join(dirpath, d)
  35. dst = os.path.join(dst_dir, subdir, d)
  36. if not os.path.exists(dst):
  37. # Directory does not exist in destination,
  38. # rename it and prune it from os.walk list.
  39. os.renames(src, dst)
  40. del dirnames[n]
  41. # Cleanup.
  42. for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True):
  43. assert not filenames
  44. os.rmdir(dirpath)
  45. class Wheel:
  46. def __init__(self, filename):
  47. match = WHEEL_NAME(os.path.basename(filename))
  48. if match is None:
  49. raise ValueError('invalid wheel name: %r' % filename)
  50. self.filename = filename
  51. for k, v in match.groupdict().items():
  52. setattr(self, k, v)
  53. def tags(self):
  54. '''List tags (py_version, abi, platform) supported by this wheel.'''
  55. return itertools.product(
  56. self.py_version.split('.'),
  57. self.abi.split('.'),
  58. self.platform.split('.'),
  59. )
  60. def is_compatible(self):
  61. '''Is the wheel is compatible with the current platform?'''
  62. supported_tags = set(
  63. (t.interpreter, t.abi, t.platform) for t in sys_tags())
  64. return next((True for t in self.tags() if t in supported_tags), False)
  65. def egg_name(self):
  66. return pkg_resources.Distribution(
  67. project_name=self.project_name, version=self.version,
  68. platform=(None if self.platform == 'any' else get_platform()),
  69. ).egg_name() + '.egg'
  70. def get_dist_info(self, zf):
  71. # find the correct name of the .dist-info dir in the wheel file
  72. for member in zf.namelist():
  73. dirname = posixpath.dirname(member)
  74. if (dirname.endswith('.dist-info') and
  75. canonicalize_name(dirname).startswith(
  76. canonicalize_name(self.project_name))):
  77. return dirname
  78. raise ValueError("unsupported wheel format. .dist-info not found")
  79. def install_as_egg(self, destination_eggdir):
  80. '''Install wheel as an egg directory.'''
  81. with zipfile.ZipFile(self.filename) as zf:
  82. self._install_as_egg(destination_eggdir, zf)
  83. def _install_as_egg(self, destination_eggdir, zf):
  84. dist_basename = '%s-%s' % (self.project_name, self.version)
  85. dist_info = self.get_dist_info(zf)
  86. dist_data = '%s.data' % dist_basename
  87. egg_info = os.path.join(destination_eggdir, 'EGG-INFO')
  88. self._convert_metadata(zf, destination_eggdir, dist_info, egg_info)
  89. self._move_data_entries(destination_eggdir, dist_data)
  90. self._fix_namespace_packages(egg_info, destination_eggdir)
  91. @staticmethod
  92. def _convert_metadata(zf, destination_eggdir, dist_info, egg_info):
  93. def get_metadata(name):
  94. with zf.open(posixpath.join(dist_info, name)) as fp:
  95. value = fp.read().decode('utf-8') if PY3 else fp.read()
  96. return email.parser.Parser().parsestr(value)
  97. wheel_metadata = get_metadata('WHEEL')
  98. # Check wheel format version is supported.
  99. wheel_version = parse_version(wheel_metadata.get('Wheel-Version'))
  100. wheel_v1 = (
  101. parse_version('1.0') <= wheel_version < parse_version('2.0dev0')
  102. )
  103. if not wheel_v1:
  104. raise ValueError(
  105. 'unsupported wheel format version: %s' % wheel_version)
  106. # Extract to target directory.
  107. os.mkdir(destination_eggdir)
  108. zf.extractall(destination_eggdir)
  109. # Convert metadata.
  110. dist_info = os.path.join(destination_eggdir, dist_info)
  111. dist = pkg_resources.Distribution.from_location(
  112. destination_eggdir, dist_info,
  113. metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info),
  114. )
  115. # Note: Evaluate and strip markers now,
  116. # as it's difficult to convert back from the syntax:
  117. # foobar; "linux" in sys_platform and extra == 'test'
  118. def raw_req(req):
  119. req.marker = None
  120. return str(req)
  121. install_requires = list(sorted(map(raw_req, dist.requires())))
  122. extras_require = {
  123. extra: sorted(
  124. req
  125. for req in map(raw_req, dist.requires((extra,)))
  126. if req not in install_requires
  127. )
  128. for extra in dist.extras
  129. }
  130. os.rename(dist_info, egg_info)
  131. os.rename(
  132. os.path.join(egg_info, 'METADATA'),
  133. os.path.join(egg_info, 'PKG-INFO'),
  134. )
  135. setup_dist = setuptools.Distribution(
  136. attrs=dict(
  137. install_requires=install_requires,
  138. extras_require=extras_require,
  139. ),
  140. )
  141. # Temporarily disable info traces.
  142. log_threshold = log._global_log.threshold
  143. log.set_threshold(log.WARN)
  144. try:
  145. write_requirements(
  146. setup_dist.get_command_obj('egg_info'),
  147. None,
  148. os.path.join(egg_info, 'requires.txt'),
  149. )
  150. finally:
  151. log.set_threshold(log_threshold)
  152. @staticmethod
  153. def _move_data_entries(destination_eggdir, dist_data):
  154. """Move data entries to their correct location."""
  155. dist_data = os.path.join(destination_eggdir, dist_data)
  156. dist_data_scripts = os.path.join(dist_data, 'scripts')
  157. if os.path.exists(dist_data_scripts):
  158. egg_info_scripts = os.path.join(
  159. destination_eggdir, 'EGG-INFO', 'scripts')
  160. os.mkdir(egg_info_scripts)
  161. for entry in os.listdir(dist_data_scripts):
  162. # Remove bytecode, as it's not properly handled
  163. # during easy_install scripts install phase.
  164. if entry.endswith('.pyc'):
  165. os.unlink(os.path.join(dist_data_scripts, entry))
  166. else:
  167. os.rename(
  168. os.path.join(dist_data_scripts, entry),
  169. os.path.join(egg_info_scripts, entry),
  170. )
  171. os.rmdir(dist_data_scripts)
  172. for subdir in filter(os.path.exists, (
  173. os.path.join(dist_data, d)
  174. for d in ('data', 'headers', 'purelib', 'platlib')
  175. )):
  176. unpack(subdir, destination_eggdir)
  177. if os.path.exists(dist_data):
  178. os.rmdir(dist_data)
  179. @staticmethod
  180. def _fix_namespace_packages(egg_info, destination_eggdir):
  181. namespace_packages = os.path.join(
  182. egg_info, 'namespace_packages.txt')
  183. if os.path.exists(namespace_packages):
  184. with open(namespace_packages) as fp:
  185. namespace_packages = fp.read().split()
  186. for mod in namespace_packages:
  187. mod_dir = os.path.join(destination_eggdir, *mod.split('.'))
  188. mod_init = os.path.join(mod_dir, '__init__.py')
  189. if not os.path.exists(mod_dir):
  190. os.mkdir(mod_dir)
  191. if not os.path.exists(mod_init):
  192. with open(mod_init, 'w') as fp:
  193. fp.write(NAMESPACE_PACKAGE_INIT)