_bdist_wheel.py 21 KB

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