diff options
| author | Tarek Ziade <tarek@ziade.org> | 2010-12-26 14:21:15 +0100 |
|---|---|---|
| committer | Tarek Ziade <tarek@ziade.org> | 2010-12-26 14:21:15 +0100 |
| commit | 7ae3ef9ae33d57b5bfe5fc890148cc0bd7472540 (patch) | |
| tree | 5b9ec74c67fbf81c82e3696c316ce83bc902351e /distutils2 | |
| parent | 3497b70289bd769edbf3f34d94ead17d6303e5db (diff) | |
| parent | c49ee83a7fb63aaefe314712f4472d55bd029f8e (diff) | |
| download | disutils2-7ae3ef9ae33d57b5bfe5fc890148cc0bd7472540.tar.gz | |
merged
Diffstat (limited to 'distutils2')
37 files changed, 265 insertions, 306 deletions
diff --git a/distutils2/__init__.py b/distutils2/__init__.py index 98d7939..0b096a0 100644 --- a/distutils2/__init__.py +++ b/distutils2/__init__.py @@ -13,8 +13,3 @@ __all__ = ['__version__', 'logger'] __version__ = "1.0a3" logger = getLogger('distutils2') - -# when set to True, converts doctests by default too -run_2to3_on_doctests = True -# Standard package names for fixer packages -lib2to3_fixer_packages = ['lib2to3.fixes'] diff --git a/distutils2/_backport/sysconfig.py b/distutils2/_backport/sysconfig.py index 7024d04..316d0bd 100644 --- a/distutils2/_backport/sysconfig.py +++ b/distutils2/_backport/sysconfig.py @@ -1,8 +1,6 @@ -"""Provide access to Python's configuration information. - -""" -import sys +"""Provide access to Python's configuration information.""" import os +import sys import re from os.path import pardir, realpath from ConfigParser import RawConfigParser @@ -18,6 +16,7 @@ _SCHEMES = RawConfigParser() _SCHEMES.read(_CONFIG_FILE) _VAR_REPL = re.compile(r'\{([^{]*?)\}') + def _expand_globals(config): if config.has_section('globals'): globals = config.items('globals') @@ -38,11 +37,13 @@ def _expand_globals(config): # for section in config.sections(): variables = dict(config.items(section)) + def _replacer(matchobj): name = matchobj.group(1) if name in variables: return variables[name] return matchobj.group(0) + for option, value in config.items(section): config.set(section, option, _VAR_REPL.sub(_replacer, value)) @@ -69,6 +70,7 @@ if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): if os.name == "nt" and "\\pcbuild\\amd64" in _PROJECT_BASE[-14:].lower(): _PROJECT_BASE = realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) + def is_python_build(): for fn in ("Setup.dist", "Setup.local"): if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)): @@ -84,10 +86,10 @@ if _PYTHON_BUILD: def _subst_vars(path, local_vars): - """In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. + """In the string `path`, replace tokens like {some.thing} with the + corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. - """ def _replacer(matchobj): name = matchobj.group(1) @@ -98,6 +100,7 @@ def _subst_vars(path, local_vars): return matchobj.group(0) return _VAR_REPL.sub(_replacer, path) + def _extend_dict(target_dict, other_dict): target_keys = target_dict.keys() for key, value in other_dict.items(): @@ -105,6 +108,7 @@ def _extend_dict(target_dict, other_dict): continue target_dict[key] = value + def _expand_vars(scheme, vars): res = {} if vars is None: @@ -117,14 +121,17 @@ def _expand_vars(scheme, vars): res[key] = os.path.normpath(_subst_vars(value, vars)) return res + def _get_default_scheme(): if os.name == 'posix': # the default scheme for posix is posix_prefix return 'posix_prefix' return os.name + def _getuserbase(): env_base = os.environ.get("PYTHONUSERBASE", None) + def joinuser(*args): return os.path.expanduser(os.path.join(*args)) @@ -158,7 +165,6 @@ def _parse_makefile(filename, vars=None): optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ - import re # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") @@ -256,7 +262,6 @@ def _parse_makefile(filename, vars=None): if name not in done: done[name] = value - else: # bogus variable reference; just drop it since we can't deal variables.remove(name) @@ -267,6 +272,7 @@ def _parse_makefile(filename, vars=None): def get_makefile_filename(): + """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") return os.path.join(get_path('stdlib'), "config", "Makefile") @@ -315,6 +321,7 @@ def _init_posix(vars): if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED'] + def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories @@ -338,7 +345,6 @@ def parse_config_h(fp, vars=None): optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ - import re if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") @@ -351,8 +357,10 @@ def parse_config_h(fp, vars=None): m = define_rx.match(line) if m: n, v = m.group(1, 2) - try: v = int(v) - except ValueError: pass + try: + v = int(v) + except ValueError: + pass vars[n] = v else: m = undef_rx.match(line) @@ -360,8 +368,9 @@ def parse_config_h(fp, vars=None): vars[m.group(1)] = 0 return vars + def get_config_h_filename(): - """Returns the path of pyconfig.h.""" + """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") @@ -371,17 +380,20 @@ def get_config_h_filename(): inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h') + def get_scheme_names(): - """Returns a tuple containing the schemes names.""" + """Return a tuple containing the schemes names.""" return tuple(sorted(_SCHEMES.sections())) + def get_path_names(): - """Returns a tuple containing the paths names.""" + """Return a tuple containing the paths names.""" # xxx see if we want a static list return _SCHEMES.options('posix_prefix') + def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): - """Returns a mapping containing an install scheme. + """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. @@ -391,13 +403,15 @@ def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): else: return dict(_SCHEMES.items(scheme)) + def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): - """Returns a path corresponding to the scheme. + """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name] + def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. @@ -408,7 +422,6 @@ def get_config_vars(*args): With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ - import re global _CONFIG_VARS if _CONFIG_VARS is None: _CONFIG_VARS = {} @@ -440,7 +453,6 @@ def get_config_vars(*args): else: _CONFIG_VARS['srcdir'] = realpath(_CONFIG_VARS['srcdir']) - # Convert srcdir into an absolute path if it appears necessary. # Normally it is relative to the build directory. However, during # testing, for example, we might be running a non-installed python @@ -456,7 +468,7 @@ def get_config_vars(*args): _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir) if sys.platform == 'darwin': - kernel_version = os.uname()[2] # Kernel version (8.4.3) + kernel_version = os.uname()[2] # Kernel version (8.4.3) major_version = int(kernel_version.split('.')[0]) if major_version < 8: @@ -522,6 +534,7 @@ def get_config_vars(*args): else: return _CONFIG_VARS + def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. @@ -530,6 +543,7 @@ def get_config_var(name): """ return get_config_vars().get(name) + def get_platform(): """Return a string that identifies the current platform. @@ -555,7 +569,6 @@ def get_platform(): For other non-POSIX platforms, currently just returns 'sys.platform'. """ - import re if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" @@ -563,7 +576,7 @@ def get_platform(): if i == -1: return sys.platform j = sys.version.find(")", i) - look = sys.version[i+len(prefix):j].lower() + look = sys.version[i + len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': @@ -600,7 +613,7 @@ def get_platform(): return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" - rel_re = re.compile (r'[\d.]+') + rel_re = re.compile(r'[\d.]+') m = rel_re.match(release) if m: release = m.group() @@ -675,19 +688,19 @@ def get_platform(): machine = 'universal' else: raise ValueError( - "Don't know machine value for archs=%r"%(archs,)) + "Don't know machine value for archs=%r" % (archs,)) elif machine == 'i386': # On OSX the machine type returned by uname is always the # 32-bit variant, even if the executable architecture is # the 64-bit variant - if sys.maxint >= 2**32: + if sys.maxint >= (2 ** 32): machine = 'x86_64' elif machine in ('PowerPC', 'Power_Macintosh'): # Pick a sane name for the PPC architecture. # See 'i386' case - if sys.maxint >= 2**32: + if sys.maxint >= (2 ** 32): machine = 'ppc64' else: machine = 'ppc' @@ -698,12 +711,14 @@ def get_platform(): def get_python_version(): return _PY_VERSION_SHORT + def _print_dict(title, data): for index, (key, value) in enumerate(sorted(data.items())): if index == 0: print '%s: ' % (title) print '\t%s = "%s"' % (key, value) + def _main(): """Display all information sysconfig detains.""" print 'Platform: "%s"' % get_platform() @@ -714,5 +729,6 @@ def _main(): print _print_dict('Variables', get_config_vars()) + if __name__ == '__main__': _main() diff --git a/distutils2/command/__init__.py b/distutils2/command/__init__.py index 441f507..46a2111 100644 --- a/distutils2/command/__init__.py +++ b/distutils2/command/__init__.py @@ -31,24 +31,23 @@ _COMMANDS = { def get_command_names(): - """Returns registered commands""" return sorted(_COMMANDS.keys()) + """Return registered commands""" def set_command(location): - klass = resolve_name(location) - # we want to do the duck-type checking here - # XXX - _COMMANDS[klass.get_command_name()] = klass + cls = resolve_name(location) + # XXX we want to do the duck-type checking here + _COMMANDS[cls.get_command_name()] = cls def get_command_class(name): """Return the registered command""" try: - klass = _COMMANDS[name] - if isinstance(klass, str): - klass = resolve_name(klass) - _COMMANDS[name] = klass - return klass + cls = _COMMANDS[name] + if isinstance(cls, str): + cls = resolve_name(cls) + _COMMANDS[name] = cls + return cls except KeyError: raise DistutilsModuleError("Invalid command %s" % name) diff --git a/distutils2/command/build.py b/distutils2/command/build.py index 3dfc1de..c7c6393 100644 --- a/distutils2/command/build.py +++ b/distutils2/command/build.py @@ -127,27 +127,27 @@ class build(Command): # Run all relevant sub-commands. This will be some subset of: # - build_py - pure Python modules # - build_clib - standalone C libraries - # - build_ext - Python extensions - # - build_scripts - (Python) scripts + # - build_ext - Python extension modules + # - build_scripts - Python scripts for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # -- Predicates for the sub-command list --------------------------- - def has_pure_modules (self): + def has_pure_modules(self): return self.distribution.has_pure_modules() - def has_c_libraries (self): + def has_c_libraries(self): return self.distribution.has_c_libraries() - def has_ext_modules (self): + def has_ext_modules(self): return self.distribution.has_ext_modules() - def has_scripts (self): + def has_scripts(self): return self.distribution.has_scripts() - sub_commands = [('build_py', has_pure_modules), - ('build_clib', has_c_libraries), - ('build_ext', has_ext_modules), + sub_commands = [('build_py', has_pure_modules), + ('build_clib', has_c_libraries), + ('build_ext', has_ext_modules), ('build_scripts', has_scripts), ] diff --git a/distutils2/command/build_ext.py b/distutils2/command/build_ext.py index 0df3db8..6575e55 100644 --- a/distutils2/command/build_ext.py +++ b/distutils2/command/build_ext.py @@ -16,10 +16,7 @@ from distutils2.compiler import customize_compiler, show_compilers from distutils2.util import newer_group from distutils2.compiler.extension import Extension from distutils2 import logger -try: - import sysconfig -except ImportError: - from distutils2._backport import sysconfig +from distutils2._backport import sysconfig # this keeps compatibility from 2.3 to 2.5 if sys.version < "2.6": @@ -260,7 +257,7 @@ class build_ext(Command): elif MSVC_VERSION == 8: self.library_dirs.append(os.path.join(sys.exec_prefix, - 'PC', 'VS8.0', 'win32release')) + 'PC', 'VS8.0')) elif MSVC_VERSION == 7: self.library_dirs.append(os.path.join(sys.exec_prefix, 'PC', 'VS7.1')) diff --git a/distutils2/command/build_scripts.py b/distutils2/command/build_scripts.py index e0c8bcb..89cdded 100644 --- a/distutils2/command/build_scripts.py +++ b/distutils2/command/build_scripts.py @@ -9,10 +9,7 @@ from stat import ST_MODE from distutils2.command.cmd import Command from distutils2.util import convert_path, newer from distutils2 import logger -try: - import sysconfig -except ImportError: - from distutils2._backport import sysconfig +from distutils2._backport import sysconfig from distutils2.compat import Mixin2to3 # check if Python is called on the first line with this expression diff --git a/distutils2/command/cmd.py b/distutils2/command/cmd.py index e2cfd52..e63c46b 100644 --- a/distutils2/command/cmd.py +++ b/distutils2/command/cmd.py @@ -19,6 +19,7 @@ try: except ImportError: from distutils2._backport.shutil import make_archive + class Command(object): """Abstract base class for defining command classes, the "worker bees" of the Distutils. A useful analogy for command classes is to think of @@ -57,7 +58,6 @@ class Command(object): pre_hook = None post_hook = None - # -- Creation/initialization methods ------------------------------- def __init__(self, dist): @@ -69,9 +69,9 @@ class Command(object): from distutils2.dist import Distribution if not isinstance(dist, Distribution): - raise TypeError, "dist must be a Distribution instance" + raise TypeError("dist must be a Distribution instance") if self.__class__ is Command: - raise RuntimeError, "Command is an abstract class" + raise RuntimeError("Command is an abstract class") self.distribution = dist self.initialize_options() @@ -143,8 +143,8 @@ class Command(object): This method must be implemented by all command classes. """ - raise RuntimeError, \ - "abstract method -- subclass %s must override" % self.__class__ + raise RuntimeError( + "abstract method -- subclass %s must override" % self.__class__) def finalize_options(self): """Set final values for all the options that this command supports. @@ -157,9 +157,8 @@ class Command(object): This method must be implemented by all command classes. """ - raise RuntimeError, \ - "abstract method -- subclass %s must override" % self.__class__ - + raise RuntimeError( + "abstract method -- subclass %s must override" % self.__class__) def dump_options(self, header=None, indent=""): if header is None: @@ -184,8 +183,8 @@ class Command(object): This method must be implemented by all command classes. """ - raise RuntimeError, \ - "abstract method -- subclass %s must override" % self.__class__ + raise RuntimeError( + "abstract method -- subclass %s must override" % self.__class__) def announce(self, msg, level=logging.INFO): """If the current verbosity level is of greater than or equal to @@ -237,8 +236,8 @@ class Command(object): setattr(self, option, default) return default elif not isinstance(val, str): - raise DistutilsOptionError, \ - "'%s' must be a %s (got `%s`)" % (option, what, val) + raise DistutilsOptionError("'%s' must be a %s (got `%s`)" % + (option, what, val)) return val def ensure_string(self, option, default=None): @@ -248,7 +247,7 @@ class Command(object): self._ensure_stringlike(option, "string", default) def ensure_string_list(self, option): - """Ensure that 'option' is a list of strings. If 'option' is + r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"]. @@ -270,17 +269,15 @@ class Command(object): ok = 0 if not ok: - raise DistutilsOptionError, \ - "'%s' must be a list of strings (got %r)" % \ - (option, val) - + raise DistutilsOptionError( + "'%s' must be a list of strings (got %r)" % (option, val)) def _ensure_tested_string(self, option, tester, what, error_fmt, default=None): val = self._ensure_stringlike(option, what, default) if val is not None and not tester(val): - raise DistutilsOptionError, \ - ("error in '%s' option: " + error_fmt) % (option, val) + raise DistutilsOptionError( + ("error in '%s' option: " + error_fmt) % (option, val)) def ensure_filename(self, option): """Ensure that 'option' is the name of an existing file.""" @@ -293,7 +290,6 @@ class Command(object): "directory name", "'%s' does not exist or is not a directory") - # -- Convenience methods for commands ------------------------------ @classmethod @@ -369,12 +365,10 @@ class Command(object): commands.append(sub_command) return commands - # -- External world manipulation ----------------------------------- def warn(self, msg): - logger.warning("warning: %s: %s\n" % - (self.get_command_name(), msg)) + logger.warning("warning: %s: %s\n" % (self.get_command_name(), msg)) def execute(self, func, args, msg=None, level=1): util.execute(func, args, msg, dry_run=self.dry_run) @@ -413,19 +407,19 @@ class Command(object): and force flags. """ if self.dry_run: - return # see if we want to display something + return # see if we want to display something return copytree(infile, outfile, preserve_symlinks) def move_file(self, src, dst, level=1): """Move a file respectin dry-run flag.""" if self.dry_run: - return # XXX log ? + return # XXX log ? return move(src, dst) def spawn(self, cmd, search_path=1, level=1): """Spawn an external command respecting dry-run flag.""" from distutils2.util import spawn - spawn(cmd, search_path, dry_run= self.dry_run) + spawn(cmd, search_path, dry_run=self.dry_run) def make_archive(self, base_name, format, root_dir=None, base_dir=None, owner=None, group=None): @@ -450,12 +444,11 @@ class Command(object): if isinstance(infiles, str): infiles = (infiles,) elif not isinstance(infiles, (list, tuple)): - raise TypeError, \ - "'infiles' must be a string, or a list or tuple of strings" + raise TypeError( + "'infiles' must be a string, or a list or tuple of strings") if exec_msg is None: - exec_msg = "generating %s from %s" % \ - (outfile, ', '.join(infiles)) + exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles)) # If 'outfile' must be regenerated (either because it doesn't # exist, is out-of-date, or the 'force' flag is true) then diff --git a/distutils2/command/install_dist.py b/distutils2/command/install_dist.py index 04a225d..f0233d1 100644 --- a/distutils2/command/install_dist.py +++ b/distutils2/command/install_dist.py @@ -520,7 +520,6 @@ class install_dist(Command): raise DistutilsPlatformError("Can't install when " "cross-compiling") - # Run all sub-commands (at least those that need to be run) for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) diff --git a/distutils2/command/register.py b/distutils2/command/register.py index 687a514..b42d73a 100644 --- a/distutils2/command/register.py +++ b/distutils2/command/register.py @@ -11,7 +11,6 @@ import getpass import urlparse import StringIO import logging -from warnings import warn from distutils2.command.cmd import Command from distutils2 import logger @@ -33,25 +32,19 @@ class register(Command): "stop the registration if the metadata is not fully compliant") ] - boolean_options = ['show-response', 'verify', 'list-classifiers', - 'strict'] + boolean_options = ['show-response', 'list-classifiers', 'strict'] def initialize_options(self): self.repository = None self.realm = None self.show_response = 0 self.list_classifiers = 0 - self.strict = 0 def finalize_options(self): if self.repository is None: self.repository = DEFAULT_REPOSITORY if self.realm is None: self.realm = DEFAULT_REALM - # setting options for the `check` subcommand - check_options = {'strict': ('register', self.strict), - 'all': ('register', 1)} - self.distribution.command_options['check'] = check_options def run(self): self.finalize_options() @@ -67,16 +60,6 @@ class register(Command): else: self.send_metadata() - def check_metadata(self): - """Deprecated API.""" - warn("distutils.command.register.check_metadata is deprecated, \ - use the check command instead", PendingDeprecationWarning) - check = self.distribution.get_command_obj('check') - check.ensure_finalized() - check.strict = self.strict - check.all = 1 - check.run() - def _set_config(self): ''' Reads the configuration file and set attributes. ''' diff --git a/distutils2/compat.py b/distutils2/compat.py index 86c733a..991b8b6 100644 --- a/distutils2/compat.py +++ b/distutils2/compat.py @@ -7,10 +7,13 @@ support distutils2 across versions(2.x and 3.x) import logging +# XXX Having two classes with the same name is not a good thing. +# XXX 2to3-related code should move from util to this module + +# TODO Move common code here: PY3 (bool indicating if we're on 3.x), any, etc. + try: from distutils2.util import Mixin2to3 as _Mixin2to3 - from distutils2 import run_2to3_on_doctests - from lib2to3.refactor import get_fixers_from_package _CONVERT = True _KLASS = _Mixin2to3 except ImportError: @@ -20,6 +23,7 @@ except ImportError: # marking public APIs __all__ = ['Mixin2to3'] + class Mixin2to3(_KLASS): """ The base class which can be used for refactoring. When run under Python 3.0, the run_2to3 method provided by Mixin2to3 is overridden. @@ -46,19 +50,10 @@ class Mixin2to3(_KLASS): logging.info("Converting doctests with '.py' files") _KLASS.run_2to3(self, files, doctests_only=True) - # If the following conditions are met, then convert:- - # 1. User has specified the 'convert_2to3_doctests' option. So, we - # can expect that the list 'doctests' is not empty. - # 2. The default is allow distutils2 to allow conversion of text files - # containing doctests. It is set as - # distutils2.run_2to3_on_doctests - - if doctests != [] and run_2to3_on_doctests: + if doctests != []: logging.info("Converting text files which contain doctests") _KLASS.run_2to3(self, doctests, doctests_only=True) else: # If run on Python 2.x, there is nothing to do. def _run_2to3(self, files, doctests=[], fixers=[]): pass - - diff --git a/distutils2/compiler/__init__.py b/distutils2/compiler/__init__.py index 9cda923..7f6bd43 100644 --- a/distutils2/compiler/__init__.py +++ b/distutils2/compiler/__init__.py @@ -4,7 +4,7 @@ import re from distutils2._backport import sysconfig from distutils2.util import resolve_name -from distutils2.errors import DistutilsModuleError, DistutilsPlatformError +from distutils2.errors import DistutilsPlatformError def customize_compiler(compiler): @@ -108,16 +108,16 @@ def get_default_compiler(osname=None, platform=None): _COMPILERS = { 'unix': 'distutils2.compiler.unixccompiler.UnixCCompiler', 'msvc': 'distutils2.compiler.msvccompiler.MSVCCompiler', - 'cygwin': 'distutils2.compiler.cygwinccompiler.CygWinCCompiler', + 'cygwin': 'distutils2.compiler.cygwinccompiler.CygwinCCompiler', 'mingw32': 'distutils2.compiler.cygwinccompiler.Mingw32CCompiler', 'bcpp': 'distutils2.compilers.bcppcompiler.BCPPCompiler'} def set_compiler(location): """Add or change a compiler""" - klass = resolve_name(location) + cls = resolve_name(location) # XXX we want to check the class here - _COMPILERS[klass.name] = klass + _COMPILERS[cls.name] = cls def show_compilers(): @@ -127,12 +127,12 @@ def show_compilers(): from distutils2.fancy_getopt import FancyGetopt compilers = [] - for name, klass in _COMPILERS.items(): - if isinstance(klass, str): - klass = resolve_name(klass) - _COMPILERS[name] = klass + for name, cls in _COMPILERS.items(): + if isinstance(cls, str): + cls = resolve_name(cls) + _COMPILERS[name] = cls - compilers.append(("compiler=" + compiler, None, klass.description)) + compilers.append(("compiler=" + name, None, cls.description)) compilers.sort() pretty_printer = FancyGetopt(compilers) @@ -157,22 +157,22 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): if compiler is None: compiler = get_default_compiler(plat) - klass = _COMPILERS[compiler] + cls = _COMPILERS[compiler] except KeyError: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler raise DistutilsPlatformError(msg) - if isinstance(klass, str): - klass = resolve_name(klass) - _COMPILERS[compiler] = klass + if isinstance(cls, str): + cls = resolve_name(cls) + _COMPILERS[compiler] = cls # XXX The None is necessary to preserve backwards compatibility # with classes that expect verbose to be the first positional # argument. - return klass(None, dry_run, force) + return cls(None, dry_run, force) def gen_preprocess_options(macros, include_dirs): diff --git a/distutils2/compiler/cygwinccompiler.py b/distutils2/compiler/cygwinccompiler.py index 2414649..dfde2aa 100644 --- a/distutils2/compiler/cygwinccompiler.py +++ b/distutils2/compiler/cygwinccompiler.py @@ -358,27 +358,3 @@ def check_config_h(): except IOError, exc: return (CONFIG_H_UNCERTAIN, "couldn't read '%s': %s" % (fn, exc.strerror)) - -class _Deprecated_SRE_Pattern(object): - def __init__(self, pattern): - self.pattern = pattern - - def __getattr__(self, name): - if name in ('findall', 'finditer', 'match', 'scanner', 'search', - 'split', 'sub', 'subn'): - warn("'distutils.cygwinccompiler.RE_VERSION' is deprecated " - "and will be removed in the next version", DeprecationWarning) - return getattr(self.pattern, name) - -RE_VERSION = _Deprecated_SRE_Pattern(re.compile('(\d+\.\d+(\.\d+)*)')) - -def get_versions(): - """ Try to find out the versions of gcc, ld and dllwrap. - - If not possible it returns None for it. - """ - warn("'distutils.cygwinccompiler.get_versions' is deprecated " - "use 'distutils.util.get_compiler_versions' instead", - DeprecationWarning) - - return get_compiler_versions() diff --git a/distutils2/dist.py b/distutils2/dist.py index 47bf750..9fdd974 100644 --- a/distutils2/dist.py +++ b/distutils2/dist.py @@ -422,7 +422,7 @@ Common commands: (see '--help-commands' for more) if hasattr(cmd_class, meth): continue raise DistutilsClassError( - 'command "%s" must implement "%s"' % (cmd_class. meth)) + 'command "%s" must implement "%s"' % (cmd_class, meth)) # Also make sure that the command object provides a list of its # known options. diff --git a/distutils2/index/dist.py b/distutils2/index/dist.py index f5d0fd9..b9365f5 100644 --- a/distutils2/index/dist.py +++ b/distutils2/index/dist.py @@ -101,7 +101,7 @@ class ReleaseInfo(IndexReference): def is_final(self): """proxy to version.is_final""" return self.version.is_final - + def fetch_distributions(self): if self.dists is None: self._index.get_distributions(self.name, '%s' % self.version) @@ -127,7 +127,7 @@ class ReleaseInfo(IndexReference): self.dists[dist_type] = DistInfo(self, dist_type, index=self._index, **params) if python_version: - self.dists[dist_type].python_version = python_version + self.dists[dist_type].python_version = python_version def get_distribution(self, dist_type=None, prefer_source=True): """Return a distribution. @@ -302,7 +302,7 @@ class DistInfo(IndexReference): def unpack(self, path=None): """Unpack the distribution to the given path. - + If not destination is given, creates a temporary location. Returns the location of the extracted files (root). @@ -310,10 +310,10 @@ class DistInfo(IndexReference): if not self._unpacked_dir: if path is None: path = tempfile.mkdtemp() - + filename = self.download() content_type = mimetypes.guess_type(filename)[0] - + if (content_type == 'application/zip' or filename.endswith('.zip') or filename.endswith('.pybundle') @@ -351,7 +351,7 @@ class ReleasesList(IndexReference): """ def __init__(self, name, releases=None, contains_hidden=False, index=None): self.set_index(index) - self.releases = [] + self.releases = [] self.name = name self.contains_hidden = contains_hidden if releases: @@ -404,7 +404,7 @@ class ReleasesList(IndexReference): raise ValueError("%s is not the same project than %s" % (release.name, self.name)) version = '%s' % release.version - + if not version in self.get_versions(): # append only if not already exists self.releases.append(release) @@ -445,8 +445,7 @@ class ReleasesList(IndexReference): reverse=reverse, *args, **kwargs) def get_release(self, version): - """Return a release from it's version. - """ + """Return a release from its version.""" matches = [r for r in self.releases if "%s" % r.version == version] if len(matches) != 1: raise KeyError(version) diff --git a/distutils2/index/simple.py b/distutils2/index/simple.py index f4d86fc..00c3d3b 100644 --- a/distutils2/index/simple.py +++ b/distutils2/index/simple.py @@ -1,7 +1,7 @@ """index.simple Contains the class "SimpleIndexCrawler", a simple spider to find and retrieve -distributions on the Python Package Index, using it's "simple" API, +distributions on the Python Package Index, using its "simple" API, avalaible at http://pypi.python.org/simple/ """ from fnmatch import translate diff --git a/distutils2/index/wrapper.py b/distutils2/index/wrapper.py index e3c4551..f5957f2 100644 --- a/distutils2/index/wrapper.py +++ b/distutils2/index/wrapper.py @@ -1,5 +1,4 @@ -import xmlrpc -import simple +from distutils2.index import simple, xmlrpc _WRAPPER_MAPPINGS = {'get_release': 'simple', 'get_releases': 'simple', diff --git a/distutils2/index/xmlrpc.py b/distutils2/index/xmlrpc.py index b9d66e0..31a2108 100644 --- a/distutils2/index/xmlrpc.py +++ b/distutils2/index/xmlrpc.py @@ -159,9 +159,16 @@ class Client(BaseClient): index=self._index)) except IrrationalVersionError, e: logging.warn("Irrational version error found: %s" % e) - return [self._projects[p['name'].lower()] for p in projects] + def get_all_projects(self): + """Return the list of all projects registered in the package index""" + projects = self.proxy.list_packages() + for name in projects: + self.get_releases(name, show_hidden=True) + + return [self._projects[name.lower()] for name in set(projects)] + @property def proxy(self): """Property used to return the XMLRPC server proxy. diff --git a/distutils2/install.py b/distutils2/install.py index 21510e8..c20538a 100644 --- a/distutils2/install.py +++ b/distutils2/install.py @@ -3,6 +3,7 @@ import logging import shutil import os import errno +import itertools from distutils2._backport.pkgutil import get_distributions from distutils2.depgraph import generate_graph @@ -27,15 +28,6 @@ class InstallationConflict(InstallationException): """Raised when a conflict is detected""" -def _update_infos(infos, new_infos): - """extends the lists contained in the `info` dict with those contained - in the `new_info` one - """ - for key, value in infos.items(): - if key in new_infos: - infos[key].extend(new_infos[key]) - - def move_files(files, destination=None): """Move the list of files in the destination folder, keeping the same structure. @@ -167,7 +159,7 @@ def get_infos(requirements, index=None, installed=None, prefer_final=True): index = wrapper.ClientWrapper() if not installed: - installed = get_distributions() + installed = get_distributions(use_egg_info=True) # Get all the releases that match the requirements try: @@ -184,7 +176,7 @@ def get_infos(requirements, index=None, installed=None, prefer_final=True): # Get the distributions already_installed on the system # and add the one we want to install - distributions = installed + [release] + distributions = itertools.chain(installed, [release]) depgraph = generate_graph(distributions) # Store all the already_installed packages in a list, in case of rollback. @@ -196,8 +188,7 @@ def get_infos(requirements, index=None, installed=None, prefer_final=True): logging.info("missing dependencies found, installing them") # we have missing deps for dist in dists: - _update_infos(infos, - get_infos(dist, index, installed)) + _update_infos(infos, get_infos(dist, index, installed)) # Fill in the infos existing = [d for d in installed if d.name == release.name] @@ -206,3 +197,22 @@ def get_infos(requirements, index=None, installed=None, prefer_final=True): infos['conflict'].extend(depgraph.reverse_list[existing[0]]) infos['install'].append(release) return infos + + +def _update_infos(infos, new_infos): + """extends the lists contained in the `info` dict with those contained + in the `new_info` one + """ + for key, value in infos.items(): + if key in new_infos: + infos[key].extend(new_infos[key]) + + +def main(**attrs): + if 'script_args' not in attrs: + import sys + attrs['requirements'] = sys.argv[1] + get_infos(**attrs) + +if __name__ == '__main__': + main() diff --git a/distutils2/tests/pypi_server.py b/distutils2/tests/pypi_server.py index a5fa0cf..0dc0f6d 100644 --- a/distutils2/tests/pypi_server.py +++ b/distutils2/tests/pypi_server.py @@ -400,7 +400,7 @@ class XMLRPCMockIndex(object): self._dists.append(dist) return [r.search_result() for r in results] - def list_package(self): + def list_packages(self): return [d.name for d in self._dists] def package_releases(self, package_name, show_hidden=False): diff --git a/distutils2/tests/test_command_build_ext.py b/distutils2/tests/test_command_build_ext.py index 2ae223d..8b707d1 100644 --- a/distutils2/tests/test_command_build_ext.py +++ b/distutils2/tests/test_command_build_ext.py @@ -103,10 +103,7 @@ class BuildExtTestCase(support.TempdirManager, old = sys.platform sys.platform = 'sunos' # fooling finalize_options - try: - from sysconfig import _CONFIG_VARS - except ImportError: - from distutils2._backport.sysconfig import _CONFIG_VARS + from distutils2._backport.sysconfig import _CONFIG_VARS old_var = _CONFIG_VARS.get('Py_ENABLE_SHARED') _CONFIG_VARS['Py_ENABLE_SHARED'] = 1 diff --git a/distutils2/tests/test_command_build_scripts.py b/distutils2/tests/test_command_build_scripts.py index fd5ca49..e8cf045 100644 --- a/distutils2/tests/test_command_build_scripts.py +++ b/distutils2/tests/test_command_build_scripts.py @@ -4,10 +4,7 @@ import os from distutils2.command.build_scripts import build_scripts from distutils2.dist import Distribution -try: - import sysconfig -except ImportError: - from distutils2._backport import sysconfig +from distutils2._backport import sysconfig from distutils2.tests import unittest, support diff --git a/distutils2/tests/test_command_cmd.py b/distutils2/tests/test_command_cmd.py index 3745291..1a6faf6 100644 --- a/distutils2/tests/test_command_cmd.py +++ b/distutils2/tests/test_command_cmd.py @@ -17,22 +17,6 @@ class CommandTestCase(unittest.TestCase): dist = Distribution() self.cmd = MyCmd(dist) - def test_ensure_string_list(self): - - cmd = self.cmd - cmd.not_string_list = ['one', 2, 'three'] - cmd.yes_string_list = ['one', 'two', 'three'] - cmd.not_string_list2 = object() - cmd.yes_string_list2 = 'ok' - cmd.ensure_string_list('yes_string_list') - cmd.ensure_string_list('yes_string_list2') - - self.assertRaises(DistutilsOptionError, - cmd.ensure_string_list, 'not_string_list') - - self.assertRaises(DistutilsOptionError, - cmd.ensure_string_list, 'not_string_list2') - def test_make_file(self): cmd = self.cmd @@ -82,12 +66,20 @@ class CommandTestCase(unittest.TestCase): cmd.ensure_string_list('option1') self.assertEqual(cmd.option1, ['ok', 'dok']) - cmd.option2 = ['xxx', 'www'] - cmd.ensure_string_list('option2') + cmd.yes_string_list = ['one', 'two', 'three'] + cmd.yes_string_list2 = 'ok' + cmd.ensure_string_list('yes_string_list') + cmd.ensure_string_list('yes_string_list2') + self.assertEqual(cmd.yes_string_list, ['one', 'two', 'three']) + self.assertEqual(cmd.yes_string_list2, ['ok']) - cmd.option3 = ['ok', 2] - self.assertRaises(DistutilsOptionError, cmd.ensure_string_list, - 'option3') + cmd.not_string_list = ['one', 2, 'three'] + cmd.not_string_list2 = object() + self.assertRaises(DistutilsOptionError, + cmd.ensure_string_list, 'not_string_list') + + self.assertRaises(DistutilsOptionError, + cmd.ensure_string_list, 'not_string_list2') def test_ensure_filename(self): cmd = self.cmd diff --git a/distutils2/tests/test_command_install_dist.py b/distutils2/tests/test_command_install_dist.py index 001ebae..2846bec 100644 --- a/distutils2/tests/test_command_install_dist.py +++ b/distutils2/tests/test_command_install_dist.py @@ -19,6 +19,7 @@ from distutils2.errors import DistutilsOptionError from distutils2.tests import unittest, support + class InstallTestCase(support.TempdirManager, support.EnvironGuard, support.LoggingCatcher, @@ -83,10 +84,12 @@ class InstallTestCase(support.TempdirManager, _CONFIG_VARS['userbase'] = self.user_base scheme = '%s_user' % os.name _SCHEMES.set(scheme, 'purelib', self.user_site) + def _expanduser(path): if path[0] == '~': path = os.path.normpath(self.tmpdir) + path[1:] return path + self.old_expand = os.path.expanduser os.path.expanduser = _expanduser @@ -212,6 +215,7 @@ class InstallTestCase(support.TempdirManager, install_module.DEBUG = False self.assertTrue(len(self.logs) > old_logs_len) + def test_suite(): return unittest.makeSuite(InstallTestCase) diff --git a/distutils2/tests/test_command_register.py b/distutils2/tests/test_command_register.py index b1ce79e..734aab7 100644 --- a/distutils2/tests/test_command_register.py +++ b/distutils2/tests/test_command_register.py @@ -87,6 +87,8 @@ class RegisterTestCase(support.TempdirManager, def tearDown(self): getpass.getpass = self._old_getpass urllib2.build_opener = self.old_opener + if hasattr(register_module, 'raw_input'): + del register_module.raw_input super(RegisterTestCase, self).tearDown() def _get_cmd(self, metadata=None): @@ -109,7 +111,6 @@ class RegisterTestCase(support.TempdirManager, # patching raw_input and getpass.getpass # so register gets happy - # # Here's what we are faking : # use your existing login (choice 1.) # Username : 'tarek' @@ -117,11 +118,7 @@ class RegisterTestCase(support.TempdirManager, # Save your login (y/N)? : 'y' inputs = RawInputs('1', 'tarek', 'y') register_module.raw_input = inputs.__call__ - # let's run the command - try: - cmd.run() - finally: - del register_module.raw_input + cmd.run() # we should have a brand new .pypirc file self.assertTrue(os.path.exists(self.rc)) @@ -135,8 +132,8 @@ class RegisterTestCase(support.TempdirManager, # if we run the command again def _no_way(prompt=''): raise AssertionError(prompt) - register_module.raw_input = _no_way + register_module.raw_input = _no_way cmd.show_response = 1 cmd.run() @@ -165,13 +162,10 @@ class RegisterTestCase(support.TempdirManager, cmd = self._get_cmd() inputs = RawInputs('2', 'tarek', 'tarek@ziade.org') register_module.raw_input = inputs.__call__ - try: - # let's run the command - # FIXME does this send a real request? use a mock server - # also, silence self.announce (with LoggingCatcher) - cmd.run() - finally: - del register_module.raw_input + # let's run the command + # FIXME does this send a real request? use a mock server + # also, silence self.announce (with LoggingCatcher) + cmd.run() # we should have send a request self.assertTrue(self.conn.reqs, 1) @@ -185,11 +179,7 @@ class RegisterTestCase(support.TempdirManager, cmd = self._get_cmd() inputs = RawInputs('3', 'tarek@ziade.org') register_module.raw_input = inputs.__call__ - try: - # let's run the command - cmd.run() - finally: - del register_module.raw_input + cmd.run() # we should have send a request self.assertTrue(self.conn.reqs, 1) @@ -209,6 +199,8 @@ class RegisterTestCase(support.TempdirManager, cmd = self._get_cmd({}) cmd.ensure_finalized() cmd.strict = 1 + inputs = RawInputs('1', 'tarek', 'y') + register_module.raw_input = inputs.__call__ self.assertRaises(DistutilsSetupError, cmd.run) # metadata is OK but long_description is broken @@ -230,22 +222,14 @@ class RegisterTestCase(support.TempdirManager, cmd.strict = 1 inputs = RawInputs('1', 'tarek', 'y') register_module.raw_input = inputs.__call__ - # let's run the command - try: - cmd.run() - finally: - del register_module.raw_input + cmd.run() # strict is not by default cmd = self._get_cmd() cmd.ensure_finalized() inputs = RawInputs('1', 'tarek', 'y') register_module.raw_input = inputs.__call__ - # let's run the command - try: - cmd.run() - finally: - del register_module.raw_input + cmd.run() def test_register_pep345(self): cmd = self._get_cmd({}) diff --git a/distutils2/tests/test_command_sdist.py b/distutils2/tests/test_command_sdist.py index 04e98fe..9744625 100644 --- a/distutils2/tests/test_command_sdist.py +++ b/distutils2/tests/test_command_sdist.py @@ -363,7 +363,7 @@ class SDistTestCase(support.TempdirManager, support.LoggingCatcher, finally: f.close() - self.assertEquals(len(manifest), 4) + self.assertEqual(len(manifest), 4) # adding a file self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') @@ -383,7 +383,7 @@ class SDistTestCase(support.TempdirManager, support.LoggingCatcher, f.close() # do we have the new file in MANIFEST ? - self.assertEquals(len(manifest2), 5) + self.assertEqual(len(manifest2), 5) self.assertIn('doc2.txt', manifest2[-1]) def test_manifest_marker(self): diff --git a/distutils2/tests/test_config.py b/distutils2/tests/test_config.py index 81ef1bd..6ac14d3 100644 --- a/distutils2/tests/test_config.py +++ b/distutils2/tests/test_config.py @@ -74,7 +74,7 @@ sdist_extra = [global] commands = - distutils2.tests.test_config.Foo + distutils2.tests.test_config.FooBarBazTest compilers = distutils2.tests.test_config.DCompiler @@ -99,7 +99,7 @@ def hook(content): content['metadata']['version'] += '.dev1' -class Foo(object): +class FooBarBazTest(object): def __init__(self, dist): self.distribution = dist @@ -121,6 +121,7 @@ class Foo(object): class ConfigTestCase(support.TempdirManager, + support.LoggingCatcher, unittest.TestCase): def setUp(self): @@ -192,11 +193,18 @@ class ConfigTestCase(support.TempdirManager, ('/etc/init.d ', ['init-script'])]) self.assertEqual(dist.package_dir['two'], 'src') - # make sure we get the foo command loaded ! - self.assertTrue(isinstance(dist.get_command_obj('foo'), Foo)) + # Make sure we get the foo command loaded. We use a string comparison + # instead of assertIsInstance because the class is not the same when + # this test is run directly: foo is distutils2.tests.test_config.Foo + # because get_command_class uses the full name, but a bare "Foo" in + # this file would be __main__.Foo when run as "python test_config.py". + # The name FooBarBazTest should be unique enough to prevent + # collisions. + self.assertEqual(dist.get_command_obj('foo').__class__.__name__, + 'FooBarBazTest') # did the README got loaded ? - self.assertEquals(dist.metadata['description'], 'yeah') + self.assertEqual(dist.metadata['description'], 'yeah') # do we have the D Compiler enabled ? from distutils2.compiler import new_compiler, _COMPILERS @@ -230,7 +238,7 @@ class ConfigTestCase(support.TempdirManager, finally: sys.argv[:] = old_sys - self.assertEquals(dist.foo_was_here, 1) + self.assertEqual(dist.foo_was_here, 1) def test_suite(): diff --git a/distutils2/tests/test_cygwinccompiler.py b/distutils2/tests/test_cygwinccompiler.py index 679f447..1114cc3 100644 --- a/distutils2/tests/test_cygwinccompiler.py +++ b/distutils2/tests/test_cygwinccompiler.py @@ -1,19 +1,16 @@ """Tests for distutils.cygwinccompiler.""" import sys import os -try: - import sysconfig -except ImportError: - from distutils2._backport import sysconfig + +from distutils2._backport import sysconfig from distutils2.tests import run_unittest from distutils2.tests import captured_stdout from distutils2.compiler import cygwinccompiler -from distutils2.compiler.cygwinccompiler import (CygwinCCompiler, check_config_h, - CONFIG_H_OK, CONFIG_H_NOTOK, - CONFIG_H_UNCERTAIN, get_versions, - get_msvcr, RE_VERSION) +from distutils2.compiler.cygwinccompiler import ( + CygwinCCompiler, check_config_h, get_msvcr, + CONFIG_H_OK, CONFIG_H_NOTOK, CONFIG_H_UNCERTAIN) from distutils2.util import get_compiler_versions from distutils2.tests import unittest, support diff --git a/distutils2/tests/test_index_simple.py b/distutils2/tests/test_index_simple.py index ce86493..20c7768 100644 --- a/distutils2/tests/test_index_simple.py +++ b/distutils2/tests/test_index_simple.py @@ -250,7 +250,7 @@ class SimpleCrawlerTestCase(support.TempdirManager, unittest.TestCase): # Test that the simple link matcher yield the good links. generator = crawler._simple_link_matcher(content, crawler.index_url) - self.assertEqual(('%stest/foobar-1.tar.gz#md5=abcdef' % crawler.index_url, + self.assertEqual(('%stest/foobar-1.tar.gz#md5=abcdef' % crawler.index_url, True), generator.next()) self.assertEqual(('http://dl-link1', True), generator.next()) self.assertEqual(('%stest' % crawler.index_url, False), @@ -260,7 +260,7 @@ class SimpleCrawlerTestCase(support.TempdirManager, unittest.TestCase): # Follow the external links is possible (eg. homepages) crawler.follow_externals = True generator = crawler._simple_link_matcher(content, crawler.index_url) - self.assertEqual(('%stest/foobar-1.tar.gz#md5=abcdef' % crawler.index_url, + self.assertEqual(('%stest/foobar-1.tar.gz#md5=abcdef' % crawler.index_url, True), generator.next()) self.assertEqual(('http://dl-link1', True), generator.next()) self.assertEqual(('http://dl-link2', False), generator.next()) @@ -304,8 +304,8 @@ class SimpleCrawlerTestCase(support.TempdirManager, unittest.TestCase): # we can search the index for some projects, on their names # the case used no matters here crawler = self._get_simple_crawler(server) - tests = (('Foobar', ['FooBar-bar', 'Foobar-baz', 'Baz-FooBar']), - ('foobar*', ['FooBar-bar', 'Foobar-baz']), + tests = (('Foobar', ['FooBar-bar', 'Foobar-baz', 'Baz-FooBar']), + ('foobar*', ['FooBar-bar', 'Foobar-baz']), ('*foobar', ['Baz-FooBar',])) for search, expected in tests: diff --git a/distutils2/tests/test_index_xmlrpc.py b/distutils2/tests/test_index_xmlrpc.py index 986a743..f3d3fbc 100644 --- a/distutils2/tests/test_index_xmlrpc.py +++ b/distutils2/tests/test_index_xmlrpc.py @@ -25,6 +25,24 @@ class TestXMLRPCClient(unittest.TestCase): invalid="test") @use_xmlrpc_server() + def test_get_all_projects(self, server): + client = self._get_client(server) + server.xmlrpc.set_distributions([ + {'name': 'FooBar', 'version': '1.1'}, + {'name': 'FooBar', 'version': '1.2'}, + {'name': 'Foo', 'version': '1.1'}, + ]) + results = client.get_all_projects() + self.assertEqual(2, len(results)) + + # check we do have two releases for Foobar's project + self.assertEqual(2, len(results[0].releases)) + + names = [r.name for r in results] + self.assertIn('FooBar', names) + self.assertIn('Foo', names) + + @use_xmlrpc_server() def test_get_releases(self, server): client = self._get_client(server) server.xmlrpc.set_distributions([ diff --git a/distutils2/tests/test_install.py b/distutils2/tests/test_install.py index fde33e1..d64d935 100644 --- a/distutils2/tests/test_install.py +++ b/distutils2/tests/test_install.py @@ -284,7 +284,7 @@ class TestInstall(TempdirManager, unittest.TestCase): install.install_from_infos(install=to_install, install_path=install_path) for dist in to_install: - self.assertEquals(dist.install_called_with, (install_path,)) + self.assertEqual(dist.install_called_with, (install_path,)) def test_suite(): suite = unittest.TestSuite() diff --git a/distutils2/tests/test_metadata.py b/distutils2/tests/test_metadata.py index 32c6895..0b37caf 100644 --- a/distutils2/tests/test_metadata.py +++ b/distutils2/tests/test_metadata.py @@ -11,6 +11,7 @@ from distutils2.tests.support import LoggingCatcher, WarningsCatcher from distutils2.errors import (MetadataConflictError, MetadataUnrecognizedVersionError) + class DistributionMetadataTestCase(LoggingCatcher, WarningsCatcher, unittest.TestCase): @@ -95,7 +96,6 @@ class DistributionMetadataTestCase(LoggingCatcher, WarningsCatcher, {'python_version': '0.1'})) def test_metadata_read_write(self): - PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') metadata = DistributionMetadata(PKG_INFO) out = StringIO() @@ -117,7 +117,7 @@ class DistributionMetadataTestCase(LoggingCatcher, WarningsCatcher, metadata['Name'] = "baz; sys.platform == 'blah'" # FIXME is None or 'UNKNOWN' correct here? # where is that documented? - self.assertEquals(metadata['Name'], None) + self.assertEqual(metadata['Name'], None) # test with context context = {'sys.platform': 'okook'} diff --git a/distutils2/tests/test_mixin2to3.py b/distutils2/tests/test_mixin2to3.py index c6661a6..546a2ed 100644 --- a/distutils2/tests/test_mixin2to3.py +++ b/distutils2/tests/test_mixin2to3.py @@ -25,7 +25,7 @@ class Mixin2to3TestCase(support.TempdirManager, support.WarningsCatcher, converted_code_content = "print('test')\n" new_code_content = "".join(open(code_name).readlines()) - self.assertEquals(new_code_content, converted_code_content) + self.assertEqual(new_code_content, converted_code_content) @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_doctests_only(self): @@ -45,7 +45,7 @@ class Mixin2to3TestCase(support.TempdirManager, support.WarningsCatcher, converted_doctest_content = '\n'.join(converted_doctest_content) new_doctest_content = "".join(open(doctest_name).readlines()) - self.assertEquals(new_doctest_content, converted_doctest_content) + self.assertEqual(new_doctest_content, converted_doctest_content) @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_additional_fixers(self): @@ -64,7 +64,7 @@ class Mixin2to3TestCase(support.TempdirManager, support.WarningsCatcher, fixers=['distutils2.tests.fixer']) converted_code_content = "isinstance(x, T)" new_code_content = "".join(open(code_name).readlines()) - self.assertEquals(new_code_content, converted_code_content) + self.assertEqual(new_code_content, converted_code_content) def test_suite(): return unittest.makeSuite(Mixin2to3TestCase) diff --git a/distutils2/tests/test_mkcfg.py b/distutils2/tests/test_mkcfg.py index 0fea9ee..2469074 100644 --- a/distutils2/tests/test_mkcfg.py +++ b/distutils2/tests/test_mkcfg.py @@ -36,8 +36,8 @@ class MkcfgTestCase(support.TempdirManager, # 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']) + self.assertEqual(set(main.data['extra_files']), + set(['setup.cfg', 'README', 'data/data1'])) def test_suite(): diff --git a/distutils2/tests/test_unixccompiler.py b/distutils2/tests/test_unixccompiler.py index 5126746..59da40e 100644 --- a/distutils2/tests/test_unixccompiler.py +++ b/distutils2/tests/test_unixccompiler.py @@ -1,11 +1,7 @@ """Tests for distutils.unixccompiler.""" import sys -try: - import sysconfig -except ImportError: - from distutils2._backport import sysconfig - +from distutils2._backport import sysconfig from distutils2.compiler.unixccompiler import UnixCCompiler from distutils2.tests import unittest diff --git a/distutils2/tests/test_util.py b/distutils2/tests/test_util.py index 785f434..72ec3cf 100644 --- a/distutils2/tests/test_util.py +++ b/distutils2/tests/test_util.py @@ -144,7 +144,7 @@ class UtilTestCase(support.EnvironGuard, os.path.join = _join self.assertEqual(convert_path('/home/to/my/stuff'), - '/home/to/my/stuff') + '/home/to/my/stuff') # win os.sep = '\\' @@ -156,9 +156,9 @@ class UtilTestCase(support.EnvironGuard, self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/') self.assertEqual(convert_path('home/to/my/stuff'), - 'home\\to\\my\\stuff') + 'home\\to\\my\\stuff') self.assertEqual(convert_path('.'), - os.curdir) + os.curdir) def test_change_root(self): # linux/mac @@ -171,9 +171,9 @@ class UtilTestCase(support.EnvironGuard, os.path.join = _join self.assertEqual(change_root('/root', '/old/its/here'), - '/root/old/its/here') + '/root/old/its/here') self.assertEqual(change_root('/root', 'its/here'), - '/root/its/here') + '/root/its/here') # windows os.name = 'nt' @@ -190,9 +190,9 @@ class UtilTestCase(support.EnvironGuard, os.path.join = _join self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'), - 'c:\\root\\old\\its\\here') + 'c:\\root\\old\\its\\here') self.assertEqual(change_root('c:\\root', 'its\\here'), - 'c:\\root\\its\\here') + 'c:\\root\\its\\here') # BugsBunny os (it's a great os) os.name = 'BugsBunny' @@ -203,7 +203,7 @@ class UtilTestCase(support.EnvironGuard, def test_split_quoted(self): self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'), - ['one', 'two', 'three', 'four']) + ['one', 'two', 'three', 'four']) def test_strtobool(self): yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') @@ -383,7 +383,7 @@ class UtilTestCase(support.EnvironGuard, run_2to3([file_name]) new_content = "".join(file_handle.read()) file_handle.close() - self.assertEquals(new_content, converted_content) + self.assertEqual(new_content, converted_content) @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_run_2to3_on_doctests(self): @@ -399,7 +399,7 @@ class UtilTestCase(support.EnvironGuard, run_2to3([file_name], doctests_only=True) new_content = "".join(file_handle.readlines()) file_handle.close() - self.assertEquals(new_content, converted_content) + self.assertEqual(new_content, converted_content) def test_nt_quote_args(self): diff --git a/distutils2/tests/test_version.py b/distutils2/tests/test_version.py index c69ef3f..b7ad57f 100644 --- a/distutils2/tests/test_version.py +++ b/distutils2/tests/test_version.py @@ -61,9 +61,9 @@ class VersionTestCase(unittest.TestCase): def test_huge_version(self): - self.assertEquals(str(V('1980.0')), '1980.0') + self.assertEqual(str(V('1980.0')), '1980.0') self.assertRaises(HugeMajorVersionNumError, V, '1981.0') - self.assertEquals(str(V('1981.0', error_on_huge_major_num=False)), '1981.0') + self.assertEqual(str(V('1981.0', error_on_huge_major_num=False)), '1981.0') def test_comparison(self): r""" @@ -225,7 +225,7 @@ class VersionWhiteBoxTestCase(unittest.TestCase): def test_parse_numdots(self): # For code coverage completeness, as pad_zeros_length can't be set or # influenced from the public interface - self.assertEquals(V('1.0')._parse_numdots('1.0', '1.0', + self.assertEqual(V('1.0')._parse_numdots('1.0', '1.0', pad_zeros_length=3), [1, 0, 0]) diff --git a/distutils2/util.py b/distutils2/util.py index 1ee1904..9a0e714 100644 --- a/distutils2/util.py +++ b/distutils2/util.py @@ -238,20 +238,20 @@ def split_quoted(s): words.append(s[:end]) break - if s[end] in string.whitespace: # unescaped, unquoted whitespace: now - words.append(s[:end]) # we definitely have a word delimiter + if s[end] in string.whitespace: # unescaped, unquoted whitespace: now + words.append(s[:end]) # we definitely have a word delimiter s = s[end:].lstrip() pos = 0 - elif s[end] == '\\': # preserve whatever is being escaped; - # will become part of the current word + elif s[end] == '\\': # preserve whatever is being escaped; + # will become part of the current word s = s[:end] + s[end + 1:] pos = end + 1 else: - if s[end] == "'": # slurp singly-quoted string + if s[end] == "'": # slurp singly-quoted string m = _squote_re.match(s, end) - elif s[end] == '"': # slurp doubly-quoted string + elif s[end] == '"': # slurp doubly-quoted string m = _dquote_re.match(s, end) else: raise RuntimeError("this can't happen " @@ -659,11 +659,12 @@ def resolve_name(name): for part in parts[1:]: try: ret = getattr(ret, part) - except AttributeError: - raise ImportError + except AttributeError, exc: + raise ImportError(exc) return ret + def splitext(path): """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) @@ -869,7 +870,8 @@ 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 - logger.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)) @@ -971,6 +973,7 @@ username:%s password:%s """ + def get_pypirc_path(): """Returns rc file path.""" return os.path.join(os.path.expanduser('~'), '.pypirc') @@ -1048,7 +1051,7 @@ def read_pypirc(repository=DEFAULT_REPOSITORY, realm=DEFAULT_REALM): def metadata_to_dict(meta): """XXX might want to move it to the Metadata class.""" data = { - 'metadata_version' : meta.version, + 'metadata_version': meta.version, 'name': meta['Name'], 'version': meta['Version'], 'summary': meta['Summary'], @@ -1079,10 +1082,11 @@ def metadata_to_dict(meta): return data + # utility functions for 2to3 support -def run_2to3(files, doctests_only=False, fixer_names=None, options=None, - explicit=None): +def run_2to3(files, doctests_only=False, fixer_names=None, + options=None, explicit=None): """ Wrapper function around the refactor() class which performs the conversions on a list of python files. Invoke 2to3 on a list of Python files. The files should all come @@ -1096,15 +1100,12 @@ def run_2to3(files, doctests_only=False, fixer_names=None, options=None, fixers = [] fixers = get_fixers_from_package('lib2to3.fixes') - if fixer_names: for fixername in fixer_names: fixers.extend([fixer for fixer in get_fixers_from_package(fixername)]) r = RefactoringTool(fixers, options=options) - if doctests_only: - r.refactor(files, doctests_only=True, write=True) - else: - r.refactor(files, write=True) + r.refactor(files, write=True, doctests_only=doctests_only) + class Mixin2to3: """ Wrapper class for commands that run 2to3. |
