Beispiel #1
0
class manifest_maker(sdist):

    template = "MANIFEST.in"

    def initialize_options (self):
        self.use_defaults = 1
        self.prune = 1
        self.manifest_only = 1
        self.force_manifest = 1

    def finalize_options(self):
        pass

    def run(self):
        self.filelist = FileList()
        if not os.path.exists(self.manifest):
            self.write_manifest()   # it must exist so it'll get in the list
        self.filelist.findall()
        self.add_defaults()
        if os.path.exists(self.template):
            self.read_template()
        self.prune_file_list()
        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def write_manifest (self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        files = self.filelist.files
        if os.sep!='/':
            files = [f.replace(os.sep,'/') for f in files]
        self.execute(write_file, (self.manifest, files),
                     "writing manifest file '{0!s}'".format(self.manifest))

    def warn(self, msg):    # suppress missing-file warnings from sdist
        if not msg.startswith("standard file not found:"):
            sdist.warn(self, msg)

    def add_defaults(self):
        sdist.add_defaults(self)
        self.filelist.append(self.template)
        self.filelist.append(self.manifest)
        rcfiles = list(walk_revctrl())
        if rcfiles:
            self.filelist.extend(rcfiles)
        elif os.path.exists(self.manifest):
            self.read_manifest()
        ei_cmd = self.get_finalized_command('egg_info')
        self.filelist.include_pattern("*", prefix=ei_cmd.egg_info)

    def prune_file_list (self):
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()
        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)
        sep = re.escape(os.sep)
        self.filelist.exclude_pattern(sep+r'(RCS|CVS|\.svn)'+sep, is_regex=1)
Beispiel #2
0
def copydir_run_2to3(src, dest, template=None, fixer_names=None,
                     options=None, explicit=None):
    """Recursively copy a directory, only copying new and changed files,
    running run_2to3 over all newly copied Python modules afterward.

    If you give a template string, it's parsed like a MANIFEST.in.
    """
    from distutils.dir_util import mkpath
    from distutils.file_util import copy_file
    from distutils.filelist import FileList
    filelist = FileList()
    curdir = os.getcwd()
    os.chdir(src)
    try:
        filelist.findall()
    finally:
        os.chdir(curdir)
    filelist.files[:] = filelist.allfiles
    if template:
        for line in template.splitlines():
            line = line.strip()
            if not line: continue
            filelist.process_template_line(line)
    copied = []
    for filename in filelist.files:
        outname = os.path.join(dest, filename)
        mkpath(os.path.dirname(outname))
        res = copy_file(os.path.join(src, filename), outname, update=1)
        if res[1]: copied.append(outname)
    run_2to3([fn for fn in copied if fn.lower().endswith('.py')],
             fixer_names=fixer_names, options=options, explicit=explicit)
    return copied
Beispiel #3
0
def copydir_run_2to3(src, dest, template=None, fixer_names=None,
                     options=None, explicit=None):
    """Recursively copy a directory, only copying new and changed files,
    running run_2to3 over all newly copied Python modules afterward.

    If you give a template string, it's parsed like a MANIFEST.in.
    """
    from distutils.dir_util import mkpath
    from distutils.file_util import copy_file
    from distutils.filelist import FileList
    filelist = FileList()
    curdir = os.getcwd()
    os.chdir(src)
    try:
        filelist.findall()
    finally:
        os.chdir(curdir)
    filelist.files[:] = filelist.allfiles
    if template:
        for line in template.splitlines():
            line = line.strip()
            if not line: continue
            filelist.process_template_line(line)
    copied = []
    for filename in filelist.files:
        outname = os.path.join(dest, filename)
        mkpath(os.path.dirname(outname))
        res = copy_file(os.path.join(src, filename), outname, update=1)
        if res[1]: copied.append(outname)
    run_2to3([fn for fn in copied if fn.lower().endswith('.py')],
             fixer_names=fixer_names, options=options, explicit=explicit)
    return copied
Beispiel #4
0
    def run(self):
        # try to run swig
        self.swig_name = None

        for swig_name in ('swig', 'swig1.3'):
            try:
                # should do a version check
                self.spawn([swig_name, '-version'])
                self.swig_name = swig_name
                if not check_swig_version(swig_name):
                    handle_wrong_swig_version()
                    self.swig_name = None
                break
            except:
                pass

        # if brain dead spawn doesn't work...
        if self.swig_name is None:
            for swig_name in ('swig', 'swig1.3'):
                try:
                    r = os.system("%s -version" % swig_name)
                except:
                    r == 99999999
                    if r == 256:
                        self.swig_name = swig_name

                        if not check_swig_version(swig_name):
                            handle_wrong_swig_version()

                        # found the swig name, stop checking.
                        break

        if self.swig_name is None:
            self.warn(
                "Can't find SWIG, will just have to do with the existing wrapper source."
            )
        else:
            self.mkpath('src/interface')
            self.mkpath('src/shadow')

            interfaces = []
            f = FileList()
            f.findall('interface')
            f.process_template_line('global-include *.i')
            f.files.sort()
            for file in f.files:
                interfaces.append(
                    string.join(
                        string.split(os.path.splitext(file)[0], os.sep)[1:],
                        '.'))
            interfaces.sort()

            for full_module_name in interfaces:
                self.swig(full_module_name)
Beispiel #5
0
def _get_manifest_files():
    filelist = FileList()
    old_wd = os.getcwd()
    try:
        os.chdir(SOURCE_DIRECTORY)
        filelist.findall()
    finally:
        os.chdir(old_wd)
    with open(MANIFEST, 'r') as source:
        for line in source:
            filelist.process_template_line(line.strip())
    return filelist.files
Beispiel #6
0
def _get_manifest_files():
    filelist = FileList()
    old_wd = os.getcwd()
    try:
        os.chdir(SOURCE_DIRECTORY)
        filelist.findall()
    finally:
        os.chdir(old_wd)
    with open(MANIFEST, 'r') as source:
        for line in source:
            filelist.process_template_line(line.strip())
    return filelist.files
Beispiel #7
0
	def run (self):
		# try to run swig
		self.swig_name = None
		
		for swig_name in ('swig', 'swig1.3'):
			try:
				# should do a version check
				self.spawn([swig_name, '-version'])
				self.swig_name = swig_name
				if not check_swig_version(swig_name):
					handle_wrong_swig_version()
					self.swig_name = None
				break
			except:
				pass

		# if brain dead spawn doesn't work...
		if self.swig_name is None:
			for swig_name in ('swig', 'swig1.3'):
				try:
					r = os.system("%s -version" % swig_name)
				except:
					r == 99999999
					if r == 256:
						self.swig_name = swig_name

						if not check_swig_version(swig_name):
							handle_wrong_swig_version()

						# found the swig name, stop checking.
						break
			

		if self.swig_name is None:
			self.warn("Can't find SWIG, will just have to do with the existing wrapper source.")
		else:
			self.mkpath('src/interface')
			self.mkpath('src/shadow')
	
			interfaces = []
			f = FileList()
			f.findall('interface')
			f.process_template_line('global-include *.i')
			f.files.sort()
			for file in f.files:
				interfaces.append(string.join(string.split(os.path.splitext(file)[0], os.sep)[1:], '.'))
			interfaces.sort()
	
			for full_module_name in interfaces:
				self.swig(full_module_name)
Beispiel #8
0
	def run(self):
		"""The primary driver for the documentation-building system
		"""
		## Build our Java class-path value
		paths = []
		for (variable,jarName, packageName) in [
			("SAXON_HOME", "saxon.jar", "Saxon XSL Processor"),
			("RESOLVER_HOME","resolver.jar", "Sun Resolver XML Package"),
		]:
			if not os.environ.has_key(variable):
				self.warn( """Could not find %(variable)s environmental variable.
Install %(packageName)s and set environmental variable %(variable)s to point
to the directory holding %(jarName)s.
Aborting documentation generation."""%locals() )
				return
			paths.append( os.path.join(os.environ[variable], jarName) )
		# Add the docbook-xsl extensions
		os.path.join(DOCBOOK_XSL_HOME, 'extensions', 'saxon643.jar')
		for path in paths:
			if not os.path.isfile( path ):
				self.warn( """The class-path value %s does not appear to be a valid file, errors may result.  Please check environmental variables."""%(path,) )
		# Following puts the CatalogManager.properties file on the
		# path, though that doesn't seem to actually help much in
		# reducing reliance on networked files :( 
		paths.append( DOCBOOK_DTD_HOME )
		self.cp = string.join( paths, os.pathsep )

		f = FileList()
		f.findall('doc')
		f.process_template_line('global-include *.xml')
		manualTemp = os.path.join('build', 'doc', 'manual.xml')
		self.make_file(
			f.files,
			manualTemp,
			self.merge_doc,
			(
				os.path.join('doc', 'manual', 'manual.xml'),
				manualTemp,
			),
			exec_msg = 'Merging manpages and Python-specific documentation',
			skip_msg = 'Manpages already merged with Python-specific documentation'
		)

		for format in self.formats:
			name = 'run_' + format
			if hasattr(self, name):
				self.announce( """Building format %s"""%( format,))
				getattr(self, name)()	
			else:
				self.announce( """No support available for format %s"""%( format,))
Beispiel #9
0
    def get_file_list(self):
        self._get_file_list()
        manifest_filelist = self.filelist
        source_filelist = FileList()
        allfiles = self.filelist.allfiles
        if allfiles:
            source_filelist.set_allfiles(allfiles)
        else:
            source_filelist.findall()
        source_filelist.extend(source_filelist.allfiles)
        # Check for template (usually "MANIFEST.in")
        if os.path.isfile(self.template):
            template = TextFile(self.template,
                                strip_comments=1,
                                skip_blanks=1,
                                join_lines=1,
                                lstrip_ws=1,
                                rstrip_ws=1,
                                collapse_join=1)
            while 1:
                line = template.readline()
                if line is None:  # end of file
                    break
                try:
                    source_filelist.process_template_line(line)
                except DistutilsTemplateError:
                    # Already been warned by "real" filelist
                    pass
        if self.prune:
            try:
                self.filelist = source_filelist
                self.prune_file_list()
            finally:
                self.filelist = manifest_filelist
        source_filelist.sort()
        source_filelist.remove_duplicates()

        # Ensure file paths are formatted the same
        # This removes any dot-slashes and converts all slashes to
        # OS-specific separators.
        manifest = set(map(os.path.normpath, manifest_filelist.files))
        missing = False
        for filename in imap(os.path.normpath, source_filelist.files):
            if filename not in manifest:
                self.warn('missing from source distribution: %s' % filename)
                missing = True
        if missing:
            raw_input('WARNING: Not all source files in distribution! '
                      ' Press <Enter> to continue.')
Beispiel #10
0
    def get_file_list(self):
        self._get_file_list()
        manifest_filelist = self.filelist
        source_filelist = FileList()
        allfiles = self.filelist.allfiles
        if allfiles:
            source_filelist.set_allfiles(allfiles)
        else:
            source_filelist.findall()
        source_filelist.extend(source_filelist.allfiles)
        # Check for template (usually "MANIFEST.in")
        if os.path.isfile(self.template):
            template = TextFile(self.template,
                                strip_comments=1,
                                skip_blanks=1,
                                join_lines=1,
                                lstrip_ws=1,
                                rstrip_ws=1,
                                collapse_join=1)
            while 1:
                line = template.readline()
                if line is None:            # end of file
                    break
                try:
                    source_filelist.process_template_line(line)
                except DistutilsTemplateError:
                    # Already been warned by "real" filelist
                    pass
        if self.prune:
            try:
                self.filelist = source_filelist
                self.prune_file_list()
            finally:
                self.filelist = manifest_filelist
        source_filelist.sort()
        source_filelist.remove_duplicates()

        # Ensure file paths are formatted the same
        # This removes any dot-slashes and converts all slashes to
        # OS-specific separators.
        manifest = set(map(os.path.normpath, manifest_filelist.files))
        missing = False
        for filename in imap(os.path.normpath, source_filelist.files):
            if filename not in manifest:
                self.warn('missing from source distribution: %s' % filename)
                missing = True
        if missing:
            raw_input('WARNING: Not all source files in distribution! '
                      ' Press <Enter> to continue.')
