您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

218 行
7.2 KiB

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