build_meta.py 8.4 KB

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