build_meta.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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, f"Multiple {suffix} directories found"
  299. return Path(parent, candidates[0])
  300. msg = f"No {suffix} directory found in {metadata_directory}"
  301. raise errors.InternalError(msg)
  302. def prepare_metadata_for_build_wheel(
  303. self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
  304. ) -> str:
  305. sys.argv = [
  306. *sys.argv[:1],
  307. *self._global_args(config_settings),
  308. "dist_info",
  309. "--output-dir",
  310. str(metadata_directory),
  311. "--keep-egg-info",
  312. ]
  313. with no_install_setup_requires():
  314. self.run_setup()
  315. self._bubble_up_info_directory(metadata_directory, ".egg-info")
  316. return self._bubble_up_info_directory(metadata_directory, ".dist-info")
  317. def _build_with_temp_dir(
  318. self,
  319. setup_command: Iterable[str],
  320. result_extension: str | tuple[str, ...],
  321. result_directory: StrPath,
  322. config_settings: _ConfigSettings,
  323. arbitrary_args: Iterable[str] = (),
  324. ):
  325. result_directory = os.path.abspath(result_directory)
  326. # Build in a temporary directory, then copy to the target.
  327. os.makedirs(result_directory, exist_ok=True)
  328. with tempfile.TemporaryDirectory(
  329. prefix=".tmp-", dir=result_directory
  330. ) as tmp_dist_dir:
  331. sys.argv = [
  332. *sys.argv[:1],
  333. *self._global_args(config_settings),
  334. *setup_command,
  335. "--dist-dir",
  336. tmp_dist_dir,
  337. *arbitrary_args,
  338. ]
  339. with no_install_setup_requires():
  340. self.run_setup()
  341. result_basename = _file_with_extension(tmp_dist_dir, result_extension)
  342. result_path = os.path.join(result_directory, result_basename)
  343. if os.path.exists(result_path):
  344. # os.rename will fail overwriting on non-Unix.
  345. os.remove(result_path)
  346. os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
  347. return result_basename
  348. def build_wheel(
  349. self,
  350. wheel_directory: StrPath,
  351. config_settings: _ConfigSettings = None,
  352. metadata_directory: StrPath | None = None,
  353. ) -> str:
  354. def _build(cmd: list[str]):
  355. with suppress_known_deprecation():
  356. return self._build_with_temp_dir(
  357. cmd,
  358. '.whl',
  359. wheel_directory,
  360. config_settings,
  361. self._arbitrary_args(config_settings),
  362. )
  363. if metadata_directory is None:
  364. return _build(['bdist_wheel'])
  365. try:
  366. return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)])
  367. except SystemExit as ex: # pragma: nocover
  368. # pypa/setuptools#4683
  369. if "--dist-info-dir not recognized" not in str(ex):
  370. raise
  371. _IncompatibleBdistWheel.emit()
  372. return _build(['bdist_wheel'])
  373. def build_sdist(
  374. self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
  375. ) -> str:
  376. return self._build_with_temp_dir(
  377. ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
  378. )
  379. def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None:
  380. if not metadata_directory:
  381. return None
  382. dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
  383. assert len(dist_info_candidates) <= 1
  384. return str(dist_info_candidates[0]) if dist_info_candidates else None
  385. def build_editable(
  386. self,
  387. wheel_directory: StrPath,
  388. config_settings: _ConfigSettings = None,
  389. metadata_directory: StrPath | None = None,
  390. ) -> str:
  391. # XXX can or should we hide our editable_wheel command normally?
  392. info_dir = self._get_dist_info_dir(metadata_directory)
  393. opts = ["--dist-info-dir", info_dir] if info_dir else []
  394. cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
  395. with suppress_known_deprecation():
  396. return self._build_with_temp_dir(
  397. cmd, ".whl", wheel_directory, config_settings
  398. )
  399. def get_requires_for_build_editable(
  400. self, config_settings: _ConfigSettings = None
  401. ) -> list[str]:
  402. return self.get_requires_for_build_wheel(config_settings)
  403. def prepare_metadata_for_build_editable(
  404. self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
  405. ) -> str:
  406. return self.prepare_metadata_for_build_wheel(
  407. metadata_directory, config_settings
  408. )
  409. class _BuildMetaLegacyBackend(_BuildMetaBackend):
  410. """Compatibility backend for setuptools
  411. This is a version of setuptools.build_meta that endeavors
  412. to maintain backwards
  413. compatibility with pre-PEP 517 modes of invocation. It
  414. exists as a temporary
  415. bridge between the old packaging mechanism and the new
  416. packaging mechanism,
  417. and will eventually be removed.
  418. """
  419. def run_setup(self, setup_script: str = 'setup.py') -> None:
  420. # In order to maintain compatibility with scripts assuming that
  421. # the setup.py script is in a directory on the PYTHONPATH, inject
  422. # '' into sys.path. (pypa/setuptools#1642)
  423. sys_path = list(sys.path) # Save the original path
  424. script_dir = os.path.dirname(os.path.abspath(setup_script))
  425. if script_dir not in sys.path:
  426. sys.path.insert(0, script_dir)
  427. # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
  428. # get the directory of the source code. They expect it to refer to the
  429. # setup.py script.
  430. sys_argv_0 = sys.argv[0]
  431. sys.argv[0] = setup_script
  432. try:
  433. super().run_setup(setup_script=setup_script)
  434. finally:
  435. # While PEP 517 frontends should be calling each hook in a fresh
  436. # subprocess according to the standard (and thus it should not be
  437. # strictly necessary to restore the old sys.path), we'll restore
  438. # the original path so that the path manipulation does not persist
  439. # within the hook after run_setup is called.
  440. sys.path[:] = sys_path
  441. sys.argv[0] = sys_argv_0
  442. class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning):
  443. _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools"
  444. _DETAILS = """
  445. Ensure that any custom bdist_wheel implementation is a subclass of
  446. setuptools.command.bdist_wheel.bdist_wheel.
  447. """
  448. _DUE_DATE = (2025, 10, 15)
  449. # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced?
  450. _SEE_URL = "https://github.com/pypa/wheel/pull/631"
  451. # The primary backend
  452. _BACKEND = _BuildMetaBackend()
  453. get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
  454. get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
  455. prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
  456. build_wheel = _BACKEND.build_wheel
  457. build_sdist = _BACKEND.build_sdist
  458. get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
  459. prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
  460. build_editable = _BACKEND.build_editable
  461. # The legacy backend
  462. __legacy__ = _BuildMetaLegacyBackend()