bdist_wheel.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. """
  2. Create a wheel (.whl) distribution.
  3. A wheel is a built archive format.
  4. """
  5. import os
  6. import shutil
  7. import stat
  8. import sys
  9. import re
  10. from collections import OrderedDict
  11. from email.generator import Generator
  12. from distutils.core import Command
  13. from distutils.sysconfig import get_python_version
  14. from distutils import log as logger
  15. from glob import iglob
  16. from shutil import rmtree
  17. from warnings import warn
  18. from zipfile import ZIP_DEFLATED, ZIP_STORED
  19. import pkg_resources
  20. from .pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag, get_platform
  21. from .pkginfo import write_pkg_info
  22. from .metadata import pkginfo_to_metadata
  23. from .wheelfile import WheelFile
  24. from . import pep425tags
  25. from . import __version__ as wheel_version
  26. safe_name = pkg_resources.safe_name
  27. safe_version = pkg_resources.safe_version
  28. PY_LIMITED_API_PATTERN = r'cp3\d'
  29. def safer_name(name):
  30. return safe_name(name).replace('-', '_')
  31. def safer_version(version):
  32. return safe_version(version).replace('-', '_')
  33. def remove_readonly(func, path, excinfo):
  34. print(str(excinfo[1]))
  35. os.chmod(path, stat.S_IWRITE)
  36. func(path)
  37. class bdist_wheel(Command):
  38. description = 'create a wheel distribution'
  39. supported_compressions = OrderedDict([
  40. ('stored', ZIP_STORED),
  41. ('deflated', ZIP_DEFLATED)
  42. ])
  43. user_options = [('bdist-dir=', 'b',
  44. "temporary directory for creating the distribution"),
  45. ('plat-name=', 'p',
  46. "platform name to embed in generated filenames "
  47. "(default: %s)" % get_platform(None)),
  48. ('keep-temp', 'k',
  49. "keep the pseudo-installation tree around after " +
  50. "creating the distribution archive"),
  51. ('dist-dir=', 'd',
  52. "directory to put final built distributions in"),
  53. ('skip-build', None,
  54. "skip rebuilding everything (for testing/debugging)"),
  55. ('relative', None,
  56. "build the archive using relative paths "
  57. "(default: false)"),
  58. ('owner=', 'u',
  59. "Owner name used when creating a tar file"
  60. " [default: current user]"),
  61. ('group=', 'g',
  62. "Group name used when creating a tar file"
  63. " [default: current group]"),
  64. ('universal', None,
  65. "make a universal wheel"
  66. " (default: false)"),
  67. ('compression=', None,
  68. "zipfile compression (one of: {})"
  69. " (default: 'deflated')"
  70. .format(', '.join(supported_compressions))),
  71. ('python-tag=', None,
  72. "Python implementation compatibility tag"
  73. " (default: py%s)" % get_impl_ver()[0]),
  74. ('build-number=', None,
  75. "Build number for this particular version. "
  76. "As specified in PEP-0427, this must start with a digit. "
  77. "[default: None]"),
  78. ('py-limited-api=', None,
  79. "Python tag (cp32|cp33|cpNN) for abi3 wheel tag"
  80. " (default: false)"),
  81. ]
  82. boolean_options = ['keep-temp', 'skip-build', 'relative', 'universal']
  83. def initialize_options(self):
  84. self.bdist_dir = None
  85. self.data_dir = None
  86. self.plat_name = None
  87. self.plat_tag = None
  88. self.format = 'zip'
  89. self.keep_temp = False
  90. self.dist_dir = None
  91. self.egginfo_dir = None
  92. self.root_is_pure = None
  93. self.skip_build = None
  94. self.relative = False
  95. self.owner = None
  96. self.group = None
  97. self.universal = False
  98. self.compression = 'deflated'
  99. self.python_tag = 'py' + get_impl_ver()[0]
  100. self.build_number = None
  101. self.py_limited_api = False
  102. self.plat_name_supplied = False
  103. def finalize_options(self):
  104. if self.bdist_dir is None:
  105. bdist_base = self.get_finalized_command('bdist').bdist_base
  106. self.bdist_dir = os.path.join(bdist_base, 'wheel')
  107. self.data_dir = self.wheel_dist_name + '.data'
  108. self.plat_name_supplied = self.plat_name is not None
  109. try:
  110. self.compression = self.supported_compressions[self.compression]
  111. except KeyError:
  112. raise ValueError('Unsupported compression: {}'.format(self.compression))
  113. need_options = ('dist_dir', 'plat_name', 'skip_build')
  114. self.set_undefined_options('bdist',
  115. *zip(need_options, need_options))
  116. self.root_is_pure = not (self.distribution.has_ext_modules()
  117. or self.distribution.has_c_libraries())
  118. if self.py_limited_api and not re.match(PY_LIMITED_API_PATTERN, self.py_limited_api):
  119. raise ValueError("py-limited-api must match '%s'" % PY_LIMITED_API_PATTERN)
  120. # Support legacy [wheel] section for setting universal
  121. wheel = self.distribution.get_option_dict('wheel')
  122. if 'universal' in wheel:
  123. # please don't define this in your global configs
  124. logger.warn('The [wheel] section is deprecated. Use [bdist_wheel] instead.')
  125. val = wheel['universal'][1].strip()
  126. if val.lower() in ('1', 'true', 'yes'):
  127. self.universal = True
  128. if self.build_number is not None and not self.build_number[:1].isdigit():
  129. raise ValueError("Build tag (build-number) must start with a digit.")
  130. @property
  131. def wheel_dist_name(self):
  132. """Return distribution full name with - replaced with _"""
  133. components = (safer_name(self.distribution.get_name()),
  134. safer_version(self.distribution.get_version()))
  135. if self.build_number:
  136. components += (self.build_number,)
  137. return '-'.join(components)
  138. def get_tag(self):
  139. # bdist sets self.plat_name if unset, we should only use it for purepy
  140. # wheels if the user supplied it.
  141. if self.plat_name_supplied:
  142. plat_name = self.plat_name
  143. elif self.root_is_pure:
  144. plat_name = 'any'
  145. else:
  146. # macosx contains system version in platform name so need special handle
  147. if self.plat_name and not self.plat_name.startswith("macosx"):
  148. plat_name = self.plat_name
  149. else:
  150. plat_name = get_platform(self.bdist_dir)
  151. if plat_name in ('linux-x86_64', 'linux_x86_64') and sys.maxsize == 2147483647:
  152. plat_name = 'linux_i686'
  153. plat_name = plat_name.replace('-', '_').replace('.', '_')
  154. if self.root_is_pure:
  155. if self.universal:
  156. impl = 'py2.py3'
  157. else:
  158. impl = self.python_tag
  159. tag = (impl, 'none', plat_name)
  160. else:
  161. impl_name = get_abbr_impl()
  162. impl_ver = get_impl_ver()
  163. impl = impl_name + impl_ver
  164. # We don't work on CPython 3.1, 3.0.
  165. if self.py_limited_api and (impl_name + impl_ver).startswith('cp3'):
  166. impl = self.py_limited_api
  167. abi_tag = 'abi3'
  168. else:
  169. abi_tag = str(get_abi_tag()).lower()
  170. tag = (impl, abi_tag, plat_name)
  171. supported_tags = pep425tags.get_supported(
  172. self.bdist_dir,
  173. supplied_platform=plat_name if self.plat_name_supplied else None)
  174. # XXX switch to this alternate implementation for non-pure:
  175. if not self.py_limited_api:
  176. assert tag == supported_tags[0], "%s != %s" % (tag, supported_tags[0])
  177. assert tag in supported_tags, "would build wheel with unsupported tag {}".format(tag)
  178. return tag
  179. def run(self):
  180. build_scripts = self.reinitialize_command('build_scripts')
  181. build_scripts.executable = 'python'
  182. build_scripts.force = True
  183. build_ext = self.reinitialize_command('build_ext')
  184. build_ext.inplace = False
  185. if not self.skip_build:
  186. self.run_command('build')
  187. install = self.reinitialize_command('install',
  188. reinit_subcommands=True)
  189. install.root = self.bdist_dir
  190. install.compile = False
  191. install.skip_build = self.skip_build
  192. install.warn_dir = False
  193. # A wheel without setuptools scripts is more cross-platform.
  194. # Use the (undocumented) `no_ep` option to setuptools'
  195. # install_scripts command to avoid creating entry point scripts.
  196. install_scripts = self.reinitialize_command('install_scripts')
  197. install_scripts.no_ep = True
  198. # Use a custom scheme for the archive, because we have to decide
  199. # at installation time which scheme to use.
  200. for key in ('headers', 'scripts', 'data', 'purelib', 'platlib'):
  201. setattr(install,
  202. 'install_' + key,
  203. os.path.join(self.data_dir, key))
  204. basedir_observed = ''
  205. if os.name == 'nt':
  206. # win32 barfs if any of these are ''; could be '.'?
  207. # (distutils.command.install:change_roots bug)
  208. basedir_observed = os.path.normpath(os.path.join(self.data_dir, '..'))
  209. self.install_libbase = self.install_lib = basedir_observed
  210. setattr(install,
  211. 'install_purelib' if self.root_is_pure else 'install_platlib',
  212. basedir_observed)
  213. logger.info("installing to %s", self.bdist_dir)
  214. self.run_command('install')
  215. impl_tag, abi_tag, plat_tag = self.get_tag()
  216. archive_basename = "{}-{}-{}-{}".format(self.wheel_dist_name, impl_tag, abi_tag, plat_tag)
  217. if not self.relative:
  218. archive_root = self.bdist_dir
  219. else:
  220. archive_root = os.path.join(
  221. self.bdist_dir,
  222. self._ensure_relative(install.install_base))
  223. self.set_undefined_options('install_egg_info', ('target', 'egginfo_dir'))
  224. distinfo_dirname = '{}-{}.dist-info'.format(
  225. safer_name(self.distribution.get_name()),
  226. safer_version(self.distribution.get_version()))
  227. distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
  228. self.egg2dist(self.egginfo_dir, distinfo_dir)
  229. self.write_wheelfile(distinfo_dir)
  230. # Make the archive
  231. if not os.path.exists(self.dist_dir):
  232. os.makedirs(self.dist_dir)
  233. wheel_path = os.path.join(self.dist_dir, archive_basename + '.whl')
  234. with WheelFile(wheel_path, 'w', self.compression) as wf:
  235. wf.write_files(archive_root)
  236. # Add to 'Distribution.dist_files' so that the "upload" command works
  237. getattr(self.distribution, 'dist_files', []).append(
  238. ('bdist_wheel', get_python_version(), wheel_path))
  239. if not self.keep_temp:
  240. logger.info('removing %s', self.bdist_dir)
  241. if not self.dry_run:
  242. rmtree(self.bdist_dir, onerror=remove_readonly)
  243. def write_wheelfile(self, wheelfile_base, generator='bdist_wheel (' + wheel_version + ')'):
  244. from email.message import Message
  245. msg = Message()
  246. msg['Wheel-Version'] = '1.0' # of the spec
  247. msg['Generator'] = generator
  248. msg['Root-Is-Purelib'] = str(self.root_is_pure).lower()
  249. if self.build_number is not None:
  250. msg['Build'] = self.build_number
  251. # Doesn't work for bdist_wininst
  252. impl_tag, abi_tag, plat_tag = self.get_tag()
  253. for impl in impl_tag.split('.'):
  254. for abi in abi_tag.split('.'):
  255. for plat in plat_tag.split('.'):
  256. msg['Tag'] = '-'.join((impl, abi, plat))
  257. wheelfile_path = os.path.join(wheelfile_base, 'WHEEL')
  258. logger.info('creating %s', wheelfile_path)
  259. with open(wheelfile_path, 'w') as f:
  260. Generator(f, maxheaderlen=0).flatten(msg)
  261. def _ensure_relative(self, path):
  262. # copied from dir_util, deleted
  263. drive, path = os.path.splitdrive(path)
  264. if path[0:1] == os.sep:
  265. path = drive + path[1:]
  266. return path
  267. @property
  268. def license_paths(self):
  269. metadata = self.distribution.get_option_dict('metadata')
  270. files = set()
  271. patterns = sorted({
  272. option for option in metadata.get('license_files', ('', ''))[1].split()
  273. })
  274. if 'license_file' in metadata:
  275. warn('The "license_file" option is deprecated. Use "license_files" instead.',
  276. DeprecationWarning)
  277. files.add(metadata['license_file'][1])
  278. if 'license_file' not in metadata and 'license_files' not in metadata:
  279. patterns = ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*')
  280. for pattern in patterns:
  281. for path in iglob(pattern):
  282. if path not in files and os.path.isfile(path):
  283. logger.info('adding license file "%s" (matched pattern "%s")', path, pattern)
  284. files.add(path)
  285. return files
  286. def egg2dist(self, egginfo_path, distinfo_path):
  287. """Convert an .egg-info directory into a .dist-info directory"""
  288. def adios(p):
  289. """Appropriately delete directory, file or link."""
  290. if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
  291. shutil.rmtree(p)
  292. elif os.path.exists(p):
  293. os.unlink(p)
  294. adios(distinfo_path)
  295. if not os.path.exists(egginfo_path):
  296. # There is no egg-info. This is probably because the egg-info
  297. # file/directory is not named matching the distribution name used
  298. # to name the archive file. Check for this case and report
  299. # accordingly.
  300. import glob
  301. pat = os.path.join(os.path.dirname(egginfo_path), '*.egg-info')
  302. possible = glob.glob(pat)
  303. err = "Egg metadata expected at %s but not found" % (egginfo_path,)
  304. if possible:
  305. alt = os.path.basename(possible[0])
  306. err += " (%s found - possible misnamed archive file?)" % (alt,)
  307. raise ValueError(err)
  308. if os.path.isfile(egginfo_path):
  309. # .egg-info is a single file
  310. pkginfo_path = egginfo_path
  311. pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path)
  312. os.mkdir(distinfo_path)
  313. else:
  314. # .egg-info is a directory
  315. pkginfo_path = os.path.join(egginfo_path, 'PKG-INFO')
  316. pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path)
  317. # ignore common egg metadata that is useless to wheel
  318. shutil.copytree(egginfo_path, distinfo_path,
  319. ignore=lambda x, y: {'PKG-INFO', 'requires.txt', 'SOURCES.txt',
  320. 'not-zip-safe'}
  321. )
  322. # delete dependency_links if it is only whitespace
  323. dependency_links_path = os.path.join(distinfo_path, 'dependency_links.txt')
  324. with open(dependency_links_path, 'r') as dependency_links_file:
  325. dependency_links = dependency_links_file.read().strip()
  326. if not dependency_links:
  327. adios(dependency_links_path)
  328. write_pkg_info(os.path.join(distinfo_path, 'METADATA'), pkg_info)
  329. for license_path in self.license_paths:
  330. filename = os.path.basename(license_path)
  331. shutil.copy(license_path, os.path.join(distinfo_path, filename))
  332. adios(egginfo_path)