build_meta.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  150. """
  151. Let the user specify ``verbose`` or ``quiet`` + escape hatch via
  152. ``--global-option``.
  153. Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
  154. so we just have to cover the basic scenario ``-v``.
  155. >>> fn = _ConfigSettingsTranslator()._global_args
  156. >>> list(fn(None))
  157. []
  158. >>> list(fn({"verbose": "False"}))
  159. ['-q']
  160. >>> list(fn({"verbose": "1"}))
  161. ['-v']
  162. >>> list(fn({"--verbose": None}))
  163. ['-v']
  164. >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
  165. ['-v', '-q', '--no-user-cfg']
  166. >>> list(fn({"--quiet": None}))
  167. ['-q']
  168. """
  169. cfg = config_settings or {}
  170. falsey = {"false", "no", "0", "off"}
  171. if "verbose" in cfg or "--verbose" in cfg:
  172. level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
  173. yield ("-q" if level.lower() in falsey else "-v")
  174. if "quiet" in cfg or "--quiet" in cfg:
  175. level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
  176. yield ("-v" if level.lower() in falsey else "-q")
  177. yield from self._get_config("--global-option", config_settings)
  178. def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  179. """
  180. The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
  181. .. warning::
  182. We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
  183. commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
  184. directory created in ``prepare_metadata_for_build_wheel``.
  185. >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
  186. >>> list(fn(None))
  187. []
  188. >>> list(fn({"tag-date": "False"}))
  189. ['--no-date']
  190. >>> list(fn({"tag-date": None}))
  191. ['--no-date']
  192. >>> list(fn({"tag-date": "true", "tag-build": ".a"}))
  193. ['--tag-date', '--tag-build', '.a']
  194. """
  195. cfg = config_settings or {}
  196. if "tag-date" in cfg:
  197. val = strtobool(str(cfg["tag-date"] or "false"))
  198. yield ("--tag-date" if val else "--no-date")
  199. if "tag-build" in cfg:
  200. yield from ["--tag-build", str(cfg["tag-build"])]
  201. def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  202. """
  203. The ``editable_wheel`` command accepts ``editable-mode=strict``.
  204. >>> fn = _ConfigSettingsTranslator()._editable_args
  205. >>> list(fn(None))
  206. []
  207. >>> list(fn({"editable-mode": "strict"}))
  208. ['--mode', 'strict']
  209. """
  210. cfg = config_settings or {}
  211. mode = cfg.get("editable-mode") or cfg.get("editable_mode")
  212. if not mode:
  213. return
  214. yield from ["--mode", str(mode)]
  215. def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  216. """
  217. Users may expect to pass arbitrary lists of arguments to a command
  218. via "--global-option" (example provided in PEP 517 of a "escape hatch").
  219. >>> fn = _ConfigSettingsTranslator()._arbitrary_args
  220. >>> list(fn(None))
  221. []
  222. >>> list(fn({}))
  223. []
  224. >>> list(fn({'--build-option': 'foo'}))
  225. ['foo']
  226. >>> list(fn({'--build-option': ['foo']}))
  227. ['foo']
  228. >>> list(fn({'--build-option': 'foo'}))
  229. ['foo']
  230. >>> list(fn({'--build-option': 'foo bar'}))
  231. ['foo', 'bar']
  232. >>> list(fn({'--global-option': 'foo'}))
  233. []
  234. """
  235. yield from self._get_config("--build-option", config_settings)
  236. class _BuildMetaBackend(_ConfigSettingsTranslator):
  237. def _get_build_requires(self, config_settings, requirements):
  238. sys.argv = [
  239. *sys.argv[:1],
  240. *self._global_args(config_settings),
  241. "egg_info",
  242. ]
  243. try:
  244. with Distribution.patch():
  245. self.run_setup()
  246. except SetupRequirementsError as e:
  247. requirements += e.specifiers
  248. return requirements
  249. def run_setup(self, setup_script='setup.py'):
  250. # Note that we can reuse our build directory between calls
  251. # Correctness comes first, then optimization later
  252. __file__ = os.path.abspath(setup_script)
  253. __name__ = '__main__'
  254. with _open_setup_script(__file__) as f:
  255. code = f.read().replace(r'\r\n', r'\n')
  256. try:
  257. exec(code, locals())
  258. except SystemExit as e:
  259. if e.code:
  260. raise
  261. # We ignore exit code indicating success
  262. SetuptoolsDeprecationWarning.emit(
  263. "Running `setup.py` directly as CLI tool is deprecated.",
  264. "Please avoid using `sys.exit(0)` or similar statements "
  265. "that don't fit in the paradigm of a configuration file.",
  266. see_url="https://blog.ganssle.io/articles/2021/10/"
  267. "setup-py-deprecated.html",
  268. )
  269. def get_requires_for_build_wheel(self, config_settings=None):
  270. return self._get_build_requires(config_settings, requirements=['wheel'])
  271. def get_requires_for_build_sdist(self, config_settings=None):
  272. return self._get_build_requires(config_settings, requirements=[])
  273. def _bubble_up_info_directory(self, metadata_directory: str, suffix: str) -> str:
  274. """
  275. PEP 517 requires that the .dist-info directory be placed in the
  276. metadata_directory. To comply, we MUST copy the directory to the root.
  277. Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.
  278. """
  279. info_dir = self._find_info_directory(metadata_directory, suffix)
  280. if not same_path(info_dir.parent, metadata_directory):
  281. shutil.move(str(info_dir), metadata_directory)
  282. # PEP 517 allow other files and dirs to exist in metadata_directory
  283. return info_dir.name
  284. def _find_info_directory(self, metadata_directory: str, suffix: str) -> Path:
  285. for parent, dirs, _ in os.walk(metadata_directory):
  286. candidates = [f for f in dirs if f.endswith(suffix)]
  287. if len(candidates) != 0 or len(dirs) != 1:
  288. assert len(candidates) == 1, f"Multiple {suffix} directories found"
  289. return Path(parent, candidates[0])
  290. msg = f"No {suffix} directory found in {metadata_directory}"
  291. raise errors.InternalError(msg)
  292. def prepare_metadata_for_build_wheel(
  293. self, metadata_directory, config_settings=None
  294. ):
  295. sys.argv = [
  296. *sys.argv[:1],
  297. *self._global_args(config_settings),
  298. "dist_info",
  299. "--output-dir",
  300. metadata_directory,
  301. "--keep-egg-info",
  302. ]
  303. with no_install_setup_requires():
  304. self.run_setup()
  305. self._bubble_up_info_directory(metadata_directory, ".egg-info")
  306. return self._bubble_up_info_directory(metadata_directory, ".dist-info")
  307. def _build_with_temp_dir(
  308. self, setup_command, result_extension, result_directory, config_settings
  309. ):
  310. result_directory = os.path.abspath(result_directory)
  311. # Build in a temporary directory, then copy to the target.
  312. os.makedirs(result_directory, exist_ok=True)
  313. temp_opts = {"prefix": ".tmp-", "dir": result_directory}
  314. with tempfile.TemporaryDirectory(**temp_opts) as tmp_dist_dir:
  315. sys.argv = [
  316. *sys.argv[:1],
  317. *self._global_args(config_settings),
  318. *setup_command,
  319. "--dist-dir",
  320. tmp_dist_dir,
  321. ]
  322. with no_install_setup_requires():
  323. self.run_setup()
  324. result_basename = _file_with_extension(tmp_dist_dir, result_extension)
  325. result_path = os.path.join(result_directory, result_basename)
  326. if os.path.exists(result_path):
  327. # os.rename will fail overwriting on non-Unix.
  328. os.remove(result_path)
  329. os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
  330. return result_basename
  331. def build_wheel(
  332. self, wheel_directory, config_settings=None, metadata_directory=None
  333. ):
  334. with suppress_known_deprecation():
  335. return self._build_with_temp_dir(
  336. ['bdist_wheel', *self._arbitrary_args(config_settings)],
  337. '.whl',
  338. wheel_directory,
  339. config_settings,
  340. )
  341. def build_sdist(self, sdist_directory, config_settings=None):
  342. return self._build_with_temp_dir(
  343. ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
  344. )
  345. def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]:
  346. if not metadata_directory:
  347. return None
  348. dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
  349. assert len(dist_info_candidates) <= 1
  350. return str(dist_info_candidates[0]) if dist_info_candidates else None
  351. if not LEGACY_EDITABLE:
  352. # PEP660 hooks:
  353. # build_editable
  354. # get_requires_for_build_editable
  355. # prepare_metadata_for_build_editable
  356. def build_editable(
  357. self, wheel_directory, config_settings=None, metadata_directory=None
  358. ):
  359. # XXX can or should we hide our editable_wheel command normally?
  360. info_dir = self._get_dist_info_dir(metadata_directory)
  361. opts = ["--dist-info-dir", info_dir] if info_dir else []
  362. cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
  363. with suppress_known_deprecation():
  364. return self._build_with_temp_dir(
  365. cmd, ".whl", wheel_directory, config_settings
  366. )
  367. def get_requires_for_build_editable(self, config_settings=None):
  368. return self.get_requires_for_build_wheel(config_settings)
  369. def prepare_metadata_for_build_editable(
  370. self, metadata_directory, config_settings=None
  371. ):
  372. return self.prepare_metadata_for_build_wheel(
  373. metadata_directory, config_settings
  374. )
  375. class _BuildMetaLegacyBackend(_BuildMetaBackend):
  376. """Compatibility backend for setuptools
  377. This is a version of setuptools.build_meta that endeavors
  378. to maintain backwards
  379. compatibility with pre-PEP 517 modes of invocation. It
  380. exists as a temporary
  381. bridge between the old packaging mechanism and the new
  382. packaging mechanism,
  383. and will eventually be removed.
  384. """
  385. def run_setup(self, setup_script='setup.py'):
  386. # In order to maintain compatibility with scripts assuming that
  387. # the setup.py script is in a directory on the PYTHONPATH, inject
  388. # '' into sys.path. (pypa/setuptools#1642)
  389. sys_path = list(sys.path) # Save the original path
  390. script_dir = os.path.dirname(os.path.abspath(setup_script))
  391. if script_dir not in sys.path:
  392. sys.path.insert(0, script_dir)
  393. # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
  394. # get the directory of the source code. They expect it to refer to the
  395. # setup.py script.
  396. sys_argv_0 = sys.argv[0]
  397. sys.argv[0] = setup_script
  398. try:
  399. super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
  400. finally:
  401. # While PEP 517 frontends should be calling each hook in a fresh
  402. # subprocess according to the standard (and thus it should not be
  403. # strictly necessary to restore the old sys.path), we'll restore
  404. # the original path so that the path manipulation does not persist
  405. # within the hook after run_setup is called.
  406. sys.path[:] = sys_path
  407. sys.argv[0] = sys_argv_0
  408. # The primary backend
  409. _BACKEND = _BuildMetaBackend()
  410. get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
  411. get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
  412. prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
  413. build_wheel = _BACKEND.build_wheel
  414. build_sdist = _BACKEND.build_sdist
  415. if not LEGACY_EDITABLE:
  416. get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
  417. prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
  418. build_editable = _BACKEND.build_editable
  419. # The legacy backend
  420. __legacy__ = _BuildMetaLegacyBackend()