Commits

Arun Mahapatra committed 088b816

Run 2to3 tool on rtm. Upgrade bootstrap.py, zc.recipe.egg to 2.0.0a1.

  • Participants
  • Parent commits 841b9a0

Comments (0)

Files changed (8)

 eggs
 parts
 src/.*.egg-info
+
+# virtualenv paths
+include
+lib

File bootstrap.py

 use the -c option to specify an alternate configuration file.
 """
 
-import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
+import os, shutil, sys, tempfile, textwrap
+try:
+    import urllib.request as urllib2
+except ImportError:
+    import urllib2
+import subprocess
 from optparse import OptionParser
 
 if sys.platform == 'win32':
 
 # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
 stdout, stderr = subprocess.Popen(
-    [sys.executable, '-Sc',
+    [sys.executable, '-S', '-c',
      'try:\n'
-     '    import ConfigParser\n'
+     '    import pickle\n'
      'except ImportError:\n'
-     '    print 1\n'
+     '    print(1)\n'
      'else:\n'
-     '    print 0\n'],
+     '    print(0)\n'],
     stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
 has_broken_dash_S = bool(int(stdout.strip()))
 
     # We will restart with python -S.
     args = sys.argv[:]
     args[0:0] = [sys.executable, '-S']
-    args = map(quote, args)
+    args = list(map(quote, args))
     os.execv(sys.executable, args)
+
 # Now we are running with -S.  We'll get the clean sys.path, import site
 # because distutils will do it later, and then reset the path and clean
 # out any namespace packages from site-packages that might have been
 clean_path = sys.path[:]
 import site
 sys.path[:] = clean_path
-for k, v in sys.modules.items():
+for k, v in list(sys.modules.items()):
     if k in ('setuptools', 'pkg_resources') or (
         hasattr(v, '__path__') and
         len(v.__path__)==1 and
     if value:
         if '://' not in value: # It doesn't smell like a URL.
             value = 'file://%s' % (
-                urllib.pathname2url(
+                urllib2.pathname2url(
                     os.path.abspath(os.path.expanduser(value))),)
         if opt_str == '--download-base' and not value.endswith('/'):
             # Download base needs a trailing slash to make the world happy.
 parser = OptionParser(usage=usage)
 parser.add_option("-v", "--version", dest="version",
                           help="use a specific zc.buildout version")
+parser.add_option("--setup-version", dest="setup_version",
+                  help="The version of setuptools or distribute to use.")
 parser.add_option("-d", "--distribute",
-                   action="store_true", dest="use_distribute", default=False,
+                   action="store_true", dest="use_distribute",
+                   default= sys.version_info[0] >= 3,
                    help="Use Distribute rather than Setuptools.")
 parser.add_option("--setup-source", action="callback", dest="setup_source",
                   callback=normalize_to_url, nargs=1, type="string",
                         "bootstrap script completes."))
 parser.add_option("-t", "--accept-buildout-test-releases",
                   dest='accept_buildout_test_releases',
-                  action="store_true", default=False,
+                  action="store_true",
+                  default=sys.version_info[0] > 2,
                   help=("Normally, if you do not specify a --version, the "
                         "bootstrap script and buildout gets the newest "
                         "*final* versions of zc.buildout and its recipes and "
         raise ImportError
 except ImportError:
     ez_code = urllib2.urlopen(
-        options.setup_source).read().replace('\r\n', '\n')
+        options.setup_source).read().replace('\r\n'.encode(), '\n'.encode())
     ez = {}
-    exec ez_code in ez
+    exec(ez_code, ez)
     setup_args = dict(to_dir=eggs_dir, download_delay=0)
     if options.download_base:
         setup_args['download_base'] = options.download_base
+    if options.setup_version:
+        setup_args['version'] = options.setup_version
     if options.use_distribute:
         setup_args['no_fake'] = True
     ez['use_setuptools'](**setup_args)
     if 'pkg_resources' in sys.modules:
-        reload(sys.modules['pkg_resources'])
+        if sys.version_info[0] >= 3:
+            import imp
+            reload_ = imp.reload
+        else:
+            reload_ = reload
+
+        reload_(sys.modules['pkg_resources'])
     import pkg_resources
     # This does not (always?) update the default working set.  We will
     # do it.
 if exitcode != 0:
     sys.stdout.flush()
     sys.stderr.flush()
-    print ("An error occurred when trying to install zc.buildout. "
-           "Look above this message for any errors that "
-           "were output by easy_install.")
+    print("An error occurred when trying to install zc.buildout. "
+          "Look above this message for any errors that "
+          "were output by easy_install.")
     sys.exit(exitcode)
 
 ws.add_entry(eggs_dir)

File buildout.cfg

 [buildout]
+newest=false
 parts = pyrtm test
 
 develop = .
 
 [pyrtm]
-recipe = zc.recipe.egg
+recipe = zc.recipe.egg>=2.0.0a1
 eggs = pyrtm
 interpreter = py
 

File src/rtm/__init__.py

 # -*- coding: utf-8 -*-
 
-from rtm import *
-from samples import *
+from .rtm import *
+from .samples import *

File src/rtm/rtm.py

 
 
 import warnings
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import logging
 from hashlib import md5
 
 # rtm constant
-from consts import *
+from .consts import *
 
 try:
     import json
         self.authInfo = AuthStateMachine(['frob', 'token'])
 
         # this enables one to do 'rtm.tasks.getList()', for example
-        for prefix, methods in API.items():
+        for prefix, methods in list(API.items()):
             setattr(self, prefix,
                     RTMAPICategory(self, prefix, methods))
 
             'frob': frob
             }
         params['api_sig'] = self._sign(params)
-        return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
+        return AUTH_SERVICE_URL + '?' + urllib.parse.urlencode(params)
 
     def getToken(self):
         frob = self.authInfo.get('frob')
     >>> list(sortedItems({'a': 1, 1: 55, 'key': 7}))
     [(1, 55), ('a', 1), ('key', 7)]
     """
