wheel.py 8.2 KB

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