Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

wheel.py 8.1KB

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