sdist.py 18 KB

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