Beispiel #11
0
	def run_htmlhelp(self):
		"""Generate MS HTMLHelp documentation"""
		self.make_file(['build/doc/manual.xml'],
		               'build/doc/htmlhelp/index.html',
		               self.gen_html,
		               ('build/doc/htmlhelp', 'build/doc/htmlhelp', 'htmlhelp.xsl'))

		self.mkpath('build/doc/htmlhelp')

		for file in ('manual.hhp', 'manual.hhc'):
			if os.path.exists(file):
				x = open(file).read()
##				x = string.replace(x, 'build/doc/htmlhelp_raw/', '')
				x = string.replace(x, 'build/doc/htmlhelp/', '')
				open(os.path.join('build', 'doc', 'htmlhelp', file), 'w').write(x)
				os.remove(file)
			
#		self.move_file('manual.hhp', 'build/doc/htmlhelp')
#		self.move_file('toc.hhc', 'build/doc/htmlhelp')
		
##		self.make_file(['build/doc/htmlhelp_raw/index.html'],
##		               'build/doc/htmlhelp/index.html',
##		               self.xform_html,
##		               ('build/doc/htmlhelp_raw', 'build/doc/htmlhelp'))

		self.copy_file('doc/misc/style.css', 'build/doc/htmlhelp')
		self.copy_file('doc/misc/greypinstripe.png', 'build/doc/htmlhelp')
	
		f = FileList()
		f.findall('build/doc/htmlhelp')
		f.process_template_line('global-include *')
		self.make_file(f.files,
		               'build/doc/htmlhelp/manual.chm',
		               self.hhc,
		               ())

		self.copy_file('build/doc/htmlhelp/manual.chm', 'OpenGL/doc')
Beispiel #12
0
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    def checking_metadata(self):
        """Callable used for the check sub-command.

        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm',
         "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None,
         "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None,
         "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None,
         "don't automatically exclude anything"),
        ('manifest-only', 'o',
         "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual. "
         "Deprecated: now the manifest is always regenerated."),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ('metadata-check', None,
         "Ensure that all required elements of meta-data "
         "are supplied. Warn if any missing. [default]"),
        ('owner=', 'u',
         "Owner name used when creating a tar file [default: current user]"),
        ('group=', 'g',
         "Group name used when creating a tar file [default: current group]"),
        ]

    boolean_options = ['use-defaults', 'prune',
                       'manifest-only', 'force-manifest',
                       'keep-temp', 'metadata-check']

    help_options = [
        ('help-formats', None,
         "list available distribution formats", show_formats),
        ]

    negative_opt = {'no-defaults': 'use-defaults',
                    'no-prune': 'prune' }

    sub_commands = [('check', checking_metadata)]

    READMES = ('README', 'README.txt', 'README.rst')

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = ['gztar']
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError(
                  "unknown archive format '%s'" % bad_format)

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):
        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Run sub commands
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn("distutils.command.sdist.check_metadata is deprecated, \
              use the check command instead", PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        # new behavior when using a template:
        # the file list is recalculated every time because
        # even if MANIFEST.in or setup.py are not changed
        # the user might have added some files in the tree that
        # need to be included.
        #
        #  This makes --force the default and only behavior with templates.
        template_exists = os.path.isfile(self.template)
        if not template_exists and self._manifest_is_not_generated():
            self.read_manifest()
            self.filelist.sort()
            self.filelist.remove_duplicates()
            return

        if not template_exists:
            self.warn(("manifest template '%s' does not exist " +
                        "(using default file list)") %
                        self.template)
        self.filelist.findall()

        if self.use_defaults:
            self.add_defaults()

        if template_exists:
            self.read_template()

        if self.prune:
            self.prune_file_list()

        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """
        self._add_defaults_standards()
        self._add_defaults_optional()
        self._add_defaults_python()
        self._add_defaults_data_files()
        self._add_defaults_ext()
        self._add_defaults_c_libs()
        self._add_defaults_scripts()

    @staticmethod
    def _cs_path_exists(fspath):
        """
        Case-sensitive path existence check

        >>> sdist._cs_path_exists(__file__)
        True
        >>> sdist._cs_path_exists(__file__.upper())
        False
        """
        if not os.path.exists(fspath):
            return False
        # make absolute so we always have a directory
        abspath = os.path.abspath(fspath)
        directory, filename = os.path.split(abspath)
        return filename in os.listdir(directory)

    def _add_defaults_standards(self):
        standards = [self.READMES, self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = False
                for fn in alts:
                    if self._cs_path_exists(fn):
                        got_it = True
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              ', '.join(alts))
            else:
                if self._cs_path_exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

    def _add_defaults_optional(self):
        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            self.filelist.extend(files)

    def _add_defaults_python(self):
        # build_py is used to get:
        #  - python modules
        #  - files defined in package_data
        build_py = self.get_finalized_command('build_py')

        # getting python files
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())

        # getting package_data files
        # (computed in build_py.data_files by build_py.finalize_options)
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

    def _add_defaults_data_files(self):
        # getting distribution.data_files
        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):
                    # plain file
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:
                    # a (dirname, filenames) tuple
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

    def _add_defaults_ext(self):
        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

    def _add_defaults_c_libs(self):
        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

    def _add_defaults_scripts(self):
        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template, strip_comments=1, skip_blanks=1,
                            join_lines=1, lstrip_ws=1, rstrip_ws=1,
                            collapse_join=1)

        try:
            while True:
                line = template.readline()
                if line is None:            # end of file
                    break

                try:
                    self.filelist.process_template_line(line)
                # the call above can raise a DistutilsTemplateError for
                # malformed lines, or a ValueError from the lower-level
                # convert_path function
                except (DistutilsTemplateError, ValueError) as msg:
                    self.warn("%s, line %d: %s" % (template.filename,
                                                   template.current_line,
                                                   msg))
        finally:
            template.close()

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()

        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)

        if sys.platform == 'win32':
            seps = r'/|\\'
        else:
            seps = '/'

        vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
                    '_darcs']
        vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        if self._manifest_is_not_generated():
            log.info("not writing to manually maintained "
                     "manifest file '%s'" % self.manifest)
            return

        content = self.filelist.files[:]
        content.insert(0, '# file GENERATED by distutils, do NOT edit')
        self.execute(file_util.write_file, (self.manifest, content),
                     "writing manifest file '%s'" % self.manifest)

    def _manifest_is_not_generated(self):
        # check for special comment used in 3.1.3 and higher
        if not os.path.isfile(self.manifest):
            return False

        fp = open(self.manifest)
        try:
            first_line = fp.readline()
        finally:
            fp.close()
        return first_line != '# file GENERATED by distutils, do NOT edit\n'

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        for line in manifest:
            # ignore comments and blank lines
            line = line.strip()
            if line.startswith('#') or not line:
                continue
            self.filelist.append(line)
        manifest.close()

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        # Create all the directories under 'base_dir' necessary to
        # put 'files' there; the 'mkpath()' is just so we don't die
        # if the manifest happens to be empty.
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)

        # And walk over the list of files, either making a hard link (if
        # os.link exists) to each one that doesn't already exist in its
        # corresponding location under 'base_dir', or copying each file
        # that's out-of-date in 'base_dir'.  (Usually, all files will be
        # out-of-date, because by default we blow away 'base_dir' when
        # we're done making the distribution archives.)

        if hasattr(os, 'link'):        # can make hard links on this system
            link = 'hard'
            msg = "making hard links in %s..." % base_dir
        else:                           # nope, have to copy
            link = None
            msg = "copying files to %s..." % base_dir

        if not files:
            log.warn("no files to distribute -- empty manifest?")
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping", file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        # Don't warn about missing meta-data here -- should be (and is!)
        # done elsewhere.
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)

        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []              # remember names of files we create
        # tar archive must be created last to avoid overwrite and remove
        if 'tar' in self.formats:
            self.formats.append(self.formats.pop(self.formats.index('tar')))

        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir,
                                     owner=self.owner, group=self.group)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files

        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    def checking_metadata(self):
        """Callable used for the check sub-command.

        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm', "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None, "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None, "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None, "don't automatically exclude anything"),
        ('manifest-only', 'o', "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual. "
         "Deprecated: now the manifest is always regenerated."),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ('medata-check', None,
         "Ensure that all required elements of meta-data "
         "are supplied. Warn if any missing. [default]"),
        ('owner=', 'u',
         "Owner name used when creating a tar file [default: current user]"),
        ('group=', 'g',
         "Group name used when creating a tar file [default: current group]"),
    ]

    boolean_options = [
        'use-defaults', 'prune', 'manifest-only', 'force-manifest',
        'keep-temp', 'metadata-check'
    ]

    help_options = [
        ('help-formats', None, "list available distribution formats",
         show_formats),
    ]

    negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune'}

    default_format = {'posix': 'gztar', 'nt': 'zip'}

    sub_commands = [('check', checking_metadata)]

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError, \
                      "don't know how to create source distributions " + \
                      "on platform %s" % os.name

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError, \
                  "unknown archive format '%s'" % bad_format

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):
        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Run sub commands
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn(
            "distutils.command.sdist.check_metadata is deprecated, \
              use the check command instead", PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        # new behavior:
        # the file list is recalculated everytime because
        # even if MANIFEST.in or setup.py are not changed
        # the user might have added some files in the tree that
        # need to be included.
        #
        #  This makes --force the default and only behavior.
        template_exists = os.path.isfile(self.template)
        if not template_exists:
            self.warn(("manifest template '%s' does not exist " +
                       "(using default file list)") % self.template)
        self.filelist.findall()

        if self.use_defaults:
            self.add_defaults()

        if template_exists:
            self.read_template()

        if self.prune:
            self.prune_file_list()

        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """

        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              string.join(alts, ', '))
            else:
                if os.path.exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        # build_py is used to get:
        #  - python modules
        #  - files defined in package_data
        build_py = self.get_finalized_command('build_py')

        # getting python files
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())

        # getting package_data files
        # (computed in build_py.data_files by build_py.finalize_options)
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        # getting distribution.data_files
        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):  # plain file
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:  # a (dirname, filenames) tuple
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template,
                            strip_comments=1,
                            skip_blanks=1,
                            join_lines=1,
                            lstrip_ws=1,
                            rstrip_ws=1,
                            collapse_join=1)

        while 1:
            line = template.readline()
            if line is None:  # end of file
                break

            try:
                self.filelist.process_template_line(line)
            except DistutilsTemplateError, msg:
                self.warn("%s, line %d: %s" %
                          (template.filename, template.current_line, msg))
