bdist_wheel.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. """
  2. Create a wheel (.whl) distribution.
  3. A wheel is a built archive format.
  4. """
  5. from __future__ import annotations
  6. import os
  7. import re
  8. import shutil
  9. import struct
  10. import sys
  11. import sysconfig
  12. import warnings
  13. from collections.abc import Iterable, Sequence
  14. from email.generator import BytesGenerator
  15. from glob import iglob
  16. from typing import Literal, cast
  17. from zipfile import ZIP_DEFLATED, ZIP_STORED
  18. from packaging import tags, version as _packaging_version
  19. from wheel.wheelfile import WheelFile
  20. from .. import Command, __version__, _shutil
  21. from .._core_metadata import _safe_license_file
  22. from .._normalization import safer_name
  23. from ..warnings import SetuptoolsDeprecationWarning
  24. from .egg_info import egg_info as egg_info_cls
  25. from distutils import log
  26. def safe_version(version: str) -> str:
  27. """
  28. Convert an arbitrary string to a standard version string
  29. """
  30. try:
  31. # normalize the version
  32. return str(_packaging_version.Version(version))
  33. except _packaging_version.InvalidVersion:
  34. version = version.replace(" ", ".")
  35. return re.sub("[^A-Za-z0-9.]+", "-", version)
  36. setuptools_major_version = int(__version__.split(".")[0])
  37. PY_LIMITED_API_PATTERN = r"cp3\d"
  38. def _is_32bit_interpreter() -> bool:
  39. return struct.calcsize("P") == 4
  40. def python_tag() -> str:
  41. return f"py{sys.version_info.major}"
  42. def get_platform(archive_root: str | None) -> str:
  43. """Return our platform name 'win32', 'linux_x86_64'"""
  44. result = sysconfig.get_platform()
  45. if result.startswith("macosx") and archive_root is not None: # pragma: no cover
  46. from wheel.macosx_libfile import calculate_macosx_platform_tag
  47. result = calculate_macosx_platform_tag(archive_root, result)
  48. elif _is_32bit_interpreter():
  49. if result == "linux-x86_64":
  50. # pip pull request #3497
  51. result = "linux-i686"
  52. elif result == "linux-aarch64":
  53. # packaging pull request #234
  54. # TODO armv8l, packaging pull request #690 => this did not land
  55. # in pip/packaging yet
  56. result = "linux-armv7l"
  57. return result.replace("-", "_")
  58. def get_flag(
  59. var: str, fallback: bool, expected: bool = True, warn: bool = True
  60. ) -> bool:
  61. """Use a fallback value for determining SOABI flags if the needed config
  62. var is unset or unavailable."""
  63. val = sysconfig.get_config_var(var)
  64. if val is None:
  65. if warn:
  66. warnings.warn(
  67. f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
  68. RuntimeWarning,
  69. stacklevel=2,
  70. )
  71. return fallback
  72. return val == expected
  73. def get_abi_tag() -> str | None:
  74. """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
  75. soabi: str = sysconfig.get_config_var("SOABI")
  76. impl = tags.interpreter_name()
  77. if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
  78. d = ""
  79. u = ""
  80. if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
  81. d = "d"
  82. abi = f"{impl}{tags.interpreter_version()}{d}{u}"
  83. elif soabi and impl == "cp" and soabi.startswith("cpython"):
  84. # non-Windows
  85. abi = "cp" + soabi.split("-")[1]
  86. elif soabi and impl == "cp" and soabi.startswith("cp"):
  87. # Windows
  88. abi = soabi.split("-")[0]
  89. if hasattr(sys, "gettotalrefcount"):
  90. # using debug build; append "d" flag
  91. abi += "d"
  92. elif soabi and impl == "pp":
  93. # we want something like pypy36-pp73
  94. abi = "-".join(soabi.split("-")[:2])
  95. abi = abi.replace(".", "_").replace("-", "_")
  96. elif soabi and impl == "graalpy":
  97. abi = "-".join(soabi.split("-")[:3])
  98. abi = abi.replace(".", "_").replace("-", "_")
  99. elif soabi:
  100. abi = soabi.replace(".", "_").replace("-", "_")
  101. else:
  102. abi = None
  103. return abi
  104. def safer_version(version: str) -> str:
  105. return safe_version(version).replace("-", "_")
  106. class bdist_wheel(Command):
  107. description = "create a wheel distribution"
  108. supported_compressions = {
  109. "stored": ZIP_STORED,
  110. "deflated": ZIP_DEFLATED,
  111. }
  112. user_options = [
  113. ("bdist-dir=", "b", "temporary directory for creating the distribution"),
  114. (
  115. "plat-name=",
  116. "p",
  117. "platform name to embed in generated filenames "
  118. f"[default: {get_platform(None)}]",
  119. ),
  120. (
  121. "keep-temp",
  122. "k",
  123. "keep the pseudo-installation tree around after "
  124. "creating the distribution archive",
  125. ),
  126. ("dist-dir=", "d", "directory to put final built distributions in"),
  127. ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
  128. (
  129. "relative",
  130. None,
  131. "build the archive using relative paths [default: false]",
  132. ),
  133. (
  134. "owner=",
  135. "u",
  136. "Owner name used when creating a tar file [default: current user]",
  137. ),
  138. (
  139. "group=",
  140. "g",
  141. "Group name used when creating a tar file [default: current group]",
  142. ),
  143. ("universal", None, "*DEPRECATED* make a universal wheel [default: false]"),
  144. (
  145. "compression=",
  146. None,
  147. f"zipfile compression (one of: {', '.join(supported_compressions)}) [default: 'deflated']",
  148. ),
  149. (
  150. "python-tag=",
  151. None,
  152. f"Python implementation compatibility tag [default: '{python_tag()}']",
  153. ),
  154. (
  155. "build-number=",
  156. None,
  157. "Build number for this particular version. "
  158. "As specified in PEP-0427, this must start with a digit. "
  159. "[default: None]",
  160. ),
  161. (
  162. "py-limited-api=",
  163. None,
  164. "Python tag (cp32|cp33|cpNN) for abi3 wheel tag [default: false]",
  165. ),
  166. (
  167. "dist-info-dir=",
  168. None,
  169. "directory where a pre-generated dist-info can be found (e.g. as a "
  170. "result of calling the PEP517 'prepare_metadata_for_build_wheel' "
  171. "method)",
  172. ),
  173. ]
  174. boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
  175. def initialize_options(self) -> None:
  176. self.bdist_dir: str | None = None
  177. self.data_dir = ""
  178. self.plat_name: str | None = None
  179. self.plat_tag: str | None = None
  180. self.format = "zip"
  181. self.keep_temp = False
  182. self.dist_dir: str | None = None
  183. self.dist_info_dir = None
  184. self.egginfo_dir: str | None = None
  185. self.root_is_pure: bool | None = None
  186. self.skip_build = False
  187. self.relative = False
  188. self.owner = None
  189. self.group = None
  190. self.universal = False
  191. self.compression: str | int = "deflated"
  192. self.python_tag = python_tag()
  193. self.build_number: str | None = None
  194. self.py_limited_api: str | Literal[False] = False
  195. self.plat_name_supplied = False
  196. def finalize_options(self) -> None:
  197. if not self.bdist_dir:
  198. bdist_base = self.get_finalized_command("bdist").bdist_base
  199. self.bdist_dir = os.path.join(bdist_base, "wheel")
  200. if self.dist_info_dir is None:
  201. egg_info = cast(egg_info_cls, self.distribution.get_command_obj("egg_info"))
  202. egg_info.ensure_finalized() # needed for correct `wheel_dist_name`
  203. self.data_dir = self.wheel_dist_name + ".data"
  204. self.plat_name_supplied = bool(self.plat_name)
  205. need_options = ("dist_dir", "plat_name", "skip_build")
  206. self.set_undefined_options("bdist", *zip(need_options, need_options))
  207. self.root_is_pure = not (
  208. self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
  209. )
  210. self._validate_py_limited_api()
  211. # Support legacy [wheel] section for setting universal
  212. wheel = self.distribution.get_option_dict("wheel")
  213. if "universal" in wheel: # pragma: no cover
  214. # please don't define this in your global configs
  215. log.warn("The [wheel] section is deprecated. Use [bdist_wheel] instead.")
  216. val = wheel["universal"][1].strip()
  217. if val.lower() in ("1", "true", "yes"):
  218. self.universal = True
  219. if self.universal:
  220. SetuptoolsDeprecationWarning.emit(
  221. "bdist_wheel.universal is deprecated",
  222. """
  223. With Python 2.7 end-of-life, support for building universal wheels
  224. (i.e., wheels that support both Python 2 and Python 3)
  225. is being obviated.
  226. Please discontinue using this option, or if you still need it,
  227. file an issue with pypa/setuptools describing your use case.
  228. """,
  229. due_date=(2025, 8, 30), # Introduced in 2024-08-30
  230. )
  231. if self.build_number is not None and not self.build_number[:1].isdigit():
  232. raise ValueError("Build tag (build-number) must start with a digit.")
  233. def _validate_py_limited_api(self) -> None:
  234. if not self.py_limited_api:
  235. return
  236. if not re.match(PY_LIMITED_API_PATTERN, self.py_limited_api):
  237. raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
  238. if sysconfig.get_config_var("Py_GIL_DISABLED"):
  239. raise ValueError(
  240. f"`py_limited_api={self.py_limited_api!r}` not supported. "
  241. "`Py_LIMITED_API` is currently incompatible with "
  242. "`Py_GIL_DISABLED`. "
  243. "See https://github.com/python/cpython/issues/111506."
  244. )
  245. @property
  246. def wheel_dist_name(self) -> str:
  247. """Return distribution full name with - replaced with _"""
  248. components = [
  249. safer_name(self.distribution.get_name()),
  250. safer_version(self.distribution.get_version()),
  251. ]
  252. if self.build_number:
  253. components.append(self.build_number)
  254. return "-".join(components)
  255. def get_tag(self) -> tuple[str, str, str]:
  256. # bdist sets self.plat_name if unset, we should only use it for purepy
  257. # wheels if the user supplied it.
  258. if self.plat_name_supplied and self.plat_name:
  259. plat_name = self.plat_name
  260. elif self.root_is_pure:
  261. plat_name = "any"
  262. else:
  263. # macosx contains system version in platform name so need special handle
  264. if self.plat_name and not self.plat_name.startswith("macosx"):
  265. plat_name = self.plat_name
  266. else:
  267. # on macosx always limit the platform name to comply with any
  268. # c-extension modules in bdist_dir, since the user can specify
  269. # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
  270. # on other platforms, and on macosx if there are no c-extension
  271. # modules, use the default platform name.
  272. plat_name = get_platform(self.bdist_dir)
  273. if _is_32bit_interpreter():
  274. if plat_name in ("linux-x86_64", "linux_x86_64"):
  275. plat_name = "linux_i686"
  276. if plat_name in ("linux-aarch64", "linux_aarch64"):
  277. # TODO armv8l, packaging pull request #690 => this did not land
  278. # in pip/packaging yet
  279. plat_name = "linux_armv7l"
  280. plat_name = (
  281. plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
  282. )
  283. if self.root_is_pure:
  284. if self.universal:
  285. impl = "py2.py3"
  286. else:
  287. impl = self.python_tag
  288. tag = (impl, "none", plat_name)
  289. else:
  290. impl_name = tags.interpreter_name()
  291. impl_ver = tags.interpreter_version()
  292. impl = impl_name + impl_ver
  293. # We don't work on CPython 3.1, 3.0.
  294. if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
  295. impl = self.py_limited_api
  296. abi_tag = "abi3"
  297. else:
  298. abi_tag = str(get_abi_tag()).lower()
  299. tag = (impl, abi_tag, plat_name)
  300. # issue gh-374: allow overriding plat_name
  301. supported_tags = [
  302. (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
  303. ]
  304. assert tag in supported_tags, (
  305. f"would build wheel with unsupported tag {tag}"
  306. )
  307. return tag
  308. def run(self):
  309. build_scripts = self.reinitialize_command("build_scripts")
  310. build_scripts.executable = "python"
  311. build_scripts.force = True
  312. build_ext = self.reinitialize_command("build_ext")
  313. build_ext.inplace = False
  314. if not self.skip_build:
  315. self.run_command("build")
  316. install = self.reinitialize_command("install", reinit_subcommands=True)
  317. install.root = self.bdist_dir
  318. install.compile = False
  319. install.skip_build = self.skip_build
  320. install.warn_dir = False
  321. # A wheel without setuptools scripts is more cross-platform.
  322. # Use the (undocumented) `no_ep` option to setuptools'
  323. # install_scripts command to avoid creating entry point scripts.
  324. install_scripts = self.reinitialize_command("install_scripts")
  325. install_scripts.no_ep = True
  326. # Use a custom scheme for the archive, because we have to decide
  327. # at installation time which scheme to use.
  328. for key in ("headers", "scripts", "data", "purelib", "platlib"):
  329. setattr(install, "install_" + key, os.path.join(self.data_dir, key))
  330. basedir_observed = ""
  331. if os.name == "nt":
  332. # win32 barfs if any of these are ''; could be '.'?
  333. # (distutils.command.install:change_roots bug)
  334. basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
  335. self.install_libbase = self.install_lib = basedir_observed
  336. setattr(
  337. install,
  338. "install_purelib" if self.root_is_pure else "install_platlib",
  339. basedir_observed,
  340. )
  341. log.info(f"installing to {self.bdist_dir}")
  342. self.run_command("install")
  343. impl_tag, abi_tag, plat_tag = self.get_tag()
  344. archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
  345. if not self.relative:
  346. archive_root = self.bdist_dir
  347. else:
  348. archive_root = os.path.join(
  349. self.bdist_dir, self._ensure_relative(install.install_base)
  350. )
  351. self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
  352. distinfo_dirname = (
  353. f"{safer_name(self.distribution.get_name())}-"
  354. f"{safer_version(self.distribution.get_version())}.dist-info"
  355. )
  356. distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
  357. if self.dist_info_dir:
  358. # Use the given dist-info directly.
  359. log.debug(f"reusing {self.dist_info_dir}")
  360. shutil.copytree(self.dist_info_dir, distinfo_dir)
  361. # Egg info is still generated, so remove it now to avoid it getting
  362. # copied into the wheel.
  363. _shutil.rmtree(self.egginfo_dir)
  364. else:
  365. # Convert the generated egg-info into dist-info.
  366. self.egg2dist(self.egginfo_dir, distinfo_dir)
  367. self.write_wheelfile(distinfo_dir)
  368. # Make the archive
  369. if not os.path.exists(self.dist_dir):
  370. os.makedirs(self.dist_dir)
  371. wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
  372. with WheelFile(wheel_path, "w", self._zip_compression()) as wf:
  373. wf.write_files(archive_root)
  374. # Add to 'Distribution.dist_files' so that the "upload" command works
  375. getattr(self.distribution, "dist_files", []).append((
  376. "bdist_wheel",
  377. f"{sys.version_info.major}.{sys.version_info.minor}",
  378. wheel_path,
  379. ))
  380. if not self.keep_temp:
  381. log.info(f"removing {self.bdist_dir}")
  382. _shutil.rmtree(self.bdist_dir)
  383. def write_wheelfile(
  384. self, wheelfile_base: str, generator: str = f"setuptools ({__version__})"
  385. ) -> None:
  386. from email.message import Message
  387. msg = Message()
  388. msg["Wheel-Version"] = "1.0" # of the spec
  389. msg["Generator"] = generator
  390. msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
  391. if self.build_number is not None:
  392. msg["Build"] = self.build_number
  393. # Doesn't work for bdist_wininst
  394. impl_tag, abi_tag, plat_tag = self.get_tag()
  395. for impl in impl_tag.split("."):
  396. for abi in abi_tag.split("."):
  397. for plat in plat_tag.split("."):
  398. msg["Tag"] = "-".join((impl, abi, plat))
  399. wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
  400. log.info(f"creating {wheelfile_path}")
  401. with open(wheelfile_path, "wb") as f:
  402. BytesGenerator(f, maxheaderlen=0).flatten(msg)
  403. def _ensure_relative(self, path: str) -> str:
  404. # copied from dir_util, deleted
  405. drive, path = os.path.splitdrive(path)
  406. if path[0:1] == os.sep:
  407. path = drive + path[1:]
  408. return path
  409. @property
  410. def license_paths(self) -> Iterable[str]:
  411. if setuptools_major_version >= 57:
  412. # Setuptools has resolved any patterns to actual file names
  413. return self.distribution.metadata.license_files or ()
  414. files = set[str]()
  415. metadata = self.distribution.get_option_dict("metadata")
  416. if setuptools_major_version >= 42:
  417. # Setuptools recognizes the license_files option but does not do globbing
  418. patterns = cast(Sequence[str], self.distribution.metadata.license_files)
  419. else:
  420. # Prior to those, wheel is entirely responsible for handling license files
  421. if "license_files" in metadata:
  422. patterns = metadata["license_files"][1].split()
  423. else:
  424. patterns = ()
  425. if "license_file" in metadata:
  426. warnings.warn(
  427. 'The "license_file" option is deprecated. Use "license_files" instead.',
  428. DeprecationWarning,
  429. stacklevel=2,
  430. )
  431. files.add(metadata["license_file"][1])
  432. if not files and not patterns and not isinstance(patterns, list):
  433. patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
  434. for pattern in patterns:
  435. for path in iglob(pattern):
  436. if path.endswith("~"):
  437. log.debug(
  438. f'ignoring license file "{path}" as it looks like a backup'
  439. )
  440. continue
  441. if path not in files and os.path.isfile(path):
  442. log.info(
  443. f'adding license file "{path}" (matched pattern "{pattern}")'
  444. )
  445. files.add(path)
  446. return files
  447. def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None:
  448. """Convert an .egg-info directory into a .dist-info directory"""
  449. def adios(p: str) -> None:
  450. """Appropriately delete directory, file or link."""
  451. if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
  452. _shutil.rmtree(p)
  453. elif os.path.exists(p):
  454. os.unlink(p)
  455. adios(distinfo_path)
  456. if not os.path.exists(egginfo_path):
  457. # There is no egg-info. This is probably because the egg-info
  458. # file/directory is not named matching the distribution name used
  459. # to name the archive file. Check for this case and report
  460. # accordingly.
  461. import glob
  462. pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
  463. possible = glob.glob(pat)
  464. err = f"Egg metadata expected at {egginfo_path} but not found"
  465. if possible:
  466. alt = os.path.basename(possible[0])
  467. err += f" ({alt} found - possible misnamed archive file?)"
  468. raise ValueError(err)
  469. # .egg-info is a directory
  470. pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
  471. # ignore common egg metadata that is useless to wheel
  472. shutil.copytree(
  473. egginfo_path,
  474. distinfo_path,
  475. ignore=lambda x, y: {
  476. "PKG-INFO",
  477. "requires.txt",
  478. "SOURCES.txt",
  479. "not-zip-safe",
  480. },
  481. )
  482. # delete dependency_links if it is only whitespace
  483. dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
  484. with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
  485. dependency_links = dependency_links_file.read().strip()
  486. if not dependency_links:
  487. adios(dependency_links_path)
  488. metadata_path = os.path.join(distinfo_path, "METADATA")
  489. shutil.copy(pkginfo_path, metadata_path)
  490. licenses_folder_path = os.path.join(distinfo_path, "licenses")
  491. for license_path in self.license_paths:
  492. safe_path = _safe_license_file(license_path)
  493. dist_info_license_path = os.path.join(licenses_folder_path, safe_path)
  494. os.makedirs(os.path.dirname(dist_info_license_path), exist_ok=True)
  495. shutil.copy(license_path, dist_info_license_path)
  496. adios(egginfo_path)
  497. def _zip_compression(self) -> int:
  498. if (
  499. isinstance(self.compression, int)
  500. and self.compression in self.supported_compressions.values()
  501. ):
  502. return self.compression
  503. compression = self.supported_compressions.get(str(self.compression))
  504. if compression is not None:
  505. return compression
  506. raise ValueError(f"Unsupported compression: {self.compression!r}")