build_meta.py 20 KB

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