Permalink
Browse files

Check in initial version of auto2to3.py.

  • Loading branch information...
0 parents commit d2e4306f3ede62ed7b5dfd3f67f35b0d8cc6b218 @bdarnell committed Feb 23, 2011
Showing with 66 additions and 0 deletions.
  1. +66 −0 auto2to3.py
@@ -0,0 +1,66 @@
+#
+# Import hook to run 2to3 transparently over imported files.
+# Only works with files that have 'python2' in the first or second line.
+#
+
+import os
+import sys
+import imp
+import runpy
+from io import StringIO
+from pkgutil import ImpImporter, ImpLoader
+import tempfile
+
+import lib2to3
+from lib2to3.refactor import RefactoringTool
+
+sys.path.append(os.path.dirname(lib2to3.__file__))
+
+class DummyOptions:
+ fix = []
+ def __getattr__(self, name):
+ return None
+
+opt = DummyOptions()
+
+rt = RefactoringTool(opt)
+
+
+class ToThreeImporter(ImpImporter):
+ def find_module(self, fullname, path=None):
+ # this duplicates most of ImpImporter.find_module
+ subname = fullname.split(".")[-1]
+ if subname != fullname and self.path is None:
+ return None
+ if self.path is None:
+ path = None
+ else:
+ path = [os.path.realpath(self.path)]
+ try:
+ file, filename, etc = imp.find_module(subname, path)
+ except ImportError:
+ return None
+ if file and etc[2] == imp.PY_SOURCE:
+ filename = '<%r converted by 2to3>' % filename
+ line1 = file.readline()
+ line2 = file.readline()
+ file.seek(0)
+ if 'python2' in line1 or 'python2' in line2:
+ try:
+ tree = rt.driver.parse_stream(file)
+ except Exception as err:
+ raise ImportError("2to3 couldn't convert %r" % filename)
+ finally:
+ file.close()
+ if rt.refactor_tree(tree, filename):
+ file = tempfile.TemporaryFile()
+ file.write(str(tree).encode('utf8'))
+ file.seek(0)
+ return ImpLoader(fullname, file, filename, etc)
+
+
+# setup the hook
+sys.path_hooks.append(ToThreeImporter)
+for key in sys.path_importer_cache:
+ if sys.path_importer_cache[key] is None:
+ sys.path_importer_cache[key] = ToThreeImporter(key)

0 comments on commit d2e4306

Please sign in to comment.