sdist.py 19 KB

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