build_meta.py 9.7 KB

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