_bdist_wheel.py 21 KB

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