bdist_wheel.py 18 KB

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