sdist.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. """distutils.command.sdist
  2. Implements the Distutils 'sdist' command (create a source distribution)."""
  3. from __future__ import annotations
  4. import os
  5. import sys
  6. from collections.abc import Callable
  7. from distutils import archive_util, dir_util, file_util
  8. from distutils._log import log
  9. from glob import glob
  10. from itertools import filterfalse
  11. from typing import ClassVar
  12. from ..core import Command
  13. from ..errors import DistutilsOptionError, DistutilsTemplateError
  14. from ..filelist import FileList
  15. from ..text_file import TextFile
  16. from ..util import convert_path
  17. def show_formats():
  18. """Print all possible values for the 'formats' option (used by
  19. the "--help-formats" command-line option).
  20. """
  21. from ..archive_util import ARCHIVE_FORMATS
  22. from ..fancy_getopt import FancyGetopt
  23. formats = sorted(
  24. ("formats=" + format, None, ARCHIVE_FORMATS[format][2])
  25. for format in ARCHIVE_FORMATS.keys()
  26. )
  27. FancyGetopt(formats).print_help("List of available source distribution formats:")
  28. class sdist(Command):
  29. description = "create a source distribution (tarball, zip file, etc.)"
  30. def checking_metadata(self) -> bool:
  31. """Callable used for the check sub-command.
  32. Placed here so user_options can view it"""
  33. return self.metadata_check
  34. user_options = [
  35. ('template=', 't', "name of manifest template file [default: MANIFEST.in]"),
  36. ('manifest=', 'm', "name of manifest file [default: MANIFEST]"),
  37. (
  38. 'use-defaults',
  39. None,
  40. "include the default file set in the manifest "
  41. "[default; disable with --no-defaults]",
  42. ),
  43. ('no-defaults', None, "don't include the default file set"),
  44. (
  45. 'prune',
  46. None,
  47. "specifically exclude files/directories that should not be "
  48. "distributed (build tree, RCS/CVS dirs, etc.) "
  49. "[default; disable with --no-prune]",
  50. ),
  51. ('no-prune', None, "don't automatically exclude anything"),
  52. (
  53. 'manifest-only',
  54. 'o',
  55. "just regenerate the manifest and then stop (implies --force-manifest)",
  56. ),
  57. (
  58. 'force-manifest',
  59. 'f',
  60. "forcibly regenerate the manifest and carry on as usual. "
  61. "Deprecated: now the manifest is always regenerated.",
  62. ),
  63. ('formats=', None, "formats for source distribution (comma-separated list)"),
  64. (
  65. 'keep-temp',
  66. 'k',
  67. "keep the distribution tree around after creating " + "archive file(s)",
  68. ),
  69. (
  70. 'dist-dir=',
  71. 'd',
  72. "directory to put the source distribution archive(s) in [default: dist]",
  73. ),
  74. (
  75. 'metadata-check',
  76. None,
  77. "Ensure that all required elements of meta-data "
  78. "are supplied. Warn if any missing. [default]",
  79. ),
  80. (
  81. 'owner=',
  82. 'u',
  83. "Owner name used when creating a tar file [default: current user]",
  84. ),
  85. (
  86. 'group=',
  87. 'g',
  88. "Group name used when creating a tar file [default: current group]",
  89. ),
  90. ]
  91. boolean_options: ClassVar[list[str]] = [
  92. 'use-defaults',
  93. 'prune',
  94. 'manifest-only',
  95. 'force-manifest',
  96. 'keep-temp',
  97. 'metadata-check',
  98. ]
  99. help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
  100. ('help-formats', None, "list available distribution formats", show_formats),
  101. ]
  102. negative_opt: ClassVar[dict[str, str]] = {
  103. 'no-defaults': 'use-defaults',
  104. 'no-prune': 'prune',
  105. }
  106. sub_commands = [('check', checking_metadata)]
  107. READMES: ClassVar[tuple[str, ...]] = ('README', 'README.txt', 'README.rst')
  108. def initialize_options(self):
  109. # 'template' and 'manifest' are, respectively, the names of
  110. # the manifest template and manifest file.
  111. self.template = None
  112. self.manifest = None
  113. # 'use_defaults': if true, we will include the default file set
  114. # in the manifest
  115. self.use_defaults = True
  116. self.prune = True
  117. self.manifest_only = False
  118. self.force_manifest = False
  119. self.formats = ['gztar']
  120. self.keep_temp = False
  121. self.dist_dir = None
  122. self.archive_files = None
  123. self.metadata_check = True
  124. self.owner = None
  125. self.group = None
  126. def finalize_options(self) -> None:
  127. if self.manifest is None:
  128. self.manifest = "MANIFEST"
  129. if self.template is None:
  130. self.template = "MANIFEST.in"
  131. self.ensure_string_list('formats')
  132. bad_format = archive_util.check_archive_formats(self.formats)
  133. if bad_format:
  134. raise DistutilsOptionError(f"unknown archive format '{bad_format}'")
  135. if self.dist_dir is None:
  136. self.dist_dir = "dist"
  137. def run(self) -> None:
  138. # 'filelist' contains the list of files that will make up the
  139. # manifest
  140. self.filelist = FileList()
  141. # Run sub commands
  142. for cmd_name in self.get_sub_commands():
  143. self.run_command(cmd_name)
  144. # Do whatever it takes to get the list of files to process
  145. # (process the manifest template, read an existing manifest,
  146. # whatever). File list is accumulated in 'self.filelist'.
  147. self.get_file_list()
  148. # If user just wanted us to regenerate the manifest, stop now.
  149. if self.manifest_only:
  150. return
  151. # Otherwise, go ahead and create the source distribution tarball,
  152. # or zipfile, or whatever.
  153. self.make_distribution()
  154. def get_file_list(self) -> None:
  155. """Figure out the list of files to include in the source
  156. distribution, and put it in 'self.filelist'. This might involve
  157. reading the manifest template (and writing the manifest), or just
  158. reading the manifest, or just using the default file set -- it all
  159. depends on the user's options.
  160. """
  161. # new behavior when using a template:
  162. # the file list is recalculated every time because
  163. # even if MANIFEST.in or setup.py are not changed
  164. # the user might have added some files in the tree that
  165. # need to be included.
  166. #
  167. # This makes --force the default and only behavior with templates.
  168. template_exists = os.path.isfile(self.template)
  169. if not template_exists and self._manifest_is_not_generated():
  170. self.read_manifest()
  171. self.filelist.sort()
  172. self.filelist.remove_duplicates()
  173. return
  174. if not template_exists:
  175. self.warn(
  176. ("manifest template '%s' does not exist " + "(using default file list)")
  177. % self.template
  178. )
  179. self.filelist.findall()
  180. if self.use_defaults:
  181. self.add_defaults()
  182. if template_exists:
  183. self.read_template()
  184. if self.prune:
  185. self.prune_file_list()
  186. self.filelist.sort()
  187. self.filelist.remove_duplicates()
  188. self.write_manifest()
  189. def add_defaults(self) -> None:
  190. """Add all the default files to self.filelist:
  191. - README or README.txt
  192. - setup.py
  193. - tests/test*.py and test/test*.py
  194. - all pure Python modules mentioned in setup script
  195. - all files pointed by package_data (build_py)
  196. - all files defined in data_files.
  197. - all files defined as scripts.
  198. - all C sources listed as part of extensions or C libraries
  199. in the setup script (doesn't catch C headers!)
  200. Warns if (README or README.txt) or setup.py are missing; everything
  201. else is optional.
  202. """
  203. self._add_defaults_standards()
  204. self._add_defaults_optional()
  205. self._add_defaults_python()
  206. self._add_defaults_data_files()
  207. self._add_defaults_ext()
  208. self._add_defaults_c_libs()
  209. self._add_defaults_scripts()
  210. @staticmethod
  211. def _cs_path_exists(fspath):
  212. """
  213. Case-sensitive path existence check
  214. >>> sdist._cs_path_exists(__file__)
  215. True
  216. >>> sdist._cs_path_exists(__file__.upper())
  217. False
  218. """
  219. if not os.path.exists(fspath):
  220. return False
  221. # make absolute so we always have a directory
  222. abspath = os.path.abspath(fspath)
  223. directory, filename = os.path.split(abspath)
  224. return filename in os.listdir(directory)
  225. def _add_defaults_standards(self):
  226. standards = [self.READMES, self.distribution.script_name]
  227. for fn in standards:
  228. if isinstance(fn, tuple):
  229. alts = fn
  230. got_it = False
  231. for fn in alts:
  232. if self._cs_path_exists(fn):
  233. got_it = True
  234. self.filelist.append(fn)
  235. break
  236. if not got_it:
  237. self.warn(
  238. "standard file not found: should have one of " + ', '.join(alts)
  239. )
  240. else:
  241. if self._cs_path_exists(fn):
  242. self.filelist.append(fn)
  243. else:
  244. self.warn(f"standard file '{fn}' not found")
  245. def _add_defaults_optional(self):
  246. optional = ['tests/test*.py', 'test/test*.py', 'setup.cfg']
  247. for pattern in optional:
  248. files = filter(os.path.isfile, glob(pattern))
  249. self.filelist.extend(files)
  250. def _add_defaults_python(self):
  251. # build_py is used to get:
  252. # - python modules
  253. # - files defined in package_data
  254. build_py = self.get_finalized_command('build_py')
  255. # getting python files
  256. if self.distribution.has_pure_modules():
  257. self.filelist.extend(build_py.get_source_files())
  258. # getting package_data files
  259. # (computed in build_py.data_files by build_py.finalize_options)
  260. for _pkg, src_dir, _build_dir, filenames in build_py.data_files:
  261. for filename in filenames:
  262. self.filelist.append(os.path.join(src_dir, filename))
  263. def _add_defaults_data_files(self):
  264. # getting distribution.data_files
  265. if self.distribution.has_data_files():
  266. for item in self.distribution.data_files:
  267. if isinstance(item, str):
  268. # plain file
  269. item = convert_path(item)
  270. if os.path.isfile(item):
  271. self.filelist.append(item)
  272. else:
  273. # a (dirname, filenames) tuple
  274. dirname, filenames = item
  275. for f in filenames:
  276. f = convert_path(f)
  277. if os.path.isfile(f):
  278. self.filelist.append(f)
  279. def _add_defaults_ext(self):
  280. if self.distribution.has_ext_modules():
  281. build_ext = self.get_finalized_command('build_ext')
  282. self.filelist.extend(build_ext.get_source_files())
  283. def _add_defaults_c_libs(self):
  284. if self.distribution.has_c_libraries():
  285. build_clib = self.get_finalized_command('build_clib')
  286. self.filelist.extend(build_clib.get_source_files())
  287. def _add_defaults_scripts(self):
  288. if self.distribution.has_scripts():
  289. build_scripts = self.get_finalized_command('build_scripts')
  290. self.filelist.extend(build_scripts.get_source_files())
  291. def read_template(self) -> None:
  292. """Read and parse manifest template file named by self.template.
  293. (usually "MANIFEST.in") The parsing and processing is done by
  294. 'self.filelist', which updates itself accordingly.
  295. """
  296. log.info("reading manifest template '%s'", self.template)
  297. template = TextFile(
  298. self.template,
  299. strip_comments=True,
  300. skip_blanks=True,
  301. join_lines=True,
  302. lstrip_ws=True,
  303. rstrip_ws=True,
  304. collapse_join=True,
  305. )
  306. try:
  307. while True:
  308. line = template.readline()
  309. if line is None: # end of file
  310. break
  311. try:
  312. self.filelist.process_template_line(line)
  313. # the call above can raise a DistutilsTemplateError for
  314. # malformed lines, or a ValueError from the lower-level
  315. # convert_path function
  316. except (DistutilsTemplateError, ValueError) as msg:
  317. self.warn(
  318. f"{template.filename}, line {int(template.current_line)}: {msg}"
  319. )
  320. finally:
  321. template.close()
  322. def prune_file_list(self) -> None:
  323. """Prune off branches that might slip into the file list as created
  324. by 'read_template()', but really don't belong there:
  325. * the build tree (typically "build")
  326. * the release tree itself (only an issue if we ran "sdist"
  327. previously with --keep-temp, or it aborted)
  328. * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
  329. """
  330. build = self.get_finalized_command('build')
  331. base_dir = self.distribution.get_fullname()
  332. self.filelist.exclude_pattern(None, prefix=os.fspath(build.build_base))
  333. self.filelist.exclude_pattern(None, prefix=base_dir)
  334. if sys.platform == 'win32':
  335. seps = r'/|\\'
  336. else:
  337. seps = '/'
  338. vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs']
  339. vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps)
  340. self.filelist.exclude_pattern(vcs_ptrn, is_regex=True)
  341. def write_manifest(self) -> None:
  342. """Write the file list in 'self.filelist' (presumably as filled in
  343. by 'add_defaults()' and 'read_template()') to the manifest file
  344. named by 'self.manifest'.
  345. """
  346. if self._manifest_is_not_generated():
  347. log.info(
  348. f"not writing to manually maintained manifest file '{self.manifest}'"
  349. )
  350. return
  351. content = self.filelist.files[:]
  352. content.insert(0, '# file GENERATED by distutils, do NOT edit')
  353. self.execute(
  354. file_util.write_file,
  355. (self.manifest, content),
  356. f"writing manifest file '{self.manifest}'",
  357. )
  358. def _manifest_is_not_generated(self):
  359. # check for special comment used in 3.1.3 and higher
  360. if not os.path.isfile(self.manifest):
  361. return False
  362. with open(self.manifest, encoding='utf-8') as fp:
  363. first_line = next(fp)
  364. return first_line != '# file GENERATED by distutils, do NOT edit\n'
  365. def read_manifest(self) -> None:
  366. """Read the manifest file (named by 'self.manifest') and use it to
  367. fill in 'self.filelist', the list of files to include in the source
  368. distribution.
  369. """
  370. log.info("reading manifest file '%s'", self.manifest)
  371. with open(self.manifest, encoding='utf-8') as lines:
  372. self.filelist.extend(
  373. # ignore comments and blank lines
  374. filter(None, filterfalse(is_comment, map(str.strip, lines)))
  375. )
  376. def make_release_tree(self, base_dir, files) -> None:
  377. """Create the directory tree that will become the source
  378. distribution archive. All directories implied by the filenames in
  379. 'files' are created under 'base_dir', and then we hard link or copy
  380. (if hard linking is unavailable) those files into place.
  381. Essentially, this duplicates the developer's source tree, but in a
  382. directory named after the distribution, containing only the files
  383. to be distributed.
  384. """
  385. # Create all the directories under 'base_dir' necessary to
  386. # put 'files' there; the 'mkpath()' is just so we don't die
  387. # if the manifest happens to be empty.
  388. self.mkpath(base_dir)
  389. dir_util.create_tree(base_dir, files)
  390. # And walk over the list of files, either making a hard link (if
  391. # os.link exists) to each one that doesn't already exist in its
  392. # corresponding location under 'base_dir', or copying each file
  393. # that's out-of-date in 'base_dir'. (Usually, all files will be
  394. # out-of-date, because by default we blow away 'base_dir' when
  395. # we're done making the distribution archives.)
  396. if hasattr(os, 'link'): # can make hard links on this system
  397. link = 'hard'
  398. msg = f"making hard links in {base_dir}..."
  399. else: # nope, have to copy
  400. link = None
  401. msg = f"copying files to {base_dir}..."
  402. if not files:
  403. log.warning("no files to distribute -- empty manifest?")
  404. else:
  405. log.info(msg)
  406. for file in files:
  407. if not os.path.isfile(file):
  408. log.warning("'%s' not a regular file -- skipping", file)
  409. else:
  410. dest = os.path.join(base_dir, file)
  411. self.copy_file(file, dest, link=link)
  412. self.distribution.metadata.write_pkg_info(base_dir)
  413. def make_distribution(self) -> None:
  414. """Create the source distribution(s). First, we create the release
  415. tree with 'make_release_tree()'; then, we create all required
  416. archive files (according to 'self.formats') from the release tree.
  417. Finally, we clean up by blowing away the release tree (unless
  418. 'self.keep_temp' is true). The list of archive files created is
  419. stored so it can be retrieved later by 'get_archive_files()'.
  420. """
  421. # Don't warn about missing meta-data here -- should be (and is!)
  422. # done elsewhere.
  423. base_dir = self.distribution.get_fullname()
  424. base_name = os.path.join(self.dist_dir, base_dir)
  425. self.make_release_tree(base_dir, self.filelist.files)
  426. archive_files = [] # remember names of files we create
  427. # tar archive must be created last to avoid overwrite and remove
  428. if 'tar' in self.formats:
  429. self.formats.append(self.formats.pop(self.formats.index('tar')))
  430. for fmt in self.formats:
  431. file = self.make_archive(
  432. base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group
  433. )
  434. archive_files.append(file)
  435. self.distribution.dist_files.append(('sdist', '', file))
  436. self.archive_files = archive_files
  437. if not self.keep_temp:
  438. dir_util.remove_tree(base_dir)
  439. def get_archive_files(self):
  440. """Return the list of archive files created when the command
  441. was run, or None if the command hasn't run yet.
  442. """
  443. return self.archive_files
  444. def is_comment(line: str) -> bool:
  445. return line.startswith('#')