build_meta.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. class SetupRequirementsError(BaseException):
  30. def __init__(self, specifiers):
  31. self.specifiers = specifiers
  32. class Distribution(setuptools.dist.Distribution):
  33. def fetch_build_eggs(self, specifiers):
  34. raise SetupRequirementsError(specifiers)
  35. @classmethod
  36. @contextlib.contextmanager
  37. def patch(cls):
  38. """
  39. Replace
  40. distutils.dist.Distribution with this class
  41. for the duration of this context.
  42. """
  43. orig = distutils.core.Distribution
  44. distutils.core.Distribution = cls
  45. try:
  46. yield
  47. finally:
  48. distutils.core.Distribution = orig
  49. def _run_setup(setup_script='setup.py'):
  50. # Note that we can reuse our build directory between calls
  51. # Correctness comes first, then optimization later
  52. __file__ = setup_script
  53. __name__ = '__main__'
  54. f = getattr(tokenize, 'open', open)(__file__)
  55. code = f.read().replace('\\r\\n', '\\n')
  56. f.close()
  57. exec(compile(code, __file__, 'exec'), locals())
  58. def _fix_config(config_settings):
  59. config_settings = config_settings or {}
  60. config_settings.setdefault('--global-option', [])
  61. return config_settings
  62. def _get_build_requires(config_settings):
  63. config_settings = _fix_config(config_settings)
  64. requirements = ['setuptools', 'wheel']
  65. sys.argv = sys.argv[:1] + ['egg_info'] + \
  66. config_settings["--global-option"]
  67. try:
  68. with Distribution.patch():
  69. _run_setup()
  70. except SetupRequirementsError as e:
  71. requirements += e.specifiers
  72. return requirements
  73. def _get_immediate_subdirectories(a_dir):
  74. return [name for name in os.listdir(a_dir)
  75. if os.path.isdir(os.path.join(a_dir, name))]
  76. def get_requires_for_build_wheel(config_settings=None):
  77. config_settings = _fix_config(config_settings)
  78. return _get_build_requires(config_settings)
  79. def get_requires_for_build_sdist(config_settings=None):
  80. config_settings = _fix_config(config_settings)
  81. return _get_build_requires(config_settings)
  82. def prepare_metadata_for_build_wheel(metadata_directory, config_settings=None):
  83. sys.argv = sys.argv[:1] + ['dist_info', '--egg-base', metadata_directory]
  84. _run_setup()
  85. dist_info_directory = metadata_directory
  86. while True:
  87. dist_infos = [f for f in os.listdir(dist_info_directory)
  88. if f.endswith('.dist-info')]
  89. if len(dist_infos) == 0 and \
  90. len(_get_immediate_subdirectories(dist_info_directory)) == 1:
  91. dist_info_directory = os.path.join(
  92. dist_info_directory, os.listdir(dist_info_directory)[0])
  93. continue
  94. assert len(dist_infos) == 1
  95. break
  96. # PEP 517 requires that the .dist-info directory be placed in the
  97. # metadata_directory. To comply, we MUST copy the directory to the root
  98. if dist_info_directory != metadata_directory:
  99. shutil.move(
  100. os.path.join(dist_info_directory, dist_infos[0]),
  101. metadata_directory)
  102. shutil.rmtree(dist_info_directory, ignore_errors=True)
  103. return dist_infos[0]
  104. def build_wheel(wheel_directory, config_settings=None,
  105. metadata_directory=None):
  106. config_settings = _fix_config(config_settings)
  107. wheel_directory = os.path.abspath(wheel_directory)
  108. sys.argv = sys.argv[:1] + ['bdist_wheel'] + \
  109. config_settings["--global-option"]
  110. _run_setup()
  111. if wheel_directory != 'dist':
  112. shutil.rmtree(wheel_directory)
  113. shutil.copytree('dist', wheel_directory)
  114. wheels = [f for f in os.listdir(wheel_directory)
  115. if f.endswith('.whl')]
  116. assert len(wheels) == 1
  117. return wheels[0]
  118. def build_sdist(sdist_directory, config_settings=None):
  119. config_settings = _fix_config(config_settings)
  120. sdist_directory = os.path.abspath(sdist_directory)
  121. sys.argv = sys.argv[:1] + ['sdist'] + \
  122. config_settings["--global-option"]
  123. _run_setup()
  124. if sdist_directory != 'dist':
  125. shutil.rmtree(sdist_directory)
  126. shutil.copytree('dist', sdist_directory)
  127. sdists = [f for f in os.listdir(sdist_directory)
  128. if f.endswith('.tar.gz')]
  129. assert len(sdists) == 1
  130. return sdists[0]