Beispiel #14
0
class spa (Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm',
         "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None,
         "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None,
         "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None,
         "don't automatically exclude anything"),
        ('manifest-only', 'o',
         "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual"),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ]

    boolean_options = ['use-defaults', 'prune',
                       'manifest-only', 'force-manifest',
                       'keep-temp']

    help_options = [
        ('help-formats', None,
         "list available distribution formats", show_formats),
        ]

    negative_opt = {'no-defaults': 'use-defaults',
                    'no-prune': 'prune' }

    default_format = { 'posix': 'gztar',
                       'nt': 'zip' }

    def initialize_options (self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None


    def finalize_options (self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError, \
                      "don't know how to create source distributions " + \
                      "on platform %s" % os.name

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError, \
                  "unknown archive format '%s'" % bad_format

        if self.dist_dir is None:
            self.dist_dir = "dist"


    def run (self):

        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Ensure that all required meta-data is given; warn if not (but
        # don't die, it's not *that* serious!)
        self.check_metadata()

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()


    def check_metadata (self):
        """Ensure that all required elements of meta-data (name, version,
        URL, (author and author_email) or (maintainer and
        maintainer_email)) are supplied by the Distribution object; warn if
        any are missing.
        """
        metadata = self.distribution.metadata

        missing = []
        for attr in ('name', 'version', 'url'):
            if not (hasattr(metadata, attr) and getattr(metadata, attr)):
                missing.append(attr)

        if missing:
            self.warn("missing required meta-data: " +
                      string.join(missing, ", "))

        if metadata.author:
            if not metadata.author_email:
                self.warn("missing meta-data: if 'author' supplied, " +
                          "'author_email' must be supplied too")
        elif metadata.maintainer:
            if not metadata.maintainer_email:
                self.warn("missing meta-data: if 'maintainer' supplied, " +
                          "'maintainer_email' must be supplied too")
        else:
            self.warn("missing meta-data: either (author and author_email) " +
                      "or (maintainer and maintainer_email) " +
                      "must be supplied")

    # check_metadata ()


    def get_file_list (self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options and the state of the filesystem.
        """

        # If we have a manifest template, see if it's newer than the
        # manifest; if so, we'll regenerate the manifest.
        template_exists = os.path.isfile(self.template)
        if template_exists:
            template_newer = dep_util.newer(self.template, self.manifest)

        # The contents of the manifest file almost certainly depend on the
        # setup script as well as the manifest template -- so if the setup
        # script is newer than the manifest, we'll regenerate the manifest
        # from the template.  (Well, not quite: if we already have a
        # manifest, but there's no template -- which will happen if the
        # developer elects to generate a manifest some other way -- then we
        # can't regenerate the manifest, so we don't.)
        self.debug_print("checking if %s newer than %s" %
                         (self.distribution.script_name, self.manifest))
        setup_newer = dep_util.newer(self.distribution.script_name,
                                     self.manifest)

        # cases:
        #   1) no manifest, template exists: generate manifest
        #      (covered by 2a: no manifest == template newer)
        #   2) manifest & template exist:
        #      2a) template or setup script newer than manifest:
        #          regenerate manifest
        #      2b) manifest newer than both:
        #          do nothing (unless --force or --manifest-only)
        #   3) manifest exists, no template:
        #      do nothing (unless --force or --manifest-only)
        #   4) no manifest, no template: generate w/ warning ("defaults only")

        manifest_outofdate = (template_exists and
                              (template_newer or setup_newer))
        force_regen = self.force_manifest or self.manifest_only
        manifest_exists = os.path.isfile(self.manifest)
        neither_exists = (not template_exists and not manifest_exists)

        # Regenerate the manifest if necessary (or if explicitly told to)
        if manifest_outofdate or neither_exists or force_regen:
            if not template_exists:
                self.warn(("manifest template '%s' does not exist " +
                           "(using default file list)") %
                          self.template)
            self.filelist.findall()

            if self.use_defaults:
                self.add_defaults()
            if template_exists:
                self.read_template()
            if self.prune:
                self.prune_file_list()

            self.filelist.sort()
            self.filelist.remove_duplicates()
            self.write_manifest()

        # Don't regenerate the manifest, just read it in.
        else:
            self.read_manifest()

    # get_file_list ()


    def add_defaults (self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """

        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            # XXX
            if fn == 'setup.py': continue # We don't want setup.py
            if type(fn) is TupleType:
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              string.join(alts, ', '))
            else:
                if os.path.exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        if self.distribution.has_pure_modules():
            build_py = self.get_finalized_command('build_py')
            self.filelist.extend(build_py.get_source_files())

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    # add_defaults ()


    def read_template (self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template,
                            strip_comments=1,
                            skip_blanks=1,
                            join_lines=1,
                            lstrip_ws=1,
                            rstrip_ws=1,
                            collapse_join=1)

        while 1:
            line = template.readline()
            if line is None:            # end of file
                break

            try:
                self.filelist.process_template_line(line)
            except DistutilsTemplateError, msg:
                self.warn("%s, line %d: %s" % (template.filename,
                                               template.current_line,
                                               msg))
Beispiel #15
0
class sdist(Command):
    description = 'create a source distribution (tarball, zip file, etc.)'

    def checking_metadata(self):
        """Callable used for the check sub-command.
        
        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [('template=', 't', 'name of manifest template file [default: MANIFEST.in]'),
     ('manifest=', 'm', 'name of manifest file [default: MANIFEST]'),
     ('use-defaults', None, 'include the default file set in the manifest [default; disable with --no-defaults]'),
     ('no-defaults', None, "don't include the default file set"),
     ('prune', None, 'specifically exclude files/directories that should not be distributed (build tree, RCS/CVS dirs, etc.) [default; disable with --no-prune]'),
     ('no-prune', None, "don't automatically exclude anything"),
     ('manifest-only', 'o', 'just regenerate the manifest and then stop (implies --force-manifest)'),
     ('force-manifest', 'f', 'forcibly regenerate the manifest and carry on as usual. Deprecated: now the manifest is always regenerated.'),
     ('formats=', None, 'formats for source distribution (comma-separated list)'),
     ('keep-temp', 'k', 'keep the distribution tree around after creating ' + 'archive file(s)'),
     ('dist-dir=', 'd', 'directory to put the source distribution archive(s) in [default: dist]'),
     ('metadata-check', None, 'Ensure that all required elements of meta-data are supplied. Warn if any missing. [default]'),
     ('owner=', 'u', 'Owner name used when creating a tar file [default: current user]'),
     ('group=', 'g', 'Group name used when creating a tar file [default: current group]')]
    boolean_options = ['use-defaults',
     'prune',
     'manifest-only',
     'force-manifest',
     'keep-temp',
     'metadata-check']
    help_options = [('help-formats',
      None,
      'list available distribution formats',
      show_formats)]
    negative_opt = {'no-defaults': 'use-defaults',
     'no-prune': 'prune'}
    default_format = {'posix': 'gztar',
     'nt': 'zip'}
    sub_commands = [('check', checking_metadata)]

    def initialize_options(self):
        self.template = None
        self.manifest = None
        self.use_defaults = 1
        self.prune = 1
        self.manifest_only = 0
        self.force_manifest = 0
        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None
        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None
        return

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = 'MANIFEST'
        if self.template is None:
            self.template = 'MANIFEST.in'
        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError, "don't know how to create source distributions " + 'on platform %s' % os.name

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError, "unknown archive format '%s'" % bad_format
        if self.dist_dir is None:
            self.dist_dir = 'dist'
        return

    def run(self):
        self.filelist = FileList()
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        self.get_file_list()
        if self.manifest_only:
            return
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn('distutils.command.sdist.check_metadata is deprecated,               use the check command instead', PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        template_exists = os.path.isfile(self.template)
        if not template_exists and self._manifest_is_not_generated():
            self.read_manifest()
            self.filelist.sort()
            self.filelist.remove_duplicates()
            return
        if not template_exists:
            self.warn(("manifest template '%s' does not exist " + '(using default file list)') % self.template)
        self.filelist.findall()
        if self.use_defaults:
            self.add_defaults()
        if template_exists:
            self.read_template()
        if self.prune:
            self.prune_file_list()
        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """
        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn('standard file not found: should have one of ' + string.join(alts, ', '))
            elif os.path.exists(fn):
                self.filelist.append(fn)
            else:
                self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        build_py = self.get_finalized_command('build_py')
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())
        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())
        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.
        
        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1)
        try:
            while 1:
                line = template.readline()
                if line is None:
                    break
                try:
                    self.filelist.process_template_line(line)
                except (DistutilsTemplateError, ValueError) as msg:
                    self.warn('%s, line %d: %s' % (template.filename, template.current_line, msg))

        finally:
            template.close()

        return

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()
        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)
        if sys.platform == 'win32':
            seps = '/|\\\\'
        else:
            seps = '/'
        vcs_dirs = ['RCS',
         'CVS',
         '\\.svn',
         '\\.hg',
         '\\.git',
         '\\.bzr',
         '_darcs']
        vcs_ptrn = '(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
        return

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        if self._manifest_is_not_generated():
            log.info("not writing to manually maintained manifest file '%s'" % self.manifest)
            return
        content = self.filelist.files[:]
        content.insert(0, '# file GENERATED by distutils, do NOT edit')
        self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest)

    def _manifest_is_not_generated(self):
        if not os.path.isfile(self.manifest):
            return False
        fp = open(self.manifest, 'rU')
        try:
            first_line = fp.readline()
        finally:
            fp.close()

        return first_line != '# file GENERATED by distutils, do NOT edit\n'

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        for line in manifest:
            line = line.strip()
            if line.startswith('#') or not line:
                continue
            self.filelist.append(line)

        manifest.close()

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
        if hasattr(os, 'link'):
            link = 'hard'
            msg = 'making hard links in %s...' % base_dir
        else:
            link = None
            msg = 'copying files to %s...' % base_dir
        if not files:
            log.warn('no files to distribute -- empty manifest?')
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping" % file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)
        return

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)
        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []
        if 'tar' in self.formats:
            self.formats.append(self.formats.pop(self.formats.index('tar')))
        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files
        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
