PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/distutils/command/sdist.py

https://github.com/albertz/CPython
Python | 495 lines | 477 code | 0 blank | 18 comment | 1 complexity | 4ed4696507cfead48769fa1bdfaa6a83 MD5 | raw file
  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. manifest = open(self.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. manifest.close()
  355. def make_release_tree(self, base_dir, files):
  356. """Create the directory tree that will become the source
  357. distribution archive. All directories implied by the filenames in
  358. 'files' are created under 'base_dir', and then we hard link or copy
  359. (if hard linking is unavailable) those files into place.
  360. Essentially, this duplicates the developer's source tree, but in a
  361. directory named after the distribution, containing only the files
  362. to be distributed.
  363. """
  364. # Create all the directories under 'base_dir' necessary to
  365. # put 'files' there; the 'mkpath()' is just so we don't die
  366. # if the manifest happens to be empty.
  367. self.mkpath(base_dir)
  368. dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
  369. # And walk over the list of files, either making a hard link (if
  370. # os.link exists) to each one that doesn't already exist in its
  371. # corresponding location under 'base_dir', or copying each file
  372. # that's out-of-date in 'base_dir'. (Usually, all files will be
  373. # out-of-date, because by default we blow away 'base_dir' when
  374. # we're done making the distribution archives.)
  375. if hasattr(os, 'link'): # can make hard links on this system
  376. link = 'hard'
  377. msg = "making hard links in %s..." % base_dir
  378. else: # nope, have to copy
  379. link = None
  380. msg = "copying files to %s..." % base_dir
  381. if not files:
  382. log.warn("no files to distribute -- empty manifest?")
  383. else:
  384. log.info(msg)
  385. for file in files:
  386. if not os.path.isfile(file):
  387. log.warn("'%s' not a regular file -- skipping", file)
  388. else:
  389. dest = os.path.join(base_dir, file)
  390. self.copy_file(file, dest, link=link)
  391. self.distribution.metadata.write_pkg_info(base_dir)
  392. def make_distribution(self):
  393. """Create the source distribution(s). First, we create the release
  394. tree with 'make_release_tree()'; then, we create all required
  395. archive files (according to 'self.formats') from the release tree.
  396. Finally, we clean up by blowing away the release tree (unless
  397. 'self.keep_temp' is true). The list of archive files created is
  398. stored so it can be retrieved later by 'get_archive_files()'.
  399. """
  400. # Don't warn about missing meta-data here -- should be (and is!)
  401. # done elsewhere.
  402. base_dir = self.distribution.get_fullname()
  403. base_name = os.path.join(self.dist_dir, base_dir)
  404. self.make_release_tree(base_dir, self.filelist.files)
  405. archive_files = [] # remember names of files we create
  406. # tar archive must be created last to avoid overwrite and remove
  407. if 'tar' in self.formats:
  408. self.formats.append(self.formats.pop(self.formats.index('tar')))
  409. for fmt in self.formats:
  410. file = self.make_archive(base_name, fmt, base_dir=base_dir,
  411. owner=self.owner, group=self.group)
  412. archive_files.append(file)
  413. self.distribution.dist_files.append(('sdist', '', file))
  414. self.archive_files = archive_files
  415. if not self.keep_temp:
  416. dir_util.remove_tree(base_dir, dry_run=self.dry_run)
  417. def get_archive_files(self):
  418. """Return the list of archive files created when the command
  419. was run, or None if the command hasn't run yet.
  420. """
  421. return self.archive_files