Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/command/sdist.py
4804 views
"""distutils.command.sdist12Implements the Distutils 'sdist' command (create a source distribution)."""34import os5import sys6from glob import glob7from warnings import warn89from distutils.core import Command10from distutils import dir_util11from distutils import file_util12from distutils import archive_util13from distutils.text_file import TextFile14from distutils.filelist import FileList15from distutils import log16from distutils.util import convert_path17from distutils.errors import DistutilsTemplateError, DistutilsOptionError181920def show_formats():21"""Print all possible values for the 'formats' option (used by22the "--help-formats" command-line option).23"""24from distutils.fancy_getopt import FancyGetopt25from distutils.archive_util import ARCHIVE_FORMATS26formats = []27for format in ARCHIVE_FORMATS.keys():28formats.append(("formats=" + format, None,29ARCHIVE_FORMATS[format][2]))30formats.sort()31FancyGetopt(formats).print_help(32"List of available source distribution formats:")333435class sdist(Command):3637description = "create a source distribution (tarball, zip file, etc.)"3839def checking_metadata(self):40"""Callable used for the check sub-command.4142Placed here so user_options can view it"""43return self.metadata_check4445user_options = [46('template=', 't',47"name of manifest template file [default: MANIFEST.in]"),48('manifest=', 'm',49"name of manifest file [default: MANIFEST]"),50('use-defaults', None,51"include the default file set in the manifest "52"[default; disable with --no-defaults]"),53('no-defaults', None,54"don't include the default file set"),55('prune', None,56"specifically exclude files/directories that should not be "57"distributed (build tree, RCS/CVS dirs, etc.) "58"[default; disable with --no-prune]"),59('no-prune', None,60"don't automatically exclude anything"),61('manifest-only', 'o',62"just regenerate the manifest and then stop "63"(implies --force-manifest)"),64('force-manifest', 'f',65"forcibly regenerate the manifest and carry on as usual. "66"Deprecated: now the manifest is always regenerated."),67('formats=', None,68"formats for source distribution (comma-separated list)"),69('keep-temp', 'k',70"keep the distribution tree around after creating " +71"archive file(s)"),72('dist-dir=', 'd',73"directory to put the source distribution archive(s) in "74"[default: dist]"),75('metadata-check', None,76"Ensure that all required elements of meta-data "77"are supplied. Warn if any missing. [default]"),78('owner=', 'u',79"Owner name used when creating a tar file [default: current user]"),80('group=', 'g',81"Group name used when creating a tar file [default: current group]"),82]8384boolean_options = ['use-defaults', 'prune',85'manifest-only', 'force-manifest',86'keep-temp', 'metadata-check']8788help_options = [89('help-formats', None,90"list available distribution formats", show_formats),91]9293negative_opt = {'no-defaults': 'use-defaults',94'no-prune': 'prune' }9596sub_commands = [('check', checking_metadata)]9798READMES = ('README', 'README.txt', 'README.rst')99100def initialize_options(self):101# 'template' and 'manifest' are, respectively, the names of102# the manifest template and manifest file.103self.template = None104self.manifest = None105106# 'use_defaults': if true, we will include the default file set107# in the manifest108self.use_defaults = 1109self.prune = 1110111self.manifest_only = 0112self.force_manifest = 0113114self.formats = ['gztar']115self.keep_temp = 0116self.dist_dir = None117118self.archive_files = None119self.metadata_check = 1120self.owner = None121self.group = None122123def finalize_options(self):124if self.manifest is None:125self.manifest = "MANIFEST"126if self.template is None:127self.template = "MANIFEST.in"128129self.ensure_string_list('formats')130131bad_format = archive_util.check_archive_formats(self.formats)132if bad_format:133raise DistutilsOptionError(134"unknown archive format '%s'" % bad_format)135136if self.dist_dir is None:137self.dist_dir = "dist"138139def run(self):140# 'filelist' contains the list of files that will make up the141# manifest142self.filelist = FileList()143144# Run sub commands145for cmd_name in self.get_sub_commands():146self.run_command(cmd_name)147148# Do whatever it takes to get the list of files to process149# (process the manifest template, read an existing manifest,150# whatever). File list is accumulated in 'self.filelist'.151self.get_file_list()152153# If user just wanted us to regenerate the manifest, stop now.154if self.manifest_only:155return156157# Otherwise, go ahead and create the source distribution tarball,158# or zipfile, or whatever.159self.make_distribution()160161def check_metadata(self):162"""Deprecated API."""163warn("distutils.command.sdist.check_metadata is deprecated, \164use the check command instead", PendingDeprecationWarning)165check = self.distribution.get_command_obj('check')166check.ensure_finalized()167check.run()168169def get_file_list(self):170"""Figure out the list of files to include in the source171distribution, and put it in 'self.filelist'. This might involve172reading the manifest template (and writing the manifest), or just173reading the manifest, or just using the default file set -- it all174depends on the user's options.175"""176# new behavior when using a template:177# the file list is recalculated every time because178# even if MANIFEST.in or setup.py are not changed179# the user might have added some files in the tree that180# need to be included.181#182# This makes --force the default and only behavior with templates.183template_exists = os.path.isfile(self.template)184if not template_exists and self._manifest_is_not_generated():185self.read_manifest()186self.filelist.sort()187self.filelist.remove_duplicates()188return189190if not template_exists:191self.warn(("manifest template '%s' does not exist " +192"(using default file list)") %193self.template)194self.filelist.findall()195196if self.use_defaults:197self.add_defaults()198199if template_exists:200self.read_template()201202if self.prune:203self.prune_file_list()204205self.filelist.sort()206self.filelist.remove_duplicates()207self.write_manifest()208209def add_defaults(self):210"""Add all the default files to self.filelist:211- README or README.txt212- setup.py213- test/test*.py214- all pure Python modules mentioned in setup script215- all files pointed by package_data (build_py)216- all files defined in data_files.217- all files defined as scripts.218- all C sources listed as part of extensions or C libraries219in the setup script (doesn't catch C headers!)220Warns if (README or README.txt) or setup.py are missing; everything221else is optional.222"""223self._add_defaults_standards()224self._add_defaults_optional()225self._add_defaults_python()226self._add_defaults_data_files()227self._add_defaults_ext()228self._add_defaults_c_libs()229self._add_defaults_scripts()230231@staticmethod232def _cs_path_exists(fspath):233"""234Case-sensitive path existence check235236>>> sdist._cs_path_exists(__file__)237True238>>> sdist._cs_path_exists(__file__.upper())239False240"""241if not os.path.exists(fspath):242return False243# make absolute so we always have a directory244abspath = os.path.abspath(fspath)245directory, filename = os.path.split(abspath)246return filename in os.listdir(directory)247248def _add_defaults_standards(self):249standards = [self.READMES, self.distribution.script_name]250for fn in standards:251if isinstance(fn, tuple):252alts = fn253got_it = False254for fn in alts:255if self._cs_path_exists(fn):256got_it = True257self.filelist.append(fn)258break259260if not got_it:261self.warn("standard file not found: should have one of " +262', '.join(alts))263else:264if self._cs_path_exists(fn):265self.filelist.append(fn)266else:267self.warn("standard file '%s' not found" % fn)268269def _add_defaults_optional(self):270optional = ['test/test*.py', 'setup.cfg']271for pattern in optional:272files = filter(os.path.isfile, glob(pattern))273self.filelist.extend(files)274275def _add_defaults_python(self):276# build_py is used to get:277# - python modules278# - files defined in package_data279build_py = self.get_finalized_command('build_py')280281# getting python files282if self.distribution.has_pure_modules():283self.filelist.extend(build_py.get_source_files())284285# getting package_data files286# (computed in build_py.data_files by build_py.finalize_options)287for pkg, src_dir, build_dir, filenames in build_py.data_files:288for filename in filenames:289self.filelist.append(os.path.join(src_dir, filename))290291def _add_defaults_data_files(self):292# getting distribution.data_files293if self.distribution.has_data_files():294for item in self.distribution.data_files:295if isinstance(item, str):296# plain file297item = convert_path(item)298if os.path.isfile(item):299self.filelist.append(item)300else:301# a (dirname, filenames) tuple302dirname, filenames = item303for f in filenames:304f = convert_path(f)305if os.path.isfile(f):306self.filelist.append(f)307308def _add_defaults_ext(self):309if self.distribution.has_ext_modules():310build_ext = self.get_finalized_command('build_ext')311self.filelist.extend(build_ext.get_source_files())312313def _add_defaults_c_libs(self):314if self.distribution.has_c_libraries():315build_clib = self.get_finalized_command('build_clib')316self.filelist.extend(build_clib.get_source_files())317318def _add_defaults_scripts(self):319if self.distribution.has_scripts():320build_scripts = self.get_finalized_command('build_scripts')321self.filelist.extend(build_scripts.get_source_files())322323def read_template(self):324"""Read and parse manifest template file named by self.template.325326(usually "MANIFEST.in") The parsing and processing is done by327'self.filelist', which updates itself accordingly.328"""329log.info("reading manifest template '%s'", self.template)330template = TextFile(self.template, strip_comments=1, skip_blanks=1,331join_lines=1, lstrip_ws=1, rstrip_ws=1,332collapse_join=1)333334try:335while True:336line = template.readline()337if line is None: # end of file338break339340try:341self.filelist.process_template_line(line)342# the call above can raise a DistutilsTemplateError for343# malformed lines, or a ValueError from the lower-level344# convert_path function345except (DistutilsTemplateError, ValueError) as msg:346self.warn("%s, line %d: %s" % (template.filename,347template.current_line,348msg))349finally:350template.close()351352def prune_file_list(self):353"""Prune off branches that might slip into the file list as created354by 'read_template()', but really don't belong there:355* the build tree (typically "build")356* the release tree itself (only an issue if we ran "sdist"357previously with --keep-temp, or it aborted)358* any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories359"""360build = self.get_finalized_command('build')361base_dir = self.distribution.get_fullname()362363self.filelist.exclude_pattern(None, prefix=build.build_base)364self.filelist.exclude_pattern(None, prefix=base_dir)365366if sys.platform == 'win32':367seps = r'/|\\'368else:369seps = '/'370371vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',372'_darcs']373vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)374self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)375376def write_manifest(self):377"""Write the file list in 'self.filelist' (presumably as filled in378by 'add_defaults()' and 'read_template()') to the manifest file379named by 'self.manifest'.380"""381if self._manifest_is_not_generated():382log.info("not writing to manually maintained "383"manifest file '%s'" % self.manifest)384return385386content = self.filelist.files[:]387content.insert(0, '# file GENERATED by distutils, do NOT edit')388self.execute(file_util.write_file, (self.manifest, content),389"writing manifest file '%s'" % self.manifest)390391def _manifest_is_not_generated(self):392# check for special comment used in 3.1.3 and higher393if not os.path.isfile(self.manifest):394return False395396fp = open(self.manifest)397try:398first_line = fp.readline()399finally:400fp.close()401return first_line != '# file GENERATED by distutils, do NOT edit\n'402403def read_manifest(self):404"""Read the manifest file (named by 'self.manifest') and use it to405fill in 'self.filelist', the list of files to include in the source406distribution.407"""408log.info("reading manifest file '%s'", self.manifest)409with open(self.manifest) as manifest:410for line in manifest:411# ignore comments and blank lines412line = line.strip()413if line.startswith('#') or not line:414continue415self.filelist.append(line)416417def make_release_tree(self, base_dir, files):418"""Create the directory tree that will become the source419distribution archive. All directories implied by the filenames in420'files' are created under 'base_dir', and then we hard link or copy421(if hard linking is unavailable) those files into place.422Essentially, this duplicates the developer's source tree, but in a423directory named after the distribution, containing only the files424to be distributed.425"""426# Create all the directories under 'base_dir' necessary to427# put 'files' there; the 'mkpath()' is just so we don't die428# if the manifest happens to be empty.429self.mkpath(base_dir)430dir_util.create_tree(base_dir, files, dry_run=self.dry_run)431432# And walk over the list of files, either making a hard link (if433# os.link exists) to each one that doesn't already exist in its434# corresponding location under 'base_dir', or copying each file435# that's out-of-date in 'base_dir'. (Usually, all files will be436# out-of-date, because by default we blow away 'base_dir' when437# we're done making the distribution archives.)438439if hasattr(os, 'link'): # can make hard links on this system440link = 'hard'441msg = "making hard links in %s..." % base_dir442else: # nope, have to copy443link = None444msg = "copying files to %s..." % base_dir445446if not files:447log.warn("no files to distribute -- empty manifest?")448else:449log.info(msg)450for file in files:451if not os.path.isfile(file):452log.warn("'%s' not a regular file -- skipping", file)453else:454dest = os.path.join(base_dir, file)455self.copy_file(file, dest, link=link)456457self.distribution.metadata.write_pkg_info(base_dir)458459def make_distribution(self):460"""Create the source distribution(s). First, we create the release461tree with 'make_release_tree()'; then, we create all required462archive files (according to 'self.formats') from the release tree.463Finally, we clean up by blowing away the release tree (unless464'self.keep_temp' is true). The list of archive files created is465stored so it can be retrieved later by 'get_archive_files()'.466"""467# Don't warn about missing meta-data here -- should be (and is!)468# done elsewhere.469base_dir = self.distribution.get_fullname()470base_name = os.path.join(self.dist_dir, base_dir)471472self.make_release_tree(base_dir, self.filelist.files)473archive_files = [] # remember names of files we create474# tar archive must be created last to avoid overwrite and remove475if 'tar' in self.formats:476self.formats.append(self.formats.pop(self.formats.index('tar')))477478for fmt in self.formats:479file = self.make_archive(base_name, fmt, base_dir=base_dir,480owner=self.owner, group=self.group)481archive_files.append(file)482self.distribution.dist_files.append(('sdist', '', file))483484self.archive_files = archive_files485486if not self.keep_temp:487dir_util.remove_tree(base_dir, dry_run=self.dry_run)488489def get_archive_files(self):490"""Return the list of archive files created when the command491was run, or None if the command hasn't run yet.492"""493return self.archive_files494495496