Beispiel #16
0
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm', "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None, "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None, "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None, "don't automatically exclude anything"),
        ('manifest-only', 'o', "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual"),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
    ]

    boolean_options = [
        'use-defaults', 'prune', 'manifest-only', 'force-manifest', 'keep-temp'
    ]

    help_options = [
        ('help-formats', None, "list available distribution formats",
         show_formats),
    ]

    negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune'}

    default_format = {'posix': 'gztar', 'java': 'gztar', 'nt': 'zip'}

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError("don't know how to create source distributions " + \
                      "on platform %s" % os.name)

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError("unknown archive format '%s'" %
                                       bad_format)

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):

        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Ensure that all required meta-data is given; warn if not (but
        # don't die, it's not *that* serious!)
        self.check_metadata()

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Ensure that all required elements of meta-data (name, version,
        URL, (author and author_email) or (maintainer and
        maintainer_email)) are supplied by the Distribution object; warn if
        any are missing.
        """
        metadata = self.distribution.metadata

        missing = []
        for attr in ('name', 'version', 'url'):
            if not (hasattr(metadata, attr) and getattr(metadata, attr)):
                missing.append(attr)

        if missing:
            self.warn("missing required meta-data: " +
                      string.join(missing, ", "))

        if metadata.author:
            if not metadata.author_email:
                self.warn("missing meta-data: if 'author' supplied, " +
                          "'author_email' must be supplied too")
        elif metadata.maintainer:
            if not metadata.maintainer_email:
                self.warn("missing meta-data: if 'maintainer' supplied, " +
                          "'maintainer_email' must be supplied too")
        else:
            self.warn("missing meta-data: either (author and author_email) " +
                      "or (maintainer and maintainer_email) " +
                      "must be supplied")

    # check_metadata ()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options and the state of the filesystem.
        """

        # If we have a manifest template, see if it's newer than the
        # manifest; if so, we'll regenerate the manifest.
        template_exists = os.path.isfile(self.template)
        if template_exists:
            template_newer = dep_util.newer(self.template, self.manifest)

        # The contents of the manifest file almost certainly depend on the
        # setup script as well as the manifest template -- so if the setup
        # script is newer than the manifest, we'll regenerate the manifest
        # from the template.  (Well, not quite: if we already have a
        # manifest, but there's no template -- which will happen if the
        # developer elects to generate a manifest some other way -- then we
        # can't regenerate the manifest, so we don't.)
        self.debug_print("checking if %s newer than %s" %
                         (self.distribution.script_name, self.manifest))
        setup_newer = dep_util.newer(self.distribution.script_name,
                                     self.manifest)

        # cases:
        #   1) no manifest, template exists: generate manifest
        #      (covered by 2a: no manifest == template newer)
        #   2) manifest & template exist:
        #      2a) template or setup script newer than manifest:
        #          regenerate manifest
        #      2b) manifest newer than both:
        #          do nothing (unless --force or --manifest-only)
        #   3) manifest exists, no template:
        #      do nothing (unless --force or --manifest-only)
        #   4) no manifest, no template: generate w/ warning ("defaults only")

        manifest_outofdate = (template_exists
                              and (template_newer or setup_newer))
        force_regen = self.force_manifest or self.manifest_only
        manifest_exists = os.path.isfile(self.manifest)
        neither_exists = (not template_exists and not manifest_exists)

        # Regenerate the manifest if necessary (or if explicitly told to)
        if manifest_outofdate or neither_exists or force_regen:
            if not template_exists:
                self.warn(("manifest template '%s' does not exist " +
                           "(using default file list)") % self.template)
            self.filelist.findall()

            if self.use_defaults:
                self.add_defaults()
            if template_exists:
                self.read_template()
            if self.prune:
                self.prune_file_list()

            self.filelist.sort()
            self.filelist.remove_duplicates()
            self.write_manifest()

        # Don't regenerate the manifest, just read it in.
        else:
            self.read_manifest()

    # get_file_list ()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """

        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if type(fn) is TupleType:
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              string.join(alts, ', '))
            else:
                if os.path.exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = list(filter(os.path.isfile, glob(pattern)))
            if files:
                self.filelist.extend(files)

        if self.distribution.has_pure_modules():
            build_py = self.get_finalized_command('build_py')
            self.filelist.extend(build_py.get_source_files())

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    # add_defaults ()

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template,
                            strip_comments=1,
                            skip_blanks=1,
                            join_lines=1,
                            lstrip_ws=1,
                            rstrip_ws=1,
                            collapse_join=1)

        while 1:
            line = template.readline()
            if line is None:  # end of file
                break

            try:
                self.filelist.process_template_line(line)
            except DistutilsTemplateError as msg:
                self.warn("%s, line %d: %s" %
                          (template.filename, template.current_line, msg))

    # read_template ()

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()

        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)
        self.filelist.exclude_pattern(
            r'(^|/)(RCS|CVS|\.svn|\.hg|\.git|\.bzr|_darcs)/.*', is_regex=1)

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        self.execute(file_util.write_file,
                     (self.manifest, self.filelist.files),
                     "writing manifest file '%s'" % self.manifest)

    # write_manifest ()

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        try:
            while 1:
                line = manifest.readline()
                if line == '':  # end of file
                    break
                if line[-1] == '\n':
                    line = line[0:-1]
                self.filelist.append(line)
        finally:
            manifest.close()

    # read_manifest ()

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        # Create all the directories under 'base_dir' necessary to
        # put 'files' there; the 'mkpath()' is just so we don't die
        # if the manifest happens to be empty.
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)

        # And walk over the list of files, either making a hard link (if
        # os.link exists) to each one that doesn't already exist in its
        # corresponding location under 'base_dir', or copying each file
        # that's out-of-date in 'base_dir'.  (Usually, all files will be
        # out-of-date, because by default we blow away 'base_dir' when
        # we're done making the distribution archives.)

        if hasattr(os, 'link'):  # can make hard links on this system
            link = 'hard'
            msg = "making hard links in %s..." % base_dir
        else:  # nope, have to copy
            link = None
            msg = "copying files to %s..." % base_dir

        if not files:
            log.warn("no files to distribute -- empty manifest?")
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping" % file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)

    # make_release_tree ()

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        # Don't warn about missing meta-data here -- should be (and is!)
        # done elsewhere.
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)

        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []  # remember names of files we create
        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files

        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
Beispiel #17
0
class manifest_maker(sdist):

    template = "MANIFEST.in"

    def initialize_options(self):
        self.use_defaults = 1
        self.prune = 1
        self.manifest_only = 1
        self.force_manifest = 1

    def finalize_options(self):
        pass

    def run(self):
        self.filelist = FileList()
        if not os.path.exists(self.manifest):
            self.write_manifest()  # it must exist so it'll get in the list
        self.filelist.findall()
        self.add_defaults()
        if os.path.exists(self.template):
            self.read_template()
        self.prune_file_list()
        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        files = self.filelist.files
        if os.sep != '/':
            files = [f.replace(os.sep, '/') for f in files]
        self.execute(write_file, (self.manifest, files),
                     "writing manifest file '%s'" % self.manifest)

    def warn(self, msg):  # suppress missing-file warnings from sdist
        if not msg.startswith("standard file not found:"):
            sdist.warn(self, msg)

    def add_defaults(self):
        sdist.add_defaults(self)
        self.filelist.append(self.template)
        self.filelist.append(self.manifest)
        rcfiles = list(walk_revctrl())
        if rcfiles:
            self.filelist.extend(rcfiles)
        elif os.path.exists(self.manifest):
            self.read_manifest()
        ei_cmd = self.get_finalized_command('egg_info')
        self.filelist.include_pattern("*", prefix=ei_cmd.egg_info)

    def prune_file_list(self):
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()
        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)
        sep = re.escape(os.sep)
        self.filelist.exclude_pattern(sep + r'(RCS|CVS|\.svn)' + sep,
                                      is_regex=1)
Beispiel #18
0
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    def checking_metadata(self):
        """Callable used for the check sub-command.

        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm',
         "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None,
         "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None,
         "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None,
         "don't automatically exclude anything"),
        ('manifest-only', 'o',
         "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual. "
         "Deprecated: now the manifest is always regenerated."),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ('metadata-check', None,
         "Ensure that all required elements of meta-data "
         "are supplied. Warn if any missing. [default]"),
        ('owner=', 'u',
         "Owner name used when creating a tar file [default: current user]"),
        ('group=', 'g',
         "Group name used when creating a tar file [default: current group]"),
        ]

    boolean_options = ['use-defaults', 'prune',
                       'manifest-only', 'force-manifest',
                       'keep-temp', 'metadata-check']

    help_options = [
        ('help-formats', None,
         "list available distribution formats", show_formats),
        ]

    negative_opt = {'no-defaults': 'use-defaults',
                    'no-prune': 'prune' }

    sub_commands = [('check', checking_metadata)]

    READMES = ('README', 'README.txt', 'README.rst')

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = ['gztar']
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError(
                  "unknown archive format '%s'" % bad_format)

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):
        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Run sub commands
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn("distutils.command.sdist.check_metadata is deprecated, \
              use the check command instead", PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        # new behavior when using a template:
        # the file list is recalculated every time because
        # even if MANIFEST.in or setup.py are not changed
        # the user might have added some files in the tree that
        # need to be included.
        #
        #  This makes --force the default and only behavior with templates.
        template_exists = os.path.isfile(self.template)
        if not template_exists and self._manifest_is_not_generated():
            self.read_manifest()
            self.filelist.sort()
            self.filelist.remove_duplicates()
            return

        if not template_exists:
            self.warn(("manifest template '%s' does not exist " +
                        "(using default file list)") %
                        self.template)
        self.filelist.findall()

        if self.use_defaults:
            self.add_defaults()

        if template_exists:
            self.read_template()

        if self.prune:
            self.prune_file_list()

        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """
        self._add_defaults_standards()
        self._add_defaults_optional()
        self._add_defaults_python()
        self._add_defaults_data_files()
        self._add_defaults_ext()
        self._add_defaults_c_libs()
        self._add_defaults_scripts()

    @staticmethod
    def _cs_path_exists(fspath):
        """
        Case-sensitive path existence check

        >>> sdist._cs_path_exists(__file__)
        True
        >>> sdist._cs_path_exists(__file__.upper())
        False
        """
        if not os.path.exists(fspath):
            return False
        # make absolute so we always have a directory
        abspath = os.path.abspath(fspath)
        directory, filename = os.path.split(abspath)
        return filename in os.listdir(directory)

    def _add_defaults_standards(self):
        standards = [self.READMES, self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = False
                for fn in alts:
                    if self._cs_path_exists(fn):
                        got_it = True
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              ', '.join(alts))
            else:
                if self._cs_path_exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

    def _add_defaults_optional(self):
        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            self.filelist.extend(files)

    def _add_defaults_python(self):
        # build_py is used to get:
        #  - python modules
        #  - files defined in package_data
        build_py = self.get_finalized_command('build_py')

        # getting python files
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())

        # getting package_data files
        # (computed in build_py.data_files by build_py.finalize_options)
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

    def _add_defaults_data_files(self):
        # getting distribution.data_files
        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):
                    # plain file
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:
                    # a (dirname, filenames) tuple
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

    def _add_defaults_ext(self):
        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

    def _add_defaults_c_libs(self):
        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

    def _add_defaults_scripts(self):
        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template, strip_comments=1, skip_blanks=1,
                            join_lines=1, lstrip_ws=1, rstrip_ws=1,
                            collapse_join=1)

        try:
            while True:
                line = template.readline()
                if line is None:            # end of file
                    break

                try:
                    self.filelist.process_template_line(line)
                # the call above can raise a DistutilsTemplateError for
                # malformed lines, or a ValueError from the lower-level
                # convert_path function
                except (DistutilsTemplateError, ValueError) as msg:
                    self.warn("%s, line %d: %s" % (template.filename,
                                                   template.current_line,
                                                   msg))
        finally:
            template.close()

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()

        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)

        if sys.platform == 'win32':
            seps = r'/|\\'
        else:
            seps = '/'

        vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
                    '_darcs']
        vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        if self._manifest_is_not_generated():
            log.info("not writing to manually maintained "
                     "manifest file '%s'" % self.manifest)
            return

        content = self.filelist.files[:]
        content.insert(0, '# file GENERATED by distutils, do NOT edit')
        self.execute(file_util.write_file, (self.manifest, content),
                     "writing manifest file '%s'" % self.manifest)

    def _manifest_is_not_generated(self):
        # check for special comment used in 3.1.3 and higher
        if not os.path.isfile(self.manifest):
            return False

        fp = open(self.manifest)
        try:
            first_line = fp.readline()
        finally:
            fp.close()
        return first_line != '# file GENERATED by distutils, do NOT edit\n'

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        with open(self.manifest) as manifest:
            for line in manifest:
                # ignore comments and blank lines
                line = line.strip()
                if line.startswith('#') or not line:
                    continue
                self.filelist.append(line)

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        # Create all the directories under 'base_dir' necessary to
        # put 'files' there; the 'mkpath()' is just so we don't die
        # if the manifest happens to be empty.
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)

        # And walk over the list of files, either making a hard link (if
        # os.link exists) to each one that doesn't already exist in its
        # corresponding location under 'base_dir', or copying each file
        # that's out-of-date in 'base_dir'.  (Usually, all files will be
        # out-of-date, because by default we blow away 'base_dir' when
        # we're done making the distribution archives.)

        if hasattr(os, 'link'):        # can make hard links on this system
            link = 'hard'
            msg = "making hard links in %s..." % base_dir
        else:                           # nope, have to copy
            link = None
            msg = "copying files to %s..." % base_dir

        if not files:
            log.warn("no files to distribute -- empty manifest?")
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping", file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        # Don't warn about missing meta-data here -- should be (and is!)
        # done elsewhere.
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)

        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []              # remember names of files we create
        # tar archive must be created last to avoid overwrite and remove
        if 'tar' in self.formats:
            self.formats.append(self.formats.pop(self.formats.index('tar')))

        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir,
                                     owner=self.owner, group=self.group)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files

        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
