Ticket #5965: twisted_383e25.patch

File twisted_383e25.patch, 23.3 KB (added by realcr, 3 years ago)

Some porting to Python3. This time the right order :)

  • .gitignore

    diff --git .gitignore .gitignore
    index afdad62..7039ee4 100644
     
    55_trial_temp*/
    66build/
    77dropin.cache
     8*.swp
  • new file in/trial3

    diff --git bin/trial3 bin/trial3
    new file mode 100755
    index 0000000..a00652b
    - +  
     1#!/usr/bin/env python3.2
     2# Copyright (c) Twisted Matrix Laboratories.
     3# See LICENSE for details.
     4import os, sys
     5
     6try:
     7    import _preamble
     8except ImportError:
     9    sys.exc_clear()
     10
     11# begin chdir armor
     12sys.path[:] = map(os.path.abspath, sys.path)
     13# end chdir armor
     14
     15sys.path.insert(0, os.path.abspath(os.getcwd()))
     16
     17from twisted.scripts.trial import run
     18run()
  • twisted/application/app.py

    diff --git twisted/application/app.py twisted/application/app.py
    index f0545d0..9384e09 100644
     
    22# Copyright (c) Twisted Matrix Laboratories.
    33# See LICENSE for details.
    44
     5from __future__ import division, absolute_import
    56import sys, os, pdb, getpass, traceback, signal
    67from operator import attrgetter
    78
    class ProfileRunner(_BasicProfiler): 
    6465        """
    6566        try:
    6667            import profile
    67         except ImportError, e:
     68        except ImportError as e:
    6869            self._reportImportError("profile", e)
    6970
    7071        p = profile.Profile()
    class HotshotRunner(_BasicProfiler): 
    9293        """
    9394        try:
    9495            import hotshot.stats
    95         except (ImportError, SystemExit), e:
     96        except (ImportError, SystemExit) as e:
    9697            # Certain versions of Debian (and Debian derivatives) raise
    9798            # SystemExit when importing hotshot if the "non-free" profiler
    9899            # module is not installed.  Someone eventually recognized this
    class CProfileRunner(_BasicProfiler): 
    133134        """
    134135        try:
    135136            import cProfile, pstats
    136         except ImportError, e:
     137        except ImportError as e:
    137138            self._reportImportError("cProfile", e)
    138139
    139140        p = cProfile.Profile()
    def fixPdb(): 
    263264
    264265
    265266    def help_stop(self):
    266         print """stop - Continue execution, then cleanly shutdown the twisted reactor."""
     267        print("stop - Continue execution, then cleanly shutdown the " + \
     268                "twisted reactor.")
    267269
    268270
    269271    def set_quit(self):
    def getApplication(config, passphrase): 
    451453        log.msg("Loading %s..." % filename)
    452454        application = service.loadApplication(filename, style, passphrase)
    453455        log.msg("Loaded.")
    454     except Exception, e:
     456    except Exception as e:
    455457        s = "Failed to load application: %s" % e
    456458        if isinstance(e, KeyError) and e.args[0] == "application":
    457459            s += """
    class ReactorSelectionMixin: 
    515517                   "See the list of available reactors with "
    516518                   "--help-reactors" % (shortName,))
    517519            raise usage.UsageError(msg)
    518         except Exception, e:
     520        except Exception as e:
    519521            msg = ("The specified reactor cannot be used, failed with error: "
    520522                   "%s.\nSee the list of available reactors with "
    521523                   "--help-reactors" % (e,))
    class ServerOptions(usage.Options, ReactorSelectionMixin): 
    610612        if self['logger'] is not None:
    611613            try:
    612614                self['logger'] = namedAny(self['logger'])
    613             except Exception, e:
     615            except Exception as e:
    614616                raise usage.UsageError("Logger '%s' could not be imported: %s"
    615617                                       % (self['logger'], e))
    616618
    def run(runApp, ServerOptions): 
    635637    config = ServerOptions()
    636638    try:
    637639        config.parseOptions()
    638     except usage.error, ue:
    639         print config
    640         print "%s: %s" % (sys.argv[0], ue)
     640    except usage.error as ue:
     641        print(config)
     642        print("%s: %s" % (sys.argv[0], ue))
    641643    else:
    642644        runApp(config)
    643645
  • twisted/application/reactors.py

    diff --git twisted/application/reactors.py twisted/application/reactors.py
    index cccddd1..429f192 100644
     
    66Plugin-based system for enumerating available reactors and installing one of
    77them.
    88"""
    9 
    10 from zope.interface import Interface, Attribute, implements
     9from __future__ import division, absolute_import
     10from zope.interface import Interface, Attribute, implementer
    1111
    1212from twisted.plugin import IPlugin, getPlugins
    1313from twisted.python.reflect import namedAny
    class NoSuchReactor(KeyError): 
    4141    """
    4242
    4343
     44@implementer(IPlugin, IReactorInstaller)
    4445class Reactor(object):
    4546    """
    4647    @ivar moduleName: The fully-qualified Python name of the module of which
    4748    the install callable is an attribute.
    4849    """
    49     implements(IPlugin, IReactorInstaller)
    50 
    5150
    5251    def __init__(self, shortName, moduleName, description):
    5352        self.shortName = shortName
  • twisted/application/service.py

    diff --git twisted/application/service.py twisted/application/service.py
    index 66fef85..668519e 100644
    a sibling). 
    1212
    1313Maintainer: Moshe Zadka
    1414"""
    15 
    16 from zope.interface import implements, Interface, Attribute
     15from __future__ import division, absolute_import
     16from zope.interface import implementer, Interface, Attribute
    1717
    1818from twisted.python.reflect import namedAny
    1919from twisted.python import components
    class IServiceMaker(Interface): 
    5656
    5757
    5858
     59@implementer(IPlugin, IServiceMaker)
    5960class ServiceMaker(object):
    6061    """
    6162    Utility class to simplify the definition of L{IServiceMaker} plugins.
    6263    """
    63     implements(IPlugin, IServiceMaker)
    6464
    6565    def __init__(self, name, module, description, tapname):
    6666        self.name = name
    class IService(Interface): 
    152152        """
    153153
    154154
     155@implementer(IService)
    155156class Service:
    156157    """
    157158    Base class for services.
    class Service: 
    161162    as not serializing this book-keeping information.
    162163    """
    163164
    164     implements(IService)
    165165
    166166    running = 0
    167167    name = None
    class IServiceCollection(Interface): 
    254254
    255255
    256256
     257@implementer(IServiceCollection)
    257258class MultiService(Service):
    258259    """
    259260    Straightforward Service Container.
    class MultiService(Service): 
    264265    will finish.
    265266    """
    266267
    267     implements(IServiceCollection)
    268 
    269268    def __init__(self):
    270269        self.services = []
    271270        self.namedServices = {}
    class IProcess(Interface): 
    347346
    348347
    349348
     349@implementer(IProcess)
    350350class Process:
    351351    """
    352352    Process running parameters.
    class Process: 
    354354    Sets up uid/gid in the constructor, and has a default
    355355    of C{None} as C{processName}.
    356356    """
    357     implements(IProcess)
    358357    processName = None
    359358
    360359    def __init__(self, uid=None, gid=None):
  • twisted/persisted/sob.py

    diff --git twisted/persisted/sob.py twisted/persisted/sob.py
    index 89d9caa..0b72b52 100644
    Save and load Small OBjects to and from files, using various formats. 
    99Maintainer: Moshe Zadka
    1010"""
    1111
     12from __future__ import division, absolute_import
     13from twisted.python.compat import _PY3
    1214import os, sys
    1315try:
    1416    import cPickle as pickle
    1517except ImportError:
    1618    import pickle
    17 try:
    18     import cStringIO as StringIO
    19 except ImportError:
    20     import StringIO
     19
     20if _PY3:
     21    from io import StringIO
     22else:
     23    try:
     24        import cStringIO as StringIO
     25    except ImportError:
     26        import StringIO
    2127from hashlib import md5
    2228from twisted.python import log, runtime
    2329from twisted.persisted import styles
    24 from zope.interface import implements, Interface
     30from zope.interface import implementer, Interface
    2531
    2632# Note:
    2733# These encrypt/decrypt functions only work for data formats
    class IPersistable(Interface): 
    5864        """
    5965
    6066
     67@implementer(IPersistable)
    6168class Persistent:
    6269
    63     implements(IPersistable)
    64 
    6570    style = "pickle"
    6671
    6772    def __init__(self, original, name):
    def loadValueFromFile(filename, variable, passphrase=None): 
    205210    if passphrase:
    206211        data = fileObj.read()
    207212        data = _decrypt(passphrase, data)
    208         exec data in d, d
     213        exec(data, d, d)
    209214    else:
    210         exec fileObj in d, d
     215        exec(fileObj, d, d)
    211216    value = d[variable]
    212217    return value
    213218
  • twisted/persisted/styles.py

    diff --git twisted/persisted/styles.py twisted/persisted/styles.py
    index e3ca39b..8f39fa8 100644
     
    33# See LICENSE for details.
    44
    55
    6 
    76"""
    87Different styles of persisted objects.
    98"""
    109
     10from __future__ import division, absolute_import
     11from twisted.python.compat import _PY3
    1112# System Imports
    1213import types
    13 import copy_reg
     14
     15
     16if not _PY3:
     17    import copy_reg
     18else:
     19    import copyreg as copy_reg
    1420import copy
    1521import inspect
    1622import sys
    1723
    18 try:
    19     import cStringIO as StringIO
    20 except ImportError:
    21     import StringIO
     24if _PY3:
     25    from io import StringIO
     26else:
     27    try:
     28        from cStringIO import StringIO
     29    except ImportError:
     30        from StringIO import StringIO
    2231
    2332# Twisted Imports
    2433from twisted.python import log
  • twisted/plugin.py

    diff --git twisted/plugin.py twisted/plugin.py
    index a4f8334..544dac4 100644
    Plugin system for Twisted. 
    1010@author: Glyph Lefkowitz
    1111"""
    1212
     13from __future__ import division, absolute_import
    1314import os
    1415import sys
    1516
    def getCache(module): 
    179180        if needsWrite:
    180181            try:
    181182                dropinPath.setContent(pickle.dumps(dropinDotCache))
    182             except OSError, e:
     183            except OSError as e:
    183184                log.msg(
    184185                    format=(
    185186                        "Unable to write to plugin cache %(path)s: error "
  • twisted/python/filepath.py

    diff --git twisted/python/filepath.py twisted/python/filepath.py
    index d3f8b8a..71e038a 100644
    class FilePath(AbstractFilePath): 
    675675        if platform.isWindows() and path.count(b":"):
    676676            # Catch paths like C:blah that don't have a slash
    677677            raise InsecurePath("%r contains a colon." % (path,))
     678
    678679        norm = normpath(path)
    679680        if self.sep in norm:
    680681            raise InsecurePath("%r contains one or more directory separators" % (path,))
  • twisted/python/logfile.py

    diff --git twisted/python/logfile.py twisted/python/logfile.py
    index f652271..bce4b56 100644
     
    77A rotating, browsable log file.
    88"""
    99
     10from __future__ import division, absolute_import
    1011# System Imports
    1112import os, glob, time, stat
    1213
    class BaseLogFile: 
    6667        else:
    6768            if self.defaultMode is not None:
    6869                # Set the lowest permissions
    69                 oldUmask = os.umask(0777)
     70                oldUmask = os.umask(int("777",8))
    7071                try:
    7172                    self._file = file(self.path, "w+", 1)
    7273                finally:
    class LogFile(BaseLogFile): 
    178179        """
    179180        filename = "%s.%d" % (self.path, identifier)
    180181        if not os.path.exists(filename):
    181             raise ValueError, "no such logfile exists"
     182            raise ValueError("no such logfile exists")
    182183        return LogReader(filename)
    183184
    184185    def write(self, data):
    class DailyLogFile(BaseLogFile): 
    266267            return self.getCurrentLog()
    267268        filename = "%s.%s" % (self.path, self.suffix(identifier))
    268269        if not os.path.exists(filename):
    269             raise ValueError, "no such logfile exists"
     270            raise ValueError("no such logfile exists")
    270271        return LogReader(filename)
    271272
    272273    def write(self, data):
  • twisted/python/modules.py

    diff --git twisted/python/modules.py twisted/python/modules.py
    index 11455be..6ec09ed 100644
    the modules outside the standard library's python-files directory:: 
    5353                modinfo.name, modinfo.filePath.path)
    5454"""
    5555
     56from __future__ import division, absolute_import
     57from twisted.python.compat import _PY3
     58
    5659__metaclass__ = type
    5760
    5861# let's try to keep path imports to a minimum...
    import sys 
    6265import zipimport
    6366import inspect
    6467import warnings
    65 from zope.interface import Interface, implements
     68from zope.interface import Interface, implementer
    6669
    6770from twisted.python.components import registerAdapter
    6871from twisted.python.filepath import FilePath, UnlistableError
    class _ModuleIteratorHelper: 
    131134            except UnlistableError:
    132135                continue
    133136
     137            if _PY3:
     138                # Might be not very efficient, but that's the price of sorting
     139                # here.
     140                children = list(children)
     141
    134142            children.sort()
    135143            for potentialTopLevel in children:
    136144                ext = potentialTopLevel.splitext()[1]
    class IPathImportMapper(Interface): 
    476484        L{ZipPath}, but more might be added later).
    477485        """
    478486
     487@implementer(IPathImportMapper)
    479488class _DefaultMapImpl:
    480489    """ Wrapper for the default importer, i.e. None.  """
    481     implements(IPathImportMapper)
    482490    def mapPath(self, fsPathString):
    483491        return FilePath(fsPathString)
    484492_theDefaultMapper = _DefaultMapImpl()
    485493
     494@implementer(IPathImportMapper)
    486495class _ZipMapImpl:
    487496    """ IPathImportMapper implementation for zipimport.ZipImporter.  """
    488     implements(IPathImportMapper)
    489497    def __init__(self, importer):
    490498        self.importer = importer
    491499
  • twisted/python/reflect.py

    diff --git twisted/python/reflect.py twisted/python/reflect.py
    index ac25d47..e8bead0 100644
    Standardized versions of various cool and/or strange things that you can do 
    77with Python's reflection capabilities.
    88"""
    99
     10from __future__ import division, absolute_import
    1011import sys
    1112import types
    1213import pickle
    import re 
    1516import warnings
    1617from collections import deque
    1718
     19from twisted.python.compat import _PY3
    1820RegexType = type(re.compile(""))
    1921
     22if _PY3:
     23    from io import StringIO
     24else:
     25    try:
     26        from cStringIO import StringIO
     27    except ImportError:
     28        from StringIO import StringIO
     29
    2030
    21 try:
    22     from cStringIO import StringIO
    23 except ImportError:
    24     from StringIO import StringIO
    2531
    2632from twisted.python.compat import _PY3
    2733from twisted.python.deprecate import deprecated
    def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None, showUnknowns 
    278284                                   'member_descriptor', 'getset_descriptor')):
    279285        pass
    280286    elif showUnknowns:
    281         print 'unknown type', type(start), start
     287        print('unknown type', type(start), start)
    282288    return paths
    283289
    284290
  • twisted/python/usage.py

    diff --git twisted/python/usage.py twisted/python/usage.py
    index 9280ae2..988f3e4 100644
    U{http://twistedmatrix.com/projects/core/documentation/howto/options.html}, 
    1212or doc/core/howto/options.xhtml in your Twisted directory.
    1313"""
    1414
     15from __future__ import division, absolute_import
     16from twisted.python.compat import _PY3
     17
    1518# System Imports
    1619import os
    1720import sys
    class CoerceParameter(object): 
    5255                             % (parameterName,))
    5356        try:
    5457            value = self.coerce(value)
    55         except ValueError, e:
     58        except ValueError as e:
    5659            raise UsageError("Parameter type enforcement failed: %s" % (e,))
    5760
    5861        self.options.opts[parameterName] = value
    class Options(dict): 
    188191        as dictionary keys.  This is an internal feature used to implement
    189192        the parser.  Do not rely on it in application code.
    190193        """
    191         return int(id(self) % sys.maxint)
     194        if _PY3:
     195            # In Python3 integer has no size limit.
     196            return int(id(self))
     197        else:
     198            return int(id(self) % sys.maxint)
    192199
    193200    def opt_help(self):
    194201        """
    195202        Display this help and exit.
    196203        """
    197         print self.__str__()
     204        print(self.__str__())
    198205        sys.exit(0)
    199206
    200207    def opt_version(self):
    class Options(dict): 
    202209        Display Twisted version and exit.
    203210        """
    204211        from twisted import copyright
    205         print "Twisted version:", copyright.version
     212        print("Twisted version:", copyright.version)
    206213        sys.exit(0)
    207214
    208215    #opt_h = opt_help # this conflicted with existing 'host' options.
    class Options(dict): 
    232239        try:
    233240            opts, args = getopt.getopt(options,
    234241                                       self.shortOpt, self.longOpt)
    235         except getopt.error, e:
     242        except getopt.error as e:
    236243            raise UsageError(str(e))
    237244
    238245        for opt, arg in opts:
    class Options(dict): 
    432439                reverse_dct[method] = []
    433440            reverse_dct[method].append(name.replace('_', '-'))
    434441
    435         cmpLength = lambda a, b: cmp(len(a), len(b))
     442        if _PY3:
     443            def sort_by_length(lst):
     444                """
     445                Sort list elements by their length.
     446                """
     447                # Here we use a key function instead of a compare function.
     448                KeyLength = lambda a:len(a)
     449                lst.sort(key=KeyLength)
     450        else:
     451            def sort_by_length(lst):
     452                # Old fashioned compare function here:
     453                cmpLength = lambda a, b: cmp(len(a), len(b))
     454                lst.sort(cmpLength)
    436455
    437456        for method, names in reverse_dct.items():
    438457            if len(names) < 2:
    439458                continue
    440459            names_ = names[:]
    441             names_.sort(cmpLength)
     460            sort_by_length(names_)
    442461            longest = names_.pop()
    443462            for name in names_:
    444463                synonyms[name] = longest
    def docMakeChunks(optList, width=80): 
    950969
    951970
    952971def flagFunction(method, name=None):
    953     reqArgs = method.im_func.func_code.co_argcount
     972    if _PY3:
     973        reqArgs = method.__func__.__code__.co_argcount
     974    else:
     975        reqArgs = method.im_func.func_code.co_argcount
    954976    if reqArgs > 2:
    955977        raise UsageError('Invalid Option function for %s' %
    956978                         (name or method.func_name))
  • twisted/python/util.py

    diff --git twisted/python/util.py twisted/python/util.py
    index 3b3a699..97e33a1 100644
    __all__ = [ 
    10781078    ]
    10791079
    10801080
    1081 if _PY3:
    1082     __all3__ = ["FancyEqMixin", "setIDFunction", "unsignedID", "untilConcludes",
    1083                 "runWithWarningsSuppressed", "FancyStrMixin", "nameToLabel",
    1084                 "InsensitiveDict"]
    1085     for name in __all__[:]:
    1086         if name not in __all3__:
    1087             __all__.remove(name)
    1088             del globals()[name]
    1089     del name, __all3__
     1081#   if _PY3:
     1082#       __all3__ = ["FancyEqMixin", "setIDFunction", "unsignedID", "untilConcludes",
     1083#                   "runWithWarningsSuppressed", "FancyStrMixin", "nameToLabel",
     1084#                   "InsensitiveDict","spewer"]
     1085#       for name in __all__[:]:
     1086#           if name not in __all3__:
     1087#               __all__.remove(name)
     1088#               del globals()[name]
     1089#       del name, __all3__
  • twisted/python/zippath.py

    diff --git twisted/python/zippath.py twisted/python/zippath.py
    index a82f253..5113e90 100644
    This module contains implementations of IFilePath for zip files. 
    88See the constructor for ZipArchive for use.
    99"""
    1010
     11from __future__ import division, absolute_import
    1112__metaclass__ = type
    1213
    1314import os
    else: 
    2728
    2829from twisted.python.filepath import IFilePath, FilePath, AbstractFilePath
    2930
    30 from zope.interface import implements
     31from zope.interface import implementer
    3132
    3233# using FilePath here exclusively rather than os to make sure that we don't do
    3334# anything OS-path-specific here.
    ZIP_PATH_SEP = '/' # In zipfiles, "/" is universally used as the 
    3637                                # path separator, regardless of platform.
    3738
    3839
     40@implementer(IFilePath)
    3941class ZipPath(AbstractFilePath):
    4042    """
    4143    I represent a file or directory contained within a zip file.
    4244    """
    4345
    44     implements(IFilePath)
    45 
    4646    sep = ZIP_PATH_SEP
    4747
    4848    def __init__(self, archive, pathInArchive):
  • twisted/scripts/trial.py

    diff --git twisted/scripts/trial.py twisted/scripts/trial.py
    index 7cdaa3c..a60d316 100644
     
    44# See LICENSE for details.
    55
    66
    7 from __future__ import print_function
     7from __future__ import print_function,division,absolute_import
    88import gc
    99import inspect
    1010import os
    def run(): 
    599599    config = Options()
    600600    try:
    601601        config.parseOptions()
    602     except usage.error, ue:
    603         raise SystemExit, "%s: %s" % (sys.argv[0], ue)
     602    except usage.error as ue:
     603        raise SystemExit("%s: %s" % (sys.argv[0], ue))
    604604    _initialDebugSetup(config)
    605605
    606606    try:
  • twisted/trial/_asyncrunner.py

    diff --git twisted/trial/_asyncrunner.py twisted/trial/_asyncrunner.py
    index a46d185..0a34a7f 100644
     
    66Infrastructure for test running and suites.
    77"""
    88
     9from __future__ import division, absolute_import
     10
    911import doctest
    1012import gc
    1113
    from twisted.trial._synctest import _logObserver 
    1618
    1719pyunit = __import__('unittest')
    1820
    19 from zope.interface import implements
     21from zope.interface import implementer
    2022
    2123
    2224
    class TestSuite(pyunit.TestSuite): 
    3840
    3941
    4042
     43@implementer(itrial.ITestCase)
    4144class TestDecorator(components.proxyForInterface(itrial.ITestCase,
    4245                                                 "_originalTest")):
    4346    """
    class TestDecorator(components.proxyForInterface(itrial.ITestCase, 
    4750    @type _originalTest: A provider of L{itrial.ITestCase}
    4851    """
    4952
    50     implements(itrial.ITestCase)
    51 
    52 
    5353    def __call__(self, result):
    5454        """
    5555        Run the unit test.
  • twisted/trial/runner.py

    diff --git twisted/trial/runner.py twisted/trial/runner.py
    index 4275c24..7e1834e 100644
    A miscellany of code used to run Trial tests. 
    88Maintainer: Jonathan Lange
    99"""
    1010
     11from __future__ import division, absolute_import
     12
    1113__all__ = [
    1214    'TestSuite',
    1315
    from twisted.trial.reporter import _ExitWrapper, UncleanWarningsReporterWrapper 
    3335# These are imported so that they remain in the public API for t.trial.runner
    3436from twisted.trial.unittest import TestSuite
    3537
    36 from zope.interface import implements
     38from zope.interface import implementer
    3739
    3840pyunit = __import__('unittest')
    3941
    def isTestCase(obj): 
    252254
    253255
    254256
     257@implementer(ITestCase)
    255258class TestHolder(object):
    256259    """
    257260    Placeholder for a L{TestCase} inside a reporter. As far as a L{TestResult}
    258261    is concerned, this looks exactly like a unit test.
    259262    """
    260263
    261     implements(ITestCase)
    262264
    263265    failureException = None
    264266
  • twisted/trial/unittest.py

    diff --git twisted/trial/unittest.py twisted/trial/unittest.py
    index 8f07556..8d33af3 100644
    from twisted.trial._asynctest import TestCase 
    1616
    1717from twisted.python.compat import _PY3
    1818
    19 if not _PY3:
    20     from twisted.trial._asyncrunner import (
    21         TestSuite, TestDecorator, decorate)
    22     from twisted.trial._asyncrunner import (
    23         _ForceGarbageCollectionDecorator, _iterateTests, _clearSuite)
     19# There was some check here, and the following was executed only on versions
     20# lower on Python3. I removed it:
     21from twisted.trial._asyncrunner import (
     22    TestSuite, TestDecorator, decorate)
     23from twisted.trial._asyncrunner import (
     24    _ForceGarbageCollectionDecorator, _iterateTests, _clearSuite)
    2425
    2526# Further obscure the origins of these objects, to reduce surprise (and this is
    2627# what the values were before code got shuffled around between files, but was