bdist_wheel.py 19 KB

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