Gary Oberbrunner avatar Gary Oberbrunner committed daaedb5

Manual python3 post-2to3 fixes from Neal Becker

Comments (0)

Files changed (19)

 
   See the following doctest for example.
 
-  >>> print FormatSubversionPropertyChanges('foo.cc', [('svn:eol-style', 'LF')])
+  >>> print(FormatSubversionPropertyChanges('foo.cc', [('svn:eol-style', 'LF')]))
   Property changes on: foo.cc
   ___________________________________________________________________
   Added: svn:eol-style

src/engine/SCons/Action.py

 
     # The code contents depends on the number of local variables
     # but not their actual names.
-    contents.append("%s,%s" % (code.co_argcount, len(code.co_varnames)))
+    contents.append(str.encode("%s,%s" % (code.co_argcount, len(code.co_varnames))))
     try:
-        contents.append(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars)))
+        contents.append(str.encode(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars))))
     except AttributeError:
         # Older versions of Python do not support closures.
         contents.append(",0,0")
     # Note that we also always ignore the first entry of co_consts
     # which contains the function doc string. We assume that the
     # function does not access its doc string.
-    contents.append(',(' + ','.join(map(_object_contents,code.co_consts[1:])) + ')')
+    contents.append(b',(' + b','.join(map(_object_contents,code.co_consts[1:])) + b')')
 
     # The code contents depends on the variable names used to
     # accessed global variable, as changing the variable name changes
     # the variable actually accessed and therefore changes the
     # function result.
-    contents.append(',(' + ','.join(map(_object_contents,code.co_names)) + ')')
+    contents.append(b',(' + b','.join(map(_object_contents,code.co_names)) + b')')
 
 
     # The code contents depends on its actual code!!!
-    contents.append(',(' + str(remove_set_lineno_codes(code.co_code)) + ')')
+    contents.append(b',(' + remove_set_lineno_codes(code.co_code) + b')')
 
-    return ''.join(contents)
+    return b''.join(contents)
 
 
 def _function_contents(func):
 
     # The function contents depends on the value of defaults arguments
     if func.__defaults__:
-        contents.append(',(' + ','.join(map(_object_contents,func.__defaults__)) + ')')
+        contents.append(b',(' + b','.join(map(_object_contents,func.__defaults__)) + b')')
     else:
-        contents.append(',()')
+        contents.append(b',()')
 
     # The function contents depends on the closure captured cell values.
     try:
         xxx = [_object_contents(x.cell_contents) for x in closure]
     except AttributeError:
         xxx = []
-    contents.append(',(' + ','.join(xxx) + ')')
+    contents.append(b',(' + b','.join(xxx) + b')')
 
-    return ''.join(contents)
+    return b''.join(contents)
 
 
 def _actionAppend(act1, act2):
 
     def get_contents(self, target, source, env):
         result = [ self.get_presig(target, source, env) ]
+        def clean (u):
+            if isinstance (u, bytes):
+                return u
+            elif isinstance (u, str):
+                return bytes (u, 'utf-8')
+        result = [ clean(r) for r in result ]
         # This should never happen, as the Action() factory should wrap
         # the varlist, but just in case an action is created directly,
         # we duplicate this check here.
         vl = self.get_varlist(target, source, env)
         if is_String(vl): vl = (vl,)
         for v in vl:
-            result.append(env.subst('${'+v+'}'))
-        return ''.join(result)
+            result.append(bytes(env.subst('${'+v+'}'), 'utf-8'))
+        return b''.join(result)
 
     def __add__(self, other):
         return _actionAppend(self, other)
 
         Simple concatenation of the signatures of the elements.
         """
-        return "".join([x.get_contents(target, source, env) for x in self.list])
+        return b"".join([x.get_contents(target, source, env) for x in self.list])
 
     def __call__(self, target, source, env, exitstatfunc=_null, presub=_null,
                  show=_null, execute=_null, chdir=_null, executor=None):

src/engine/SCons/Conftest.py

 #
 
 import re
-from types import IntType
 
 #
 # PUBLIC VARIABLES

src/engine/SCons/Errors.py

 
 import SCons.Util
 
-import exceptions
-
 class BuildError(Exception):
     """ Errors occuring while building.
 
             status=2,
             exitstatus=2,
             exc_info=exc_info)
