sdist.py 6.9 KB

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