/Lib/distutils/command/sdist.py

http://unladen-swallow.googlecode.com/ · Python · 481 lines · 402 code · 23 blank · 56 comment · 34 complexity · 0434dbed50961be06c51a804402abc89 MD5 · raw file

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