sdist.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. from distutils import log
  2. import distutils.command.sdist as orig
  3. import os
  4. import sys
  5. import contextlib
  6. from itertools import chain
  7. from .._importlib import metadata
  8. from .build import _ORIGINAL_SUBCOMMANDS
  9. _default_revctrl = list
  10. def walk_revctrl(dirname=''):
  11. """Find all files under revision control"""
  12. for ep in metadata.entry_points(group='setuptools.file_finders'):
  13. for item in ep.load()(dirname):
  14. yield item
  15. class sdist(orig.sdist):
  16. """Smart sdist that finds anything supported by revision control"""
  17. user_options = [
  18. ('formats=', None, "formats for source distribution (comma-separated list)"),
  19. (
  20. 'keep-temp',
  21. 'k',
  22. "keep the distribution tree around after creating " + "archive file(s)",
  23. ),
  24. (
  25. 'dist-dir=',
  26. 'd',
  27. "directory to put the source distribution archive(s) in " "[default: dist]",
  28. ),
  29. (
  30. 'owner=',
  31. 'u',
  32. "Owner name used when creating a tar file [default: current user]",
  33. ),
  34. (
  35. 'group=',
  36. 'g',
  37. "Group name used when creating a tar file [default: current group]",
  38. ),
  39. ]
  40. negative_opt = {}
  41. README_EXTENSIONS = ['', '.rst', '.txt', '.md']
  42. READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)
  43. def run(self):
  44. self.run_command('egg_info')
  45. ei_cmd = self.get_finalized_command('egg_info')
  46. self.filelist = ei_cmd.filelist
  47. self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
  48. self.check_readme()
  49. # Run sub commands
  50. for cmd_name in self.get_sub_commands():
  51. self.run_command(cmd_name)
  52. self.make_distribution()
  53. dist_files = getattr(self.distribution, 'dist_files', [])
  54. for file in self.archive_files:
  55. data = ('sdist', '', file)
  56. if data not in dist_files:
  57. dist_files.append(data)
  58. def initialize_options(self):
  59. orig.sdist.initialize_options(self)
  60. self._default_to_gztar()
  61. def _default_to_gztar(self):
  62. # only needed on Python prior to 3.6.
  63. if sys.version_info >= (3, 6, 0, 'beta', 1):
  64. return
  65. self.formats = ['gztar']
  66. def make_distribution(self):
  67. """
  68. Workaround for #516
  69. """
  70. with self._remove_os_link():
  71. orig.sdist.make_distribution(self)
  72. @staticmethod
  73. @contextlib.contextmanager
  74. def _remove_os_link():
  75. """
  76. In a context, remove and restore os.link if it exists
  77. """
  78. class NoValue:
  79. pass
  80. orig_val = getattr(os, 'link', NoValue)
  81. try:
  82. del os.link
  83. except Exception:
  84. pass
  85. try:
  86. yield
  87. finally:
  88. if orig_val is not NoValue:
  89. setattr(os, 'link', orig_val)
  90. def add_defaults(self):
  91. super().add_defaults()
  92. self._add_defaults_build_sub_commands()
  93. def _add_defaults_optional(self):
  94. super()._add_defaults_optional()
  95. if os.path.isfile('pyproject.toml'):
  96. self.filelist.append('pyproject.toml')
  97. def _add_defaults_python(self):
  98. """getting python files"""
  99. if self.distribution.has_pure_modules():
  100. build_py = self.get_finalized_command('build_py')
  101. self.filelist.extend(build_py.get_source_files())
  102. self._add_data_files(self._safe_data_files(build_py))
  103. def _add_defaults_build_sub_commands(self):
  104. build = self.get_finalized_command("build")
  105. missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS
  106. # ^-- the original built-in sub-commands are already handled by default.
  107. cmds = (self.get_finalized_command(c) for c in missing_cmds)
  108. files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files"))
  109. self.filelist.extend(chain.from_iterable(files))
  110. def _safe_data_files(self, build_py):
  111. """
  112. Since the ``sdist`` class is also used to compute the MANIFEST
  113. (via :obj:`setuptools.command.egg_info.manifest_maker`),
  114. there might be recursion problems when trying to obtain the list of
  115. data_files and ``include_package_data=True`` (which in turn depends on
  116. the files included in the MANIFEST).
  117. To avoid that, ``manifest_maker`` should be able to overwrite this
  118. method and avoid recursive attempts to build/analyze the MANIFEST.
  119. """
  120. return build_py.data_files
  121. def _add_data_files(self, data_files):
  122. """
  123. Add data files as found in build_py.data_files.
  124. """
  125. self.filelist.extend(
  126. os.path.join(src_dir, name)
  127. for _, src_dir, _, filenames in data_files
  128. for name in filenames
  129. )
  130. def _add_defaults_data_files(self):
  131. try:
  132. super()._add_defaults_data_files()
  133. except TypeError:
  134. log.warn("data_files contains unexpected objects")
  135. def check_readme(self):
  136. for f in self.READMES:
  137. if os.path.exists(f):
  138. return
  139. else:
  140. self.warn(
  141. "standard file not found: should have one of " + ', '.join(self.READMES)
  142. )
  143. def make_release_tree(self, base_dir, files):
  144. orig.sdist.make_release_tree(self, base_dir, files)
  145. # Save any egg_info command line options used to create this sdist
  146. dest = os.path.join(base_dir, 'setup.cfg')
  147. if hasattr(os, 'link') and os.path.exists(dest):
  148. # unlink and re-copy, since it might be hard-linked, and
  149. # we don't want to change the source version
  150. os.unlink(dest)
  151. self.copy_file('setup.cfg', dest)
  152. self.get_finalized_command('egg_info').save_version_info(dest)
  153. def _manifest_is_not_generated(self):
  154. # check for special comment used in 2.7.1 and higher
  155. if not os.path.isfile(self.manifest):
  156. return False
  157. with open(self.manifest, 'rb') as fp:
  158. first_line = fp.readline()
  159. return first_line != '# file GENERATED by distutils, do NOT edit\n'.encode()
  160. def read_manifest(self):
  161. """Read the manifest file (named by 'self.manifest') and use it to
  162. fill in 'self.filelist', the list of files to include in the source
  163. distribution.
  164. """
  165. log.info("reading manifest file '%s'", self.manifest)
  166. manifest = open(self.manifest, 'rb')
  167. for line in manifest:
  168. # The manifest must contain UTF-8. See #303.
  169. try:
  170. line = line.decode('UTF-8')
  171. except UnicodeDecodeError:
  172. log.warn("%r not UTF-8 decodable -- skipping" % line)
  173. continue
  174. # ignore comments and blank lines
  175. line = line.strip()
  176. if line.startswith('#') or not line:
  177. continue
  178. self.filelist.append(line)
  179. manifest.close()