sdist.py 18 KB

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