summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorErik M. Bray <embray@stsci.edu>2013-03-05 12:05:01 -0500
committerErik M. Bray <embray@stsci.edu>2013-03-05 12:05:29 -0500
commit06e151665e0f021a6f944a4c73e13bb0791e22ce (patch)
tree93be22278314d375a302424ccbf982dbbaca6f46
parenta44c84b90ac254d74235c0d2327c17f542c5fcbe (diff)
downloadpbr-06e151665e0f021a6f944a4c73e13bb0791e22ce.tar.gz
Adds six.py and makes the necessary tweaks to improve support for using d2to1 natively across Python versions
-rw-r--r--pbr/d2to1/core.py15
-rw-r--r--pbr/d2to1/extern/__init__.py0
-rw-r--r--pbr/d2to1/extern/six.py386
-rw-r--r--pbr/d2to1/tests/__init__.py4
-rw-r--r--pbr/d2to1/tests/testpackage/d2to1_testpackage/_setup_hooks.py10
-rw-r--r--pbr/d2to1/tests/util.py3
-rw-r--r--pbr/d2to1/util.py13
-rw-r--r--pbr/d2to1/zestreleaser.py3
8 files changed, 414 insertions, 20 deletions
diff --git a/pbr/d2to1/core.py b/pbr/d2to1/core.py
index 231d2a3..6c93f2b 100644
--- a/pbr/d2to1/core.py
+++ b/pbr/d2to1/core.py
@@ -1,11 +1,13 @@
import os
+import sys
import warnings
from distutils.core import Distribution as _Distribution
from distutils.errors import DistutilsFileError, DistutilsSetupError
from setuptools.dist import _get_unpatched
-from d2to1.util import DefaultGetDict, IgnoreDict, cfg_to_args, resolve_name
+from .extern import six
+from .util import DefaultGetDict, IgnoreDict, cfg_to_args, resolve_name
_Distribution = _get_unpatched(_Distribution)
@@ -31,7 +33,7 @@ def d2to1(dist, attr, value):
if not value:
return
- if isinstance(value, basestring):
+ if isinstance(value, six.string_types):
path = os.path.abspath(value)
else:
path = os.path.abspath('setup.cfg')
@@ -42,17 +44,18 @@ def d2to1(dist, attr, value):
# Converts the setup.cfg file to setup() arguments
try:
attrs = cfg_to_args(path)
- except Exception, e:
+ except:
+ e = sys.exc_info()[1]
raise DistutilsSetupError(
'Error parsing %s: %s: %s' % (path, e.__class__.__name__,
- unicode(e)))
+ six.u(e)))
# Repeat some of the Distribution initialization code with the newly
# provided attrs
if attrs:
# Skips 'options' and 'licence' support which are rarely used; may add
# back in later if demanded
- for key, val in attrs.iteritems():
+ for key, val in six.iteritems(attrs):
if hasattr(dist.metadata, 'set_' + key):
getattr(dist.metadata, 'set_' + key)(val)
elif hasattr(dist.metadata, key):
@@ -67,7 +70,7 @@ def d2to1(dist, attr, value):
_Distribution.finalize_options(dist)
# This bit comes out of distribute/setuptools
- if isinstance(dist.metadata.version, (int, long, float)):
+ if isinstance(dist.metadata.version, six.integer_types + (float,)):
# Some people apparently take "version number" too literally :)
dist.metadata.version = str(dist.metadata.version)
diff --git a/pbr/d2to1/extern/__init__.py b/pbr/d2to1/extern/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/pbr/d2to1/extern/__init__.py
diff --git a/pbr/d2to1/extern/six.py b/pbr/d2to1/extern/six.py
new file mode 100644
index 0000000..0cdd1c7
--- /dev/null
+++ b/pbr/d2to1/extern/six.py
@@ -0,0 +1,386 @@
+# Copyright (c) 2010-2011 Benjamin Peterson
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+"""Utilities for writing code that runs on Python 2 and 3"""
+
+import operator
+import sys
+import types
+
+__author__ = "Benjamin Peterson <benjamin@python.org>"
+__version__ = "1.2.0"
+
+
+# True if we are running on Python 3.
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+ string_types = str,
+ integer_types = int,
+ class_types = type,
+ text_type = str
+ binary_type = bytes
+
+ MAXSIZE = sys.maxsize
+else:
+ string_types = basestring,
+ integer_types = (int, long)
+ class_types = (type, types.ClassType)
+ text_type = unicode
+ binary_type = str
+
+ if sys.platform == "java":
+ # Jython always uses 32 bits.
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
+ class X(object):
+ def __len__(self):
+ return 1 << 31
+ try:
+ len(X())
+ except OverflowError:
+ # 32-bit
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # 64-bit
+ MAXSIZE = int((1 << 63) - 1)
+ del X
+
+
+def _add_doc(func, doc):
+ """Add documentation to a function."""
+ func.__doc__ = doc
+
+
+def _import_module(name):
+ """Import module, returning the module after the last dot."""
+ __import__(name)
+ return sys.modules[name]
+
+
+class _LazyDescr(object):
+
+ def __init__(self, name):
+ self.name = name
+
+ def __get__(self, obj, tp):
+ result = self._resolve()
+ setattr(obj, self.name, result)
+ # This is a bit ugly, but it avoids running this again.
+ delattr(tp, self.name)
+ return result
+
+
+class MovedModule(_LazyDescr):
+
+ def __init__(self, name, old, new=None):
+ super(MovedModule, self).__init__(name)
+ if PY3:
+ if new is None:
+ new = name
+ self.mod = new
+ else:
+ self.mod = old
+
+ def _resolve(self):
+ return _import_module(self.mod)
+
+
+class MovedAttribute(_LazyDescr):
+
+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
+ super(MovedAttribute, self).__init__(name)
+ if PY3:
+ if new_mod is None:
+ new_mod = name
+ self.mod = new_mod
+ if new_attr is None:
+ if old_attr is None:
+ new_attr = name
+ else:
+ new_attr = old_attr
+ self.attr = new_attr
+ else:
+ self.mod = old_mod
+ if old_attr is None:
+ old_attr = name
+ self.attr = old_attr
+
+ def _resolve(self):
+ module = _import_module(self.mod)
+ return getattr(module, self.attr)
+
+
+
+class _MovedItems(types.ModuleType):
+ """Lazy loading of moved objects"""
+
+
+_moved_attributes = [
+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),
+ MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
+ MovedAttribute("reduce", "__builtin__", "functools"),
+ MovedAttribute("StringIO", "StringIO", "io"),
+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
+
+ MovedModule("builtins", "__builtin__"),
+ MovedModule("configparser", "ConfigParser"),
+ MovedModule("copyreg", "copy_reg"),
+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
+ MovedModule("http_cookies", "Cookie", "http.cookies"),
+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),
+ MovedModule("html_parser", "HTMLParser", "html.parser"),
+ MovedModule("http_client", "httplib", "http.client"),
+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
+ MovedModule("cPickle", "cPickle", "pickle"),
+ MovedModule("queue", "Queue"),
+ MovedModule("reprlib", "repr"),
+ MovedModule("socketserver", "SocketServer"),
+ MovedModule("tkinter", "Tkinter"),
+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
+ MovedModule("tkinter_colorchooser", "tkColorChooser",
+ "tkinter.colorchooser"),
+ MovedModule("tkinter_commondialog", "tkCommonDialog",
+ "tkinter.commondialog"),
+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),
+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
+ "tkinter.simpledialog"),
+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
+ MovedModule("winreg", "_winreg"),
+]
+for attr in _moved_attributes:
+ setattr(_MovedItems, attr.name, attr)
+del attr
+
+moves = sys.modules["six.moves"] = _MovedItems("moves")
+
+
+def add_move(move):
+ """Add an item to six.moves."""
+ setattr(_MovedItems, move.name, move)
+
+
+def remove_move(name):
+ """Remove item from six.moves."""
+ try:
+ delattr(_MovedItems, name)
+ except AttributeError:
+ try:
+ del moves.__dict__[name]
+ except KeyError:
+ raise AttributeError("no such move, %r" % (name,))
+
+
+if PY3:
+ _meth_func = "__func__"
+ _meth_self = "__self__"
+
+ _func_code = "__code__"
+ _func_defaults = "__defaults__"
+
+ _iterkeys = "keys"
+ _itervalues = "values"
+ _iteritems = "items"
+else:
+ _meth_func = "im_func"
+ _meth_self = "im_self"
+
+ _func_code = "func_code"
+ _func_defaults = "func_defaults"
+
+ _iterkeys = "iterkeys"
+ _itervalues = "itervalues"
+ _iteritems = "iteritems"
+
+
+try:
+ advance_iterator = next
+except NameError:
+ def advance_iterator(it):
+ return it.next()
+next = advance_iterator
+
+
+if PY3:
+ def get_unbound_function(unbound):
+ return unbound
+
+ Iterator = object
+
+ def callable(obj):
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
+else:
+ def get_unbound_function(unbound):
+ return unbound.im_func
+
+ class Iterator(object):
+
+ def next(self):
+ return type(self).__next__(self)
+
+ callable = callable
+_add_doc(get_unbound_function,
+ """Get the function out of a possibly unbound function""")
+
+
+get_method_function = operator.attrgetter(_meth_func)
+get_method_self = operator.attrgetter(_meth_self)
+get_function_code = operator.attrgetter(_func_code)
+get_function_defaults = operator.attrgetter(_func_defaults)
+
+
+def iterkeys(d):
+ """Return an iterator over the keys of a dictionary."""
+ return iter(getattr(d, _iterkeys)())
+
+def itervalues(d):
+ """Return an iterator over the values of a dictionary."""
+ return iter(getattr(d, _itervalues)())
+
+def iteritems(d):
+ """Return an iterator over the (key, value) pairs of a dictionary."""
+ return iter(getattr(d, _iteritems)())
+
+
+if PY3:
+ def b(s):
+ return s.encode("latin-1")
+ def u(s):
+ return s
+ if sys.version_info[1] <= 1:
+ def int2byte(i):
+ return bytes((i,))
+ else:
+ # This is about 2x faster than the implementation above on 3.2+
+ int2byte = operator.methodcaller("to_bytes", 1, "big")
+ import io
+ StringIO = io.StringIO
+ BytesIO = io.BytesIO
+else:
+ def b(s):
+ return s
+ def u(s):
+ return unicode(s, "unicode_escape")
+ int2byte = chr
+ import StringIO
+ StringIO = BytesIO = StringIO.StringIO
+_add_doc(b, """Byte literal""")
+_add_doc(u, """Text literal""")
+
+
+if PY3:
+ import builtins
+ exec_ = getattr(builtins, "exec")
+
+
+ def reraise(tp, value, tb=None):
+ if value.__traceback__ is not tb:
+ raise value.with_traceback(tb)
+ raise value
+
+
+ print_ = getattr(builtins, "print")
+ del builtins
+
+else:
+ def exec_(code, globs=None, locs=None):
+ """Execute code in a namespace."""
+ if globs is None:
+ frame = sys._getframe(1)
+ globs = frame.f_globals
+ if locs is None:
+ locs = frame.f_locals
+ del frame
+ elif locs is None:
+ locs = globs
+ exec("""exec code in globs, locs""")
+
+
+ exec_("""def reraise(tp, value, tb=None):
+ raise tp, value, tb
+""")
+
+
+ def print_(*args, **kwargs):
+ """The new-style print function."""
+ fp = kwargs.pop("file", sys.stdout)
+ if fp is None:
+ return
+ def write(data):
+ if not isinstance(data, basestring):
+ data = str(data)
+ fp.write(data)
+ want_unicode = False
+ sep = kwargs.pop("sep", None)
+ if sep is not None:
+ if isinstance(sep, unicode):
+ want_unicode = True
+ elif not isinstance(sep, str):
+ raise TypeError("sep must be None or a string")
+ end = kwargs.pop("end", None)
+ if end is not None:
+ if isinstance(end, unicode):
+ want_unicode = True
+ elif not isinstance(end, str):
+ raise TypeError("end must be None or a string")
+ if kwargs:
+ raise TypeError("invalid keyword arguments to print()")
+ if not want_unicode:
+ for arg in args:
+ if isinstance(arg, unicode):
+ want_unicode = True
+ break
+ if want_unicode:
+ newline = unicode("\n")
+ space = unicode(" ")
+ else:
+ newline = "\n"
+ space = " "
+ if sep is None:
+ sep = space
+ if end is None:
+ end = newline
+ for i, arg in enumerate(args):
+ if i:
+ write(sep)
+ write(arg)
+ write(end)
+
+_add_doc(reraise, """Reraise an exception.""")
+
+
+def with_metaclass(meta, base=object):
+ """Create a base class with a metaclass."""
+ return meta("NewBase", (base,), {})
diff --git a/pbr/d2to1/tests/__init__.py b/pbr/d2to1/tests/__init__.py
index fdaf958..6146af2 100644
--- a/pbr/d2to1/tests/__init__.py
+++ b/pbr/d2to1/tests/__init__.py
@@ -67,7 +67,8 @@ class D2to1TestCase(object):
cmd = ('-c',
'import sys;sys.path.insert(0, %r);'
'from d2to1.tests import fake_d2to1_dist;'
- 'fake_d2to1_dist();execfile("setup.py")' % D2TO1_DIR)
+ 'from d2to1.extern.six import exec_;'
+ 'fake_d2to1_dist();exec_(open("setup.py").read())' % D2TO1_DIR)
return self._run_cmd(sys.executable, cmd + args)
def run_svn(self, *args):
@@ -85,4 +86,5 @@ class D2to1TestCase(object):
stderr=subprocess.PIPE)
streams = tuple(s.decode('latin1').strip() for s in p.communicate())
+ print(streams)
return (streams) + (p.returncode,)
diff --git a/pbr/d2to1/tests/testpackage/d2to1_testpackage/_setup_hooks.py b/pbr/d2to1/tests/testpackage/d2to1_testpackage/_setup_hooks.py
index 453d707..77005b2 100644
--- a/pbr/d2to1/tests/testpackage/d2to1_testpackage/_setup_hooks.py
+++ b/pbr/d2to1/tests/testpackage/d2to1_testpackage/_setup_hooks.py
@@ -2,24 +2,24 @@ from distutils.command.build_py import build_py
def test_hook_1(config):
- print 'test_hook_1'
+ print('test_hook_1')
def test_hook_2(config):
- print 'test_hook_2'
+ print('test_hook_2')
class test_command(build_py):
command_name = 'build_py'
def run(self):
- print 'Running custom build_py command.'
+ print('Running custom build_py command.')
return build_py.run(self)
def test_pre_hook(cmdobj):
- print 'build_ext pre-hook'
+ print('build_ext pre-hook')
def test_post_hook(cmdobj):
- print 'build_ext post-hook'
+ print('build_ext post-hook')
diff --git a/pbr/d2to1/tests/util.py b/pbr/d2to1/tests/util.py
index 0337b7f..fa55587 100644
--- a/pbr/d2to1/tests/util.py
+++ b/pbr/d2to1/tests/util.py
@@ -6,7 +6,8 @@ import shutil
import stat
-from ConfigParser import ConfigParser
+from ..extern.six import moves as m
+ConfigParser = m.configparser.ConfigParser
@contextlib.contextmanager
diff --git a/pbr/d2to1/util.py b/pbr/d2to1/util.py
index a95adcf..4e14c13 100644
--- a/pbr/d2to1/util.py
+++ b/pbr/d2to1/util.py
@@ -28,10 +28,9 @@ from distutils.errors import (DistutilsOptionError, DistutilsModuleError,
from setuptools.command.egg_info import manifest_maker
from setuptools.dist import Distribution
from setuptools.extension import Extension
-try:
- from ConfigParser import RawConfigParser
-except ImportError:
- from configparser import RawConfigParser
+
+from .extern.six import moves as m
+RawConfigParser = m.configparser.RawConfigParser
# A simplified RE for this; just checks that the line ends with version
@@ -173,7 +172,8 @@ def cfg_to_args(path='setup.cfg'):
hook_fn = resolve_name(hook)
try :
hook_fn(config)
- except Exception, e:
+ except:
+ e = sys.exc_info()[1]
log.error('setup hook %s raised exception: %s\n' %
(hook, e))
log.error(traceback.format_exc())
@@ -492,7 +492,8 @@ def run_command_hooks(cmd_obj, hook_kind):
try :
hook_obj(cmd_obj)
- except Exception, e :
+ except:
+ e = sys.exc_info()[1]
log.error('hook %s raised exception: %s\n' % (hook, e))
log.error(traceback.format_exc())
sys.exit(1)
diff --git a/pbr/d2to1/zestreleaser.py b/pbr/d2to1/zestreleaser.py
index 550413c..896b6db 100644
--- a/pbr/d2to1/zestreleaser.py
+++ b/pbr/d2to1/zestreleaser.py
@@ -18,7 +18,8 @@ is added then support for it should be included here as well.
import logging
import os
-from ConfigParser import ConfigParser
+from .extern.six import moves as m
+ConfigParser = m.configparser.ConfigParser
logger = logging.getLogger(__name__)