build_meta.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 sys
  25. import tokenize
  26. import shutil
  27. import contextlib
  28. import tempfile
  29. import warnings
  30. import setuptools
  31. import distutils
  32. from ._reqs import parse_strings
  33. from .extern.more_itertools import always_iterable
  34. __all__ = ['get_requires_for_build_sdist',
  35. 'get_requires_for_build_wheel',
  36. 'prepare_metadata_for_build_wheel',
  37. 'build_wheel',
  38. 'build_sdist',
  39. '__legacy__',
  40. 'SetupRequirementsError']
  41. class SetupRequirementsError(BaseException):
  42. def __init__(self, specifiers):
  43. self.specifiers = specifiers
  44. class Distribution(setuptools.dist.Distribution):
  45. def fetch_build_eggs(self, specifiers):
  46. specifier_list = list(parse_strings(specifiers))
  47. raise SetupRequirementsError(specifier_list)
  48. @classmethod
  49. @contextlib.contextmanager
  50. def patch(cls):
  51. """
  52. Replace
  53. distutils.dist.Distribution with this class
  54. for the duration of this context.
  55. """
  56. orig = distutils.core.Distribution
  57. distutils.core.Distribution = cls
  58. try:
  59. yield
  60. finally:
  61. distutils.core.Distribution = orig
  62. @contextlib.contextmanager
  63. def no_install_setup_requires():
  64. """Temporarily disable installing setup_requires
  65. Under PEP 517, the backend reports build dependencies to the frontend,
  66. and the frontend is responsible for ensuring they're installed.
  67. So setuptools (acting as a backend) should not try to install them.
  68. """
  69. orig = setuptools._install_setup_requires
  70. setuptools._install_setup_requires = lambda attrs: None
  71. try:
  72. yield
  73. finally:
  74. setuptools._install_setup_requires = orig
  75. def _get_immediate_subdirectories(a_dir):
  76. return [name for name in os.listdir(a_dir)
  77. if os.path.isdir(os.path.join(a_dir, name))]
  78. def _file_with_extension(directory, extension):
  79. matching = (
  80. f for f in os.listdir(directory)
  81. if f.endswith(extension)
  82. )
  83. try:
  84. file, = matching
  85. except ValueError:
  86. raise ValueError(
  87. 'No distribution was found. Ensure that `setup.py` '
  88. 'is not empty and that it calls `setup()`.')
  89. return file
  90. def _open_setup_script(setup_script):
  91. if not os.path.exists(setup_script):
  92. # Supply a default setup.py
  93. return io.StringIO(u"from setuptools import setup; setup()")
  94. return getattr(tokenize, 'open', open)(setup_script)
  95. @contextlib.contextmanager
  96. def suppress_known_deprecation():
  97. with warnings.catch_warnings():
  98. warnings.filterwarnings('ignore', 'setup.py install is deprecated')
  99. yield
  100. class _BuildMetaBackend:
  101. @staticmethod
  102. def _fix_config(config_settings):
  103. """
  104. Ensure config settings meet certain expectations.
  105. >>> fc = _BuildMetaBackend._fix_config
  106. >>> fc(None)
  107. {'--global-option': []}
  108. >>> fc({})
  109. {'--global-option': []}
  110. >>> fc({'--global-option': 'foo'})
  111. {'--global-option': ['foo']}
  112. >>> fc({'--global-option': ['foo']})
  113. {'--global-option': ['foo']}
  114. """
  115. config_settings = config_settings or {}
  116. config_settings['--global-option'] = list(always_iterable(
  117. config_settings.get('--global-option')))
  118. return config_settings
  119. def _get_build_requires(self, config_settings, requirements):
  120. config_settings = self._fix_config(config_settings)
  121. sys.argv = sys.argv[:1] + ['egg_info'] + \
  122. config_settings["--global-option"]
  123. try:
  124. with Distribution.patch():
  125. self.run_setup()
  126. except SetupRequirementsError as e:
  127. requirements += e.specifiers
  128. return requirements
  129. def run_setup(self, setup_script='setup.py'):
  130. # Note that we can reuse our build directory between calls
  131. # Correctness comes first, then optimization later
  132. __file__ = setup_script
  133. __name__ = '__main__'
  134. with _open_setup_script(__file__) as f:
  135. code = f.read().replace(r'\r\n', r'\n')
  136. exec(compile(code, __file__, 'exec'), locals())
  137. def get_requires_for_build_wheel(self, config_settings=None):
  138. return self._get_build_requires(
  139. config_settings, requirements=['wheel'])
  140. def get_requires_for_build_sdist(self, config_settings=None):
  141. return self._get_build_requires(config_settings, requirements=[])
  142. def prepare_metadata_for_build_wheel(self, metadata_directory,
  143. config_settings=None):
  144. sys.argv = sys.argv[:1] + [
  145. 'dist_info', '--egg-base', metadata_directory]
  146. with no_install_setup_requires():
  147. self.run_setup()
  148. dist_info_directory = metadata_directory
  149. while True:
  150. dist_infos = [f for f in os.listdir(dist_info_directory)
  151. if f.endswith('.dist-info')]
  152. if (
  153. len(dist_infos) == 0 and
  154. len(_get_immediate_subdirectories(dist_info_directory)) == 1
  155. ):
  156. dist_info_directory = os.path.join(
  157. dist_info_directory, os.listdir(dist_info_directory)[0])
  158. continue
  159. assert len(dist_infos) == 1
  160. break
  161. # PEP 517 requires that the .dist-info directory be placed in the
  162. # metadata_directory. To comply, we MUST copy the directory to the root
  163. if dist_info_directory != metadata_directory:
  164. shutil.move(
  165. os.path.join(dist_info_directory, dist_infos[0]),
  166. metadata_directory)
  167. shutil.rmtree(dist_info_directory, ignore_errors=True)
  168. return dist_infos[0]
  169. def _build_with_temp_dir(self, setup_command, result_extension,
  170. result_directory, config_settings):
  171. config_settings = self._fix_config(config_settings)
  172. result_directory = os.path.abspath(result_directory)
  173. # Build in a temporary directory, then copy to the target.
  174. os.makedirs(result_directory, exist_ok=True)
  175. with tempfile.TemporaryDirectory(dir=result_directory) as tmp_dist_dir:
  176. sys.argv = (sys.argv[:1] + setup_command +
  177. ['--dist-dir', tmp_dist_dir] +
  178. config_settings["--global-option"])
  179. with no_install_setup_requires():
  180. self.run_setup()
  181. result_basename = _file_with_extension(
  182. tmp_dist_dir, result_extension)
  183. result_path = os.path.join(result_directory, result_basename)
  184. if os.path.exists(result_path):
  185. # os.rename will fail overwriting on non-Unix.
  186. os.remove(result_path)
  187. os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
  188. return result_basename
  189. def build_wheel(self, wheel_directory, config_settings=None,
  190. metadata_directory=None):
  191. with suppress_known_deprecation():
  192. return self._build_with_temp_dir(['bdist_wheel'], '.whl',
  193. wheel_directory, config_settings)
  194. def build_sdist(self, sdist_directory, config_settings=None):
  195. return self._build_with_temp_dir(['sdist', '--formats', 'gztar'],
  196. '.tar.gz', sdist_directory,
  197. config_settings)
  198. class _BuildMetaLegacyBackend(_BuildMetaBackend):
  199. """Compatibility backend for setuptools
  200. This is a version of setuptools.build_meta that endeavors
  201. to maintain backwards
  202. compatibility with pre-PEP 517 modes of invocation. It
  203. exists as a temporary
  204. bridge between the old packaging mechanism and the new
  205. packaging mechanism,
  206. and will eventually be removed.
  207. """
  208. def run_setup(self, setup_script='setup.py'):
  209. # In order to maintain compatibility with scripts assuming that
  210. # the setup.py script is in a directory on the PYTHONPATH, inject
  211. # '' into sys.path. (pypa/setuptools#1642)
  212. sys_path = list(sys.path) # Save the original path
  213. script_dir = os.path.dirname(os.path.abspath(setup_script))
  214. if script_dir not in sys.path:
  215. sys.path.insert(0, script_dir)
  216. # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
  217. # get the directory of the source code. They expect it to refer to the
  218. # setup.py script.
  219. sys_argv_0 = sys.argv[0]
  220. sys.argv[0] = setup_script
  221. try:
  222. super(_BuildMetaLegacyBackend,
  223. self).run_setup(setup_script=setup_script)
  224. finally:
  225. # While PEP 517 frontends should be calling each hook in a fresh
  226. # subprocess according to the standard (and thus it should not be
  227. # strictly necessary to restore the old sys.path), we'll restore
  228. # the original path so that the path manipulation does not persist
  229. # within the hook after run_setup is called.
  230. sys.path[:] = sys_path
  231. sys.argv[0] = sys_argv_0
  232. # The primary backend
  233. _BACKEND = _BuildMetaBackend()
  234. get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
  235. get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
  236. prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
  237. build_wheel = _BACKEND.build_wheel
  238. build_sdist = _BACKEND.build_sdist
  239. # The legacy backend
  240. __legacy__ = _BuildMetaLegacyBackend()