build_meta.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. """A PEP 517 interface to setuptools
  2. Previously, when a user or a command line tool (let's call it a "frontend")
  3. needed to make a request of setuptools to take a certain action, for
  4. example, generating a list of installation requirements, the frontend
  5. would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line.
  6. PEP 517 defines a different method of interfacing with setuptools. Rather
  7. than calling "setup.py" directly, the frontend should:
  8. 1. Set the current directory to the directory with a setup.py file
  9. 2. Import this module into a safe python interpreter (one in which
  10. setuptools can potentially set global variables or crash hard).
  11. 3. Call one of the functions defined in PEP 517.
  12. What each function does is defined in PEP 517. However, here is a "casual"
  13. definition of the functions (this definition should not be relied on for
  14. bug reports or API stability):
  15. - `build_wheel`: build a wheel in the folder and return the basename
  16. - `get_requires_for_build_wheel`: get the `setup_requires` to build
  17. - `prepare_metadata_for_build_wheel`: get the `install_requires`
  18. - `build_sdist`: build an sdist in the folder and return the basename
  19. - `get_requires_for_build_sdist`: get the `setup_requires` to build
  20. Again, this is not a formal definition! Just a "taste" of the module.
  21. """
  22. from __future__ import annotations
  23. import contextlib
  24. import io
  25. import os
  26. import shlex
  27. import shutil
  28. import sys
  29. import tempfile
  30. import tokenize
  31. import warnings
  32. from collections.abc import Iterable, Iterator, Mapping
  33. from pathlib import Path
  34. from typing import TYPE_CHECKING, NoReturn, Union
  35. import setuptools
  36. from . import errors
  37. from ._path import StrPath, same_path
  38. from ._reqs import parse_strings
  39. from .warnings import SetuptoolsDeprecationWarning
  40. import distutils
  41. from distutils.util import strtobool
  42. if TYPE_CHECKING:
  43. from typing_extensions import TypeAlias
  44. __all__ = [
  45. 'get_requires_for_build_sdist',
  46. 'get_requires_for_build_wheel',
  47. 'prepare_metadata_for_build_wheel',
  48. 'build_wheel',
  49. 'build_sdist',
  50. 'get_requires_for_build_editable',
  51. 'prepare_metadata_for_build_editable',
  52. 'build_editable',
  53. '__legacy__',
  54. 'SetupRequirementsError',
  55. ]
  56. class SetupRequirementsError(BaseException):
  57. def __init__(self, specifiers) -> None:
  58. self.specifiers = specifiers
  59. class Distribution(setuptools.dist.Distribution):
  60. def fetch_build_eggs(self, specifiers) -> NoReturn:
  61. specifier_list = list(parse_strings(specifiers))
  62. raise SetupRequirementsError(specifier_list)
  63. @classmethod
  64. @contextlib.contextmanager
  65. def patch(cls) -> Iterator[None]:
  66. """
  67. Replace
  68. distutils.dist.Distribution with this class
  69. for the duration of this context.
  70. """
  71. orig = distutils.core.Distribution
  72. distutils.core.Distribution = cls # type: ignore[misc] # monkeypatching
  73. try:
  74. yield
  75. finally:
  76. distutils.core.Distribution = orig # type: ignore[misc] # monkeypatching
  77. @contextlib.contextmanager
  78. def no_install_setup_requires():
  79. """Temporarily disable installing setup_requires
  80. Under PEP 517, the backend reports build dependencies to the frontend,
  81. and the frontend is responsible for ensuring they're installed.
  82. So setuptools (acting as a backend) should not try to install them.
  83. """
  84. orig = setuptools._install_setup_requires
  85. setuptools._install_setup_requires = lambda attrs: None
  86. try:
  87. yield
  88. finally:
  89. setuptools._install_setup_requires = orig
  90. def _get_immediate_subdirectories(a_dir):
  91. return [
  92. name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))
  93. ]
  94. def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]):
  95. matching = (f for f in os.listdir(directory) if f.endswith(extension))
  96. try:
  97. (file,) = matching
  98. except ValueError:
  99. raise ValueError(
  100. 'No distribution was found. Ensure that `setup.py` '
  101. 'is not empty and that it calls `setup()`.'
  102. ) from None
  103. return file
  104. def _open_setup_script(setup_script):
  105. if not os.path.exists(setup_script):
  106. # Supply a default setup.py
  107. return io.StringIO("from setuptools import setup; setup()")
  108. return tokenize.open(setup_script)
  109. @contextlib.contextmanager
  110. def suppress_known_deprecation():
  111. with warnings.catch_warnings():
  112. warnings.filterwarnings('ignore', 'setup.py install is deprecated')
  113. yield
  114. _ConfigSettings: TypeAlias = Union[Mapping[str, Union[str, list[str], None]], None]
  115. """
  116. Currently the user can run::
  117. pip install -e . --config-settings key=value
  118. python -m build -C--key=value -C key=value
  119. - pip will pass both key and value as strings and overwriting repeated keys
  120. (pypa/pip#11059).
  121. - build will accumulate values associated with repeated keys in a list.
  122. It will also accept keys with no associated value.
  123. This means that an option passed by build can be ``str | list[str] | None``.
  124. - PEP 517 specifies that ``config_settings`` is an optional dict.
  125. """
  126. class _ConfigSettingsTranslator:
  127. """Translate ``config_settings`` into distutils-style command arguments.
  128. Only a limited number of options is currently supported.
  129. """
  130. # See pypa/setuptools#1928 pypa/setuptools#2491
  131. def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
  132. """
  133. Get the value of a specific key in ``config_settings`` as a list of strings.
  134. >>> fn = _ConfigSettingsTranslator()._get_config
  135. >>> fn("--global-option", None)
  136. []
  137. >>> fn("--global-option", {})
  138. []
  139. >>> fn("--global-option", {'--global-option': 'foo'})
  140. ['foo']
  141. >>> fn("--global-option", {'--global-option': ['foo']})
  142. ['foo']
  143. >>> fn("--global-option", {'--global-option': 'foo'})
  144. ['foo']
  145. >>> fn("--global-option", {'--global-option': 'foo bar'})
  146. ['foo', 'bar']
  147. """
  148. cfg = config_settings or {}
  149. opts = cfg.get(key) or []
  150. return shlex.split(opts) if isinstance(opts, str) else opts
  151. def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  152. """
  153. Let the user specify ``verbose`` or ``quiet`` + escape hatch via
  154. ``--global-option``.
  155. Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
  156. so we just have to cover the basic scenario ``-v``.
  157. >>> fn = _ConfigSettingsTranslator()._global_args
  158. >>> list(fn(None))
  159. []
  160. >>> list(fn({"verbose": "False"}))
  161. ['-q']
  162. >>> list(fn({"verbose": "1"}))
  163. ['-v']
  164. >>> list(fn({"--verbose": None}))
  165. ['-v']
  166. >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
  167. ['-v', '-q', '--no-user-cfg']
  168. >>> list(fn({"--quiet": None}))
  169. ['-q']
  170. """
  171. cfg = config_settings or {}
  172. falsey = {"false", "no", "0", "off"}
  173. if "verbose" in cfg or "--verbose" in cfg:
  174. level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
  175. yield ("-q" if level.lower() in falsey else "-v")
  176. if "quiet" in cfg or "--quiet" in cfg:
  177. level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
  178. yield ("-v" if level.lower() in falsey else "-q")
  179. yield from self._get_config("--global-option", config_settings)
  180. def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  181. """
  182. The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
  183. .. warning::
  184. We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
  185. commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
  186. directory created in ``prepare_metadata_for_build_wheel``.
  187. >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
  188. >>> list(fn(None))
  189. []
  190. >>> list(fn({"tag-date": "False"}))
  191. ['--no-date']
  192. >>> list(fn({"tag-date": None}))
  193. ['--no-date']
  194. >>> list(fn({"tag-date": "true", "tag-build": ".a"}))
  195. ['--tag-date', '--tag-build', '.a']
  196. """
  197. cfg = config_settings or {}
  198. if "tag-date" in cfg:
  199. val = strtobool(str(cfg["tag-date"] or "false"))
  200. yield ("--tag-date" if val else "--no-date")
  201. if "tag-build" in cfg:
  202. yield from ["--tag-build", str(cfg["tag-build"])]
  203. def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  204. """
  205. The ``editable_wheel`` command accepts ``editable-mode=strict``.
  206. >>> fn = _ConfigSettingsTranslator()._editable_args
  207. >>> list(fn(None))
  208. []
  209. >>> list(fn({"editable-mode": "strict"}))
  210. ['--mode', 'strict']
  211. """
  212. cfg = config_settings or {}
  213. mode = cfg.get("editable-mode") or cfg.get("editable_mode")
  214. if not mode:
  215. return
  216. yield from ["--mode", str(mode)]
  217. def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  218. """
  219. Users may expect to pass arbitrary lists of arguments to a command
  220. via "--global-option" (example provided in PEP 517 of a "escape hatch").
  221. >>> fn = _ConfigSettingsTranslator()._arbitrary_args
  222. >>> list(fn(None))
  223. []
  224. >>> list(fn({}))
  225. []
  226. >>> list(fn({'--build-option': 'foo'}))
  227. ['foo']
  228. >>> list(fn({'--build-option': ['foo']}))
  229. ['foo']
  230. >>> list(fn({'--build-option': 'foo'}))
  231. ['foo']
  232. >>> list(fn({'--build-option': 'foo bar'}))
  233. ['foo', 'bar']
  234. >>> list(fn({'--global-option': 'foo'}))
  235. []
  236. """
  237. yield from self._get_config("--build-option", config_settings)
  238. class _BuildMetaBackend(_ConfigSettingsTranslator):
  239. def _get_build_requires(
  240. self, config_settings: _ConfigSettings, requirements: list[str]
  241. ):
  242. sys.argv = [
  243. *sys.argv[:1],
  244. *self._global_args(config_settings),
  245. "egg_info",
  246. ]
  247. try:
  248. with Distribution.patch():
  249. self.run_setup()
  250. except SetupRequirementsError as e:
  251. requirements += e.specifiers
  252. return requirements
  253. def run_setup(self, setup_script: str = 'setup.py') -> None:
  254. # Note that we can reuse our build directory between calls
  255. # Correctness comes first, then optimization later
  256. __file__ = os.path.abspath(setup_script)
  257. __name__ = '__main__'
  258. with _open_setup_script(__file__) as f:
  259. code = f.read().replace(r'\r\n', r'\n')
  260. try:
  261. exec(code, locals())
  262. except SystemExit as e:
  263. if e.code:
  264. raise
  265. # We ignore exit code indicating success
  266. SetuptoolsDeprecationWarning.emit(
  267. "Running `setup.py` directly as CLI tool is deprecated.",
  268. "Please avoid using `sys.exit(0)` or similar statements "
  269. "that don't fit in the paradigm of a configuration file.",
  270. see_url="https://blog.ganssle.io/articles/2021/10/"
  271. "setup-py-deprecated.html",
  272. )
  273. def get_requires_for_build_wheel(
  274. self, config_settings: _ConfigSettings = None
  275. ) -> list[str]:
  276. return self._get_build_requires(config_settings, requirements=[])
  277. def get_requires_for_build_sdist(
  278. self, config_settings: _ConfigSettings = None
  279. ) -> list[str]:
  280. return self._get_build_requires(config_settings, requirements=[])
  281. def _bubble_up_info_directory(
  282. self, metadata_directory: StrPath, suffix: str
  283. ) -> str:
  284. """
  285. PEP 517 requires that the .dist-info directory be placed in the
  286. metadata_directory. To comply, we MUST copy the directory to the root.
  287. Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.
  288. """
  289. info_dir = self._find_info_directory(metadata_directory, suffix)
  290. if not same_path(info_dir.parent, metadata_directory):
  291. shutil.move(str(info_dir), metadata_directory)
  292. # PEP 517 allow other files and dirs to exist in metadata_directory
  293. return info_dir.name
  294. def _find_info_directory(self, metadata_directory: StrPath, suffix: str) -> Path:
  295. for parent, dirs, _ in os.walk(metadata_directory):
  296. candidates = [f for f in dirs if f.endswith(suffix)]
  297. if len(candidates) != 0 or len(dirs) != 1:
  298. assert len(candidates) == 1, (
  299. f"Exactly one {suffix} should have been produced, but found {len(candidates)}: {candidates}"
  300. )
  301. return Path(parent, candidates[0])
  302. msg = f"No {suffix} directory found in {metadata_directory}"
  303. raise errors.InternalError(msg)
  304. def prepare_metadata_for_build_wheel(
  305. self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
  306. ) -> str:
  307. sys.argv = [
  308. *sys.argv[:1],
  309. *self._global_args(config_settings),
  310. "dist_info",
  311. "--output-dir",
  312. str(metadata_directory),
  313. "--keep-egg-info",
  314. ]
  315. with no_install_setup_requires():
  316. self.run_setup()
  317. self._bubble_up_info_directory(metadata_directory, ".egg-info")
  318. return self._bubble_up_info_directory(metadata_directory, ".dist-info")
  319. def _build_with_temp_dir(
  320. self,
  321. setup_command: Iterable[str],
  322. result_extension: str | tuple[str, ...],
  323. result_directory: StrPath,
  324. config_settings: _ConfigSettings,
  325. arbitrary_args: Iterable[str] = (),
  326. ):
  327. result_directory = os.path.abspath(result_directory)
  328. # Build in a temporary directory, then copy to the target.
  329. os.makedirs(result_directory, exist_ok=True)
  330. with tempfile.TemporaryDirectory(
  331. prefix=".tmp-", dir=result_directory
  332. ) as tmp_dist_dir:
  333. sys.argv = [
  334. *sys.argv[:1],
  335. *self._global_args(config_settings),
  336. *setup_command,
  337. "--dist-dir",
  338. tmp_dist_dir,
  339. *arbitrary_args,
  340. ]
  341. with no_install_setup_requires():
  342. self.run_setup()
  343. result_basename = _file_with_extension(tmp_dist_dir, result_extension)
  344. result_path = os.path.join(result_directory, result_basename)
  345. if os.path.exists(result_path):
  346. # os.rename will fail overwriting on non-Unix.
  347. os.remove(result_path)
  348. os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
  349. return result_basename
  350. def build_wheel(
  351. self,
  352. wheel_directory: StrPath,
  353. config_settings: _ConfigSettings = None,
  354. metadata_directory: StrPath | None = None,
  355. ) -> str:
  356. def _build(cmd: list[str]):
  357. with suppress_known_deprecation():
  358. return self._build_with_temp_dir(
  359. cmd,
  360. '.whl',
  361. wheel_directory,
  362. config_settings,
  363. self._arbitrary_args(config_settings),
  364. )
  365. if metadata_directory is None:
  366. return _build(['bdist_wheel'])
  367. try:
  368. return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)])
  369. except SystemExit as ex: # pragma: nocover
  370. # pypa/setuptools#4683
  371. if "--dist-info-dir not recognized" not in str(ex):
  372. raise
  373. _IncompatibleBdistWheel.emit()
  374. return _build(['bdist_wheel'])
  375. def build_sdist(
  376. self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
  377. ) -> str:
  378. return self._build_with_temp_dir(
  379. ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
  380. )
  381. def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None:
  382. if not metadata_directory:
  383. return None
  384. dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
  385. assert len(dist_info_candidates) <= 1
  386. return str(dist_info_candidates[0]) if dist_info_candidates else None
  387. def build_editable(
  388. self,
  389. wheel_directory: StrPath,
  390. config_settings: _ConfigSettings = None,
  391. metadata_directory: StrPath | None = None,
  392. ) -> str:
  393. # XXX can or should we hide our editable_wheel command normally?
  394. info_dir = self._get_dist_info_dir(metadata_directory)
  395. opts = ["--dist-info-dir", info_dir] if info_dir else []
  396. cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
  397. with suppress_known_deprecation():
  398. return self._build_with_temp_dir(
  399. cmd, ".whl", wheel_directory, config_settings
  400. )
  401. def get_requires_for_build_editable(
  402. self, config_settings: _ConfigSettings = None
  403. ) -> list[str]:
  404. return self.get_requires_for_build_wheel(config_settings)
  405. def prepare_metadata_for_build_editable(
  406. self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
  407. ) -> str:
  408. return self.prepare_metadata_for_build_wheel(
  409. metadata_directory, config_settings
  410. )
  411. class _BuildMetaLegacyBackend(_BuildMetaBackend):
  412. """Compatibility backend for setuptools
  413. This is a version of setuptools.build_meta that endeavors
  414. to maintain backwards
  415. compatibility with pre-PEP 517 modes of invocation. It
  416. exists as a temporary
  417. bridge between the old packaging mechanism and the new
  418. packaging mechanism,
  419. and will eventually be removed.
  420. """
  421. def run_setup(self, setup_script: str = 'setup.py') -> None:
  422. # In order to maintain compatibility with scripts assuming that
  423. # the setup.py script is in a directory on the PYTHONPATH, inject
  424. # '' into sys.path. (pypa/setuptools#1642)
  425. sys_path = list(sys.path) # Save the original path
  426. script_dir = os.path.dirname(os.path.abspath(setup_script))
  427. if script_dir not in sys.path:
  428. sys.path.insert(0, script_dir)
  429. # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
  430. # get the directory of the source code. They expect it to refer to the
  431. # setup.py script.
  432. sys_argv_0 = sys.argv[0]
  433. sys.argv[0] = setup_script
  434. try:
  435. super().run_setup(setup_script=setup_script)
  436. finally:
  437. # While PEP 517 frontends should be calling each hook in a fresh
  438. # subprocess according to the standard (and thus it should not be
  439. # strictly necessary to restore the old sys.path), we'll restore
  440. # the original path so that the path manipulation does not persist
  441. # within the hook after run_setup is called.
  442. sys.path[:] = sys_path
  443. sys.argv[0] = sys_argv_0
  444. class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning):
  445. _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools"
  446. _DETAILS = """
  447. Ensure that any custom bdist_wheel implementation is a subclass of
  448. setuptools.command.bdist_wheel.bdist_wheel.
  449. """
  450. _DUE_DATE = (2025, 10, 15)
  451. # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced?
  452. _SEE_URL = "https://github.com/pypa/wheel/pull/631"
  453. # The primary backend
  454. _BACKEND = _BuildMetaBackend()
  455. get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
  456. get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
  457. prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
  458. build_wheel = _BACKEND.build_wheel
  459. build_sdist = _BACKEND.build_sdist
  460. get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
  461. prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
  462. build_editable = _BACKEND.build_editable
  463. # The legacy backend
  464. __legacy__ = _BuildMetaLegacyBackend()