build_meta.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 ._deprecation_warning import SetuptoolsDeprecationWarning
  39. from distutils.util import strtobool
  40. __all__ = ['get_requires_for_build_sdist',
  41. 'get_requires_for_build_wheel',
  42. 'prepare_metadata_for_build_wheel',
  43. 'build_wheel',
  44. 'build_sdist',
  45. 'get_requires_for_build_editable',
  46. 'prepare_metadata_for_build_editable',
  47. 'build_editable',
  48. '__legacy__',
  49. 'SetupRequirementsError']
  50. SETUPTOOLS_ENABLE_FEATURES = os.getenv("SETUPTOOLS_ENABLE_FEATURES", "").lower()
  51. LEGACY_EDITABLE = "legacy-editable" in SETUPTOOLS_ENABLE_FEATURES.replace("_", "-")
  52. class SetupRequirementsError(BaseException):
  53. def __init__(self, specifiers):
  54. self.specifiers = specifiers
  55. class Distribution(setuptools.dist.Distribution):
  56. def fetch_build_eggs(self, specifiers):
  57. specifier_list = list(parse_strings(specifiers))
  58. raise SetupRequirementsError(specifier_list)
  59. @classmethod
  60. @contextlib.contextmanager
  61. def patch(cls):
  62. """
  63. Replace
  64. distutils.dist.Distribution with this class
  65. for the duration of this context.
  66. """
  67. orig = distutils.core.Distribution
  68. distutils.core.Distribution = cls
  69. try:
  70. yield
  71. finally:
  72. distutils.core.Distribution = orig
  73. @contextlib.contextmanager
  74. def no_install_setup_requires():
  75. """Temporarily disable installing setup_requires
  76. Under PEP 517, the backend reports build dependencies to the frontend,
  77. and the frontend is responsible for ensuring they're installed.
  78. So setuptools (acting as a backend) should not try to install them.
  79. """
  80. orig = setuptools._install_setup_requires
  81. setuptools._install_setup_requires = lambda attrs: None
  82. try:
  83. yield
  84. finally:
  85. setuptools._install_setup_requires = orig
  86. def _get_immediate_subdirectories(a_dir):
  87. return [name for name in os.listdir(a_dir)
  88. if os.path.isdir(os.path.join(a_dir, name))]
  89. def _file_with_extension(directory, extension):
  90. matching = (
  91. f for f in os.listdir(directory)
  92. if f.endswith(extension)
  93. )
  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. return file
  101. def _open_setup_script(setup_script):
  102. if not os.path.exists(setup_script):
  103. # Supply a default setup.py
  104. return io.StringIO(u"from setuptools import setup; setup()")
  105. return getattr(tokenize, 'open', open)(setup_script)
  106. @contextlib.contextmanager
  107. def suppress_known_deprecation():
  108. with warnings.catch_warnings():
  109. warnings.filterwarnings('ignore', 'setup.py install is deprecated')
  110. yield
  111. _ConfigSettings = Optional[Dict[str, Union[str, List[str], None]]]
  112. """
  113. Currently the user can run::
  114. pip install -e . --config-settings key=value
  115. python -m build -C--key=value -C key=value
  116. - pip will pass both key and value as strings and overwriting repeated keys
  117. (pypa/pip#11059).
  118. - build will accumulate values associated with repeated keys in a list.
  119. It will also accept keys with no associated value.
  120. This means that an option passed by build can be ``str | list[str] | None``.
  121. - PEP 517 specifies that ``config_settings`` is an optional dict.
  122. """
  123. class _ConfigSettingsTranslator:
  124. """Translate ``config_settings`` into distutils-style command arguments.
  125. Only a limited number of options is currently supported.
  126. """
  127. # See pypa/setuptools#1928 pypa/setuptools#2491
  128. def _get_config(self, key: str, config_settings: _ConfigSettings) -> List[str]:
  129. """
  130. Get the value of a specific key in ``config_settings`` as a list of strings.
  131. >>> fn = _ConfigSettingsTranslator()._get_config
  132. >>> fn("--global-option", None)
  133. []
  134. >>> fn("--global-option", {})
  135. []
  136. >>> fn("--global-option", {'--global-option': 'foo'})
  137. ['foo']
  138. >>> fn("--global-option", {'--global-option': ['foo']})
  139. ['foo']
  140. >>> fn("--global-option", {'--global-option': 'foo'})
  141. ['foo']
  142. >>> fn("--global-option", {'--global-option': 'foo bar'})
  143. ['foo', 'bar']
  144. """
  145. cfg = config_settings or {}
  146. opts = cfg.get(key) or []
  147. return shlex.split(opts) if isinstance(opts, str) else opts
  148. def _valid_global_options(self):
  149. """Global options accepted by setuptools (e.g. quiet or verbose)."""
  150. options = (opt[:2] for opt in setuptools.dist.Distribution.global_options)
  151. return {flag for long_and_short in options for flag in long_and_short if flag}
  152. def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  153. """
  154. Let the user specify ``verbose`` or ``quiet`` + escape hatch via
  155. ``--global-option``.
  156. Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
  157. so we just have to cover the basic scenario ``-v``.
  158. >>> fn = _ConfigSettingsTranslator()._global_args
  159. >>> list(fn(None))
  160. []
  161. >>> list(fn({"verbose": "False"}))
  162. ['-q']
  163. >>> list(fn({"verbose": "1"}))
  164. ['-v']
  165. >>> list(fn({"--verbose": None}))
  166. ['-v']
  167. >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
  168. ['-v', '-q', '--no-user-cfg']
  169. >>> list(fn({"--quiet": None}))
  170. ['-q']
  171. """
  172. cfg = config_settings or {}
  173. falsey = {"false", "no", "0", "off"}
  174. if "verbose" in cfg or "--verbose" in cfg:
  175. level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
  176. yield ("-q" if level.lower() in falsey else "-v")
  177. if "quiet" in cfg or "--quiet" in cfg:
  178. level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
  179. yield ("-v" if level.lower() in falsey else "-q")
  180. valid = self._valid_global_options()
  181. args = self._get_config("--global-option", config_settings)
  182. yield from (arg for arg in args if arg.strip("-") in valid)
  183. def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  184. """
  185. The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
  186. .. warning::
  187. We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
  188. commands run in ``build_sdist`` and ``build_wheel`` to re-use the egg-info
  189. directory created in ``prepare_metadata_for_build_wheel``.
  190. >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
  191. >>> list(fn(None))
  192. []
  193. >>> list(fn({"tag-date": "False"}))
  194. ['--no-date']
  195. >>> list(fn({"tag-date": None}))
  196. ['--no-date']
  197. >>> list(fn({"tag-date": "true", "tag-build": ".a"}))
  198. ['--tag-date', '--tag-build', '.a']
  199. """
  200. cfg = config_settings or {}
  201. if "tag-date" in cfg:
  202. val = strtobool(str(cfg["tag-date"] or "false"))
  203. yield ("--tag-date" if val else "--no-date")
  204. if "tag-build" in cfg:
  205. yield from ["--tag-build", str(cfg["tag-build"])]
  206. def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  207. """
  208. The ``editable_wheel`` command accepts ``editable-mode=strict``.
  209. >>> fn = _ConfigSettingsTranslator()._editable_args
  210. >>> list(fn(None))
  211. []
  212. >>> list(fn({"editable-mode": "strict"}))
  213. ['--mode', 'strict']
  214. """
  215. cfg = config_settings or {}
  216. mode = cfg.get("editable-mode") or cfg.get("editable_mode")
  217. if not mode:
  218. return
  219. yield from ["--mode", str(mode)]
  220. def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
  221. """
  222. Users may expect to pass arbitrary lists of arguments to a command
  223. via "--global-option" (example provided in PEP 517 of a "escape hatch").
  224. >>> fn = _ConfigSettingsTranslator()._arbitrary_args
  225. >>> list(fn(None))
  226. []
  227. >>> list(fn({}))
  228. []
  229. >>> list(fn({'--build-option': 'foo'}))
  230. ['foo']
  231. >>> list(fn({'--build-option': ['foo']}))
  232. ['foo']
  233. >>> list(fn({'--build-option': 'foo'}))
  234. ['foo']
  235. >>> list(fn({'--build-option': 'foo bar'}))
  236. ['foo', 'bar']
  237. >>> warnings.simplefilter('error', SetuptoolsDeprecationWarning)
  238. >>> list(fn({'--global-option': 'foo'})) # doctest: +IGNORE_EXCEPTION_DETAIL
  239. Traceback (most recent call last):
  240. SetuptoolsDeprecationWarning: ...arguments given via `--global-option`...
  241. """
  242. args = self._get_config("--global-option", config_settings)
  243. global_opts = self._valid_global_options()
  244. bad_args = []
  245. for arg in args:
  246. if arg.strip("-") not in global_opts:
  247. bad_args.append(arg)
  248. yield arg
  249. yield from self._get_config("--build-option", config_settings)
  250. if bad_args:
  251. msg = f"""
  252. The arguments {bad_args!r} were given via `--global-option`.
  253. Please use `--build-option` instead,
  254. `--global-option` is reserved to flags like `--verbose` or `--quiet`.
  255. """
  256. warnings.warn(msg, SetuptoolsDeprecationWarning)
  257. class _BuildMetaBackend(_ConfigSettingsTranslator):
  258. def _get_build_requires(self, config_settings, requirements):
  259. sys.argv = [
  260. *sys.argv[:1],
  261. *self._global_args(config_settings),
  262. "egg_info",
  263. *self._arbitrary_args(config_settings),
  264. ]
  265. try:
  266. with Distribution.patch():
  267. self.run_setup()
  268. except SetupRequirementsError as e:
  269. requirements += e.specifiers
  270. return requirements
  271. def run_setup(self, setup_script='setup.py'):
  272. # Note that we can reuse our build directory between calls
  273. # Correctness comes first, then optimization later
  274. __file__ = setup_script
  275. __name__ = '__main__'
  276. with _open_setup_script(__file__) as f:
  277. code = f.read().replace(r'\r\n', r'\n')
  278. exec(code, locals())
  279. def get_requires_for_build_wheel(self, config_settings=None):
  280. return self._get_build_requires(config_settings, requirements=['wheel'])
  281. def get_requires_for_build_sdist(self, config_settings=None):
  282. return self._get_build_requires(config_settings, requirements=[])
  283. def _bubble_up_info_directory(self, metadata_directory: str, suffix: str) -> 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: str, 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(self, metadata_directory,
  303. config_settings=None):
  304. sys.argv = [
  305. *sys.argv[:1],
  306. *self._global_args(config_settings),
  307. "dist_info",
  308. "--output-dir", 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(self, setup_command, result_extension,
  316. result_directory, config_settings):
  317. result_directory = os.path.abspath(result_directory)
  318. # Build in a temporary directory, then copy to the target.
  319. os.makedirs(result_directory, exist_ok=True)
  320. with tempfile.TemporaryDirectory(dir=result_directory) as tmp_dist_dir:
  321. sys.argv = [
  322. *sys.argv[:1],
  323. *self._global_args(config_settings),
  324. *setup_command,
  325. "--dist-dir", tmp_dist_dir,
  326. *self._arbitrary_args(config_settings),
  327. ]
  328. with no_install_setup_requires():
  329. self.run_setup()
  330. result_basename = _file_with_extension(
  331. tmp_dist_dir, result_extension)
  332. result_path = os.path.join(result_directory, result_basename)
  333. if os.path.exists(result_path):
  334. # os.rename will fail overwriting on non-Unix.
  335. os.remove(result_path)
  336. os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
  337. return result_basename
  338. def build_wheel(self, wheel_directory, config_settings=None,
  339. metadata_directory=None):
  340. with suppress_known_deprecation():
  341. return self._build_with_temp_dir(['bdist_wheel'], '.whl',
  342. wheel_directory, config_settings)
  343. def build_sdist(self, sdist_directory, config_settings=None):
  344. return self._build_with_temp_dir(['sdist', '--formats', 'gztar'],
  345. '.tar.gz', sdist_directory,
  346. config_settings)
  347. def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]:
  348. if not metadata_directory:
  349. return None
  350. dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
  351. assert len(dist_info_candidates) <= 1
  352. return str(dist_info_candidates[0]) if dist_info_candidates else None
  353. if not LEGACY_EDITABLE:
  354. # PEP660 hooks:
  355. # build_editable
  356. # get_requires_for_build_editable
  357. # prepare_metadata_for_build_editable
  358. def build_editable(
  359. self, wheel_directory, config_settings=None, metadata_directory=None
  360. ):
  361. # XXX can or should we hide our editable_wheel command normally?
  362. info_dir = self._get_dist_info_dir(metadata_directory)
  363. opts = ["--dist-info-dir", info_dir] if info_dir else []
  364. cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
  365. with suppress_known_deprecation():
  366. return self._build_with_temp_dir(
  367. cmd, ".whl", wheel_directory, config_settings
  368. )
  369. def get_requires_for_build_editable(self, config_settings=None):
  370. return self.get_requires_for_build_wheel(config_settings)
  371. def prepare_metadata_for_build_editable(self, metadata_directory,
  372. config_settings=None):
  373. return self.prepare_metadata_for_build_wheel(
  374. metadata_directory, config_settings
  375. )
  376. class _BuildMetaLegacyBackend(_BuildMetaBackend):
  377. """Compatibility backend for setuptools
  378. This is a version of setuptools.build_meta that endeavors
  379. to maintain backwards
  380. compatibility with pre-PEP 517 modes of invocation. It
  381. exists as a temporary
  382. bridge between the old packaging mechanism and the new
  383. packaging mechanism,
  384. and will eventually be removed.
  385. """
  386. def run_setup(self, setup_script='setup.py'):
  387. # In order to maintain compatibility with scripts assuming that
  388. # the setup.py script is in a directory on the PYTHONPATH, inject
  389. # '' into sys.path. (pypa/setuptools#1642)
  390. sys_path = list(sys.path) # Save the original path
  391. script_dir = os.path.dirname(os.path.abspath(setup_script))
  392. if script_dir not in sys.path:
  393. sys.path.insert(0, script_dir)
  394. # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
  395. # get the directory of the source code. They expect it to refer to the
  396. # setup.py script.
  397. sys_argv_0 = sys.argv[0]
  398. sys.argv[0] = setup_script
  399. try:
  400. super(_BuildMetaLegacyBackend,
  401. self).run_setup(setup_script=setup_script)
  402. finally:
  403. # While PEP 517 frontends should be calling each hook in a fresh
  404. # subprocess according to the standard (and thus it should not be
  405. # strictly necessary to restore the old sys.path), we'll restore
  406. # the original path so that the path manipulation does not persist
  407. # within the hook after run_setup is called.
  408. sys.path[:] = sys_path
  409. sys.argv[0] = sys_argv_0
  410. # The primary backend
  411. _BACKEND = _BuildMetaBackend()
  412. get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
  413. get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
  414. prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
  415. build_wheel = _BACKEND.build_wheel
  416. build_sdist = _BACKEND.build_sdist
  417. if not LEGACY_EDITABLE:
  418. get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
  419. prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
  420. build_editable = _BACKEND.build_editable
  421. # The legacy backend
  422. __legacy__ = _BuildMetaLegacyBackend()