diff options
| author | ?ric Araujo <merwok@netwok.org> | 2010-11-06 05:34:26 +0100 |
|---|---|---|
| committer | ?ric Araujo <merwok@netwok.org> | 2010-11-06 05:34:26 +0100 |
| commit | 1ba779a9ac2a14a707a576dc121d4bee9deb0d42 (patch) | |
| tree | 5c9f9086a66c65873b28127e49f8d8375f742707 /distutils2 | |
| parent | 8f2fdfad831885fe5048fc0205b3b48dad54ea98 (diff) | |
| parent | 3b95c92aeaf8b4c4b13bddd462fd0d4a99826acb (diff) | |
| download | disutils2-1ba779a9ac2a14a707a576dc121d4bee9deb0d42.tar.gz | |
Branch merge
Diffstat (limited to 'distutils2')
81 files changed, 680 insertions, 1604 deletions
diff --git a/distutils2/__init__.py b/distutils2/__init__.py index 2b35a32..98d7939 100644 --- a/distutils2/__init__.py +++ b/distutils2/__init__.py @@ -1,12 +1,5 @@ """distutils -The main package for the Python Distribution Utilities 2. Setup -scripts should import the setup function from distutils2.core: - - from distutils2.core import setup - - setup(name=..., version=..., ...) - Third-party tools can use parts of Distutils2 as building blocks without causing the other modules to be imported: @@ -14,10 +7,12 @@ without causing the other modules to be imported: import distutils2.pypi.simple import distutils2.tests.pypi_server """ -__all__ = ['__version__'] +from logging import getLogger -__version__ = "1.0a3" +__all__ = ['__version__', 'logger'] +__version__ = "1.0a3" +logger = getLogger('distutils2') # when set to True, converts doctests by default too run_2to3_on_doctests = True diff --git a/distutils2/_backport/tests/test_pkgutil.py b/distutils2/_backport/tests/test_pkgutil.py index 1b52cd3..e290005 100644 --- a/distutils2/_backport/tests/test_pkgutil.py +++ b/distutils2/_backport/tests/test_pkgutil.py @@ -13,8 +13,8 @@ except ImportError: from distutils2._backport.hashlib import md5 from test.test_support import TESTFN -from distutils2.tests import unittest, run_unittest +from distutils2.tests import unittest, run_unittest, support from distutils2._backport import pkgutil try: @@ -323,7 +323,8 @@ class TestPkgUtilDistribution(unittest.TestCase): self.assertEqual(sorted(found), sorted(distinfo_record_paths)) -class TestPkgUtilPEP376(unittest.TestCase): +class TestPkgUtilPEP376(support.LoggingCatcher, support.WarningsCatcher, + unittest.TestCase): # Tests for the new functionality added in PEP 376. def setUp(self): diff --git a/distutils2/command/__init__.py b/distutils2/command/__init__.py index c817b4f..cb2fa3f 100644 --- a/distutils2/command/__init__.py +++ b/distutils2/command/__init__.py @@ -12,7 +12,7 @@ __all__ = ['check', 'build_clib', 'build_scripts', 'clean', - 'install', + 'install_dist', 'install_lib', 'install_headers', 'install_scripts', diff --git a/distutils2/command/bdist.py b/distutils2/command/bdist.py index 1b7ce16..c7ffc7f 100644 --- a/distutils2/command/bdist.py +++ b/distutils2/command/bdist.py @@ -2,12 +2,10 @@ Implements the Distutils 'bdist' command (create a built [binary] distribution).""" - - import os from distutils2.util import get_platform -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsPlatformError, DistutilsOptionError diff --git a/distutils2/command/bdist_dumb.py b/distutils2/command/bdist_dumb.py index c02d6e0..8aed45c 100644 --- a/distutils2/command/bdist_dumb.py +++ b/distutils2/command/bdist_dumb.py @@ -12,9 +12,9 @@ try: except ImportError: from distutils2._backport.sysconfig import get_python_version from distutils2.util import get_platform -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsPlatformError -from distutils2 import log +from distutils2 import logger class bdist_dumb (Command): @@ -82,13 +82,13 @@ class bdist_dumb (Command): if not self.skip_build: self.run_command('build') - install = self.get_reinitialized_command('install', reinit_subcommands=1) + install = self.get_reinitialized_command('install_dist', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 - log.info("installing to %s" % self.bdist_dir) - self.run_command('install') + logger.info("installing to %s" % self.bdist_dir) + self.run_command('install_dist') # And make an archive relative to the root of the # pseudo-installation tree. @@ -129,7 +129,7 @@ class bdist_dumb (Command): if not self.keep_temp: if self.dry_run: - log.info('Removing %s' % self.bdist_dir) + logger.info('Removing %s' % self.bdist_dir) else: rmtree(self.bdist_dir) diff --git a/distutils2/command/bdist_msi.py b/distutils2/command/bdist_msi.py index 3728fe5..e2176a7 100644 --- a/distutils2/command/bdist_msi.py +++ b/distutils2/command/bdist_msi.py @@ -174,7 +174,7 @@ class bdist_msi (Command): if not self.skip_build: self.run_command('build') - install = self.get_reinitialized_command('install', reinit_subcommands=1) + install = self.get_reinitialized_command('install_dist', reinit_subcommands=1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 diff --git a/distutils2/command/bdist_wininst.py b/distutils2/command/bdist_wininst.py index 67a514d..40f151f 100644 --- a/distutils2/command/bdist_wininst.py +++ b/distutils2/command/bdist_wininst.py @@ -12,9 +12,9 @@ try: from sysconfig import get_python_version except ImportError: from distutils2._backport.sysconfig import get_python_version -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsOptionError, DistutilsPlatformError -from distutils2 import log +from distutils2 import logger from distutils2.util import get_platform class bdist_wininst (Command): @@ -160,7 +160,7 @@ class bdist_wininst (Command): 'install_' + key, value) - log.info("installing to %s", self.bdist_dir) + logger.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing @@ -187,12 +187,12 @@ class bdist_wininst (Command): self.distribution.dist_files.append(('bdist_wininst', pyversion, self.get_installer_filename(fullname))) # remove the zip-file again - log.debug("removing temporary file '%s'", arcname) + logger.debug("removing temporary file '%s'", arcname) os.remove(arcname) if not self.keep_temp: if self.dry_run: - log.info('Removing %s' % self.bdist_dir) + logger.info('Removing %s' % self.bdist_dir) else: rmtree(self.bdist_dir) diff --git a/distutils2/command/build.py b/distutils2/command/build.py index 6336ac4..ed2ccdf 100644 --- a/distutils2/command/build.py +++ b/distutils2/command/build.py @@ -6,7 +6,7 @@ Implements the Distutils 'build' command.""" import sys, os from distutils2.util import get_platform -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsOptionError def show_compilers(): diff --git a/distutils2/command/build_clib.py b/distutils2/command/build_clib.py index 0c8701e..5f20bb0 100644 --- a/distutils2/command/build_clib.py +++ b/distutils2/command/build_clib.py @@ -16,10 +16,10 @@ module.""" # cut 'n paste. Sigh. import os -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsSetupError from distutils2.compiler.ccompiler import customize_compiler -from distutils2 import log +from distutils2 import logger def show_compilers(): from distutils2.compiler.ccompiler import show_compilers @@ -185,7 +185,7 @@ class build_clib(Command): "a list of source filenames") % lib_name sources = list(sources) - log.info("building '%s' library", lib_name) + logger.info("building '%s' library", lib_name) # First, compile the source code to object files in the library # directory. (This should probably change to putting object diff --git a/distutils2/command/build_ext.py b/distutils2/command/build_ext.py index cb4f691..df71f1c 100644 --- a/distutils2/command/build_ext.py +++ b/distutils2/command/build_ext.py @@ -9,13 +9,13 @@ import sys, os, re from warnings import warn from distutils2.util import get_platform -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import (CCompilerError, CompileError, DistutilsError, DistutilsPlatformError, DistutilsSetupError) from distutils2.compiler.ccompiler import customize_compiler from distutils2.util import newer_group from distutils2.extension import Extension -from distutils2 import log +from distutils2 import logger try: import sysconfig except ImportError: @@ -449,10 +449,10 @@ class build_ext(Command): ext_path = self.get_ext_fullpath(ext.name) depends = sources + ext.depends if not (self.force or newer_group(depends, ext_path, 'newer')): - log.debug("skipping '%s' extension (up-to-date)", ext.name) + logger.debug("skipping '%s' extension (up-to-date)", ext.name) return else: - log.info("building '%s' extension", ext.name) + logger.info("building '%s' extension", ext.name) # First, scan the sources for SWIG definition files (.i), run # SWIG on 'em to create .c files, and modify the sources list @@ -536,7 +536,7 @@ class build_ext(Command): # the temp dir. if self.swig_cpp: - log.warn("--swig-cpp is deprecated - use --swig-opts=-c++") + logger.warn("--swig-cpp is deprecated - use --swig-opts=-c++") if self.swig_cpp or ('-c++' in self.swig_opts) or \ ('-c++' in extension.swig_opts): @@ -569,7 +569,7 @@ class build_ext(Command): for source in swig_sources: target = swig_targets[source] - log.info("swigging %s to %s", source, target) + logger.info("swigging %s to %s", source, target) self.spawn(swig_cmd + ["-o", target, source]) return new_sources diff --git a/distutils2/command/build_py.py b/distutils2/command/build_py.py index 92a8d9e..c24a13b 100644 --- a/distutils2/command/build_py.py +++ b/distutils2/command/build_py.py @@ -9,7 +9,7 @@ import logging from glob import glob import distutils2 -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsOptionError, DistutilsFileError from distutils2.util import convert_path from distutils2.compat import Mixin2to3 diff --git a/distutils2/command/build_scripts.py b/distutils2/command/build_scripts.py index b76d2b5..e0c8bcb 100644 --- a/distutils2/command/build_scripts.py +++ b/distutils2/command/build_scripts.py @@ -5,9 +5,10 @@ Implements the Distutils 'build_scripts' command.""" import os, re from stat import ST_MODE -from distutils2.core import Command + +from distutils2.command.cmd import Command from distutils2.util import convert_path, newer -from distutils2 import log +from distutils2 import logger try: import sysconfig except ImportError: @@ -73,7 +74,7 @@ class build_scripts (Command, Mixin2to3): outfiles.append(outfile) if not self.force and not newer(script, outfile): - log.debug("not copying %s (up-to-date)", script) + logger.debug("not copying %s (up-to-date)", script) continue # Always open the file, but ignore failures in dry-run mode -- @@ -97,7 +98,7 @@ class build_scripts (Command, Mixin2to3): post_interp = match.group(1) or '' if adjust: - log.info("copying and adjusting %s -> %s", script, + logger.info("copying and adjusting %s -> %s", script, self.build_dir) if not self.dry_run: outf = open(outfile, "w") @@ -124,12 +125,12 @@ class build_scripts (Command, Mixin2to3): if os.name == 'posix': for file in outfiles: if self.dry_run: - log.info("changing mode of %s", file) + logger.info("changing mode of %s", file) else: oldmode = os.stat(file)[ST_MODE] & 07777 newmode = (oldmode | 0555) & 07777 if newmode != oldmode: - log.info("changing mode of %s from %o to %o", + logger.info("changing mode of %s from %o to %o", file, oldmode, newmode) os.chmod(file, newmode) return outfiles diff --git a/distutils2/command/check.py b/distutils2/command/check.py index c661e6f..8bf55f1 100644 --- a/distutils2/command/check.py +++ b/distutils2/command/check.py @@ -3,7 +3,7 @@ Implements the Distutils 'check' command. """ -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsSetupError from distutils2.util import resolve_name diff --git a/distutils2/command/clean.py b/distutils2/command/clean.py index dc2ef0b..295cfac 100644 --- a/distutils2/command/clean.py +++ b/distutils2/command/clean.py @@ -7,8 +7,8 @@ Implements the Distutils 'clean' command.""" import os from shutil import rmtree -from distutils2.core import Command -from distutils2 import log +from distutils2.command.cmd import Command +from distutils2 import logger class clean(Command): @@ -48,11 +48,11 @@ class clean(Command): # gone) if os.path.exists(self.build_temp): if self.dry_run: - log.info('Removing %s' % self.build_temp) + logger.info('Removing %s' % self.build_temp) else: rmtree(self.build_temp) else: - log.debug("'%s' does not exist -- can't clean it", + logger.debug("'%s' does not exist -- can't clean it", self.build_temp) if self.all: @@ -62,19 +62,19 @@ class clean(Command): self.build_scripts): if os.path.exists(directory): if self.dry_run: - log.info('Removing %s' % directory) + logger.info('Removing %s' % directory) else: rmtree(directory) else: - log.warn("'%s' does not exist -- can't clean it", - directory) + logger.warn("'%s' does not exist -- can't clean it", + directory) # just for the heck of it, try to remove the base build directory: # we might have emptied it right now, but if not we don't care if not self.dry_run: try: os.rmdir(self.build_base) - log.info("removing '%s'", self.build_base) + logger.info("removing '%s'", self.build_base) except OSError: pass diff --git a/distutils2/command/cmd.py b/distutils2/command/cmd.py index 4dd825f..91b5589 100644 --- a/distutils2/command/cmd.py +++ b/distutils2/command/cmd.py @@ -3,12 +3,13 @@ Provides the Command class, the base class for the command classes in the distutils.command package. """ +import os +import re +import logging - -import os, re from distutils2.errors import DistutilsOptionError from distutils2 import util -from distutils2 import log +from distutils2 import logger # XXX see if we want to backport this from distutils2._backport.shutil import copytree, copyfile, move @@ -35,7 +36,7 @@ class Command(object): """ # 'sub_commands' formalizes the notion of a "family" of commands, - # eg. "install" as the parent with sub-commands "install_lib", + # eg. "install_dist" as the parent with sub-commands "install_lib", # "install_headers", etc. The parent of a family of commands # defines 'sub_commands' as a class attribute; it's a list of # (command_name : string, predicate : unbound_method | string | None) @@ -47,7 +48,7 @@ class Command(object): # # 'sub_commands' is usually defined at the *end* of a class, because # predicates can be unbound methods, so they must already have been - # defined. The canonical example is the "install" command. + # defined. The canonical example is the "install_dist" command. sub_commands = [] # Pre and post command hooks are run just before or just after the command @@ -163,7 +164,7 @@ class Command(object): def dump_options(self, header=None, indent=""): if header is None: header = "command options for '%s':" % self.get_command_name() - self.announce(indent + header, level=log.INFO) + self.announce(indent + header, level=logging.INFO) indent = indent + " " for (option, _, _) in self.user_options: option = option.replace('-', '_') @@ -171,7 +172,7 @@ class Command(object): option = option[:-1] value = getattr(self, option) self.announce(indent + "%s = %s" % (option, value), - level=log.INFO) + level=logging.INFO) def run(self): """A command's raison d'etre: carry out the action it exists to @@ -186,11 +187,11 @@ class Command(object): raise RuntimeError, \ "abstract method -- subclass %s must override" % self.__class__ - def announce(self, msg, level=1): + def announce(self, msg, level=logging.INFO): """If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout. """ - log.log(level, msg) + logger.log(level, msg) # -- External interface -------------------------------------------- # (called by outsiders) @@ -367,7 +368,7 @@ class Command(object): # -- External world manipulation ----------------------------------- def warn(self, msg): - log.warn("warning: %s: %s\n" % + logger.warning("warning: %s: %s\n" % (self.get_command_name(), msg)) def execute(self, func, args, msg=None, level=1): @@ -382,7 +383,7 @@ class Command(object): if dry_run: head = '' for part in name.split(os.sep): - log.info("created directory %s%s", head, part) + logger.info("created directory %s%s", head, part) head += part + os.sep return os.makedirs(name, mode) @@ -459,7 +460,7 @@ class Command(object): # Otherwise, print the "skip" message else: - log.debug(skip_msg) + logger.debug(skip_msg) # XXX 'install_misc' class not currently used -- it was the base class for # both 'install_scripts' and 'install_data', but they outgrew it. It might @@ -478,7 +479,7 @@ class install_misc(Command): self.outfiles = [] def _install_dir_from(self, dirname): - self.set_undefined_options('install', (dirname, 'install_dir')) + self.set_undefined_options('install_dist', (dirname, 'install_dir')) def _copy_files(self, filelist): self.outfiles = [] diff --git a/distutils2/command/config.py b/distutils2/command/config.py index 5bea91e..20c3a2c 100644 --- a/distutils2/command/config.py +++ b/distutils2/command/config.py @@ -13,10 +13,10 @@ this header file lives". import os import re -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsExecError from distutils2.compiler.ccompiler import customize_compiler -from distutils2 import log +from distutils2 import logger LANG_EXT = {'c': '.c', 'c++': '.cxx'} @@ -156,7 +156,7 @@ class config(Command): if not filenames: filenames = self.temp_files self.temp_files = [] - log.info("removing: %s", ' '.join(filenames)) + logger.info("removing: %s", ' '.join(filenames)) for filename in filenames: try: os.remove(filename) @@ -233,7 +233,7 @@ class config(Command): except CompileError: ok = 0 - log.info(ok and "success!" or "failure.") + logger.info(ok and "success!" or "failure.") self._clean() return ok @@ -252,7 +252,7 @@ class config(Command): except (CompileError, LinkError): ok = 0 - log.info(ok and "success!" or "failure.") + logger.info(ok and "success!" or "failure.") self._clean() return ok @@ -272,7 +272,7 @@ class config(Command): except (CompileError, LinkError, DistutilsExecError): ok = 0 - log.info(ok and "success!" or "failure.") + logger.info(ok and "success!" or "failure.") self._clean() return ok @@ -346,11 +346,11 @@ def dump_file(filename, head=None): If head is not None, will be dumped before the file content. """ if head is None: - log.info('%s' % filename) + logger.info('%s' % filename) else: - log.info(head) + logger.info(head) file = open(filename) try: - log.info(file.read()) + logger.info(file.read()) finally: file.close() diff --git a/distutils2/command/install_data.py b/distutils2/command/install_data.py index 1d5828f..e77b11c 100644 --- a/distutils2/command/install_data.py +++ b/distutils2/command/install_data.py @@ -7,7 +7,7 @@ platform-independent data files.""" import os -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.util import change_root, convert_path class install_data(Command): @@ -34,7 +34,7 @@ class install_data(Command): self.warn_dir = 1 def finalize_options(self): - self.set_undefined_options('install', + self.set_undefined_options('install_dist', ('install_data', 'install_dir'), 'root', 'force') diff --git a/distutils2/command/install.py b/distutils2/command/install_dist.py index b059fd9..f0233d1 100644 --- a/distutils2/command/install.py +++ b/distutils2/command/install_dist.py @@ -1,6 +1,6 @@ """distutils.command.install -Implements the Distutils 'install' command.""" +Implements the Distutils 'install_dist' command.""" import sys @@ -10,8 +10,8 @@ from distutils2._backport import sysconfig from distutils2._backport.sysconfig import (get_config_vars, get_paths, get_path, get_config_var) -from distutils2 import log -from distutils2.core import Command +from distutils2 import logger +from distutils2.command.cmd import Command from distutils2.errors import DistutilsPlatformError from distutils2.util import write_file from distutils2.util import convert_path, change_root, get_platform @@ -24,7 +24,7 @@ else: HAS_USER_SITE = True -class install(Command): +class install_dist(Command): description = "install everything from build directory" @@ -406,7 +406,7 @@ class install(Command): def dump_dirs(self, msg): """Dump the list of user options.""" - log.debug(msg + ":") + logger.debug(msg + ":") for opt in self.user_options: opt_name = opt[0] if opt_name[-1] == "=": @@ -418,7 +418,7 @@ class install(Command): else: opt_name = opt_name.replace('-', '_') val = getattr(self, opt_name) - log.debug(" %s: %s" % (opt_name, val)) + logger.debug(" %s: %s" % (opt_name, val)) def select_scheme(self, name): """Set the install directories by applying the install schemes.""" @@ -513,7 +513,7 @@ class install(Command): self.run_command('build') # If we built for any other platform, we can't install. build_plat = self.distribution.get_command_obj('build').plat_name - # check warn_dir - it is a clue that the 'install' is happening + # check warn_dir - it is a clue that the 'install_dist' is happening # internally, and not to sys.path, so we don't check the platform # matches what we are running. if self.warn_dir and build_plat != get_platform(): @@ -545,7 +545,7 @@ class install(Command): if (self.warn_dir and not (self.path_file and self.install_path_file) and install_lib not in sys_path): - log.debug(("modules installed to '%s', which is not in " + logger.debug(("modules installed to '%s', which is not in " "Python's module search path (sys.path) -- " "you'll have to change the search path yourself"), self.install_lib) diff --git a/distutils2/command/install_distinfo.py b/distutils2/command/install_distinfo.py index 64174dd..6e76546 100644 --- a/distutils2/command/install_distinfo.py +++ b/distutils2/command/install_distinfo.py @@ -7,7 +7,7 @@ distutils.command.install_distinfo This module implements the ``install_distinfo`` command that creates the ``.dist-info`` directory for the distribution, as specified in :pep:`376`. Usually, you do not have to call this command directly, it gets called -automatically by the ``install`` command. +automatically by the ``install_dist`` command. """ # This file was created from the code for the former command install_egg_info @@ -16,7 +16,7 @@ import os import csv import re from distutils2.command.cmd import Command -from distutils2 import log +from distutils2 import logger from distutils2._backport.shutil import rmtree try: import hashlib @@ -52,7 +52,7 @@ class install_distinfo(Command): self.no_record = None def finalize_options(self): - self.set_undefined_options('install', + self.set_undefined_options('install_dist', 'installer', 'requested', 'no_record') self.set_undefined_options('install_lib', @@ -93,12 +93,12 @@ class install_distinfo(Command): self.execute(os.makedirs, (target,), "creating " + target) metadata_path = os.path.join(self.distinfo_dir, 'METADATA') - log.info('creating %s', metadata_path) + logger.info('creating %s', metadata_path) self.distribution.metadata.write(metadata_path) self.outputs.append(metadata_path) installer_path = os.path.join(self.distinfo_dir, 'INSTALLER') - log.info('creating %s', installer_path) + logger.info('creating %s', installer_path) f = open(installer_path, 'w') try: f.write(self.installer) @@ -108,21 +108,21 @@ class install_distinfo(Command): if self.requested: requested_path = os.path.join(self.distinfo_dir, 'REQUESTED') - log.info('creating %s', requested_path) + logger.info('creating %s', requested_path) f = open(requested_path, 'w') f.close() self.outputs.append(requested_path) if not self.no_record: record_path = os.path.join(self.distinfo_dir, 'RECORD') - log.info('creating %s', record_path) + logger.info('creating %s', record_path) f = open(record_path, 'wb') try: writer = csv.writer(f, delimiter=',', lineterminator=os.linesep, quotechar='"') - install = self.get_finalized_command('install') + install = self.get_finalized_command('install_dist') for fpath in install.get_outputs(): if fpath.endswith('.pyc') or fpath.endswith('.pyo'): diff --git a/distutils2/command/install_headers.py b/distutils2/command/install_headers.py index bece686..86db07f 100644 --- a/distutils2/command/install_headers.py +++ b/distutils2/command/install_headers.py @@ -4,7 +4,7 @@ Implements the Distutils 'install_headers' command, to install C/C++ header files to the Python include directory.""" -from distutils2.core import Command +from distutils2.command.cmd import Command # XXX force is never used @@ -26,7 +26,7 @@ class install_headers(Command): self.outfiles = [] def finalize_options(self): - self.set_undefined_options('install', + self.set_undefined_options('install_dist', ('install_headers', 'install_dir'), 'force') diff --git a/distutils2/command/install_lib.py b/distutils2/command/install_lib.py index 223205e..f9de095 100644 --- a/distutils2/command/install_lib.py +++ b/distutils2/command/install_lib.py @@ -7,7 +7,7 @@ Implements the Distutils 'install_lib' command import os import sys -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsOptionError @@ -52,7 +52,7 @@ class install_lib(Command): negative_opt = {'no-compile' : 'compile'} def initialize_options(self): - # let the 'install' command dictate our installation directory + # let the 'install_dist' command dictate our installation directory self.install_dir = None self.build_dir = None self.force = 0 @@ -62,9 +62,9 @@ class install_lib(Command): def finalize_options(self): # Get all the information we need to install pure Python modules - # from the umbrella 'install' command -- build (source) directory, + # from the umbrella 'install_dist' command -- build (source) directory, # install (target) directory, and whether to compile .py files. - self.set_undefined_options('install', + self.set_undefined_options('install_dist', ('build_lib', 'build_dir'), ('install_lib', 'install_dir'), 'force', 'compile', 'optimize', 'skip_build') @@ -121,11 +121,11 @@ class install_lib(Command): from distutils2.util import byte_compile - # Get the "--root" directory supplied to the "install" command, + # Get the "--root" directory supplied to the "install_dist" command, # and use it as a prefix to strip off the purported filename # encoded in bytecode files. This is far from complete, but it # should at least generate usable bytecode in RPM distributions. - install_root = self.get_finalized_command('install').root + install_root = self.get_finalized_command('install_dist').root if self.compile: byte_compile(files, optimize=0, diff --git a/distutils2/command/install_scripts.py b/distutils2/command/install_scripts.py index 3fe6f9b..c0b35b1 100644 --- a/distutils2/command/install_scripts.py +++ b/distutils2/command/install_scripts.py @@ -7,8 +7,8 @@ Python scripts.""" import os -from distutils2.core import Command -from distutils2 import log +from distutils2.command.cmd import Command +from distutils2 import logger from stat import ST_MODE class install_scripts (Command): @@ -33,7 +33,7 @@ class install_scripts (Command): def finalize_options (self): self.set_undefined_options('build', ('build_scripts', 'build_dir')) - self.set_undefined_options('install', + self.set_undefined_options('install_dist', ('install_scripts', 'install_dir'), 'force', 'skip_build') @@ -46,10 +46,10 @@ class install_scripts (Command): # all the scripts we just installed. for file in self.get_outputs(): if self.dry_run: - log.info("changing mode of %s", file) + logger.info("changing mode of %s", file) else: mode = ((os.stat(file)[ST_MODE]) | 0555) & 07777 - log.info("changing mode of %s to %o", file, mode) + logger.info("changing mode of %s to %o", file, mode) os.chmod(file, mode) def get_inputs (self): diff --git a/distutils2/command/register.py b/distutils2/command/register.py index 07d692e..687a514 100644 --- a/distutils2/command/register.py +++ b/distutils2/command/register.py @@ -10,10 +10,11 @@ import urllib2 import getpass import urlparse import StringIO +import logging from warnings import warn from distutils2.command.cmd import Command -from distutils2 import log +from distutils2 import logger from distutils2.util import (metadata_to_dict, read_pypirc, generate_pypirc, DEFAULT_REPOSITORY, DEFAULT_REALM, get_pypirc_path) @@ -97,14 +98,14 @@ class register(Command): ''' Fetch the list of classifiers from the server. ''' response = urllib2.urlopen(self.repository+'?:action=list_classifiers') - log.info(response.read()) + logger.info(response.read()) def verify_metadata(self): ''' Send the metadata to the package index server to be checked. ''' # send the info to the server and report the result - (code, result) = self.post_to_server(self.build_post_data('verify')) - log.info('Server response (%s): %s' % (code, result)) + code, result = self.post_to_server(self.build_post_data('verify')) + logger.info('Server response (%s): %s' % (code, result)) def send_metadata(self): @@ -154,7 +155,7 @@ We need to know who you are, so please choose either: 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit -Your selection [default 1]: ''', log.INFO) +Your selection [default 1]: ''', logging.INFO) choice = raw_input() if not choice: @@ -177,7 +178,7 @@ Your selection [default 1]: ''', log.INFO) code, result = self.post_to_server(self.build_post_data('submit'), auth) self.announce('Server response (%s): %s' % (code, result), - log.INFO) + logging.INFO) # possibly save the login if code == 200: @@ -187,9 +188,10 @@ Your selection [default 1]: ''', log.INFO) self.distribution.password = password else: self.announce(('I can store your PyPI login so future ' - 'submissions will be faster.'), log.INFO) + 'submissions will be faster.'), + logging.INFO) self.announce('(the login will be stored in %s)' % \ - get_pypirc_path(), log.INFO) + get_pypirc_path(), logging.INFO) choice = 'X' while choice.lower() not in 'yn': choice = raw_input('Save your login (y/N)?') @@ -217,18 +219,18 @@ Your selection [default 1]: ''', log.INFO) data['email'] = raw_input(' EMail: ') code, result = self.post_to_server(data) if code != 200: - log.info('Server response (%s): %s' % (code, result)) + logger.info('Server response (%s): %s' % (code, result)) else: - log.info('You will receive an email shortly.') - log.info(('Follow the instructions in it to ' - 'complete registration.')) + logger.info('You will receive an email shortly.') + logger.info(('Follow the instructions in it to ' + 'complete registration.')) elif choice == '3': data = {':action': 'password_reset'} data['email'] = '' while not data['email']: data['email'] = raw_input('Your email address: ') code, result = self.post_to_server(data) - log.info('Server response (%s): %s' % (code, result)) + logger.info('Server response (%s): %s' % (code, result)) def build_post_data(self, action): # figure the data to send - the metadata plus some additional @@ -244,7 +246,7 @@ Your selection [default 1]: ''', log.INFO) if 'name' in data: self.announce('Registering %s to %s' % (data['name'], self.repository), - log.INFO) + logging.INFO) # Build up the MIME payload for the urllib2 POST data boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = '\n--' + boundary diff --git a/distutils2/command/sdist.py b/distutils2/command/sdist.py index 50c685a..b15f0a2 100644 --- a/distutils2/command/sdist.py +++ b/distutils2/command/sdist.py @@ -1,8 +1,6 @@ """distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" - - import os import string import sys @@ -10,17 +8,18 @@ from glob import glob from warnings import warn from shutil import rmtree import re +from StringIO import StringIO try: from shutil import get_archive_formats except ImportError: from distutils2._backport.shutil import get_archive_formats -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import (DistutilsPlatformError, DistutilsOptionError, DistutilsTemplateError) from distutils2.manifest import Manifest -from distutils2 import log +from distutils2 import logger from distutils2.util import convert_path def show_formats(): @@ -44,8 +43,6 @@ 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, @@ -93,9 +90,6 @@ class sdist(Command): '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 @@ -123,8 +117,6 @@ class sdist(Command): 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: @@ -176,18 +168,16 @@ class sdist(Command): 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) + template_exists = len(self.distribution.extra_files) > 0 if not template_exists: - self.warn(("manifest template '%s' does not exist " + - "(using default file list)") % - self.template) - + self.warn('Using default file list') self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: - self.filelist.read_template(self.template) + template = '\n'.join(self.distribution.extra_files) + self.filelist.read_template(StringIO(template)) if self.prune: self.prune_file_list() @@ -297,12 +287,12 @@ class sdist(Command): msg = "copying files to %s..." % base_dir if not files: - log.warn("no files to distribute -- empty manifest?") + logger.warn("no files to distribute -- empty manifest?") else: - log.info(msg) + logger.info(msg) for file in files: if not os.path.isfile(file): - log.warn("'%s' not a regular file -- skipping" % file) + logger.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) @@ -338,7 +328,7 @@ class sdist(Command): if not self.keep_temp: if self.dry_run: - log.info('Removing %s' % base_dir) + logger.info('Removing %s' % base_dir) else: rmtree(base_dir) diff --git a/distutils2/command/test.py b/distutils2/command/test.py index d64ebd3..57c23bf 100644 --- a/distutils2/command/test.py +++ b/distutils2/command/test.py @@ -2,7 +2,7 @@ import os import sys import unittest -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.errors import DistutilsOptionError from distutils2.util import resolve_name diff --git a/distutils2/command/upload.py b/distutils2/command/upload.py index 3fdb5b3..b5e072c 100644 --- a/distutils2/command/upload.py +++ b/distutils2/command/upload.py @@ -4,6 +4,7 @@ Implements the Distutils 'upload' subcommand (upload package to PyPI).""" import os import socket import platform +import logging from urllib2 import urlopen, Request, HTTPError from base64 import standard_b64encode import urlparse @@ -18,9 +19,7 @@ except ImportError: from distutils2.errors import DistutilsOptionError from distutils2.util import spawn -from distutils2 import log from distutils2.command.cmd import Command -from distutils2 import log from distutils2.util import (metadata_to_dict, read_pypirc, DEFAULT_REPOSITORY, DEFAULT_REALM) @@ -173,7 +172,7 @@ class upload(Command): body = body.getvalue() self.announce("Submitting %s to %s" % (filename, self.repository), - log.INFO) + logging.INFO) # build the Request headers = {'Content-type': @@ -189,7 +188,7 @@ class upload(Command): status = result.code reason = result.msg except socket.error, e: - self.announce(str(e), log.ERROR) + self.announce(str(e), logging.ERROR) return except HTTPError, e: status = e.code @@ -197,11 +196,11 @@ class upload(Command): if status == 200: self.announce('Server response (%s): %s' % (status, reason), - log.INFO) + logging.INFO) else: self.announce('Upload failed (%s): %s' % (status, reason), - log.ERROR) + logging.ERROR) if self.show_response: msg = '\n'.join(('-' * 75, result.read(), '-' * 75)) - self.announce(msg, log.INFO) + self.announce(msg, logging.INFO) diff --git a/distutils2/command/upload_docs.py b/distutils2/command/upload_docs.py index 79f204f..8147f98 100644 --- a/distutils2/command/upload_docs.py +++ b/distutils2/command/upload_docs.py @@ -4,12 +4,13 @@ import httplib import socket import urlparse import zipfile +import logging try: from cStringIO import StringIO except ImportError: from StringIO import StringIO -from distutils2 import log +from distutils2 import logger from distutils2.command.upload import upload from distutils2.command.cmd import Command from distutils2.errors import DistutilsFileError @@ -114,8 +115,7 @@ class upload_docs(Command): credentials = self.username + ':' + self.password auth = "Basic " + base64.encodestring(credentials).strip() - self.announce("Submitting documentation to %s" % (self.repository), - log.INFO) + self.announce("Submitting documentation to %s" % (self.repository)) schema, netloc, url, params, query, fragments = \ urlparse.urlparse(self.repository) @@ -135,24 +135,22 @@ class upload_docs(Command): conn.endheaders() conn.send(body) except socket.error, e: - self.announce(str(e), log.ERROR) + self.announce(str(e), logging.ERROR) return r = conn.getresponse() if r.status == 200: - self.announce('Server response (%s): %s' % (r.status, r.reason), - log.INFO) + self.announce('Server response (%s): %s' % (r.status, r.reason)) elif r.status == 301: location = r.getheader('Location') if location is None: location = 'http://packages.python.org/%s/' % name - self.announce('Upload successful. Visit %s' % location, - log.INFO) + self.announce('Upload successful. Visit %s' % location) else: self.announce('Upload failed (%s): %s' % (r.status, r.reason), - log.ERROR) + logging.ERROR) if self.show_response: msg = '\n'.join(('-' * 75, r.read(), '-' * 75)) - self.announce(msg, log.INFO) + self.announce(msg) diff --git a/distutils2/compiler/bcppcompiler.py b/distutils2/compiler/bcppcompiler.py index 115b71b..929994b 100644 --- a/distutils2/compiler/bcppcompiler.py +++ b/distutils2/compiler/bcppcompiler.py @@ -19,7 +19,7 @@ from distutils2.errors import (DistutilsExecError, CompileError, LibError, from distutils2.compiler.ccompiler import CCompiler, gen_preprocess_options from distutils2.file_util import write_file from distutils2.dep_util import newer -from distutils2 import log +from distutils2 import logger class BCPPCompiler(CCompiler) : """Concrete class that implements an interface to the Borland C/C++ @@ -162,7 +162,7 @@ class BCPPCompiler(CCompiler) : except DistutilsExecError, msg: raise LibError, msg else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) # create_static_lib () @@ -190,7 +190,8 @@ class BCPPCompiler(CCompiler) : self._fix_lib_args (libraries, library_dirs, runtime_library_dirs) if runtime_library_dirs: - log.warn("I don't know what to do with 'runtime_library_dirs': %s", + logger.warning(("I don't know what to do with " + "'runtime_library_dirs': %s"), str(runtime_library_dirs)) if output_dir is not None: @@ -297,7 +298,7 @@ class BCPPCompiler(CCompiler) : raise LinkError, msg else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) # link () diff --git a/distutils2/compiler/ccompiler.py b/distutils2/compiler/ccompiler.py index da7e061..744b596 100644 --- a/distutils2/compiler/ccompiler.py +++ b/distutils2/compiler/ccompiler.py @@ -7,12 +7,13 @@ for the Distutils compiler abstraction model.""" import sys import os import re +from shutil import move from distutils2.errors import (CompileError, LinkError, UnknownFileError, DistutilsPlatformError, DistutilsModuleError) from distutils2.util import split_quoted, execute, newer_group, spawn -from distutils2 import log -from shutil import move +from distutils2 import logger + try: import sysconfig @@ -911,8 +912,8 @@ main (int argc, char **argv) { # -- Utility methods ----------------------------------------------- - def announce(self, msg, level=1): - log.debug(msg) + def announce(self, msg, level=None): + logger.debug(msg) def debug_print(self, msg): from distutils2.debug import DEBUG @@ -940,7 +941,7 @@ main (int argc, char **argv) { if self.dry_run: head = '' for part in name.split(os.sep): - log.info("created directory %s%s", head, part) + logger.info("created directory %s%s", head, part) head += part + os.sep return os.makedirs(name, mode) diff --git a/distutils2/compiler/msvc9compiler.py b/distutils2/compiler/msvc9compiler.py index 2f42a65..63a5570 100644 --- a/distutils2/compiler/msvc9compiler.py +++ b/distutils2/compiler/msvc9compiler.py @@ -21,7 +21,7 @@ import re from distutils2.errors import (DistutilsExecError, DistutilsPlatformError, CompileError, LibError, LinkError) from distutils2.compiler.ccompiler import CCompiler, gen_lib_options -from distutils2 import log +from distutils2 import logger from distutils2.util import get_platform import _winreg @@ -215,7 +215,7 @@ def find_vcvarsall(version): productdir = Reg.get_value(r"%s\Setup\VC" % vsbase, "productdir") except KeyError: - log.debug("Unable to find productdir in registry") + logger.debug("Unable to find productdir in registry") productdir = None if not productdir or not os.path.isdir(productdir): @@ -226,17 +226,17 @@ def find_vcvarsall(version): productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") productdir = os.path.abspath(productdir) if not os.path.isdir(productdir): - log.debug("%s is not a valid directory" % productdir) + logger.debug("%s is not a valid directory" % productdir) return None else: - log.debug("Env var %s is not set or invalid" % toolskey) + logger.debug("Env var %s is not set or invalid" % toolskey) if not productdir: - log.debug("No productdir found") + logger.debug("No productdir found") return None vcvarsall = os.path.join(productdir, "vcvarsall.bat") if os.path.isfile(vcvarsall): return vcvarsall - log.debug("Unable to find vcvarsall.bat") + logger.debug("Unable to find vcvarsall.bat") return None def query_vcvarsall(version, arch="x86"): @@ -248,7 +248,7 @@ def query_vcvarsall(version, arch="x86"): if vcvarsall is None: raise DistutilsPlatformError("Unable to find vcvarsall.bat") - log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) + logger.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -547,7 +547,7 @@ class MSVCCompiler(CCompiler) : except DistutilsExecError, msg: raise LibError(msg) else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) def link(self, @@ -653,7 +653,7 @@ class MSVCCompiler(CCompiler) : except DistutilsExecError, msg: raise LinkError(msg) else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) def _remove_visual_c_ref(self, manifest_file): try: diff --git a/distutils2/compiler/msvccompiler.py b/distutils2/compiler/msvccompiler.py index ee3e5cb..e24fb93 100644 --- a/distutils2/compiler/msvccompiler.py +++ b/distutils2/compiler/msvccompiler.py @@ -16,7 +16,7 @@ import string from distutils2.errors import (DistutilsExecError, DistutilsPlatformError, CompileError, LibError, LinkError) from distutils2.compiler.ccompiler import CCompiler, gen_lib_options -from distutils2 import log +from distutils2 import logger _can_read_reg = 0 try: @@ -43,7 +43,7 @@ except ImportError: RegError = win32api.error except ImportError: - log.info("Warning: Can't read registry to find the " + logger.info("Warning: Can't read registry to find the " "necessary compiler setting\n" "Make sure that Python modules _winreg, " "win32api or win32con are installed.") @@ -456,7 +456,7 @@ class MSVCCompiler (CCompiler) : raise LibError, msg else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) # create_static_lib () @@ -535,7 +535,7 @@ class MSVCCompiler (CCompiler) : raise LinkError, msg else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) # link () @@ -651,7 +651,7 @@ class MSVCCompiler (CCompiler) : if get_build_version() >= 8.0: - log.debug("Importing new compiler from distutils.msvc9compiler") + logger.debug("Importing new compiler from distutils.msvc9compiler") OldMSVCCompiler = MSVCCompiler from distutils2.compiler.msvc9compiler import MSVCCompiler # get_build_architecture not really relevant now we support cross-compile diff --git a/distutils2/compiler/unixccompiler.py b/distutils2/compiler/unixccompiler.py index 2152a71..55c98f1 100644 --- a/distutils2/compiler/unixccompiler.py +++ b/distutils2/compiler/unixccompiler.py @@ -22,7 +22,7 @@ from distutils2.compiler.ccompiler import (CCompiler, gen_preprocess_options, gen_lib_options) from distutils2.errors import (DistutilsExecError, CompileError, LibError, LinkError) -from distutils2 import log +from distutils2 import logger try: import sysconfig @@ -102,9 +102,9 @@ def _darwin_compiler_fixup(compiler_so, cc_args): sysroot = compiler_so[idx+1] if sysroot and not os.path.isdir(sysroot): - log.warn("Compiling with an SDK that doesn't seem to exist: %s", + logger.warning("Compiling with an SDK that doesn't seem to exist: %s", sysroot) - log.warn("Please check your Xcode installation") + logger.warning("Please check your Xcode installation") return compiler_so @@ -207,7 +207,7 @@ class UnixCCompiler(CCompiler): except DistutilsExecError, msg: raise LibError, msg else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, @@ -261,7 +261,7 @@ class UnixCCompiler(CCompiler): except DistutilsExecError, msg: raise LinkError, msg else: - log.debug("skipping %s (up-to-date)", output_filename) + logger.debug("skipping %s (up-to-date)", output_filename) # -- Miscellaneous methods ----------------------------------------- # These are all used by the 'gen_lib_options() function, in diff --git a/distutils2/config.py b/distutils2/config.py index b6fd100..b2bdd0f 100644 --- a/distutils2/config.py +++ b/distutils2/config.py @@ -6,7 +6,7 @@ import os import sys from ConfigParser import RawConfigParser -from distutils2 import log +from distutils2 import logger from distutils2.util import check_environ, resolve_name @@ -66,7 +66,7 @@ class Config(object): if os.path.isfile(local_file): files.append(local_file) - log.debug("using config files: %s" % ', '.join(files)) + logger.debug("using config files: %s" % ', '.join(files)) return files def _convert_metadata(self, name, value): @@ -151,7 +151,7 @@ class Config(object): self.dist.package_dir[package] = dir_ self.dist.packages.append(package) - self.dist.py_modules = files.get('py_modules', []) + self.dist.py_modules = files.get('modules', []) if isinstance(self.dist.py_modules, str): self.dist.py_modules = [self.dist.py_modules] self.dist.scripts = files.get('scripts', []) @@ -176,17 +176,17 @@ class Config(object): self.dist.data_files.append((key, values)) # manifest template - # XXX see later + self.dist.extra_files = files.get('extra_files', []) def parse_config_files(self, filenames=None): if filenames is None: filenames = self.find_config_files() - log.debug("Distribution.parse_config_files():") + logger.debug("Distribution.parse_config_files():") parser = RawConfigParser() for filename in filenames: - log.debug(" reading %s" % filename) + logger.debug(" reading %s" % filename) parser.read(filename) if os.path.split(filename)[-1] == 'setup.cfg': diff --git a/distutils2/converter/__init__.py b/distutils2/converter/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/distutils2/converter/__init__.py +++ /dev/null diff --git a/distutils2/converter/fixers/__init__.py b/distutils2/converter/fixers/__init__.py deleted file mode 100644 index cd6acf4..0000000 --- a/distutils2/converter/fixers/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""distutils2.converter.fixers - -Contains all fixers for the converter. -""" diff --git a/distutils2/converter/fixers/fix_imports.py b/distutils2/converter/fixers/fix_imports.py deleted file mode 100644 index 38d185e..0000000 --- a/distutils2/converter/fixers/fix_imports.py +++ /dev/null @@ -1,52 +0,0 @@ -"""distutils2.converter.fixers.fix_imports - -Fixer for import statements in setup.py -""" -from lib2to3.fixer_base import BaseFix -from lib2to3.fixer_util import syms - - -class FixImports(BaseFix): - """Makes sure all import in setup.py are translated""" - - PATTERN = """ - import_from< 'from' imp=any 'import' ['('] any [')'] > - | - import_name< 'import' imp=any > - """ - - def transform(self, node, results): - imp = results['imp'] - if node.type != syms.import_from: - return - - if not hasattr(imp, "next_sibling"): - imp.next_sibling = imp.get_next_sibling() - - while not hasattr(imp, 'value'): - imp = imp.children[0] - - if imp.value == 'distutils': - imp.value = 'distutils2' - imp.changed() - return node - - if imp.value == 'setuptools': - # catching "from setuptools import setup" - pattern = [] - next = imp.next_sibling - while next is not None: - # Get the first child if we have a Node - if not hasattr(next, "value"): - next = next.children[0] - pattern.append(next.value) - if not hasattr(next, "next_sibling"): - next.next_sibling = next.get_next_sibling() - next = next.next_sibling - - if set(pattern).issubset(set( - ['import', ',', 'setup', 'find_packages'])): - imp.value = 'distutils2.core' - imp.changed() - - return node diff --git a/distutils2/converter/fixers/fix_setup_options.py b/distutils2/converter/fixers/fix_setup_options.py deleted file mode 100644 index 7d319fb..0000000 --- a/distutils2/converter/fixers/fix_setup_options.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Fixer for setup() options. - -All distutils or setuptools options are translated -into PEP 345-style options. -""" -from lib2to3.pytree import Leaf, Node -from lib2to3.pgen2 import token -from lib2to3.fixer_base import BaseFix - -# XXX where is that defined ? -_ARG = 260 - -# name mapping : we want to convert -# all old-style options to distutils2 style -_OLD_NAMES = {'url': 'home_page', - 'long_description': 'description', - 'description': 'summary', - 'install_requires': 'requires_dist'} - -_SEQUENCE_NAMES = ['requires_dist'] - - -class FixSetupOptions(BaseFix): - - # XXX need to find something better here : - # identify a setup call, whatever alias is used - PATTERN = """ - power< name='setup' trailer< '(' [any] ')' > any* > - """ - - def _get_list(self, *nodes): - """A List node, filled""" - lbrace = Leaf(token.LBRACE, u"[") - lbrace.prefix = u" " - if len(nodes) > 0: - nodes[0].prefix = u"" - return Node(self.syms.trailer, - [lbrace] + - [node.clone() for node in nodes] + - [Leaf(token.RBRACE, u"]")]) - - def _fix_name(self, argument, remove_list): - name = argument.children[0] - - if not hasattr(name, "next_sibling"): - name.next_sibling = name.get_next_sibling() - - sibling = name.next_sibling - if sibling is None or sibling.type != token.EQUAL: - return False - - if name.value in _OLD_NAMES: - name.value = _OLD_NAMES[name.value] - if name.value in _SEQUENCE_NAMES: - if not hasattr(sibling, "next_sibling"): - sibling.next_sibling = sibling.get_next_sibling() - right_operand = sibling.next_sibling - # replacing string -> list[string] - if right_operand.type == token.STRING: - # we want this to be a list now - new_node = self._get_list(right_operand) - right_operand.replace(new_node) - - - return True - - return False - - def transform(self, node, results): - arglist = node.children[1].children[1] - remove_list = [] - changed = False - - for subnode in arglist.children: - if subnode.type != _ARG: - continue - if self._fix_name(subnode, remove_list) and not changed: - changed = True - - for subnode in remove_list: - subnode.remove() - - if changed: - node.changed() - return node diff --git a/distutils2/converter/refactor.py b/distutils2/converter/refactor.py deleted file mode 100644 index 28fbd44..0000000 --- a/distutils2/converter/refactor.py +++ /dev/null @@ -1,12 +0,0 @@ -"""distutils2.converter.refactor - -""" -try: - from lib2to3.refactor import RefactoringTool - _LIB2TO3 = True -except ImportError: - # we need 2.6 at least to run this - _LIB2TO3 = False - -_DISTUTILS_FIXERS = ['distutils2.converter.fixers.fix_imports', - 'distutils2.converter.fixers.fix_setup_options']
\ No newline at end of file diff --git a/distutils2/core.py b/distutils2/core.py deleted file mode 100644 index b11110e..0000000 --- a/distutils2/core.py +++ /dev/null @@ -1,219 +0,0 @@ -"""distutils2.core - -The only module that needs to be imported to use the Distutils; provides -the 'setup' function (which is to be called from the setup script). Also -exports useful classes so that setup scripts can import them from here -although they are really defined in other modules: Distribution, Command, -PyPIRCommand, Extension, find_packages. -""" - - -import sys -import os - -from distutils2.errors import (DistutilsSetupError, DistutilsArgError, - DistutilsError, CCompilerError) -from distutils2.util import grok_environment_error - -# Mainly import these so setup scripts can "from distutils2.core import" them. -from distutils2.dist import Distribution -from distutils2.command.cmd import Command -from distutils2.extension import Extension -from distutils2.util import find_packages - -# This is a barebones help message generated displayed when the user -# runs the setup script with no arguments at all. More useful help -# is generated with various --help options: global help, list commands, -# and per-command help. -USAGE = """\ -usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] - or: %(script)s --help [cmd1 cmd2 ...] - or: %(script)s --help-commands - or: %(script)s cmd --help -""" - - -def gen_usage(script_name): - script = os.path.basename(script_name) - return USAGE % {'script': script} - - -# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'. -_setup_stop_after = None -_setup_distribution = None - -# Legal keyword arguments for the setup() function -setup_keywords = ('distclass', 'script_name', 'script_args', 'options', - 'name', 'version', 'author', 'author_email', - 'maintainer', 'maintainer_email', 'url', 'license', - 'description', 'long_description', 'keywords', - 'platforms', 'classifiers', 'download_url', - 'requires', 'provides', 'obsoletes', 'use_2to3_fixers', - 'convert_2to3_doctests', 'use_2to3_fixers' - ) - -# Legal keyword arguments for the Extension constructor -extension_keywords = ('name', 'sources', 'include_dirs', - 'define_macros', 'undef_macros', - 'library_dirs', 'libraries', 'runtime_library_dirs', - 'extra_objects', 'extra_compile_args', 'extra_link_args', - 'swig_opts', 'export_symbols', 'depends', 'language') - - -def setup(**attrs): - """The gateway to the Distutils: do everything your setup script needs - to do, in a highly flexible and user-driven way. Briefly: create a - Distribution instance; find and parse config files; parse the command - line; run each Distutils command found there, customized by the options - supplied to 'setup()' (as keyword arguments), in config files, and on - the command line. - - The Distribution instance might be an instance of a class supplied via - the 'distclass' keyword argument to 'setup'; if no such class is - supplied, then the Distribution class (in dist.py) is instantiated. - All other arguments to 'setup' (except for 'cmdclass') are used to set - attributes of the Distribution instance. - - The 'cmdclass' argument, if supplied, is a dictionary mapping command - names to command classes. Each command encountered on the command line - will be turned into a command class, which is in turn instantiated; any - class found in 'cmdclass' is used in place of the default, which is - (for command 'foo_bar') class 'foo_bar' in module - 'distutils2.command.foo_bar'. The command class must provide a - 'user_options' attribute which is a list of option specifiers for - 'distutils2.fancy_getopt'. Any command-line options between the current - and the next command are used to set attributes of the current command - object. - - When the entire command line has been successfully parsed, calls the - 'run()' method on each command object in turn. This method will be - driven entirely by the Distribution object (which each command object - has a reference to, thanks to its constructor), and the - command-specific options that became attributes of each command - object. - """ - - global _setup_stop_after, _setup_distribution - - # Determine the distribution class -- either caller-supplied or - # our Distribution (see below). - distclass = attrs.pop('distclass', Distribution) - - if 'script_name' not in attrs: - attrs['script_name'] = os.path.basename(sys.argv[0]) - if 'script_args' not in attrs: - attrs['script_args'] = sys.argv[1:] - - # Create the Distribution instance, using the remaining arguments - # (ie. everything except distclass) to initialize it - try: - _setup_distribution = dist = distclass(attrs) - except DistutilsSetupError, msg: - if 'name' in attrs: - raise SystemExit, "error in %s setup command: %s" % \ - (attrs['name'], msg) - else: - raise SystemExit, "error in setup command: %s" % msg - - if _setup_stop_after == "init": - return dist - - # Find and parse the config file(s): they will override options from - # the setup script, but be overridden by the command line. - dist.parse_config_files() - - if _setup_stop_after == "config": - return dist - - # Parse the command line and override config files; any - # command line errors are the end user's fault, so turn them into - # SystemExit to suppress tracebacks. - try: - ok = dist.parse_command_line() - except DistutilsArgError, msg: - raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg - - if _setup_stop_after == "commandline": - return dist - - # And finally, run all the commands found on the command line. - if ok: - try: - dist.run_commands() - except KeyboardInterrupt: - raise SystemExit, "interrupted" - except (IOError, os.error), exc: - error = grok_environment_error(exc) - raise SystemExit, error - - except (DistutilsError, - CCompilerError), msg: - raise SystemExit, "error: " + str(msg) - - return dist - - -def run_setup(script_name, script_args=None, stop_after="run"): - """Run a setup script in a somewhat controlled environment, and - return the Distribution instance that drives things. This is useful - if you need to find out the distribution metadata (passed as - keyword args from 'script' to 'setup()', or the contents of the - config files or command line. - - 'script_name' is a file that will be run with 'execfile()'; - 'sys.argv[0]' will be replaced with 'script' for the duration of the - call. 'script_args' is a list of strings; if supplied, - 'sys.argv[1:]' will be replaced by 'script_args' for the duration of - the call. - - 'stop_after' tells 'setup()' when to stop processing; possible - values: - init - stop after the Distribution instance has been created and - populated with the keyword arguments to 'setup()' - config - stop after config files have been parsed (and their data - stored in the Distribution instance) - commandline - stop after the command line ('sys.argv[1:]' or 'script_args') - has been parsed (and the data stored in the Distribution) - run [default] - stop after all commands have been run (the same as if 'setup()' - had been called in the usual way - - Returns the Distribution instance, which provides all information - used to drive the Distutils. - """ - if stop_after not in ('init', 'config', 'commandline', 'run'): - raise ValueError, "invalid value for 'stop_after': %r" % (stop_after,) - - global _setup_stop_after, _setup_distribution - _setup_stop_after = stop_after - - save_argv = sys.argv - g = {'__file__': script_name} - l = {} - try: - try: - if script_args is not None: - sys.argv = [script_name] + script_args - else: - sys.argv = [script_name] - exec open(script_name, 'r').read() in g, l - finally: - sys.argv = save_argv - _setup_stop_after = None - except SystemExit: - # Hmm, should we do something if exiting with a non-zero code - # (ie. error)? - pass - - if _setup_distribution is None: - raise RuntimeError, \ - ("'distutils2.core.setup()' was never called -- " - "perhaps '%s' is not a Distutils setup script?") % \ - script_name - - # I wonder if the setup script's namespace -- g and l -- would be of - # any interest to callers? - return _setup_distribution diff --git a/distutils2/dist.py b/distutils2/dist.py index a08a62e..6663b3e 100644 --- a/distutils2/dist.py +++ b/distutils2/dist.py @@ -9,12 +9,13 @@ import sys import os import re import warnings +import logging from distutils2.errors import (DistutilsOptionError, DistutilsArgError, DistutilsModuleError, DistutilsClassError) from distutils2.fancy_getopt import FancyGetopt from distutils2.util import strtobool, resolve_name -from distutils2 import log +from distutils2 import logger from distutils2.metadata import DistributionMetadata from distutils2.config import Config @@ -36,7 +37,7 @@ class Distribution(object): Distribution for some specialized purpose, and then pass the subclass to 'setup()' as the 'distclass' keyword argument. If so, it is necessary to respect the expectations that 'setup' has of Distribution. - See the code for 'setup()', in core.py, for details. + See the code for 'setup()', in run.py, for details. """ # 'global_options' describes the command-line options that may be @@ -202,6 +203,7 @@ Common commands: (see '--help-commands' for more) self.password = '' self.use_2to3 = False self.convert_2to3_doctests = [] + self.extra_files = [] # And now initialize bookkeeping stuff that can't be supplied by # the caller at all. 'command_obj' maps command names to @@ -321,7 +323,7 @@ Common commands: (see '--help-commands' for more) def parse_command_line(self): """Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' - -- see 'setup()' in core.py). This list is first processed for + -- see 'setup()' in run.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the @@ -356,7 +358,14 @@ Common commands: (see '--help-commands' for more) parser.set_aliases({'licence': 'license'}) args = parser.getopt(args=self.script_args, object=self) option_order = parser.get_option_order() - log.set_verbosity(self.verbose) + + handler = logging.StreamHandler() + logger.addHandler(handler) + + if self.verbose: + handler.setLevel(logging.DEBUG) + else: + handler.setLevel(logging.INFO) # for display options we return immediately if self.handle_display_options(option_order): @@ -513,7 +522,7 @@ Common commands: (see '--help-commands' for more) in 'commands'. """ # late import because of mutual dependence between these modules - from distutils2.core import gen_usage + from distutils2.run import gen_usage from distutils2.command.cmd import Command if global_options: @@ -554,7 +563,7 @@ Common commands: (see '--help-commands' for more) line, display the requested info and return true; else return false. """ - from distutils2.core import gen_usage + from distutils2.run import gen_usage # User just wants a list of commands -- we'll print it out and stop # processing now (ie. if they ran "setup --help-commands foo bar", @@ -736,8 +745,8 @@ Common commands: (see '--help-commands' for more) """ cmd_obj = self.command_obj.get(command) if not cmd_obj and create: - log.debug("Distribution.get_command_obj(): " \ - "creating '%s' command object" % command) + logger.debug("Distribution.get_command_obj(): " \ + "creating '%s' command object" % command) cls = self.get_command_class(command) cmd_obj = self.command_obj[command] = cls(self) @@ -767,11 +776,10 @@ Common commands: (see '--help-commands' for more) if option_dict is None: option_dict = self.get_option_dict(command_name) - log.debug(" setting options for '%s' command:" % command_name) + logger.debug(" setting options for '%s' command:" % command_name) for (option, (source, value)) in option_dict.items(): - log.debug(" %s = %s (from %s)" % (option, value, - source)) + logger.debug(" %s = %s (from %s)" % (option, value, source)) try: bool_opts = [x.replace('-', '_') for x in command_obj.boolean_options] @@ -810,7 +818,7 @@ Common commands: (see '--help-commands' for more) 'command' should be a command name (string) or command object. If 'reinit_subcommands' is true, also reinitializes the command's sub-commands, as declared by the 'sub_commands' class attribute (if - it has one). See the "install" command for an example. Only + it has one). See the "install_dist" command for an example. Only reinitializes the sub-commands that actually matter, ie. those whose test predicates return true. @@ -838,8 +846,8 @@ Common commands: (see '--help-commands' for more) # -- Methods that operate on the Distribution ---------------------- - def announce(self, msg, level=log.INFO): - log.log(level, msg) + def announce(self, msg, level=logging.INFO): + logger.log(level, msg) def run_commands(self): """Run each command that was seen on the setup script command line. @@ -866,7 +874,7 @@ Common commands: (see '--help-commands' for more) cmd_obj = self.get_command_obj(command) cmd_obj.ensure_finalized() self.run_command_hooks(cmd_obj, 'pre_hook') - log.info("running %s", command) + logger.info("running %s", command) cmd_obj.run() self.run_command_hooks(cmd_obj, 'post_hook') self.have_run[command] = 1 @@ -897,8 +905,8 @@ Common commands: (see '--help-commands' for more) if not hasattr(hook_obj, '__call__'): raise DistutilsOptionError('hook %r is not callable' % hook) - log.info('running %s %s for command %s', - hook_kind, hook, cmd_obj.get_command_name()) + logger.info('running %s %s for command %s', + hook_kind, hook, cmd_obj.get_command_name()) hook_obj(cmd_obj) # -- Distribution query methods ------------------------------------ diff --git a/distutils2/log.py b/distutils2/log.py deleted file mode 100644 index 1293bf4..0000000 --- a/distutils2/log.py +++ /dev/null @@ -1,71 +0,0 @@ -"""A simple log mechanism styled after PEP 282.""" - -# The class here is styled after PEP 282 so that it could later be -# replaced with a standard Python logging implementation. - -DEBUG = 1 -INFO = 2 -WARN = 3 -ERROR = 4 -FATAL = 5 - -import sys - -class Log(object): - - def __init__(self, threshold=WARN): - self.threshold = threshold - - def _log(self, level, msg, args): - if level not in (DEBUG, INFO, WARN, ERROR, FATAL): - raise ValueError('%s wrong log level' % level) - - if level >= self.threshold: - if args: - msg = msg % args - if level in (WARN, ERROR, FATAL): - stream = sys.stderr - else: - stream = sys.stdout - stream.write('%s\n' % msg) - stream.flush() - - def log(self, level, msg, *args): - self._log(level, msg, args) - - def debug(self, msg, *args): - self._log(DEBUG, msg, args) - - def info(self, msg, *args): - self._log(INFO, msg, args) - - def warn(self, msg, *args): - self._log(WARN, msg, args) - - def error(self, msg, *args): - self._log(ERROR, msg, args) - - def fatal(self, msg, *args): - self._log(FATAL, msg, args) - -_global_log = Log() -log = _global_log.log -debug = _global_log.debug -info = _global_log.info -warn = _global_log.warn -error = _global_log.error -fatal = _global_log.fatal - -def set_threshold(level): - # return the old threshold for use from tests - old = _global_log.threshold - _global_log.threshold = level - return old - -def set_verbosity(v): - if v <= 0: - set_threshold(WARN) - elif v == 1: - set_threshold(INFO) - elif v >= 2: - set_threshold(DEBUG) diff --git a/distutils2/manifest.py b/distutils2/manifest.py index 27b3dce..e5862dd 100644 --- a/distutils2/manifest.py +++ b/distutils2/manifest.py @@ -22,7 +22,7 @@ __all__ = ['Manifest'] # a \ followed by some spaces + EOL _COLLAPSE_PATTERN = re.compile('\\\w*\n', re.M) -_COMMENTED_LINE = re.compile('#.*?(?=\n)|^\w*\n|\n(?=$)', re.M | re.S) +_COMMENTED_LINE = re.compile('#.*?(?=\n)|\n(?=$)', re.M | re.S) class Manifest(object): """A list of files built by on exploring the filesystem and filtered by @@ -66,17 +66,21 @@ class Manifest(object): if self.files[i] == self.files[i - 1]: del self.files[i] - def read_template(self, path): + def read_template(self, path_or_file): """Read and parse a manifest template file. + 'path' can be a path or a file-like object. Updates the list accordingly. """ - f = open(path) + if isinstance(path_or_file, str): + f = open(path_or_file) + else: + f = path_or_file + try: content = f.read() # first, let's unwrap collapsed lines content = _COLLAPSE_PATTERN.sub('', content) - # next, let's remove commented lines and empty lines content = _COMMENTED_LINE.sub('', content) @@ -86,10 +90,12 @@ class Manifest(object): f.close() for line in lines: + if line == '': + continue try: self._process_template_line(line) except DistutilsTemplateError, msg: - logging.warning("%s, %s" % (path, msg)) + logging.warning("%s, %s" % (path_or_file, msg)) def write(self, path): """Write the file list in 'self.filelist' (presumably as filled in @@ -151,8 +157,11 @@ class Manifest(object): def _parse_template_line(self, line): words = line.split() - action = words[0] + if len(words) == 1: + # no action given, let's use the default 'include' + words.insert(0, 'include') + action = words[0] patterns = dir = dir_pattern = None if action in ('include', 'exclude', diff --git a/distutils2/metadata.py b/distutils2/metadata.py index 047912f..269c962 100644 --- a/distutils2/metadata.py +++ b/distutils2/metadata.py @@ -11,7 +11,7 @@ from StringIO import StringIO from email import message_from_file from tokenize import tokenize, NAME, OP, STRING, ENDMARKER -from distutils2.log import warn +from distutils2 import logger from distutils2.version import (is_valid_predicate, is_valid_version, is_valid_versions) from distutils2.errors import (MetadataConflictError, @@ -391,16 +391,16 @@ class DistributionMetadata(object): for v in value: # check that the values are valid predicates if not is_valid_predicate(v.split(';')[0]): - warn('"%s" is not a valid predicate (field "%s")' % + logger.warn('"%s" is not a valid predicate (field "%s")' % (v, name)) # FIXME this rejects UNKNOWN, is that right? elif name in _VERSIONS_FIELDS and value is not None: if not is_valid_versions(value): - warn('"%s" is not a valid version (field "%s")' % + logger.warn('"%s" is not a valid version (field "%s")' % (value, name)) elif name in _VERSION_FIELDS and value is not None: if not is_valid_version(value): - warn('"%s" is not a valid version (field "%s")' % + logger.warn('"%s" is not a valid version (field "%s")' % (value, name)) if name in _UNICODEFIELDS: diff --git a/distutils2/mkcfg.py b/distutils2/mkcfg.py index 3826435..9dd57d4 100644 --- a/distutils2/mkcfg.py +++ b/distutils2/mkcfg.py @@ -44,15 +44,15 @@ Version number of the software, typically 2 or 3 numbers separated by dots such as "1.00", "0.6", or "3.02.01". "0.1.0" is recommended for initial development. ''', - 'description': ''' -A short summary of what this package is or does, typically a sentence 80 + 'summary': ''' +A one-line summary of what this project is or does, typically a sentence 80 characters or less in length. ''', 'author': ''' The full name of the author (typically you). ''', 'author_email': ''' -E-mail address of the package author (typically you). +E-mail address of the project author (typically you). ''', 'do_classifier': ''' Trove classifiers are optional identifiers that allow you to specify the @@ -60,12 +60,19 @@ intended audience by saying things like "Beta software with a text UI for Linux under the PSF license. However, this can be a somewhat involved process. ''', - 'package': ''' + 'packages': ''' You can provide a package name contained in your project. ''', + 'modules': ''' +You can provide a python module contained in your project. +''', + 'extra_files': ''' +You can provide extra files/dirs contained in your project. +It has to follow the template syntax. XXX add help here. +''', 'home_page': ''' -The home page for the package, typically starting with "http://". +The home page for the project, typically starting with "http://". ''', 'trove_license': ''' Optionally you can specify a license. Type a string that identifies a common @@ -149,6 +156,8 @@ class MainProgram(object): self.data = {} self.data['classifier'] = self.classifiers self.data['packages'] = [] + self.data['modules'] = [] + self.data['extra_files'] = [] self.load_config_file() def lookup_option(self, key): @@ -222,8 +231,8 @@ class MainProgram(object): _helptext['name']) self.data['version'] = ask('Current version number', self.data.get('version'), _helptext['version']) - self.data['description'] = ask('Package description', - self.data.get('description'), _helptext['description'], + self.data['summary'] = ask('Package summary', + self.data.get('summary'), _helptext['summary'], lengthy=True) self.data['author'] = ask('Author name', self.data.get('author'), _helptext['author']) @@ -233,21 +242,106 @@ class MainProgram(object): self.data.get('home_page'), _helptext['home_page'], required=False) - while ask_yn('Do you want to add a package ?', - helptext=_helptext['package']) == 'y': - self.set_package() + if ask_yn('Do you want me to automatically build the file list ' + 'with everything I can find in the current directory ? ' + 'If you say no, you will have to define them manually.') == 'y': + self._find_files() + else: + while ask_yn('Do you want to add a single module ?' + ' (you will be able to add full packages next)', + helptext=_helptext['modules']) == 'y': + self._set_multi('Module name', 'modules') + + while ask_yn('Do you want to add a package ?', + helptext=_helptext['packages']) == 'y': + self._set_multi('Package name', 'packages') + + while ask_yn('Do you want to add an extra file ?', + helptext=_helptext['extra_files']) == 'y': + self._set_multi('Extra file/dir name', 'extra_files') + if ask_yn('Do you want to set Trove classifiers?', helptext=_helptext['do_classifier']) == 'y': self.set_classifier() - def set_package(self): - packages = self.data['packages'] - name = ask('Package name', helptext=_helptext['package']).strip() - if name == '': + def _find_files(self): + # we are looking for python modules and packages, + # other stuff are added as regular files + pkgs = self.data['packages'] + modules = self.data['modules'] + extra_files = self.data['extra_files'] + + def is_package(path): + return os.path.exists(os.path.join(path, '__init__.py')) + + curdir = os.getcwd() + scanned = [] + _pref = ['lib', 'include', 'dist', 'build', '.', '~'] + _suf = ['.pyc'] + + + def to_skip(path): + path = relative(path) + + for pref in _pref: + if path.startswith(pref): + return True + + for suf in _suf: + if path.endswith(suf): + return True + + return False + + def relative(path): + return path[len(curdir) + 1:] + + def dotted(path): + res = relative(path).replace(os.path.sep, '.') + if res.endswith('.py'): + res = res[:-len('.py')] + return res + + # first pass : packages + for root, dirs, files in os.walk(curdir): + if to_skip(root): + continue + for dir_ in dirs: + if to_skip(dir_): + continue + fullpath = os.path.join(root, dir_) + dotted_name = dotted(fullpath) + if is_package(fullpath) and dotted_name not in pkgs: + pkgs.append(dotted_name) + scanned.append(fullpath) + + # modules and extra files + for root, dirs, files in os.walk(curdir): + if to_skip(root): + continue + + for path in scanned: + if root.startswith(path): + continue + + for file in files: + fullpath = os.path.join(root, file) + if to_skip(fullpath): + continue + # single module ? + if os.path.splitext(file)[-1] == '.py': + modules.append(dotted(fullpath)) + else: + extra_files.append(relative(fullpath)) + + def _set_multi(self, question, name): + existing_values = self.data[name] + value = ask(question, helptext=_helptext[name]).strip() + if value == '': return - if name not in packages: - packages.append(name) + if value not in existing_values: + existing_values.append(value) def set_classifier(self): self.set_devel_status(self.classifiers) @@ -379,7 +473,7 @@ class MainProgram(object): fp.write('version = %s\n' % self.data['version']) fp.write('author = %s\n' % self.data['author']) fp.write('author_email = %s\n' % self.data['author_email']) - fp.write('description = %s\n' % self.data['description']) + fp.write('summary = %s\n' % self.data['summary']) fp.write('home_page = %s\n' % self.data['home_page']) fp.write('\n') if len(self.data['classifier']) > 0: @@ -389,10 +483,14 @@ class MainProgram(object): fp.write('\n') fp.write('[files]\n') - packages = '\n'.join([' %s' % pkg for pkg in - self.data['packages']]) + for element in ('packages', 'modules', 'extra_files'): + if len(self.data[element]) == 0: + continue + items = '\n'.join([' %s' % item for item in + self.data[element]]) + fp.write('%s = %s\n' % (element, items.strip())) + fp.write('\n') - fp.write('packages = %s\n' % packages.strip()) finally: fp.close() diff --git a/distutils2/run.py b/distutils2/run.py index af3ab60..cb51dc5 100644 --- a/distutils2/run.py +++ b/distutils2/run.py @@ -1,4 +1,109 @@ -from distutils2.core import setup +import os +import sys + +from distutils2.util import grok_environment_error +from distutils2.errors import (DistutilsSetupError, DistutilsArgError, + DistutilsError, CCompilerError) +from distutils2.dist import Distribution + +# This is a barebones help message generated displayed when the user +# runs the setup script with no arguments at all. More useful help +# is generated with various --help options: global help, list commands, +# and per-command help. +USAGE = """\ +usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] + or: %(script)s --help [cmd1 cmd2 ...] + or: %(script)s --help-commands + or: %(script)s cmd --help +""" + + +def gen_usage(script_name): + script = os.path.basename(script_name) + return USAGE % {'script': script} + + +def main(**attrs): + """The gateway to the Distutils: do everything your setup script needs + to do, in a highly flexible and user-driven way. Briefly: create a + Distribution instance; find and parse config files; parse the command + line; run each Distutils command found there, customized by the options + supplied to 'setup()' (as keyword arguments), in config files, and on + the command line. + + The Distribution instance might be an instance of a class supplied via + the 'distclass' keyword argument to 'setup'; if no such class is + supplied, then the Distribution class (in dist.py) is instantiated. + All other arguments to 'setup' (except for 'cmdclass') are used to set + attributes of the Distribution instance. + + The 'cmdclass' argument, if supplied, is a dictionary mapping command + names to command classes. Each command encountered on the command line + will be turned into a command class, which is in turn instantiated; any + class found in 'cmdclass' is used in place of the default, which is + (for command 'foo_bar') class 'foo_bar' in module + 'distutils2.command.foo_bar'. The command class must provide a + 'user_options' attribute which is a list of option specifiers for + 'distutils2.fancy_getopt'. Any command-line options between the current + and the next command are used to set attributes of the current command + object. + + When the entire command line has been successfully parsed, calls the + 'run()' method on each command object in turn. This method will be + driven entirely by the Distribution object (which each command object + has a reference to, thanks to its constructor), and the + command-specific options that became attributes of each command + object. + """ + # Determine the distribution class -- either caller-supplied or + # our Distribution (see below). + distclass = attrs.pop('distclass', Distribution) + + if 'script_name' not in attrs: + attrs['script_name'] = os.path.basename(sys.argv[0]) + + if 'script_args' not in attrs: + attrs['script_args'] = sys.argv[1:] + + # Create the Distribution instance, using the remaining arguments + # (ie. everything except distclass) to initialize it + try: + dist = distclass(attrs) + except DistutilsSetupError, msg: + if 'name' in attrs: + raise SystemExit, "error in %s setup command: %s" % \ + (attrs['name'], msg) + else: + raise SystemExit, "error in setup command: %s" % msg + + # Find and parse the config file(s): they will override options from + # the setup script, but be overridden by the command line. + dist.parse_config_files() + + # Parse the command line and override config files; any + # command line errors are the end user's fault, so turn them into + # SystemExit to suppress tracebacks. + try: + res = dist.parse_command_line() + except DistutilsArgError, msg: + raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg + + # And finally, run all the commands found on the command line. + if res: + try: + dist.run_commands() + except KeyboardInterrupt: + raise SystemExit, "interrupted" + except (IOError, os.error), exc: + error = grok_environment_error(exc) + raise SystemExit, error + + except (DistutilsError, + CCompilerError), msg: + raise SystemExit, "error: " + str(msg) + + return dist + if __name__ == '__main__': - setup() + main() diff --git a/distutils2/tests/conversions/01_after.py b/distutils2/tests/conversions/01_after.py deleted file mode 100644 index 93f818a..0000000 --- a/distutils2/tests/conversions/01_after.py +++ /dev/null @@ -1,4 +0,0 @@ -from distutils2.core import setup - -setup(name='Foo') - diff --git a/distutils2/tests/conversions/01_before.py b/distutils2/tests/conversions/01_before.py deleted file mode 100644 index 3e818d8..0000000 --- a/distutils2/tests/conversions/01_before.py +++ /dev/null @@ -1,4 +0,0 @@ -from distutils.core import setup - -setup(name='Foo') - diff --git a/distutils2/tests/conversions/02_after.py b/distutils2/tests/conversions/02_after.py deleted file mode 100644 index bfc2d8f..0000000 --- a/distutils2/tests/conversions/02_after.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- encoding: utf-8 -*- -import sys -import os -from distutils2.core import setup, Extension -from distutils2.errors import CCompilerError, DistutilsError, CompileError -from distutils2.command.build_ext import build_ext as distutils_build_ext - -VERSION = "0.1" - -class build_ext(distutils_build_ext): - - def build_extension(self, ext): - try: - return distutils_build_ext.build_extension(self, ext) - except (CCompilerError, DistutilsError, CompileError), e: - pass - -def _get_ext_modules(): - levenshtein = Extension('_levenshtein', - sources=[os.path.join('texttools', - '_levenshtein.c')]) - return [levenshtein] - -with open('README.txt') as f: - LONG_DESCRIPTION = f.read() - -setup(name="TextTools", version=VERSION, author="Tarek Ziade", - author_email="tarek@ziade.org", - home_page="http://bitbucket.org/tarek/texttools", - summary="Text manipulation utilities", - description=LONG_DESCRIPTION, - keywords="text,guess,levenshtein", - classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Python Software Foundation License' - ], - cmdclass={'build_ext': build_ext}, - packages=['texttools'], - package_dir={'texttools': 'texttools'}, - package_data={'texttools': [os.path.join('samples', '*.txt')]}, - scripts=[os.path.join('scripts', 'levenshtein.py'), - os.path.join('scripts', 'guesslang.py')], - ext_modules=_get_ext_modules() - ) - diff --git a/distutils2/tests/conversions/02_before.py b/distutils2/tests/conversions/02_before.py deleted file mode 100644 index f7ccc12..0000000 --- a/distutils2/tests/conversions/02_before.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- encoding: utf-8 -*- -import sys -import os -from distutils.core import setup, Extension -from distutils.errors import CCompilerError, DistutilsError, CompileError -from distutils.command.build_ext import build_ext as distutils_build_ext - -VERSION = "0.1" - -class build_ext(distutils_build_ext): - - def build_extension(self, ext): - try: - return distutils_build_ext.build_extension(self, ext) - except (CCompilerError, DistutilsError, CompileError), e: - pass - -def _get_ext_modules(): - levenshtein = Extension('_levenshtein', - sources=[os.path.join('texttools', - '_levenshtein.c')]) - return [levenshtein] - -with open('README.txt') as f: - LONG_DESCRIPTION = f.read() - -setup(name="TextTools", version=VERSION, author="Tarek Ziade", - author_email="tarek@ziade.org", - url="http://bitbucket.org/tarek/texttools", - description="Text manipulation utilities", - long_description=LONG_DESCRIPTION, - keywords="text,guess,levenshtein", - classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Python Software Foundation License' - ], - cmdclass={'build_ext': build_ext}, - packages=['texttools'], - package_dir={'texttools': 'texttools'}, - package_data={'texttools': [os.path.join('samples', '*.txt')]}, - scripts=[os.path.join('scripts', 'levenshtein.py'), - os.path.join('scripts', 'guesslang.py')], - ext_modules=_get_ext_modules() - ) - diff --git a/distutils2/tests/conversions/03_after.py b/distutils2/tests/conversions/03_after.py deleted file mode 100644 index 3d4dafa..0000000 --- a/distutils2/tests/conversions/03_after.py +++ /dev/null @@ -1,93 +0,0 @@ -############################################################################## -# -# Copyright (c) 2006-2009 Zope Corporation and Contributors. -# All Rights Reserved. -# -# This software is subject to the provisions of the Zope Public License, -# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. -# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED -# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS -# FOR A PARTICULAR PURPOSE. -# -############################################################################## -name = "zc.buildout" -version = "1.5.0dev" - -import os -from distutils2.core import setup - -def read(*rnames): - return open(os.path.join(os.path.dirname(__file__), *rnames)).read() - -long_description=( - read('README.txt') - + '\n' + - 'Detailed Documentation\n' - '**********************\n' - + '\n' + - read('src', 'zc', 'buildout', 'buildout.txt') - + '\n' + - read('src', 'zc', 'buildout', 'unzip.txt') - + '\n' + - read('src', 'zc', 'buildout', 'repeatable.txt') - + '\n' + - read('src', 'zc', 'buildout', 'download.txt') - + '\n' + - read('src', 'zc', 'buildout', 'downloadcache.txt') - + '\n' + - read('src', 'zc', 'buildout', 'extends-cache.txt') - + '\n' + - read('src', 'zc', 'buildout', 'setup.txt') - + '\n' + - read('src', 'zc', 'buildout', 'update.txt') - + '\n' + - read('src', 'zc', 'buildout', 'debugging.txt') - + '\n' + - read('src', 'zc', 'buildout', 'testing.txt') - + '\n' + - read('src', 'zc', 'buildout', 'easy_install.txt') - + '\n' + - read('src', 'zc', 'buildout', 'distribute.txt') - + '\n' + - read('CHANGES.txt') - + '\n' + - 'Download\n' - '**********************\n' - ) - -entry_points = """ -[console_scripts] -buildout = %(name)s.buildout:main - -[zc.buildout] -debug = %(name)s.testrecipes:Debug - -""" % dict(name=name) - -setup( - name = name, - version = version, - author = "Jim Fulton", - author_email = "jim@zope.com", - summary = "System for managing development buildouts", - description=long_description, - license = "ZPL 2.1", - keywords = "development build", - home_page='http://buildout.org', - - data_files = [('.', ['README.txt'])], - packages = ['zc', 'zc.buildout'], - package_dir = {'': 'src'}, - namespace_packages = ['zc'], - requires_dist = ['setuptools'], - include_package_data = True, - entry_points = entry_points, - zip_safe=False, - classifiers = [ - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Zope Public License', - 'Topic :: Software Development :: Build Tools', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - ) diff --git a/distutils2/tests/conversions/03_before.py b/distutils2/tests/conversions/03_before.py deleted file mode 100644 index 31a99fc..0000000 --- a/distutils2/tests/conversions/03_before.py +++ /dev/null @@ -1,93 +0,0 @@ -############################################################################## -# -# Copyright (c) 2006-2009 Zope Corporation and Contributors. -# All Rights Reserved. -# -# This software is subject to the provisions of the Zope Public License, -# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. -# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED -# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS -# FOR A PARTICULAR PURPOSE. -# -############################################################################## -name = "zc.buildout" -version = "1.5.0dev" - -import os -from setuptools import setup - -def read(*rnames): - return open(os.path.join(os.path.dirname(__file__), *rnames)).read() - -long_description=( - read('README.txt') - + '\n' + - 'Detailed Documentation\n' - '**********************\n' - + '\n' + - read('src', 'zc', 'buildout', 'buildout.txt') - + '\n' + - read('src', 'zc', 'buildout', 'unzip.txt') - + '\n' + - read('src', 'zc', 'buildout', 'repeatable.txt') - + '\n' + - read('src', 'zc', 'buildout', 'download.txt') - + '\n' + - read('src', 'zc', 'buildout', 'downloadcache.txt') - + '\n' + - read('src', 'zc', 'buildout', 'extends-cache.txt') - + '\n' + - read('src', 'zc', 'buildout', 'setup.txt') - + '\n' + - read('src', 'zc', 'buildout', 'update.txt') - + '\n' + - read('src', 'zc', 'buildout', 'debugging.txt') - + '\n' + - read('src', 'zc', 'buildout', 'testing.txt') - + '\n' + - read('src', 'zc', 'buildout', 'easy_install.txt') - + '\n' + - read('src', 'zc', 'buildout', 'distribute.txt') - + '\n' + - read('CHANGES.txt') - + '\n' + - 'Download\n' - '**********************\n' - ) - -entry_points = """ -[console_scripts] -buildout = %(name)s.buildout:main - -[zc.buildout] -debug = %(name)s.testrecipes:Debug - -""" % dict(name=name) - -setup( - name = name, - version = version, - author = "Jim Fulton", - author_email = "jim@zope.com", - description = "System for managing development buildouts", - long_description=long_description, - license = "ZPL 2.1", - keywords = "development build", - url='http://buildout.org', - - data_files = [('.', ['README.txt'])], - packages = ['zc', 'zc.buildout'], - package_dir = {'': 'src'}, - namespace_packages = ['zc'], - install_requires = 'setuptools', - include_package_data = True, - entry_points = entry_points, - zip_safe=False, - classifiers = [ - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Zope Public License', - 'Topic :: Software Development :: Build Tools', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - ) diff --git a/distutils2/tests/conversions/04_after.py b/distutils2/tests/conversions/04_after.py deleted file mode 100644 index f366a48..0000000 --- a/distutils2/tests/conversions/04_after.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys, os -try: - from distutils2.core import setup - kw = {'entry_points': - """[console_scripts]\nvirtualenv = virtualenv:main\n""", - 'zip_safe': False} -except ImportError: - from distutils2.core import setup - if sys.platform == 'win32': - print('Note: without Setuptools installed you will have to use "python -m virtualenv ENV"') - else: - kw = {'scripts': ['scripts/virtualenv']} -import re - -here = os.path.dirname(os.path.abspath(__file__)) - -## Figure out the version from virtualenv.py: -version_re = re.compile( - r'virtualenv_version = "(.*?)"') -fp = open(os.path.join(here, 'virtualenv.py')) -version = None -for line in fp: - match = version_re.search(line) - if match: - version = match.group(1) - break -else: - raise Exception("Cannot find version in virtualenv.py") -fp.close() - -## Get long_description from index.txt: -f = open(os.path.join(here, 'docs', 'index.txt')) -long_description = f.read().strip() -long_description = long_description.split('split here', 1)[1] -f.close() - -## A warning just for Ian (related to distribution): -try: - import getpass -except ImportError: - is_ianb = False -else: - is_ianb = getpass.getuser() == 'ianb' - -if is_ianb and 'register' in sys.argv: - if 'hg tip\n~~~~~~' in long_description: - print >> sys.stderr, ( - "WARNING: hg tip is in index.txt") - -setup(name='virtualenv', - version=version, - summary="Virtual Python Environment builder", - description=long_description, - classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - ], - keywords='setuptools deployment installation distutils', - author='Ian Bicking', - author_email='ianb@colorstudy.com', - home_page='http://virtualenv.openplans.org', - license='MIT', - use_2to3=True, - py_modules=['virtualenv'], - packages=['virtualenv_support'], - package_data={'virtualenv_support': ['*-py%s.egg' % sys.version[:3], '*.tar.gz']}, - **kw - ) diff --git a/distutils2/tests/conversions/04_before.py b/distutils2/tests/conversions/04_before.py deleted file mode 100644 index 4792595..0000000 --- a/distutils2/tests/conversions/04_before.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys, os -try: - from setuptools import setup - kw = {'entry_points': - """[console_scripts]\nvirtualenv = virtualenv:main\n""", - 'zip_safe': False} -except ImportError: - from distutils.core import setup - if sys.platform == 'win32': - print('Note: without Setuptools installed you will have to use "python -m virtualenv ENV"') - else: - kw = {'scripts': ['scripts/virtualenv']} -import re - -here = os.path.dirname(os.path.abspath(__file__)) - -## Figure out the version from virtualenv.py: -version_re = re.compile( - r'virtualenv_version = "(.*?)"') -fp = open(os.path.join(here, 'virtualenv.py')) -version = None -for line in fp: - match = version_re.search(line) - if match: - version = match.group(1) - break -else: - raise Exception("Cannot find version in virtualenv.py") -fp.close() - -## Get long_description from index.txt: -f = open(os.path.join(here, 'docs', 'index.txt')) -long_description = f.read().strip() -long_description = long_description.split('split here', 1)[1] -f.close() - -## A warning just for Ian (related to distribution): -try: - import getpass -except ImportError: - is_ianb = False -else: - is_ianb = getpass.getuser() == 'ianb' - -if is_ianb and 'register' in sys.argv: - if 'hg tip\n~~~~~~' in long_description: - print >> sys.stderr, ( - "WARNING: hg tip is in index.txt") - -setup(name='virtualenv', - version=version, - description="Virtual Python Environment builder", - long_description=long_description, - classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - ], - keywords='setuptools deployment installation distutils', - author='Ian Bicking', - author_email='ianb@colorstudy.com', - url='http://virtualenv.openplans.org', - license='MIT', - use_2to3=True, - py_modules=['virtualenv'], - packages=['virtualenv_support'], - package_data={'virtualenv_support': ['*-py%s.egg' % sys.version[:3], '*.tar.gz']}, - **kw - ) diff --git a/distutils2/tests/conversions/05_after.py b/distutils2/tests/conversions/05_after.py deleted file mode 100644 index 2f6a7b3..0000000 --- a/distutils2/tests/conversions/05_after.py +++ /dev/null @@ -1,137 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright (C) 2003-2009 Edgewall Software -# All rights reserved. -# -# This software is licensed as described in the file COPYING, which -# you should have received as part of this distribution. The terms -# are also available at http://trac.edgewall.org/wiki/TracLicense. -# -# This software consists of voluntary contributions made by many -# individuals. For the exact contribution history, see the revision -# history and logs, available at http://trac.edgewall.org/log/. - -from distutils2.core import setup, find_packages - -extra = {} - -try: - import babel - - extractors = [ - ('**.py', 'python', None), - ('**/templates/**.html', 'genshi', None), - ('**/templates/**.txt', 'genshi', - {'template_class': 'genshi.template:NewTextTemplate'}), - ] - extra['message_extractors'] = { - 'trac': extractors, - 'tracopt': extractors, - } - - from trac.util.dist import get_l10n_js_cmdclass - extra['cmdclass'] = get_l10n_js_cmdclass() - -except ImportError, e: - pass - -setup( - name = 'Trac', - version = '0.12.1', - summary = 'Integrated SCM, wiki, issue tracker and project environment', - description = """ -Trac is a minimalistic web-based software project management and bug/issue -tracking system. It provides an interface to the Subversion revision control -systems, an integrated wiki, flexible issue tracking and convenient report -facilities. -""", - author = 'Edgewall Software', - author_email = 'info@edgewall.com', - license = 'BSD', - home_page = 'http://trac.edgewall.org/', - download_url = 'http://trac.edgewall.org/wiki/TracDownload', - classifiers = [ - 'Environment :: Web Environment', - 'Framework :: Trac', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Topic :: Software Development :: Bug Tracking', - 'Topic :: Software Development :: Version Control', - ], - - packages = find_packages(exclude=['*.tests']), - package_data = { - '': ['templates/*'], - 'trac': ['htdocs/*.*', 'htdocs/README', 'htdocs/js/*.*', - 'htdocs/js/messages/*.*', 'htdocs/css/*.*', - 'htdocs/guide/*', 'locale/*/LC_MESSAGES/messages.mo'], - 'trac.wiki': ['default-pages/*'], - 'trac.ticket': ['workflows/*.ini'], - }, - - test_suite = 'trac.test.suite', - zip_safe = True, - - requires_dist = [ - 'setuptools>=0.6b1', - 'Genshi>=0.6', - ], - extras_require = { - 'Babel': ['Babel>=0.9.5'], - 'Pygments': ['Pygments>=0.6'], - 'reST': ['docutils>=0.3'], - 'SilverCity': ['SilverCity>=0.9.4'], - 'Textile': ['textile>=2.0'], - }, - - entry_points = """ - [console_scripts] - trac-admin = trac.admin.console:run - tracd = trac.web.standalone:main - - [trac.plugins] - trac.about = trac.about - trac.admin.console = trac.admin.console - trac.admin.web_ui = trac.admin.web_ui - trac.attachment = trac.attachment - trac.db.mysql = trac.db.mysql_backend - trac.db.postgres = trac.db.postgres_backend - trac.db.sqlite = trac.db.sqlite_backend - trac.mimeview.patch = trac.mimeview.patch - trac.mimeview.pygments = trac.mimeview.pygments[Pygments] - trac.mimeview.rst = trac.mimeview.rst[reST] - trac.mimeview.silvercity = trac.mimeview.silvercity[SilverCity] - trac.mimeview.txtl = trac.mimeview.txtl[Textile] - trac.prefs = trac.prefs.web_ui - trac.search = trac.search.web_ui - trac.ticket.admin = trac.ticket.admin - trac.ticket.query = trac.ticket.query - trac.ticket.report = trac.ticket.report - trac.ticket.roadmap = trac.ticket.roadmap - trac.ticket.web_ui = trac.ticket.web_ui - trac.timeline = trac.timeline.web_ui - trac.versioncontrol.admin = trac.versioncontrol.admin - trac.versioncontrol.svn_authz = trac.versioncontrol.svn_authz - trac.versioncontrol.svn_fs = trac.versioncontrol.svn_fs - trac.versioncontrol.svn_prop = trac.versioncontrol.svn_prop - trac.versioncontrol.web_ui = trac.versioncontrol.web_ui - trac.web.auth = trac.web.auth - trac.web.session = trac.web.session - trac.wiki.admin = trac.wiki.admin - trac.wiki.interwiki = trac.wiki.interwiki - trac.wiki.macros = trac.wiki.macros - trac.wiki.web_ui = trac.wiki.web_ui - trac.wiki.web_api = trac.wiki.web_api - tracopt.mimeview.enscript = tracopt.mimeview.enscript - tracopt.mimeview.php = tracopt.mimeview.php - tracopt.perm.authz_policy = tracopt.perm.authz_policy - tracopt.perm.config_perm_provider = tracopt.perm.config_perm_provider - tracopt.ticket.commit_updater = tracopt.ticket.commit_updater - tracopt.ticket.deleter = tracopt.ticket.deleter - """, - - **extra -) diff --git a/distutils2/tests/conversions/05_before.py b/distutils2/tests/conversions/05_before.py deleted file mode 100644 index ccce17b..0000000 --- a/distutils2/tests/conversions/05_before.py +++ /dev/null @@ -1,137 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright (C) 2003-2009 Edgewall Software -# All rights reserved. -# -# This software is licensed as described in the file COPYING, which -# you should have received as part of this distribution. The terms -# are also available at http://trac.edgewall.org/wiki/TracLicense. -# -# This software consists of voluntary contributions made by many -# individuals. For the exact contribution history, see the revision -# history and logs, available at http://trac.edgewall.org/log/. - -from setuptools import setup, find_packages - -extra = {} - -try: - import babel - - extractors = [ - ('**.py', 'python', None), - ('**/templates/**.html', 'genshi', None), - ('**/templates/**.txt', 'genshi', - {'template_class': 'genshi.template:NewTextTemplate'}), - ] - extra['message_extractors'] = { - 'trac': extractors, - 'tracopt': extractors, - } - - from trac.util.dist import get_l10n_js_cmdclass - extra['cmdclass'] = get_l10n_js_cmdclass() - -except ImportError, e: - pass - -setup( - name = 'Trac', - version = '0.12.1', - description = 'Integrated SCM, wiki, issue tracker and project environment', - long_description = """ -Trac is a minimalistic web-based software project management and bug/issue -tracking system. It provides an interface to the Subversion revision control -systems, an integrated wiki, flexible issue tracking and convenient report -facilities. -""", - author = 'Edgewall Software', - author_email = 'info@edgewall.com', - license = 'BSD', - url = 'http://trac.edgewall.org/', - download_url = 'http://trac.edgewall.org/wiki/TracDownload', - classifiers = [ - 'Environment :: Web Environment', - 'Framework :: Trac', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Topic :: Software Development :: Bug Tracking', - 'Topic :: Software Development :: Version Control', - ], - - packages = find_packages(exclude=['*.tests']), - package_data = { - '': ['templates/*'], - 'trac': ['htdocs/*.*', 'htdocs/README', 'htdocs/js/*.*', - 'htdocs/js/messages/*.*', 'htdocs/css/*.*', - 'htdocs/guide/*', 'locale/*/LC_MESSAGES/messages.mo'], - 'trac.wiki': ['default-pages/*'], - 'trac.ticket': ['workflows/*.ini'], - }, - - test_suite = 'trac.test.suite', - zip_safe = True, - - install_requires = [ - 'setuptools>=0.6b1', - 'Genshi>=0.6', - ], - extras_require = { - 'Babel': ['Babel>=0.9.5'], - 'Pygments': ['Pygments>=0.6'], - 'reST': ['docutils>=0.3'], - 'SilverCity': ['SilverCity>=0.9.4'], - 'Textile': ['textile>=2.0'], - }, - - entry_points = """ - [console_scripts] - trac-admin = trac.admin.console:run - tracd = trac.web.standalone:main - - [trac.plugins] - trac.about = trac.about - trac.admin.console = trac.admin.console - trac.admin.web_ui = trac.admin.web_ui - trac.attachment = trac.attachment - trac.db.mysql = trac.db.mysql_backend - trac.db.postgres = trac.db.postgres_backend - trac.db.sqlite = trac.db.sqlite_backend - trac.mimeview.patch = trac.mimeview.patch - trac.mimeview.pygments = trac.mimeview.pygments[Pygments] - trac.mimeview.rst = trac.mimeview.rst[reST] - trac.mimeview.silvercity = trac.mimeview.silvercity[SilverCity] - trac.mimeview.txtl = trac.mimeview.txtl[Textile] - trac.prefs = trac.prefs.web_ui - trac.search = trac.search.web_ui - trac.ticket.admin = trac.ticket.admin - trac.ticket.query = trac.ticket.query - trac.ticket.report = trac.ticket.report - trac.ticket.roadmap = trac.ticket.roadmap - trac.ticket.web_ui = trac.ticket.web_ui - trac.timeline = trac.timeline.web_ui - trac.versioncontrol.admin = trac.versioncontrol.admin - trac.versioncontrol.svn_authz = trac.versioncontrol.svn_authz - trac.versioncontrol.svn_fs = trac.versioncontrol.svn_fs - trac.versioncontrol.svn_prop = trac.versioncontrol.svn_prop - trac.versioncontrol.web_ui = trac.versioncontrol.web_ui - trac.web.auth = trac.web.auth - trac.web.session = trac.web.session - trac.wiki.admin = trac.wiki.admin - trac.wiki.interwiki = trac.wiki.interwiki - trac.wiki.macros = trac.wiki.macros - trac.wiki.web_ui = trac.wiki.web_ui - trac.wiki.web_api = trac.wiki.web_api - tracopt.mimeview.enscript = tracopt.mimeview.enscript - tracopt.mimeview.php = tracopt.mimeview.php - tracopt.perm.authz_policy = tracopt.perm.authz_policy - tracopt.perm.config_perm_provider = tracopt.perm.config_perm_provider - tracopt.ticket.commit_updater = tracopt.ticket.commit_updater - tracopt.ticket.deleter = tracopt.ticket.deleter - """, - - **extra -) diff --git a/distutils2/tests/pypi_server.py b/distutils2/tests/pypi_server.py index a009e61..a5fa0cf 100644 --- a/distutils2/tests/pypi_server.py +++ b/distutils2/tests/pypi_server.py @@ -106,7 +106,7 @@ class PyPIServer(threading.Thread): #TODO allow to serve XMLRPC and HTTP static files at the same time. if not self._serve_xmlrpc: - self.server = HTTPServer(('', 0), PyPIRequestHandler) + self.server = HTTPServer(('127.0.0.1', 0), PyPIRequestHandler) self.server.RequestHandlerClass.pypi_server = self self.request_queue = Queue.Queue() @@ -123,7 +123,7 @@ class PyPIServer(threading.Thread): for path in static_filesystem_paths] else: # XMLRPC server - self.server = PyPIXMLRPCServer(('', 0)) + self.server = PyPIXMLRPCServer(('127.0.0.1', 0)) self.xmlrpc = XMLRPCMockIndex() # register the xmlrpc methods self.server.register_introspection_functions() diff --git a/distutils2/tests/support.py b/distutils2/tests/support.py index fe343dc..a5a6c21 100644 --- a/distutils2/tests/support.py +++ b/distutils2/tests/support.py @@ -28,10 +28,10 @@ import shutil import tempfile import warnings from copy import deepcopy +import logging -from distutils2 import log +from distutils2 import logger from distutils2.dist import Distribution -from distutils2.log import DEBUG, INFO, WARN, ERROR, FATAL from distutils2.tests import unittest __all__ = ['LoggingCatcher', 'WarningsCatcher', 'TempdirManager', @@ -49,23 +49,18 @@ class LoggingCatcher(object): def setUp(self): super(LoggingCatcher, self).setUp() - self.threshold = log.set_threshold(FATAL) - # when log is replaced by logging we won't need - # such monkey-patching anymore - self._old_log = log.Log._log - log.Log._log = self._log + self.old_log = logger._log + logger._log = self._log + logger.setLevel(logging.INFO) self.logs = [] + def _log(self, *args, **kw): + self.logs.append(args) + def tearDown(self): - log.set_threshold(self.threshold) - log.Log._log = self._old_log + logger._log = self.old_log super(LoggingCatcher, self).tearDown() - def _log(self, level, msg, args): - if level not in (DEBUG, INFO, WARN, ERROR, FATAL): - raise ValueError('%s wrong log level' % level) - self.logs.append((level, msg, args)) - def get_logs(self, *levels): """Return a list of caught messages with level in `levels`. @@ -83,13 +78,6 @@ class LoggingCatcher(object): del self.logs[:] -class LoggingSilencer(object): - "Class that raises an exception to make sure the renaming is noticed." - - def __init__(self, *args): - raise DeprecationWarning("LoggingSilencer renamed to LoggingCatcher") - - class WarningsCatcher(object): def setUp(self): diff --git a/distutils2/tests/test_command_bdist_dumb.py b/distutils2/tests/test_command_bdist_dumb.py index ffe98b9..15559fc 100644 --- a/distutils2/tests/test_command_bdist_dumb.py +++ b/distutils2/tests/test_command_bdist_dumb.py @@ -12,12 +12,12 @@ except ImportError: from distutils2.tests import run_unittest, unittest -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.command.bdist_dumb import bdist_dumb from distutils2.tests import support SETUP_PY = """\ -from distutils.core import setup +from distutils.run import setup import foo setup(name='foo', version='0.1', py_modules=['foo'], diff --git a/distutils2/tests/test_command_build_ext.py b/distutils2/tests/test_command_build_ext.py index 8eb4106..f7e8b40 100644 --- a/distutils2/tests/test_command_build_ext.py +++ b/distutils2/tests/test_command_build_ext.py @@ -5,7 +5,8 @@ from StringIO import StringIO import distutils2.tests from distutils2.tests import unittest -from distutils2.core import Extension, Distribution +from distutils2.extension import Extension +from distutils2.dist import Distribution from distutils2.command.build_ext import build_ext from distutils2.tests import support from distutils2.extension import Extension diff --git a/distutils2/tests/test_command_build_py.py b/distutils2/tests/test_command_build_py.py index f3e330e..eefdc69 100644 --- a/distutils2/tests/test_command_build_py.py +++ b/distutils2/tests/test_command_build_py.py @@ -5,7 +5,7 @@ import sys import StringIO from distutils2.command.build_py import build_py -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.errors import DistutilsFileError from distutils2.tests import unittest, support diff --git a/distutils2/tests/test_command_build_scripts.py b/distutils2/tests/test_command_build_scripts.py index e7624cd..fd5ca49 100644 --- a/distutils2/tests/test_command_build_scripts.py +++ b/distutils2/tests/test_command_build_scripts.py @@ -3,7 +3,7 @@ import os from distutils2.command.build_scripts import build_scripts -from distutils2.core import Distribution +from distutils2.dist import Distribution try: import sysconfig except ImportError: diff --git a/distutils2/tests/test_command_check.py b/distutils2/tests/test_command_check.py index 93da1f2..60ed4cb 100644 --- a/distutils2/tests/test_command_check.py +++ b/distutils2/tests/test_command_check.py @@ -69,7 +69,7 @@ class CheckTestCase(support.LoggingCatcher, def test_check_hooks(self): pkg_info, dist = self.create_dist() - dist.command_options['install'] = { + dist.command_options['install_dist'] = { 'pre_hook': ('file', {"a": 'some.nonextistant.hook.ghrrraarrhll'}), } cmd = check(dist) diff --git a/distutils2/tests/test_command_config.py b/distutils2/tests/test_command_config.py index cf4bbe1..ec519a6 100644 --- a/distutils2/tests/test_command_config.py +++ b/distutils2/tests/test_command_config.py @@ -4,26 +4,11 @@ import sys from distutils2.command.config import dump_file, config from distutils2.tests import unittest, support -from distutils2 import log class ConfigTestCase(support.LoggingCatcher, support.TempdirManager, unittest.TestCase): - def _info(self, msg, *args): - for line in msg.splitlines(): - self._logs.append(line) - - def setUp(self): - super(ConfigTestCase, self).setUp() - self._logs = [] - self.old_log = log.info - log.info = self._info - - def tearDown(self): - log.info = self.old_log - super(ConfigTestCase, self).tearDown() - def test_dump_file(self): this_file = os.path.splitext(__file__)[0] + '.py' f = open(this_file) @@ -33,7 +18,11 @@ class ConfigTestCase(support.LoggingCatcher, f.close() dump_file(this_file, 'I am the header') - self.assertEqual(len(self._logs), numlines+1) + logs = [] + for log in self.logs: + log = log[1] + logs.extend([log for log in log.split('\n')]) + self.assertEqual(len(logs), numlines+2) def test_search_cpp(self): if sys.platform == 'win32': diff --git a/distutils2/tests/test_command_install.py b/distutils2/tests/test_command_install_dist.py index 87e3e80..001ebae 100644 --- a/distutils2/tests/test_command_install.py +++ b/distutils2/tests/test_command_install_dist.py @@ -12,9 +12,9 @@ _CONFIG_VARS = get_config_vars() from distutils2.tests import captured_stdout -from distutils2.command.install import install -from distutils2.command import install as install_module -from distutils2.core import Distribution +from distutils2.command.install_dist import install_dist +from distutils2.command import install_dist as install_module +from distutils2.dist import Distribution from distutils2.errors import DistutilsOptionError from distutils2.tests import unittest, support @@ -47,7 +47,7 @@ class InstallTestCase(support.TempdirManager, _SCHEMES.set('posix_home', 'platinclude', '{platbase}/include/python') try: - cmd = install(dist) + cmd = install_dist(dist) cmd.home = destination cmd.ensure_finalized() finally: @@ -104,7 +104,7 @@ class InstallTestCase(support.TempdirManager, self.assertTrue(key in schemes) dist = Distribution({'name': 'xx'}) - cmd = install(dist) + cmd = install_dist(dist) # making sure the user option is there options = [name for name, short, lable in cmd.user_options] @@ -129,7 +129,7 @@ class InstallTestCase(support.TempdirManager, def test_handle_extra_path(self): dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) - cmd = install(dist) + cmd = install_dist(dist) # two elements cmd.handle_extra_path() @@ -157,7 +157,7 @@ class InstallTestCase(support.TempdirManager, def test_finalize_options(self): dist = Distribution({'name': 'xx'}) - cmd = install(dist) + cmd = install_dist(dist) # must supply either prefix/exec-prefix/home or # install-base/install-platbase -- not both @@ -183,8 +183,8 @@ class InstallTestCase(support.TempdirManager, pkgdir, dist = self.create_dist() dist = Distribution() - cmd = install(dist) - dist.command_obj['install'] = cmd + cmd = install_dist(dist) + dist.command_obj['install_dist'] = cmd cmd.root = install_dir cmd.record = os.path.join(pkgdir, 'RECORD') cmd.ensure_finalized() diff --git a/distutils2/tests/test_command_install_distinfo.py b/distutils2/tests/test_command_install_distinfo.py index 07f8b1f..48f6ee5 100644 --- a/distutils2/tests/test_command_install_distinfo.py +++ b/distutils2/tests/test_command_install_distinfo.py @@ -5,7 +5,7 @@ import sys import csv from distutils2.command.install_distinfo import install_distinfo -from distutils2.core import Command +from distutils2.command.cmd import Command from distutils2.metadata import DistributionMetadata from distutils2.tests import unittest, support @@ -45,7 +45,7 @@ class InstallDistinfoTestCase(support.TempdirManager, install_dir = self.mkdtemp() install = DummyInstallCmd(dist) - dist.command_obj['install'] = install + dist.command_obj['install_dist'] = install cmd = install_distinfo(dist) dist.command_obj['install_distinfo'] = cmd @@ -73,7 +73,7 @@ class InstallDistinfoTestCase(support.TempdirManager, install_dir = self.mkdtemp() install = DummyInstallCmd(dist) - dist.command_obj['install'] = install + dist.command_obj['install_dist'] = install cmd = install_distinfo(dist) dist.command_obj['install_distinfo'] = cmd @@ -94,7 +94,7 @@ class InstallDistinfoTestCase(support.TempdirManager, install_dir = self.mkdtemp() install = DummyInstallCmd(dist) - dist.command_obj['install'] = install + dist.command_obj['install_dist'] = install cmd = install_distinfo(dist) dist.command_obj['install_distinfo'] = cmd @@ -115,7 +115,7 @@ class InstallDistinfoTestCase(support.TempdirManager, install_dir = self.mkdtemp() install = DummyInstallCmd(dist) - dist.command_obj['install'] = install + dist.command_obj['install_dist'] = install cmd = install_distinfo(dist) dist.command_obj['install_distinfo'] = cmd @@ -136,7 +136,7 @@ class InstallDistinfoTestCase(support.TempdirManager, install_dir = self.mkdtemp() install = DummyInstallCmd(dist) - dist.command_obj['install'] = install + dist.command_obj['install_dist'] = install fake_dists = os.path.join(os.path.dirname(__file__), '..', '_backport', 'tests', 'fake_dists') diff --git a/distutils2/tests/test_command_install_scripts.py b/distutils2/tests/test_command_install_scripts.py index 89184e5..30318d5 100644 --- a/distutils2/tests/test_command_install_scripts.py +++ b/distutils2/tests/test_command_install_scripts.py @@ -3,7 +3,7 @@ import os from distutils2.command.install_scripts import install_scripts -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.tests import unittest, support @@ -16,7 +16,7 @@ class InstallScriptsTestCase(support.TempdirManager, dist = Distribution() dist.command_obj["build"] = support.DummyCommand( build_scripts="/foo/bar") - dist.command_obj["install"] = support.DummyCommand( + dist.command_obj["install_dist"] = support.DummyCommand( install_scripts="/splat/funk", force=1, skip_build=1, @@ -59,7 +59,7 @@ class InstallScriptsTestCase(support.TempdirManager, target = self.mkdtemp() dist = Distribution() dist.command_obj["build"] = support.DummyCommand(build_scripts=source) - dist.command_obj["install"] = support.DummyCommand( + dist.command_obj["install_dist"] = support.DummyCommand( install_scripts=target, force=1, skip_build=1, diff --git a/distutils2/tests/test_command_register.py b/distutils2/tests/test_command_register.py index 3113e80..b1ce79e 100644 --- a/distutils2/tests/test_command_register.py +++ b/distutils2/tests/test_command_register.py @@ -13,7 +13,7 @@ except ImportError: from distutils2.command import register as register_module from distutils2.command.register import register -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.errors import DistutilsSetupError from distutils2.tests import unittest, support diff --git a/distutils2/tests/test_command_sdist.py b/distutils2/tests/test_command_sdist.py index 34059a1..ae37cf5 100644 --- a/distutils2/tests/test_command_sdist.py +++ b/distutils2/tests/test_command_sdist.py @@ -3,6 +3,7 @@ import os import shutil import zipfile import tarfile +import logging # zlib is not used here, but if it's not available # the tests that use zipfile may fail @@ -25,12 +26,11 @@ from distutils2.tests import captured_stdout from distutils2.command.sdist import sdist from distutils2.command.sdist import show_formats -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.tests import unittest from distutils2.errors import DistutilsExecError, DistutilsOptionError from distutils2.util import find_executable from distutils2.tests import support -from distutils2.log import WARN try: from shutil import get_archive_formats except ImportError: @@ -247,7 +247,7 @@ class SDistTestCase(support.TempdirManager, support.LoggingCatcher, # with the `check` subcommand cmd.ensure_finalized() cmd.run() - warnings = self.get_logs(WARN) + warnings = self.get_logs(logging.WARN) self.assertEqual(len(warnings), 1) # trying with a complete set of metadata @@ -256,7 +256,7 @@ class SDistTestCase(support.TempdirManager, support.LoggingCatcher, cmd.ensure_finalized() cmd.metadata_check = 0 cmd.run() - warnings = self.get_logs(WARN) + warnings = self.get_logs(logging.WARN) # removing manifest generated warnings warnings = [warn for warn in warnings if not warn.endswith('-- skipping')] @@ -279,7 +279,6 @@ class SDistTestCase(support.TempdirManager, support.LoggingCatcher, # default options set by finalize self.assertEqual(cmd.manifest, 'MANIFEST') - self.assertEqual(cmd.template, 'MANIFEST.in') self.assertEqual(cmd.dist_dir, 'dist') # formats has to be a string splitable on (' ', ',') or @@ -415,6 +414,21 @@ class SDistTestCase(support.TempdirManager, support.LoggingCatcher, self.assertEqual(manifest, ['README.manual']) + def test_template(self): + dist, cmd = self.get_cmd() + dist.extra_files = ['include yeah'] + cmd.ensure_finalized() + self.write_file((self.tmp_dir, 'yeah'), 'xxx') + cmd.run() + f = open(cmd.manifest) + try: + content = f.read() + finally: + f.close() + + self.assertIn('yeah', content) + + def test_suite(): return unittest.makeSuite(SDistTestCase) diff --git a/distutils2/tests/test_test.py b/distutils2/tests/test_command_test.py index 5e4c03f..9b0c950 100644 --- a/distutils2/tests/test_test.py +++ b/distutils2/tests/test_command_test.py @@ -8,7 +8,8 @@ from copy import copy from os.path import join from operator import getitem, setitem, delitem from StringIO import StringIO -from distutils2.core import Command + +from distutils2.command.cmd import Command from distutils2.tests import unittest from distutils2.tests.support import TempdirManager, LoggingCatcher from distutils2.command.test import test diff --git a/distutils2/tests/test_command_upload.py b/distutils2/tests/test_command_upload.py index df8ae91..48e7e7b 100644 --- a/distutils2/tests/test_command_upload.py +++ b/distutils2/tests/test_command_upload.py @@ -4,7 +4,7 @@ import os import sys from distutils2.command.upload import upload -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.tests import unittest, support from distutils2.tests.pypi_server import PyPIServer, PyPIServerTestCase @@ -128,7 +128,7 @@ class UploadTestCase(support.TempdirManager, support.EnvironGuard, handler, request_data = self.pypi.requests[-1] action, name, content =\ request_data.split("----------------GHSKFJDLGDS7543FJKLFHRE75642756743254")[1:4] - + self.assertIn('name=":action"', action) self.assertIn("doc_upload", action) diff --git a/distutils2/tests/test_command_upload_docs.py b/distutils2/tests/test_command_upload_docs.py index c9c4b91..4b1dc82 100644 --- a/distutils2/tests/test_command_upload_docs.py +++ b/distutils2/tests/test_command_upload_docs.py @@ -13,7 +13,7 @@ except ImportError: from distutils2.command import upload_docs as upload_docs_mod from distutils2.command.upload_docs import (upload_docs, zip_dir, encode_multipart) -from distutils2.core import Distribution +from distutils2.dist import Distribution from distutils2.errors import DistutilsFileError, DistutilsOptionError from distutils2.tests import unittest, support @@ -176,7 +176,7 @@ class UploadDocsTestCase(support.TempdirManager, support.EnvironGuard, self.pypi.default_response_status = '301 Moved Permanently' self.pypi.default_response_headers.append(("Location", "brand_new_location")) self.cmd.run() - message, _ = calls[-1] + message = calls[-1][0] self.assertIn('brand_new_location', message) def test_reads_pypirc_data(self): diff --git a/distutils2/tests/test_config.py b/distutils2/tests/test_config.py index 7ae932e..9ec6860 100644 --- a/distutils2/tests/test_config.py +++ b/distutils2/tests/test_config.py @@ -51,7 +51,7 @@ packages = one src:two src2:three -py_modules = haven +modules = haven scripts = script1.py @@ -109,8 +109,8 @@ class ConfigTestCase(support.TempdirManager, sys.argv[:] = ['setup.py', '--version'] old_sys = sys.argv[:] try: - from distutils2.core import setup - dist = setup() + from distutils2.run import main + dist = main() finally: sys.argv[:] = old_sys diff --git a/distutils2/tests/test_core.py b/distutils2/tests/test_core.py deleted file mode 100644 index 11c5561..0000000 --- a/distutils2/tests/test_core.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Tests for distutils2.core.""" - -import StringIO -import distutils2.core -import os -import shutil -import sys -from distutils2.tests import captured_stdout -from distutils2.tests import unittest, support - -# setup script that uses __file__ -setup_using___file__ = """\ - -__file__ - -from distutils2.core import setup -setup() -""" - -setup_prints_cwd = """\ - -import os -print os.getcwd() - -from distutils2.core import setup -setup() -""" - - -class CoreTestCase(support.EnvironGuard, unittest.TestCase): - - def setUp(self): - super(CoreTestCase, self).setUp() - self.old_stdout = sys.stdout - self.cleanup_testfn() - self.old_argv = sys.argv, sys.argv[:] - - def tearDown(self): - sys.stdout = self.old_stdout - self.cleanup_testfn() - sys.argv = self.old_argv[0] - sys.argv[:] = self.old_argv[1] - super(CoreTestCase, self).tearDown() - - def cleanup_testfn(self): - path = distutils2.tests.TESTFN - if os.path.isfile(path): - os.remove(path) - elif os.path.isdir(path): - shutil.rmtree(path) - - def write_setup(self, text, path=distutils2.tests.TESTFN): - open(path, "w").write(text) - return path - - def test_run_setup_provides_file(self): - # Make sure the script can use __file__; if that's missing, the test - # setup.py script will raise NameError. - distutils2.core.run_setup( - self.write_setup(setup_using___file__)) - - def test_run_setup_stop_after(self): - f = self.write_setup(setup_using___file__) - for s in ['init', 'config', 'commandline', 'run']: - distutils2.core.run_setup(f, stop_after=s) - self.assertRaises(ValueError, distutils2.core.run_setup, - f, stop_after='bob') - - def test_run_setup_args(self): - f = self.write_setup(setup_using___file__) - d = distutils2.core.run_setup(f, script_args=["--help"], - stop_after="init") - self.assertEqual(['--help'], d.script_args) - - def test_run_setup_uses_current_dir(self): - # This tests that the setup script is run with the current directory - # as its own current directory; this was temporarily broken by a - # previous patch when TESTFN did not use the current directory. - sys.stdout = StringIO.StringIO() - cwd = os.getcwd() - - # Create a directory and write the setup.py file there: - os.mkdir(distutils2.tests.TESTFN) - setup_py = os.path.join(distutils2.tests.TESTFN, "setup.py") - distutils2.core.run_setup( - self.write_setup(setup_prints_cwd, path=setup_py)) - - output = sys.stdout.getvalue() - if output.endswith("\n"): - output = output[:-1] - self.assertEqual(cwd, output) - -def test_suite(): - return unittest.makeSuite(CoreTestCase) - -if __name__ == "__main__": - unittest.main(defaultTest="test_suite") diff --git a/distutils2/tests/test_depgraph.py b/distutils2/tests/test_depgraph.py index abd0836..3ab9975 100644 --- a/distutils2/tests/test_depgraph.py +++ b/distutils2/tests/test_depgraph.py @@ -13,6 +13,7 @@ except ImportError: import StringIO class DepGraphTestCase(support.LoggingCatcher, + support.WarningsCatcher, unittest.TestCase): DISTROS_DIST = ('choxie', 'grammar', 'towel-stuff') diff --git a/distutils2/tests/test_dist.py b/distutils2/tests/test_dist.py index 4e834d8..46d366b 100644 --- a/distutils2/tests/test_dist.py +++ b/distutils2/tests/test_dist.py @@ -205,7 +205,7 @@ class DistributionTestCase(support.TempdirManager, dist = Distribution() args = ('ok',) kwargs = {'level': 'ok2'} - self.assertRaises(ValueError, dist.announce, args, kwargs) + self.assertRaises(TypeError, dist.announce, args, kwargs) def test_find_config_files_disable(self): # Bug #1180: Allow users to disable their own config file. diff --git a/distutils2/tests/test_manifest.py b/distutils2/tests/test_manifest.py index bb8c96c..5f768eb 100644 --- a/distutils2/tests/test_manifest.py +++ b/distutils2/tests/test_manifest.py @@ -2,6 +2,7 @@ import os import sys import logging +from StringIO import StringIO from distutils2.tests import run_unittest from distutils2.tests import unittest, support @@ -17,6 +18,12 @@ recursive-include bar \\ *.dat *.txt """ +_MANIFEST2 = """\ +README +file1 +""" + + class ManifestTestCase(support.TempdirManager, unittest.TestCase): @@ -48,7 +55,31 @@ class ManifestTestCase(support.TempdirManager, for warn in warns: self.assertIn('warning: no files found matching', warn) + # manifest also accepts file-like objects + old_warn = logging.warning + logging.warning = _warn + try: + manifest.read_template(open(MANIFEST)) + finally: + logging.warning = old_warn + + # the manifest should have been read + # and 3 warnings issued (we ddidn't provided the files) + self.assertEqual(len(warns), 6) + def test_default_actions(self): + tmpdir = self.mkdtemp() + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + self.write_file('README', 'xxx') + self.write_file('file1', 'xxx') + content = StringIO(_MANIFEST2) + manifest = Manifest() + manifest.read_template(content) + self.assertEqual(manifest.files, ['README', 'file1']) + finally: + os.chdir(old_dir) def test_suite(): return unittest.makeSuite(ManifestTestCase) diff --git a/distutils2/tests/test_metadata.py b/distutils2/tests/test_metadata.py index e05a713..32c6895 100644 --- a/distutils2/tests/test_metadata.py +++ b/distutils2/tests/test_metadata.py @@ -7,11 +7,12 @@ from StringIO import StringIO from distutils2.metadata import (DistributionMetadata, _interpret, PKG_INFO_PREFERRED_VERSION) from distutils2.tests import run_unittest, unittest -from distutils2.tests.support import LoggingCatcher +from distutils2.tests.support import LoggingCatcher, WarningsCatcher from distutils2.errors import (MetadataConflictError, MetadataUnrecognizedVersionError) -class DistributionMetadataTestCase(LoggingCatcher, unittest.TestCase): +class DistributionMetadataTestCase(LoggingCatcher, WarningsCatcher, + unittest.TestCase): def test_instantiation(self): PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') @@ -195,49 +196,21 @@ class DistributionMetadataTestCase(LoggingCatcher, unittest.TestCase): values = (('Requires-Dist', 'Funky (Groovie)'), ('Requires-Python', '1-4')) - from distutils2 import metadata as m - old = m.warn - m.warns = 0 - - def _warn(*args): - m.warns += 1 - - m.warn = _warn - - try: - for name, value in values: - metadata.set(name, value) - finally: - m.warn = old - res = m.warns - del m.warns + for name, value in values: + metadata.set(name, value) # we should have a certain amount of warnings - num_wanted = len(values) - self.assertEqual(num_wanted, res) + self.assertEqual(len(self.logs), 2) def test_multiple_predicates(self): metadata = DistributionMetadata() - from distutils2 import metadata as m - old = m.warn - m.warns = 0 - - def _warn(*args): - m.warns += 1 - # see for "3" instead of "3.0" ??? # its seems like the MINOR VERSION can be omitted - m.warn = _warn - try: - metadata['Requires-Python'] = '>=2.6, <3.0' - metadata['Requires-Dist'] = ['Foo (>=2.6, <3.0)'] - finally: - m.warn = old - res = m.warns - del m.warns + metadata['Requires-Python'] = '>=2.6, <3.0' + metadata['Requires-Dist'] = ['Foo (>=2.6, <3.0)'] - self.assertEqual(res, 0) + self.assertEqual(len(self.warnings), 0) def test_project_url(self): metadata = DistributionMetadata() diff --git a/distutils2/tests/test_Mixin2to3.py b/distutils2/tests/test_mixin2to3.py index 2ffd248..c6661a6 100644 --- a/distutils2/tests/test_Mixin2to3.py +++ b/distutils2/tests/test_mixin2to3.py @@ -7,7 +7,8 @@ from distutils2.tests import unittest, support from distutils2.compat import Mixin2to3 -class Mixin2to3TestCase(support.TempdirManager, unittest.TestCase): +class Mixin2to3TestCase(support.TempdirManager, support.WarningsCatcher, + unittest.TestCase): @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_convert_code_only(self): diff --git a/distutils2/tests/test_mkcfg.py b/distutils2/tests/test_mkcfg.py new file mode 100644 index 0000000..0fea9ee --- /dev/null +++ b/distutils2/tests/test_mkcfg.py @@ -0,0 +1,47 @@ +"""Tests for distutils.mkcfg.""" +import os +from distutils2.tests import run_unittest, support, unittest +from distutils2.mkcfg import MainProgram + + +class MkcfgTestCase(support.TempdirManager, + unittest.TestCase): + + def test_find_files(self): + # making sure we scan a project dir correctly + main = MainProgram() + + # building the structure + tempdir = self.mkdtemp() + dirs = ['pkg1', 'data', 'pkg2', 'pkg2/sub'] + files = ['README', 'setup.cfg', 'foo.py', + 'pkg1/__init__.py', 'pkg1/bar.py', + 'data/data1', 'pkg2/__init__.py', + 'pkg2/sub/__init__.py'] + + for dir_ in dirs: + os.mkdir(os.path.join(tempdir, dir_)) + + for file_ in files: + path = os.path.join(tempdir, file_) + self.write_file(path, 'xxx') + + old_dir = os.getcwd() + os.chdir(tempdir) + try: + main._find_files() + finally: + os.chdir(old_dir) + + # do we have what we want ? + self.assertEqual(main.data['packages'], ['pkg1', 'pkg2', 'pkg2.sub']) + self.assertEqual(main.data['modules'], ['foo']) + self.assertEqual(main.data['extra_files'], + ['setup.cfg', 'README', 'data/data1']) + + +def test_suite(): + return unittest.makeSuite(MkcfgTestCase) + +if __name__ == '__main__': + run_unittest(test_suite()) diff --git a/distutils2/tests/test_run.py b/distutils2/tests/test_run.py new file mode 100644 index 0000000..e66c7f4 --- /dev/null +++ b/distutils2/tests/test_run.py @@ -0,0 +1,61 @@ +"""Tests for distutils2.run.""" + +import StringIO +import os +import shutil +import sys + +import distutils2 +from distutils2.tests import captured_stdout +from distutils2.tests import unittest, support + +# setup script that uses __file__ +setup_using___file__ = """\ + +__file__ + +from distutils2.run import setup +setup() +""" + +setup_prints_cwd = """\ + +import os +print os.getcwd() + +from distutils2.run import setup +setup() +""" + + +class CoreTestCase(support.EnvironGuard, unittest.TestCase): + + def setUp(self): + super(CoreTestCase, self).setUp() + self.old_stdout = sys.stdout + self.cleanup_testfn() + self.old_argv = sys.argv, sys.argv[:] + + def tearDown(self): + sys.stdout = self.old_stdout + self.cleanup_testfn() + sys.argv = self.old_argv[0] + sys.argv[:] = self.old_argv[1] + super(CoreTestCase, self).tearDown() + + def cleanup_testfn(self): + path = distutils2.tests.TESTFN + if os.path.isfile(path): + os.remove(path) + elif os.path.isdir(path): + shutil.rmtree(path) + + def write_setup(self, text, path=distutils2.tests.TESTFN): + open(path, "w").write(text) + return path + +def test_suite(): + return unittest.makeSuite(CoreTestCase) + +if __name__ == "__main__": + unittest.main(defaultTest="test_suite") diff --git a/distutils2/util.py b/distutils2/util.py index b7d73d5..1ee1904 100644 --- a/distutils2/util.py +++ b/distutils2/util.py @@ -18,7 +18,7 @@ from ConfigParser import RawConfigParser from distutils2.errors import (DistutilsPlatformError, DistutilsFileError, DistutilsByteCompileError, DistutilsExecError) -from distutils2 import log +from distutils2 import logger from distutils2._backport import sysconfig as _sysconfig _PLATFORM = None @@ -286,7 +286,7 @@ def execute(func, args, msg=None, verbose=0, dry_run=0): if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' - log.info(msg) + logger.info(msg) if not dry_run: func(*args) @@ -360,7 +360,7 @@ def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None, if not direct: from tempfile import mkstemp script_fd, script_name = mkstemp(".py") - log.info("writing byte-compilation script '%s'", script_name) + logger.info("writing byte-compilation script '%s'", script_name) if not dry_run: if script_fd is not None: script = os.fdopen(script_fd, "w") @@ -441,11 +441,11 @@ byte_compile(files, optimize=%r, force=%r, cfile_base = os.path.basename(cfile) if direct: if force or newer(file, cfile): - log.info("byte-compiling %s to %s", file, cfile_base) + logger.info("byte-compiling %s to %s", file, cfile_base) if not dry_run: compile(file, cfile, dfile) else: - log.debug("skipping byte-compilation of %s to %s", + logger.debug("skipping byte-compilation of %s to %s", file, cfile_base) @@ -830,7 +830,7 @@ def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0, env=None): if search_path: # either we find one or it stays the same executable = find_executable(executable) or executable - log.info(' '.join([executable] + cmd[1:])) + logger.info(' '.join([executable] + cmd[1:])) if not dry_run: # spawn for NT requires a full path to the .exe try: @@ -854,7 +854,7 @@ def _spawn_os2(cmd, search_path=1, verbose=0, dry_run=0, env=None): if search_path: # either we find one or it stays the same executable = find_executable(executable) or executable - log.info(' '.join([executable] + cmd[1:])) + logger.info(' '.join([executable] + cmd[1:])) if not dry_run: # spawnv for OS/2 EMX requires a full path to the .exe try: @@ -869,13 +869,13 @@ def _spawn_os2(cmd, search_path=1, verbose=0, dry_run=0, env=None): "command '%s' failed: %s" % (cmd[0], exc[-1])) if rc != 0: # and this reflects the command running but failing - log.debug("command '%s' failed with exit status %d" % (cmd[0], rc)) + logger.debug("command '%s' failed with exit status %d" % (cmd[0], rc)) raise DistutilsExecError( "command '%s' failed with exit status %d" % (cmd[0], rc)) def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0, env=None): - log.info(' '.join(cmd)) + logger.info(' '.join(cmd)) if dry_run: return |
