Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

561 wiersze
20 KiB

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