Beispiel #19
0
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    def checking_metadata(self):
        """Callable used for the check sub-command.

        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm',
         "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None,
         "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None,
         "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None,
         "don't automatically exclude anything"),
        ('manifest-only', 'o',
         "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual. "
         "Deprecated: now the manifest is always regenerated."),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ('metadata-check', None,
         "Ensure that all required elements of meta-data "
         "are supplied. Warn if any missing. [default]"),
        ('owner=', 'u',
         "Owner name used when creating a tar file [default: current user]"),
        ('group=', 'g',
         "Group name used when creating a tar file [default: current group]"),
        ]

    boolean_options = ['use-defaults', 'prune',
                       'manifest-only', 'force-manifest',
                       'keep-temp', 'metadata-check']

    help_options = [
        ('help-formats', None,
         "list available distribution formats", show_formats),
        ]

    negative_opt = {'no-defaults': 'use-defaults',
                    'no-prune': 'prune' }

    default_format = {'posix': 'gztar',
                      'nt': 'zip' }

    sub_commands = [('check', checking_metadata)]

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError, \
                      "don't know how to create source distributions " + \
                      "on platform %s" % os.name

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError, \
                  "unknown archive format '%s'" % bad_format

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):
        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Run sub commands
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn("distutils.command.sdist.check_metadata is deprecated, \
              use the check command instead", PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        # new behavior:
        # the file list is recalculated everytime because
        # even if MANIFEST.in or setup.py are not changed
        # the user might have added some files in the tree that
        # need to be included.
        #
        #  This makes --force the default and only behavior.
        template_exists = os.path.isfile(self.template)
        if not template_exists:
            self.warn(("manifest template '%s' does not exist " +
                        "(using default file list)") %
                        self.template)
        self.filelist.findall()

        if self.use_defaults:
            self.add_defaults()

        if template_exists:
            self.read_template()

        if self.prune:
            self.prune_file_list()

        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """

        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              string.join(alts, ', '))
            else:
                if os.path.exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        # build_py is used to get:
        #  - python modules
        #  - files defined in package_data
        build_py = self.get_finalized_command('build_py')

        # getting python files
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())

        # getting package_data files
        # (computed in build_py.data_files by build_py.finalize_options)
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        # getting distribution.data_files
        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str): # plain file
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:    # a (dirname, filenames) tuple
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template,
                            strip_comments=1,
                            skip_blanks=1,
                            join_lines=1,
                            lstrip_ws=1,
                            rstrip_ws=1,
                            collapse_join=1)

        while 1:
            line = template.readline()
            if line is None:            # end of file
                break

            try:
                self.filelist.process_template_line(line)
            except DistutilsTemplateError, msg:
                self.warn("%s, line %d: %s" % (template.filename,
                                               template.current_line,
                                               msg))
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    def checking_metadata(self):
        """Callable used for the check sub-command.

        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [
        ('template=', 't',
         "name of manifest template file [default: MANIFEST.in]"),
        ('manifest=', 'm',
         "name of manifest file [default: MANIFEST]"),
        ('use-defaults', None,
         "include the default file set in the manifest "
         "[default; disable with --no-defaults]"),
        ('no-defaults', None,
         "don't include the default file set"),
        ('prune', None,
         "specifically exclude files/directories that should not be "
         "distributed (build tree, RCS/CVS dirs, etc.) "
         "[default; disable with --no-prune]"),
        ('no-prune', None,
         "don't automatically exclude anything"),
        ('manifest-only', 'o',
         "just regenerate the manifest and then stop "
         "(implies --force-manifest)"),
        ('force-manifest', 'f',
         "forcibly regenerate the manifest and carry on as usual"),
        ('formats=', None,
         "formats for source distribution (comma-separated list)"),
        ('keep-temp', 'k',
         "keep the distribution tree around after creating " +
         "archive file(s)"),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ('medata-check', None,
         "Ensure that all required elements of meta-data "
         "are supplied. Warn if any missing. [default]"),
        ]

    boolean_options = ['use-defaults', 'prune',
                       'manifest-only', 'force-manifest',
                       'keep-temp', 'metadata-check']

    help_options = [
        ('help-formats', None,
         "list available distribution formats", show_formats),
        ]

    negative_opt = {'no-defaults': 'use-defaults',
                    'no-prune': 'prune' }

    default_format = {'posix': 'gztar',
                      'nt': 'zip' }

    sub_commands = [('check', checking_metadata)]

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None
        self.metadata_check = 1

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError(
                      "don't know how to create source distributions "
                      "on platform %s" % os.name)

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError(
                  "unknown archive format '%s'" % bad_format)

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):
        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Run sub commands
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn("distutils.command.sdist.check_metadata is deprecated, \
              use the check command instead", PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options and the state of the filesystem.
        """
        # If we have a manifest template, see if it's newer than the
        # manifest; if so, we'll regenerate the manifest.
        template_exists = os.path.isfile(self.template)
        if template_exists:
            template_newer = dep_util.newer(self.template, self.manifest)

        # The contents of the manifest file almost certainly depend on the
        # setup script as well as the manifest template -- so if the setup
        # script is newer than the manifest, we'll regenerate the manifest
        # from the template.  (Well, not quite: if we already have a
        # manifest, but there's no template -- which will happen if the
        # developer elects to generate a manifest some other way -- then we
        # can't regenerate the manifest, so we don't.)
        self.debug_print("checking if %s newer than %s" %
                         (self.distribution.script_name, self.manifest))
        setup_newer = dep_util.newer(self.distribution.script_name,
                                     self.manifest)

        # cases:
        #   1) no manifest, template exists: generate manifest
        #      (covered by 2a: no manifest == template newer)
        #   2) manifest & template exist:
        #      2a) template or setup script newer than manifest:
        #          regenerate manifest
        #      2b) manifest newer than both:
        #          do nothing (unless --force or --manifest-only)
        #   3) manifest exists, no template:
        #      do nothing (unless --force or --manifest-only)
        #   4) no manifest, no template: generate w/ warning ("defaults only")

        manifest_outofdate = (template_exists and
                              (template_newer or setup_newer))
        force_regen = self.force_manifest or self.manifest_only
        manifest_exists = os.path.isfile(self.manifest)
        neither_exists = (not template_exists and not manifest_exists)

        # Regenerate the manifest if necessary (or if explicitly told to)
        if manifest_outofdate or neither_exists or force_regen:
            if not template_exists:
                self.warn("manifest template '%s' does not exist "
                          "(using default file list)"
                          % self.template)
            self.filelist.findall()

            if self.use_defaults:
                self.add_defaults()
            if template_exists:
                self.read_template()
            if self.prune:
                self.prune_file_list()

            self.filelist.sort()
            self.filelist.remove_duplicates()
            self.write_manifest()

        # Don't regenerate the manifest, just read it in.
        else:
            self.read_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """
        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = False
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = True
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " +
                              ', '.join(alts))
            else:
                if os.path.exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        # build_py is used to get:
        #  - python modules
        #  - files defined in package_data
        build_py = self.get_finalized_command('build_py')

        # getting python files
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())

        # getting package_data files
        # (computed in build_py.data_files by build_py.finalize_options)
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        # getting distribution.data_files
        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str): # plain file
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:    # a (dirname, filenames) tuple
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())

        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())

        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template, strip_comments=1, skip_blanks=1,
                            join_lines=1, lstrip_ws=1, rstrip_ws=1,
                            collapse_join=1)

        while True:
            line = template.readline()
            if line is None:            # end of file
                break

            try:
                self.filelist.process_template_line(line)
            except DistutilsTemplateError as msg:
                self.warn("%s, line %d: %s" % (template.filename,
                                               template.current_line,
                                               msg))

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()

        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)

        if sys.platform == 'win32':
            seps = r'/|\\'
        else:
            seps = '/'

        vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
                    '_darcs']
        vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        self.execute(file_util.write_file,
                     (self.manifest, self.filelist.files),
                     "writing manifest file '%s'" % self.manifest)

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        while True:
            line = manifest.readline()
            if line == '':              # end of file
                break
            if line[-1] == '\n':
                line = line[0:-1]
            self.filelist.append(line)
        manifest.close()

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        # Create all the directories under 'base_dir' necessary to
        # put 'files' there; the 'mkpath()' is just so we don't die
        # if the manifest happens to be empty.
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)

        # And walk over the list of files, either making a hard link (if
        # os.link exists) to each one that doesn't already exist in its
        # corresponding location under 'base_dir', or copying each file
        # that's out-of-date in 'base_dir'.  (Usually, all files will be
        # out-of-date, because by default we blow away 'base_dir' when
        # we're done making the distribution archives.)

        if hasattr(os, 'link'):        # can make hard links on this system
            link = 'hard'
            msg = "making hard links in %s..." % base_dir
        else:                           # nope, have to copy
            link = None
            msg = "copying files to %s..." % base_dir

        if not files:
            log.warn("no files to distribute -- empty manifest?")
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping" % file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        # Don't warn about missing meta-data here -- should be (and is!)
        # done elsewhere.
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)

        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []              # remember names of files we create
        # tar archive must be created last to avoid overwrite and remove
        if 'tar' in self.formats:
            self.formats.append(self.formats.pop(self.formats.index('tar')))

        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files

        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
    def copy_transformed_tree(self, install_specs, dst_root=None, src_root=None, substitutions={}):
        """
        Copy parts of a source tree to a destination tree with a
        different tree structure and/or names.

        The basic idea: given a set of source files, copy them to a
        destination directory, let's call this operation an
        install_spec. A sequence of install_spec's allows one to build
        up the destrination tree in any structure desired.

        Each install_spec consists of 3 components
        (manifest_template, dst_xforms, dst_dir):

        The manifest_template is a sequence where each item is identical
        to a line in the MANIFEST.in template described in distutils. This
        gives you ability to easily specify a set of source files in a
        compact abstract manner (with recursion, exclusion, etc.) The
        manifest_template yields a sequence of source paths.

        dst_xforms is a sequence of regular expression substitutions
        applied to the each source path to yield a rewritten destination
        path. Each transform is expressed as a two-valued sequence
        (pattern, replacement)

        dst_dir is a destination directory where the destinations paths
        are written to. dst_dir is always relative to the dst_root.

        All input may be parametrized via variable substitutions
        supplied by a substitution dict. Any use of $name will cause
        name to be looked up first in the substitution dict and then
        if its not found there in the enviorment. If found it will be
        replaced with it's value.

        The pseudo code algorithm for processing an install_spec is:

        substitute all variables in manifest template
        src_list = evaluate manifest template
        for each src_path in src_list:
            dst_path = src_path
            for each xform in dst_xform:
                apply xform to dst_path
            copy src_root+src_path to dst_root+dest_dir+dest_path

        This process is repeated for each install spec. The src_root and
        dst_root are also subject to variable substitution.


        Examples:

        Copy all text files in build/doc to doc:

            copy_transformed_tree([[["include build/doc *.txt"], None, 'doc']])

        Copy all html files found under build to doc/html and change the extension from
        .html to .htm

            copy_transformed_tree([[["include build *.html"], [('\.html$','.htm')], 'doc']])

    """

        if src_root is not None: src_root = subst_vars(src_root, substitutions)
        if dst_root is not None: dst_root = subst_vars(dst_root, substitutions)

        filelist = FileList()
        if src_root is None:
            filelist.findall()
        else:
            filelist.findall(src_root)

        for manifest_template, dst_xforms, dst_dir in install_specs:
            if dst_dir is not None: dst_dir = subst_vars(dst_dir, substitutions)

            filelist.files = [] # reinitialize to empty

            for line in manifest_template:
                filelist.process_template_line(subst_vars(line, substitutions))

            for src_path in filelist.files:
                dst_path = src_path
                if dst_xforms:
                    for dst_xform in dst_xforms:
                        dst_path = re.sub(dst_xform[0], dst_xform[1], dst_path)
                if dst_dir is not None:
                    dst_path = change_root(dst_dir, dst_path)
                if dst_root is None:
                    full_dst_path = dst_path
                else:
                    full_dst_path = change_root(dst_root, dst_path)
                full_dst_dir = os.path.dirname(full_dst_path)
                self.mkpath(full_dst_dir)
                self.copy_file(src_path, full_dst_path)
class sdist(Command):
    description = 'create a source distribution (tarball, zip file, etc.)'

    def checking_metadata(self):
        return self.metadata_check

    user_options = [('template=', 't', 'name of manifest template file [default: MANIFEST.in]'),
     ('manifest=', 'm', 'name of manifest file [default: MANIFEST]'),
     ('use-defaults', None, 'include the default file set in the manifest [default; disable with --no-defaults]'),
     ('no-defaults', None, "don't include the default file set"),
     ('prune', None, 'specifically exclude files/directories that should not be distributed (build tree, RCS/CVS dirs, etc.) [default; disable with --no-prune]'),
     ('no-prune', None, "don't automatically exclude anything"),
     ('manifest-only', 'o', 'just regenerate the manifest and then stop (implies --force-manifest)'),
     ('force-manifest', 'f', 'forcibly regenerate the manifest and carry on as usual. Deprecated: now the manifest is always regenerated.'),
     ('formats=', None, 'formats for source distribution (comma-separated list)'),
     ('keep-temp', 'k', 'keep the distribution tree around after creating ' + 'archive file(s)'),
     ('dist-dir=', 'd', 'directory to put the source distribution archive(s) in [default: dist]'),
     ('metadata-check', None, 'Ensure that all required elements of meta-data are supplied. Warn if any missing. [default]'),
     ('owner=', 'u', 'Owner name used when creating a tar file [default: current user]'),
     ('group=', 'g', 'Group name used when creating a tar file [default: current group]')]
    boolean_options = ['use-defaults',
     'prune',
     'manifest-only',
     'force-manifest',
     'keep-temp',
     'metadata-check']
    help_options = [('help-formats',
      None,
      'list available distribution formats',
      show_formats)]
    negative_opt = {'no-defaults': 'use-defaults',
     'no-prune': 'prune'}
    default_format = {'posix': 'gztar',
     'nt': 'zip'}
    sub_commands = [('check', checking_metadata)]

    def initialize_options(self):
        self.template = None
        self.manifest = None
        self.use_defaults = 1
        self.prune = 1
        self.manifest_only = 0
        self.force_manifest = 0
        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None
        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None
        return

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = 'MANIFEST'
        if self.template is None:
            self.template = 'MANIFEST.in'
        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError, "don't know how to create source distributions " + 'on platform %s' % os.name

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError, "unknown archive format '%s'" % bad_format
        if self.dist_dir is None:
            self.dist_dir = 'dist'
        return

    def run(self):
        self.filelist = FileList()
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        self.get_file_list()
        if self.manifest_only:
            return
        self.make_distribution()

    def check_metadata(self):
        warn('distutils.command.sdist.check_metadata is deprecated,               use the check command instead', PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        template_exists = os.path.isfile(self.template)
        if not template_exists and self._manifest_is_not_generated():
            self.read_manifest()
            self.filelist.sort()
            self.filelist.remove_duplicates()
            return
        if not template_exists:
            self.warn(("manifest template '%s' does not exist " + '(using default file list)') % self.template)
        self.filelist.findall()
        if self.use_defaults:
            self.add_defaults()
        if template_exists:
            self.read_template()
        if self.prune:
            self.prune_file_list()
        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn('standard file not found: should have one of ' + string.join(alts, ', '))
            if os.path.exists(fn):
                self.filelist.append(fn)
            self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        build_py = self.get_finalized_command('build_py')
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                dirname, filenames = item
                for f in filenames:
                    f = convert_path(f)
                    if os.path.isfile(f):
                        self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())
        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())
        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1)
        try:
            while 1:
                line = template.readline()
                if line is None:
                    break
                try:
                    self.filelist.process_template_line(line)
                except (DistutilsTemplateError, ValueError) as msg:
                    self.warn('%s, line %d: %s' % (template.filename, template.current_line, msg))

        finally:
            template.close()

        return

    def prune_file_list(self):
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()
        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)
        if sys.platform == 'win32':
            seps = '/|\\\\'
        else:
            seps = '/'
        vcs_dirs = ['RCS',
         'CVS',
         '\\.svn',
         '\\.hg',
         '\\.git',
         '\\.bzr',
         '_darcs']
        vcs_ptrn = '(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
        return

    def write_manifest(self):
        if self._manifest_is_not_generated():
            log.info("not writing to manually maintained manifest file '%s'" % self.manifest)
            return
        content = self.filelist.files[:]
        content.insert(0, '# file GENERATED by distutils, do NOT edit')
        self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest)

    def _manifest_is_not_generated(self):
        if not os.path.isfile(self.manifest):
            return False
        fp = open(self.manifest, 'rU')
        try:
            first_line = fp.readline()
        finally:
            fp.close()

        return first_line != '# file GENERATED by distutils, do NOT edit\n'

    def read_manifest(self):
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        for line in manifest:
            line = line.strip()
            if line.startswith('#') or not line:
                continue
            self.filelist.append(line)

        manifest.close()

    def make_release_tree(self, base_dir, files):
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
        if hasattr(os, 'link'):
            link = 'hard'
            msg = 'making hard links in %s...' % base_dir
        else:
            link = None
            msg = 'copying files to %s...' % base_dir
        if not files:
            log.warn('no files to distribute -- empty manifest?')
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping" % file)
            dest = os.path.join(base_dir, file)
            self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)
        return

    def make_distribution(self):
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)
        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []
        if 'tar' in self.formats:
            self.formats.append(self.formats.pop(self.formats.index('tar')))
        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files
        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        return self.archive_files
Beispiel #23
0
class sdist(Command):

    description = "create a source distribution (tarball, zip file, etc.)"

    def checking_metadata(self):
        """Callable used for the check sub-command.

        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [
        ("template=", "t", "name of manifest template file [default: MANIFEST.in]"),
        ("manifest=", "m", "name of manifest file [default: MANIFEST]"),
        ("use-defaults", None, "include the default file set in the manifest " "[default; disable with --no-defaults]"),
        ("no-defaults", None, "don't include the default file set"),
        (
            "prune",
            None,
            "specifically exclude files/directories that should not be "
            "distributed (build tree, RCS/CVS dirs, etc.) "
            "[default; disable with --no-prune]",
        ),
        ("no-prune", None, "don't automatically exclude anything"),
        ("manifest-only", "o", "just regenerate the manifest and then stop " "(implies --force-manifest)"),
        (
            "force-manifest",
            "f",
            "forcibly regenerate the manifest and carry on as usual. "
            "Deprecated: now the manifest is always regenerated.",
        ),
        ("formats=", None, "formats for source distribution (comma-separated list)"),
        ("keep-temp", "k", "keep the distribution tree around after creating " + "archive file(s)"),
        ("dist-dir=", "d", "directory to put the source distribution archive(s) in " "[default: dist]"),
        (
            "metadata-check",
            None,
            "Ensure that all required elements of meta-data " "are supplied. Warn if any missing. [default]",
        ),
    ]

    boolean_options = ["use-defaults", "prune", "manifest-only", "force-manifest", "keep-temp", "metadata-check"]

    help_options = [("help-formats", None, "list available distribution formats", show_formats)]

    negative_opt = {"no-defaults": "use-defaults", "no-prune": "prune"}

    default_format = {"posix": "gztar", "nt": "zip"}

    sub_commands = [("check", checking_metadata)]

    def initialize_options(self):
        # 'template' and 'manifest' are, respectively, the names of
        # the manifest template and manifest file.
        self.template = None
        self.manifest = None

        # 'use_defaults': if true, we will include the default file set
        # in the manifest
        self.use_defaults = 1
        self.prune = 1

        self.manifest_only = 0
        self.force_manifest = 0

        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None

        self.archive_files = None
        self.metadata_check = 1

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = "MANIFEST"
        if self.template is None:
            self.template = "MANIFEST.in"

        self.ensure_string_list("formats")
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError(
                    "don't know how to create source distributions " "on platform %s" % os.name
                )

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError("unknown archive format '%s'" % bad_format)

        if self.dist_dir is None:
            self.dist_dir = "dist"

    def run(self):
        # 'filelist' contains the list of files that will make up the
        # manifest
        self.filelist = FileList()

        # Run sub commands
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        # Do whatever it takes to get the list of files to process
        # (process the manifest template, read an existing manifest,
        # whatever).  File list is accumulated in 'self.filelist'.
        self.get_file_list()

        # If user just wanted us to regenerate the manifest, stop now.
        if self.manifest_only:
            return

        # Otherwise, go ahead and create the source distribution tarball,
        # or zipfile, or whatever.
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn(
            "distutils.command.sdist.check_metadata is deprecated, \
              use the check command instead",
            PendingDeprecationWarning,
        )
        check = self.distribution.get_command_obj("check")
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        # new behavior:
        # the file list is recalculated everytime because
        # even if MANIFEST.in or setup.py are not changed
        # the user might have added some files in the tree that
        # need to be included.
        #
        #  This makes --force the default and only behavior.
        template_exists = os.path.isfile(self.template)
        if not template_exists:
            self.warn(("manifest template '%s' does not exist " + "(using default file list)") % self.template)
        self.filelist.findall()

        if self.use_defaults:
            self.add_defaults()

        if template_exists:
            self.read_template()

        if self.prune:
            self.prune_file_list()

        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """
        standards = [("README", "README.txt"), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = False
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = True
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn("standard file not found: should have one of " + ", ".join(alts))
            else:
                if os.path.exists(fn):
                    self.filelist.append(fn)
                else:
                    self.warn("standard file '%s' not found" % fn)

        optional = ["test/test*.py", "setup.cfg"]
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            self.filelist.extend(files)

        # build_py is used to get:
        #  - python modules
        #  - files defined in package_data
        build_py = self.get_finalized_command("build_py")

        # getting python files
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())

        # getting package_data files
        # (computed in build_py.data_files by build_py.finalize_options)
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        # getting distribution.data_files
        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):  # plain file
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:  # a (dirname, filenames) tuple
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command("build_ext")
            self.filelist.extend(build_ext.get_source_files())

        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command("build_clib")
            self.filelist.extend(build_clib.get_source_files())

        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command("build_scripts")
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.

        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(
            self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1
        )

        while True:
            line = template.readline()
            if line is None:  # end of file
                break

            try:
                self.filelist.process_template_line(line)
            except DistutilsTemplateError as msg:
                self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg))

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command("build")
        base_dir = self.distribution.get_fullname()

        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)

        if sys.platform == "win32":
            seps = r"/|\\"
        else:
            seps = "/"

        vcs_dirs = ["RCS", "CVS", r"\.svn", r"\.hg", r"\.git", r"\.bzr", "_darcs"]
        vcs_ptrn = r"(^|%s)(%s)(%s).*" % (seps, "|".join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        if os.path.isfile(self.manifest):
            fp = open(self.manifest)
            try:
                first_line = fp.readline()
            finally:
                fp.close()

            if first_line != "# file GENERATED by distutils, do NOT edit\n":
                log.info("not writing to manually maintained " "manifest file '%s'" % self.manifest)
                return

        content = self.filelist.files[:]
        content.insert(0, "# file GENERATED by distutils, do NOT edit")
        self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest)

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        while True:
            line = manifest.readline()
            if line == "":  # end of file
                break
            if line[-1] == "\n":
                line = line[0:-1]
            self.filelist.append(line)
        manifest.close()

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        # Create all the directories under 'base_dir' necessary to
        # put 'files' there; the 'mkpath()' is just so we don't die
        # if the manifest happens to be empty.
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)

        # And walk over the list of files, either making a hard link (if
        # os.link exists) to each one that doesn't already exist in its
        # corresponding location under 'base_dir', or copying each file
        # that's out-of-date in 'base_dir'.  (Usually, all files will be
        # out-of-date, because by default we blow away 'base_dir' when
        # we're done making the distribution archives.)

        if hasattr(os, "link"):  # can make hard links on this system
            link = "hard"
            msg = "making hard links in %s..." % base_dir
        else:  # nope, have to copy
            link = None
            msg = "copying files to %s..." % base_dir

        if not files:
            log.warn("no files to distribute -- empty manifest?")
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping" % file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        # Don't warn about missing meta-data here -- should be (and is!)
        # done elsewhere.
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)

        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []  # remember names of files we create
        # tar archive must be created last to avoid overwrite and remove
        if "tar" in self.formats:
            self.formats.append(self.formats.pop(self.formats.index("tar")))

        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir)
            archive_files.append(file)
            self.distribution.dist_files.append(("sdist", "", file))

        self.archive_files = archive_files

        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
Beispiel #24
0
	def finalize_options(self):
		distutils.dist.Distribution.finalize_options(self)

		cfg = ConfigParser()
		name = sys.platform
		config_name = os.path.join('config', name + '.cfg')
		while len(name) and not os.path.exists(config_name):
			name = name[:-1]
			config_name = os.path.join('config', name + '.cfg')

		if not os.path.exists(config_name):
			print "Can't find a config file for the \"%s\" platform.  Look in the config directory." % sys.platform
			sys.exit(1)

		try:
			self.announce( "Using cfg file: %s"%( config_name,))
			cfg.read(config_name)
		except ParsingError:
			print "parse error in config file."
			sys.exit(1)

		self.lib_aliases = {}

		for section in cfg.sections():
			if section != 'General':
				try:
					self.lib_aliases[section] = config_list(cfg.get(section, 'libs'))
				except:
					pass

		try:
			self.include_dirs = config_list(cfg.get('General', 'include_dirs'))
		except:
			self.include_dirs = []

		try:
			self.library_dirs = config_list(cfg.get('General', 'library_dirs'))
		except:
			self.library_dirs = []

		try:
			self.BUILD_TOGL = cfg.getint('General', 'build_togl')
		except:
			self.BUILD_TOGL = 0
			
		try:
			self.extra_link_args = config_list(cfg.get('General', 'extra_link_args'))
		except:
			self.extra_link_args = []

		try:
			self.define_macros = [(string.upper(string.strip(cfg.get('General', 'gl_platform'))) + '_PLATFORM', None)]
			self.gl_platform = cfg.get('General', 'gl_platform')
		except:
			self.define_macros = []
			print 'No gl_platform defined in the config file "%s"' % config_name

		self.togl_libs = self.transform_libs(['GL', 'GLU', 'Togl'])

##		build_togl = self.get_command_obj( 'build_togl' )
##		for field in ('tk-source','tcl-source'):
##			if not getattr(build_togl, field, None):
##				try:
##					setattr(build_togl, field.replace('-','_'), cfg.get('Togl', field))
##				except:
##					pass
		
		try:
			import Numeric
			include_dirs = find_file(get_python_inc(), 'arrayobject.h')
			if not len(include_dirs):
				self.announce("Successfully imported Numeric, but can't find the Numeric headers!")
				self.HAS_NUMERIC = 0
			else:
				self.include_dirs = self.include_dirs + include_dirs
				self.HAS_NUMERIC = 1
		except ImportError:
			self.HAS_NUMERIC = 0

		if self.HAS_NUMERIC:
			Numeric_version = 'yes'
			self.define_macros.append(('NUMERIC', None))
			try:
				import numeric_version
				Numeric_version = numeric_version.version
##				if int(string.split(Numeric_version, '.')[0]) == 20:
##					self.announce('Numeric %s is present...beware!  This is buggy!')
			except:
				pass
		else:
			Numeric_version = 'no'

		boolean = ['no', 'yes']

		self.announce('PyOpenGL %s setup' % self.get_version())
		self.announce('')
		self.announce('System configuration:')
		self.announce('    Platform    = %s' % sys.platform)
		self.announce('    GL Platform = %s' % self.gl_platform)
		self.announce('    Numeric     = %s' % Numeric_version)
		self.announce('    Build Togl  = %s' % boolean[self.BUILD_TOGL])
		self.announce('')

		# get the list of platforms
		self.announce('Getting the list of platforms...')
		self.metadata.platforms = []
		f = FileList()
		f.findall('config')
		f.process_template_line('global-include *.cfg')
		for file in f.files:
			self.metadata.platforms.append(os.path.splitext(os.path.split(file)[1])[0])

		# get the list of packages for this platform
		self.announce('Getting the list of packages...')
		if self.packages is None:
			self.packages = []
		f = FileList()
		# first the real packages
		if os.path.exists('OpenGL'):
			f.findall('OpenGL')
			f.process_template_line('global-include __init__.py')
			# second the Demo's
			Demo = os.path.join('OpenGL', 'Demo')
			if os.path.exists(Demo):
				f.findall(Demo)
				f.process_template_line('global-include *.py')
			# last the scripts
			scripts = os.path.join('OpenGL', 'scripts')
			if os.path.exists(scripts):
				f.findall(scripts)
				f.process_template_line('global-include *.py')
		for file in f.files:
			package = string.replace(os.path.dirname(file), os.sep, '.')
			if package not in self.packages:
				g = {'__name__':'__build__'}
				l = {}
				try:
					exec open(file) in g, l
				except:
					pass
				if not l.has_key('gl_platforms') or self.gl_platform in l['gl_platforms']:
					self.packages.append(package)

		# get the list of extension modules for this platform
		self.announce('Getting the list of extension modules...')
		if self.ext_modules is None:
			self.ext_modules = []

		f = FileList()
		f.findall('interface')
		f.process_template_line('global-include *.i')
		if not len(f.files):
			print "Whoa!  I can't find any interfaces...panic!"
			sys.exit()

		f.files.sort()
		for file in f.files:
			BUILD = get_build_info(file)
			actual_libs = []

			if not BUILD.has_key('gl_platforms') or self.gl_platform in BUILD['gl_platforms']:
				# everything requires GL and GLU
				libs = ['GL', 'GLU']
				if BUILD.has_key('libs'):
					libs.extend(BUILD['libs'])


				directory,name = os.path.split( os.path.splitext(file)[0] )
				module = ".".join(
					directory.split( os.sep)[1:] +
					[ '_'+ name ],
				)

				BUILD['sources'].append('src/interface/' + module + '.c')
				self.ext_modules.append(Extension(module,
												  BUILD['sources'],
												  include_dirs = BUILD['include_dirs'],
												  define_macros = self.define_macros,
												  libraries = self.transform_libs(libs),
												  library_dirs = self.library_dirs,
												  extra_link_args = self.extra_link_args))

#		print self.libraries
		l = []
		for i in range(len(self.libraries)):
			d = self.libraries[i][1]
			d['include_dirs'] = [get_python_inc()] + self.include_dirs
			d['macros'] = self.define_macros
			l.append((self.libraries[i][0], d))
		self.libraries = l
Beispiel #25
0
"""distutils.command.sdist
Beispiel #26
0
    def copy_transformed_tree(self, install_specs, dst_root=None, src_root=None, substitutions={}):
        """
        Copy parts of a source tree to a destination tree with a
        different tree structure and/or names.

        The basic idea: given a set of source files, copy them to a
        destination directory, let's call this operation an
        install_spec. A sequence of install_spec's allows one to build
        up the destrination tree in any structure desired.

        Each install_spec consists of 3 components
        (manifest_template, dst_xforms, dst_dir):

        The manifest_template is a sequence where each item is identical
        to a line in the MANIFEST.in template described in distutils. This
        gives you ability to easily specify a set of source files in a
        compact abstract manner (with recursion, exclusion, etc.) The
        manifest_template yields a sequence of source paths.

        dst_xforms is a sequence of regular expression substitutions
        applied to the each source path to yield a rewritten destination
        path. Each transform is expressed as a two-valued sequence
        (pattern, replacement)

        dst_dir is a destination directory where the destinations paths
        are written to. dst_dir is always relative to the dst_root.

        All input may be parametrized via variable substitutions
        supplied by a substitution dict. Any use of $name will cause
        name to be looked up first in the substitution dict and then
        if its not found there in the enviorment. If found it will be
        replaced with it's value.

        The pseudo code algorithm for processing an install_spec is:

        substitute all variables in manifest template
        src_list = evaluate manifest template
        for each src_path in src_list:
            dst_path = src_path
            for each xform in dst_xform:
                apply xform to dst_path
            copy src_root+src_path to dst_root+dest_dir+dest_path

        This process is repeated for each install spec. The src_root and
        dst_root are also subject to variable substitution.


        Examples:

        Copy all text files in build/doc to doc:

            copy_transformed_tree([[["include build/doc *.txt"], None, 'doc']])

        Copy all html files found under build to doc/html and change the extension from
        .html to .htm

            copy_transformed_tree([[["include build *.html"], [('\.html$','.htm')], 'doc']])

    """

        if src_root is not None: src_root = subst_vars(src_root, substitutions)
        if dst_root is not None: dst_root = subst_vars(dst_root, substitutions)

        filelist = FileList()
        if src_root is None:
            filelist.findall()
        else:
            filelist.findall(src_root)

        for manifest_template, dst_xforms, dst_dir in install_specs:
            if dst_dir is not None: dst_dir = subst_vars(dst_dir, substitutions)

            filelist.files = [] # reinitialize to empty

            for line in manifest_template:
                filelist.process_template_line(subst_vars(line, substitutions))

            for src_path in filelist.files:
                dst_path = src_path
                if dst_xforms:
                    for dst_xform in dst_xforms:
                        dst_path = re.sub(dst_xform[0], dst_xform[1], dst_path)
                if dst_dir is not None:
                    dst_path = change_root(dst_dir, dst_path)
                if dst_root is None:
                    full_dst_path = dst_path
                else:
                    full_dst_path = change_root(dst_root, dst_path)
                full_dst_dir = os.path.dirname(full_dst_path)
                self.mkpath(full_dst_dir)
                self.copy_file(src_path, full_dst_path)
