sdist.py 19 KB

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