bdist_wheel.py 21 KB

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