-    keys = dictionary.keys()
+    keys = list(dictionary.keys())
     keys.sort()
     for key in keys:
         yield key, dictionary[key]
     'http://www.rememberthemilk.com/?query=test'
     """
     if queryArgs:
-        url = url + '?' + urllib.urlencode(queryArgs)
+        url = url + '?' + urllib.parse.urlencode(queryArgs)
     LOG.debug("URL> %s", url)
-    return urllib.urlopen(url)
+    return urllib.request.urlopen(url)
 
 class dottedDict(object):
     """Make dictionary items accessible via the object-dot notation."""
         self._name = name
 
         if type(dictionary) is dict:
-            for key, value in dictionary.items():
+            for key, value in list(dictionary.items()):
                 if type(value) is dict:
                     value = dottedDict(key, value)
                 elif type(value) in (list, tuple) and key != 'tag':
     rtm = RTM(apiKey, secret, token)
 
     if token is None:
-        print 'No token found'
-        print 'Give me access here:', rtm.getAuthURL()
-        raw_input('Press enter once you gave access')
-        print 'Note down this token for future use:', rtm.getToken()
+        print('No token found')
+        print('Give me access here:', rtm.getAuthURL())
+        input('Press enter once you gave access')
+        print('Note down this token for future use:', rtm.getToken())
 
     return rtm
 

File src/rtm/samples/app.py

 
 from rtm import createRTM
 
-from Tkinter import *
+from tkinter import *
 
 def createApp(rtm):
     rspTasks = rtm.tasks.getList(filter='dueWithin:"1 week of today"')
                     tasks.append(t.name)
             else:
                 tasks.append(l.taskseries.name)
-    print tasks
+    print(tasks)
     if not tasks:
         tasks.append('No tasks due within a week')
 
     try:
         api_key, secret = sys.argv[1:3]
     except ValueError:
-        print >>sys.stderr, 'Usage: rtm_appsample APIKEY SECRET [TOKEN]'
+        print('Usage: rtm_appsample APIKEY SECRET [TOKEN]', file=sys.stderr)
     else:
         try:
             token = sys.argv[3]

File src/rtm/tests/test_pep8.py

-# -*- coding: utf-8 -*-
-
-from os.path import (abspath, dirname, isdir)
-import pep8
-
-CURRENT_DIR = dirname(abspath(__file__))
-BASE_DIR = dirname(CURRENT_DIR)
-
-
-def test_pep8():
-    arglist = [
-        "--statistics",
-        "--filename=*.py",
-        "--show-source",
-        "--repeat",
-        "--exclude=SVGdraw.py",
-        "--ignore=E302,E701",
-        #"--show-pep8",
-        #"-qq",
-        #"-v",
-        BASE_DIR,
-    ]
-
-    options, args = pep8.process_options(arglist)
-    runner = pep8.input_file
-
-    for path in args:
-        if isdir(path):
-            pep8.input_dir(path, runner=runner)
-        elif not pep8.excluded(path):
-            options.counters["files"] += 1
-            runner(path)
-
-    pep8.print_statistics()
-    errors = pep8.get_count("E")
-    warnings = pep8.get_count("W")
-    message = "pep8: %d errors / %d warnings" % (errors, warnings)
-    print message
-    assert errors + warnings == 0, message
+# -*- coding: utf-8 -*-
+
+from os.path import (abspath, dirname, isdir)
+import pep8
+
+CURRENT_DIR = dirname(abspath(__file__))
+BASE_DIR = dirname(CURRENT_DIR)
+
+
+def test_pep8():
+    arglist = [
+        "--statistics",
+        "--filename=*.py",
+        "--show-source",
+        "--repeat",
+        "--exclude=SVGdraw.py",
+        "--ignore=E302,E701",
+        #"--show-pep8",
+        #"-qq",
+        #"-v",
+        BASE_DIR,
+    ]
+
+    options, args = pep8.process_options(arglist)
+    runner = pep8.input_file
+
+    for path in args:
+        if isdir(path):
+            pep8.input_dir(path, runner=runner)
+        elif not pep8.excluded(path):
+            options.counters["files"] += 1
+            runner(path)
+
+    pep8.print_statistics()
+    errors = pep8.get_count("E")
+    warnings = pep8.get_count("W")
+    message = "pep8: %d errors / %d warnings" % (errors, warnings)
+    print(message)
+    assert errors + warnings == 0, message

File src/rtm/tests/test_rtm_object.py

 
 import os
 import sys
-from ConfigParser import RawConfigParser
+from configparser import RawConfigParser
 from operator import attrgetter
 from os.path import dirname, join as pathjoin, realpath
 from nose.plugins.skip import SkipTest
             self.secret = c.get('rtm', 'secret')
             self.token = c.get('rtm', 'token')
         except Exception as err:
-            print >> sys.stderr, err
+            print(err, file=sys.stderr)
             raise SkipTest(self.message['cannot_read'])
 
     def assert_stat_ok(self, rsp):
-        assert_equal(u"ok", rsp.stat)
+        assert_equal("ok", rsp.stat)
 
     def assert_response(self, func, elem=None, **params):
         """assert the stat/attr(only top) of response from api"""
-        api, method = func.func_name.replace('test_', '').split('_')
+        api, method = func.__name__.replace('test_', '').split('_')
         elem = elem or api
         api_method = "%s.%s" % (api, method)
         rsp = attrgetter(api_method)(self.rtm)(**params)
         rsp_attr = getattr(rsp, api)
         if not isinstance(rsp_attr, RTM.dottedDict):
             raise SkipTest(self.message['no_item'] % (api, method))
-        attr = RTM.API_RESPONSE[api][method][elem].keys()[0]
+        attr = list(RTM.API_RESPONSE[api][method][elem].keys())[0]
         assert_true(hasattr(rsp_attr, attr))  # has item
 
     def test_auth_checkToken(self):