Beispiel #27
0
long_description = """\
tel is a little console-based phone book program. It allows adding,
modifing, editing and searching of phone book entries right on your
terminal. Pretty printing capabilites are also provided.
Entries are stored in simple csv file. This eases import and export with
common spread sheet applications like Microsoft Excel or OpenOffice.org
Calc."""


# gettext source file for i18n
optparse_source = optparse.__file__.rstrip('c')

# collect all python sources for i18n
tel_sources = FileList()
tel_sources.findall('./src')
tel_sources.include_pattern('*.py', anchor=False)


setup(name='tel',
      version=config.version,
      description='A little terminal phone book',
      long_description=long_description,
      author='Sebastian Wiesner',
      author_email='*****@*****.**',
      url='http://tel.lunaryorn.de',
      license='MIT/X11',
      # list packages
      packages=['tel'],
      package_dir={'': 'src'},
      package_data={'tel': ['backends/*.py']},
	# slurp through all the files
	eater = TokenEater(options)
	filelist = FileList()

	for filename in args:
		##rint ">>", filename
		if filename == '-' or (not options.recursive and not (filename.find('*') == -1 or filename.find('?') == -1)):
			##print "pass single"
			pass_file(filename, eater)
		else:
			path, file = os.path.split(filename)
			##print ">> path=%s file=%s" % (path, file)
			if not path: path = os.curdir
			if options.recursive:
				##print ">> findall"
				filelist.findall(path)
				# replace 'file.ext' to './file.ext'
				# we will matching with '*/wildcard.ext'
				for i in range(len(filelist.allfiles)):
					__file = filelist.allfiles[i]
					if not os.path.isabs(__file):   # if not full path, windows or unixx
						filelist.allfiles[i] = '.' + os.sep + __file
			else:
				##print ">> list", list_files(path)
				filelist.set_allfiles(list_files(path))
			##print ">> all files", filelist.allfiles
			##print ">> pattern", file
			filelist.include_pattern(file, anchor=0)
			##print ">> final list", filelist.files

			for file in filelist.files:
Beispiel #29
0
class sdist(Command):
    description = 'create a source distribution (tarball, zip file, etc.)'

    def checking_metadata(self):
        """Callable used for the check sub-command.
        
        Placed here so user_options can view it"""
        return self.metadata_check

    user_options = [('template=', 't', 'name of manifest template file [default: MANIFEST.in]'),
     ('manifest=', 'm', 'name of manifest file [default: MANIFEST]'),
     ('use-defaults', None, 'include the default file set in the manifest [default; disable with --no-defaults]'),
     ('no-defaults', None, "don't include the default file set"),
     ('prune', None, 'specifically exclude files/directories that should not be distributed (build tree, RCS/CVS dirs, etc.) [default; disable with --no-prune]'),
     ('no-prune', None, "don't automatically exclude anything"),
     ('manifest-only', 'o', 'just regenerate the manifest and then stop (implies --force-manifest)'),
     ('force-manifest', 'f', 'forcibly regenerate the manifest and carry on as usual. Deprecated: now the manifest is always regenerated.'),
     ('formats=', None, 'formats for source distribution (comma-separated list)'),
     ('keep-temp', 'k', 'keep the distribution tree around after creating ' + 'archive file(s)'),
     ('dist-dir=', 'd', 'directory to put the source distribution archive(s) in [default: dist]'),
     ('metadata-check', None, 'Ensure that all required elements of meta-data are supplied. Warn if any missing. [default]'),
     ('owner=', 'u', 'Owner name used when creating a tar file [default: current user]'),
     ('group=', 'g', 'Group name used when creating a tar file [default: current group]')]
    boolean_options = ['use-defaults',
     'prune',
     'manifest-only',
     'force-manifest',
     'keep-temp',
     'metadata-check']
    help_options = [('help-formats',
      None,
      'list available distribution formats',
      show_formats)]
    negative_opt = {'no-defaults': 'use-defaults',
     'no-prune': 'prune'}
    default_format = {'posix': 'gztar',
     'nt': 'zip'}
    sub_commands = [('check', checking_metadata)]

    def initialize_options(self):
        self.template = None
        self.manifest = None
        self.use_defaults = 1
        self.prune = 1
        self.manifest_only = 0
        self.force_manifest = 0
        self.formats = None
        self.keep_temp = 0
        self.dist_dir = None
        self.archive_files = None
        self.metadata_check = 1
        self.owner = None
        self.group = None
        return

    def finalize_options(self):
        if self.manifest is None:
            self.manifest = 'MANIFEST'
        if self.template is None:
            self.template = 'MANIFEST.in'
        self.ensure_string_list('formats')
        if self.formats is None:
            try:
                self.formats = [self.default_format[os.name]]
            except KeyError:
                raise DistutilsPlatformError, "don't know how to create source distributions " + 'on platform %s' % os.name

        bad_format = archive_util.check_archive_formats(self.formats)
        if bad_format:
            raise DistutilsOptionError, "unknown archive format '%s'" % bad_format
        if self.dist_dir is None:
            self.dist_dir = 'dist'
        return

    def run(self):
        self.filelist = FileList()
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

        self.get_file_list()
        if self.manifest_only:
            return
        self.make_distribution()

    def check_metadata(self):
        """Deprecated API."""
        warn('distutils.command.sdist.check_metadata is deprecated,               use the check command instead', PendingDeprecationWarning)
        check = self.distribution.get_command_obj('check')
        check.ensure_finalized()
        check.run()

    def get_file_list(self):
        """Figure out the list of files to include in the source
        distribution, and put it in 'self.filelist'.  This might involve
        reading the manifest template (and writing the manifest), or just
        reading the manifest, or just using the default file set -- it all
        depends on the user's options.
        """
        template_exists = os.path.isfile(self.template)
        if not template_exists and self._manifest_is_not_generated():
            self.read_manifest()
            self.filelist.sort()
            self.filelist.remove_duplicates()
            return
        if not template_exists:
            self.warn(("manifest template '%s' does not exist " + '(using default file list)') % self.template)
        self.filelist.findall()
        if self.use_defaults:
            self.add_defaults()
        if template_exists:
            self.read_template()
        if self.prune:
            self.prune_file_list()
        self.filelist.sort()
        self.filelist.remove_duplicates()
        self.write_manifest()

    def add_defaults(self):
        """Add all the default files to self.filelist:
          - README or README.txt
          - setup.py
          - test/test*.py
          - all pure Python modules mentioned in setup script
          - all files pointed by package_data (build_py)
          - all files defined in data_files.
          - all files defined as scripts.
          - all C sources listed as part of extensions or C libraries
            in the setup script (doesn't catch C headers!)
        Warns if (README or README.txt) or setup.py are missing; everything
        else is optional.
        """
        standards = [('README', 'README.txt'), self.distribution.script_name]
        for fn in standards:
            if isinstance(fn, tuple):
                alts = fn
                got_it = 0
                for fn in alts:
                    if os.path.exists(fn):
                        got_it = 1
                        self.filelist.append(fn)
                        break

                if not got_it:
                    self.warn('standard file not found: should have one of ' + string.join(alts, ', '))
            elif os.path.exists(fn):
                self.filelist.append(fn)
            else:
                self.warn("standard file '%s' not found" % fn)

        optional = ['test/test*.py', 'setup.cfg']
        for pattern in optional:
            files = filter(os.path.isfile, glob(pattern))
            if files:
                self.filelist.extend(files)

        build_py = self.get_finalized_command('build_py')
        if self.distribution.has_pure_modules():
            self.filelist.extend(build_py.get_source_files())
        for pkg, src_dir, build_dir, filenames in build_py.data_files:
            for filename in filenames:
                self.filelist.append(os.path.join(src_dir, filename))

        if self.distribution.has_data_files():
            for item in self.distribution.data_files:
                if isinstance(item, str):
                    item = convert_path(item)
                    if os.path.isfile(item):
                        self.filelist.append(item)
                else:
                    dirname, filenames = item
                    for f in filenames:
                        f = convert_path(f)
                        if os.path.isfile(f):
                            self.filelist.append(f)

        if self.distribution.has_ext_modules():
            build_ext = self.get_finalized_command('build_ext')
            self.filelist.extend(build_ext.get_source_files())
        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.filelist.extend(build_clib.get_source_files())
        if self.distribution.has_scripts():
            build_scripts = self.get_finalized_command('build_scripts')
            self.filelist.extend(build_scripts.get_source_files())

    def read_template(self):
        """Read and parse manifest template file named by self.template.
        
        (usually "MANIFEST.in") The parsing and processing is done by
        'self.filelist', which updates itself accordingly.
        """
        log.info("reading manifest template '%s'", self.template)
        template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1)
        try:
            while 1:
                line = template.readline()
                if line is None:
                    break
                try:
                    self.filelist.process_template_line(line)
                except (DistutilsTemplateError, ValueError) as msg:
                    self.warn('%s, line %d: %s' % (template.filename, template.current_line, msg))

        finally:
            template.close()

        return

    def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()
        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)
        if sys.platform == 'win32':
            seps = '/|\\\\'
        else:
            seps = '/'
        vcs_dirs = ['RCS',
         'CVS',
         '\\.svn',
         '\\.hg',
         '\\.git',
         '\\.bzr',
         '_darcs']
        vcs_ptrn = '(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
        return

    def write_manifest(self):
        """Write the file list in 'self.filelist' (presumably as filled in
        by 'add_defaults()' and 'read_template()') to the manifest file
        named by 'self.manifest'.
        """
        if self._manifest_is_not_generated():
            log.info("not writing to manually maintained manifest file '%s'" % self.manifest)
            return
        content = self.filelist.files[:]
        content.insert(0, '# file GENERATED by distutils, do NOT edit')
        self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest)

    def _manifest_is_not_generated(self):
        if not os.path.isfile(self.manifest):
            return False
        fp = open(self.manifest, 'rU')
        try:
            first_line = fp.readline()
        finally:
            fp.close()

        return first_line != '# file GENERATED by distutils, do NOT edit\n'

    def read_manifest(self):
        """Read the manifest file (named by 'self.manifest') and use it to
        fill in 'self.filelist', the list of files to include in the source
        distribution.
        """
        log.info("reading manifest file '%s'", self.manifest)
        manifest = open(self.manifest)
        for line in manifest:
            line = line.strip()
            if line.startswith('#') or not line:
                continue
            self.filelist.append(line)

        manifest.close()

    def make_release_tree(self, base_dir, files):
        """Create the directory tree that will become the source
        distribution archive.  All directories implied by the filenames in
        'files' are created under 'base_dir', and then we hard link or copy
        (if hard linking is unavailable) those files into place.
        Essentially, this duplicates the developer's source tree, but in a
        directory named after the distribution, containing only the files
        to be distributed.
        """
        self.mkpath(base_dir)
        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
        if hasattr(os, 'link'):
            link = 'hard'
            msg = 'making hard links in %s...' % base_dir
        else:
            link = None
            msg = 'copying files to %s...' % base_dir
        if not files:
            log.warn('no files to distribute -- empty manifest?')
        else:
            log.info(msg)
        for file in files:
            if not os.path.isfile(file):
                log.warn("'%s' not a regular file -- skipping" % file)
            else:
                dest = os.path.join(base_dir, file)
                self.copy_file(file, dest, link=link)

        self.distribution.metadata.write_pkg_info(base_dir)
        return

    def make_distribution(self):
        """Create the source distribution(s).  First, we create the release
        tree with 'make_release_tree()'; then, we create all required
        archive files (according to 'self.formats') from the release tree.
        Finally, we clean up by blowing away the release tree (unless
        'self.keep_temp' is true).  The list of archive files created is
        stored so it can be retrieved later by 'get_archive_files()'.
        """
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)
        self.make_release_tree(base_dir, self.filelist.files)
        archive_files = []
        if 'tar' in self.formats:
            self.formats.append(self.formats.pop(self.formats.index('tar')))
        for fmt in self.formats:
            file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group)
            archive_files.append(file)
            self.distribution.dist_files.append(('sdist', '', file))

        self.archive_files = archive_files
        if not self.keep_temp:
            dir_util.remove_tree(base_dir, dry_run=self.dry_run)

    def get_archive_files(self):
        """Return the list of archive files created when the command
        was run, or None if the command hasn't run yet.
        """
        return self.archive_files
Beispiel #30
0
from tel import config

long_description = """\
tel is a little console-based phone book program. It allows adding,
modifing, editing and searching of phone book entries right on your
terminal. Pretty printing capabilites are also provided.
Entries are stored in simple csv file. This eases import and export with
common spread sheet applications like Microsoft Excel or OpenOffice.org
Calc."""

# gettext source file for i18n
optparse_source = optparse.__file__.rstrip('c')

# collect all python sources for i18n
tel_sources = FileList()
tel_sources.findall('./src')
tel_sources.include_pattern('*.py', anchor=False)

setup(
    name='tel',
    version=config.version,
    description='A little terminal phone book',
    long_description=long_description,
    author='Sebastian Wiesner',
    author_email='*****@*****.**',
    url='http://tel.lunaryorn.de',
    license='MIT/X11',
    # list packages
    packages=['tel'],
    package_dir={'': 'src'},
    package_data={'tel': ['backends/*.py']},