-    elif isinstance(status, exceptions.EnvironmentError):
+    elif isinstance(status, EnvironmentError):
         # If an IOError/OSError happens, raise a BuildError.
         # Report the name of the file or directory that caused the
         # error, which might be different from the target being built

src/engine/SCons/Executor.py

         except KeyError:
             pass
         env = self.get_build_env()
-        result = "".join([action.get_contents(self.get_all_targets(),
+        result = b"".join([action.get_contents(self.get_all_targets(),
                                               self.get_all_sources(),
                                               env)
                           for action in self.get_action_list()])

src/engine/SCons/SConf.py

     """
     def __init__(self, orig):
         self.orig = orig
-        self.s = io.StringIO()
+        try:
+            import StringIO
+            self.s = StringIO.StringIO()
+        except:
+            self.s = io.StringIO()
 
     def write(self, str):
-        if self.orig:
-            self.orig.write(str)
-        self.s.write(str)
-
+        try:
+            if self.orig:
+                self.orig.write(str)
+            self.s.write(str)
+        except:
+            print ('oops')
     def writelines(self, lines):
         for l in lines:
             self.write(l + '\n')

src/engine/SCons/Scanner/__init__.py

 
     def __init__(self, name, suffixes, path_variable, regex, *args, **kw):
 
-        self.cre = re.compile(regex, re.M)
+        self.cre = re.compile(SCons.Util.to_bytes(regex), re.M)
 
         def _scan(node, env, path=(), self=self):
             node = node.rfile()

src/engine/SCons/Script/SConscript.py

                         pass
                     try:
                         try:
-                            exec(_file_, call_stack[-1].globals)
+                            exec(_file_.read(), call_stack[-1].globals)
                         except SConscriptReturn:
                             pass
                     finally:

src/engine/SCons/Script/__init__.py

 ]
 
 for name in GlobalDefaultEnvironmentFunctions + GlobalDefaultBuilders:
-    exec("%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name)))
+    exec ("%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name)))
 del name
 
 # There are a handful of variables that used to live in the

src/engine/SCons/Taskmaster.py

         Raises a pending exception that was recorded while getting a
         Task ready for execution.
         """
-        exc = self.exc_info()[:]
-        try:
-            exc_type, exc_value, exc_traceback = exc
-        except ValueError:
-            exc_type, exc_value = exc
-            exc_traceback = None
-        raise exc_type(exc_value).with_traceback(exc_traceback)
+
+        import six
+        six.reraise(*self.exc_info())
 
 class AlwaysTask(Task):
     def needs_execute(self):

src/engine/SCons/Tool/__init__.py

                     if file:
                         file.close()
             except ImportError as e:
-                if str(e)!="No module named %s"%self.name:
+                if not str(e).startswith ("No module"):
                     raise SCons.Errors.EnvironmentError(e)
                 try:
                     import zipimport
                         file.close()
                     return module
                 except ImportError as e:
-                    if str(e)!="No module named %s"%self.name:
+                    if not str(e).startswith("No module"):
                         raise SCons.Errors.EnvironmentError(e)
                     try:
                         import zipimport

src/engine/SCons/Tool/g++.py

 import SCons.Tool
 import SCons.Util
 
-cplusplus = __import__('c++', globals(), locals(), [])
-
+cplusplus = __import__(__package__+'.c++', globals(), locals(), ['*'])
 compilers = ['g++']
 
 def generate(env):
         #line = pipe.stdout.read().strip()
         #if line:
         #    env['CXXVERSION'] = line
-        line = pipe.stdout.readline()
+        line = SCons.Util.to_str (pipe.stdout.readline())
         match = re.search(r'[0-9]+(\.[0-9]+)+', line)
         if match:
             env['CXXVERSION'] = match.group(0)

src/engine/SCons/Tool/gas.py

 
 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
-as_module = __import__('as', globals(), locals(), [])
+try:
+    as_module = __import__('as', globals(), locals(), [])
+except:
+    as_module = __import__(__package__+'.as', globals(), locals(), ['*'])
 
 assemblers = ['as', 'gas']
 

src/engine/SCons/Tool/gcc.py

         #line = pipe.stdout.read().strip()
         #if line:
         #    env['CCVERSION'] = line
-        line = pipe.stdout.readline()
+        line = SCons.Util.to_str (pipe.stdout.readline())
         match = re.search(r'[0-9]+(\.[0-9]+)+', line)
         if match:
             env['CCVERSION'] = match.group(0)

src/engine/SCons/Tool/link.py

 
 from SCons.Tool.FortranCommon import isfortran
 
-cplusplus = __import__('c++', globals(), locals(), [])
+cplusplus = __import__(__package__+'.c++', globals(), locals(), ['*'])
 
 issued_mixed_link_warning = False
 

src/engine/SCons/Tool/swig.py

                                  stdout = subprocess.PIPE)
     if pipe.wait() != 0: return
 
-    out = pipe.stdout.read()
+    out = SCons.Util.to_str (pipe.stdout.read())
     match = re.search(r'SWIG Version\s+(\S+)$', out, re.MULTILINE)
     if match:
         return match.group(1)

src/engine/SCons/Util.py

 
 # Don't "from types import ..." these because we need to get at the
 # types module later to look for UnicodeType.
-InstanceType    = types.InstanceType
 MethodType      = types.MethodType
 FunctionType    = types.FunctionType
 try: str
         setattr(obj, name, MethodType(function, obj, obj.__class__))
     else:
         # "obj" is a class, so it gets an unbound method.
-        setattr(obj, name, MethodType(function, None, obj))
+        setattr(obj, name, function)
 
 def RenameFunction(function, name):
     """
         md5 = True
         def MD5signature(s):
             m = hashlib.md5()
-            m.update(str(s))
+            m.update(to_bytes(str(s)))
             return m.hexdigest()
 
         def MD5filesignature(fname, chunksize=65536):
                 blck = f.read(chunksize)
                 if not blck:
                     break
-                m.update(str(blck))
+                m.update(to_bytes (str(blck)))
             f.close()
             return m.hexdigest()
             
 
 del __revision__
 
+def to_bytes (s):
+    if bytes is str:
+        return s
+    else:
+        return bytes (s, 'utf-8')
+
+def to_str (s):
+    if bytes is str:
+        return s
+    else:
+        return str (s, 'utf-8')
+
 # Local Variables:
 # tab-width:4
 # indent-tabs-mode:nil

src/engine/SCons/dblite.py

 def corruption_warning(filename):
     print("Warning: Discarding corrupt database:", filename)
 
-try: str
-except NameError:
-    def is_string(s):
-        return isinstance(s, str)
-else:
-    def is_string(s):
-        return type(s) in (str, str)
-
+def is_string(s):
+    return isinstance(s, str)
+def is_bytes(s):
+    return isinstance (s, bytes)
 try:
     str('a')
 except NameError:
     self._check_writable()
     if (not is_string(key)):
       raise TypeError("key `%s' must be a string but is %s" % (key, type(key)))
-    if (not is_string(value)):
-      raise TypeError("value `%s' must be a string but is %s" % (value, type(value)))
+    if (not is_bytes(value)):
+      raise TypeError("value `%s' must be a bytes but is %s" % (value, type(value)))
     self._dict[key] = value
     self._needs_sync = 0o001
 

src/script/scons.py

 # engine modules if they're in either directory.
 
 
-if sys.version_info >= (3,0,0):
-    msg = "scons: *** SCons version %s does not run under Python version %s.\n\
-Python 3 is not yet supported.\n"
-    sys.stderr.write(msg % (__version__, sys.version.split()[0]))
-    sys.exit(1)
+## if sys.version_info >= (3,0,0):
+##     msg = "scons: *** SCons version %s does not run under Python version %s.\n\
+## Python 3 is not yet supported.\n"
+##     sys.stderr.write(msg % (__version__, sys.version.split()[0]))
+##     sys.exit(1)
 
 
 script_dir = sys.path[0]
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.