Commits

Ali Gholami Rudi  committed 4fcfbe5

autoimport: added find_insertion_line

  • Participants
  • Parent commits fbbae12

Comments (0)

Files changed (5)

File docs/done.txt

 ===========
 
 
+- Added rope.contrib.autoimport : January 25, 2008
+
+
 - Added use function refactoring : January 25, 2008
 
 

File rope/contrib/autoimport.py

-from rope.base import exceptions, pynames, resourceobserver, taskhandle
+import re
+
+from rope.base import exceptions, pynames, resourceobserver, taskhandle, ast
 from rope.refactor import importutils
 
 
             self.update_module(modname)
             job_set.finished_job()
 
+    def find_insertion_line(self, code):
+        """Guess at what line the new import should be inserted"""
+        match = re.search(r'^(def|class)\s+', code)
+        if match is not None:
+            code = code[:match.start()]
+        try:
+            pymodule = self.project.pycore.get_string_module(code)
+        except exceptions.ModuleSyntaxError:
+            return 1
+        testmodname = '__rope_testmodule_rope'
+        importinfo = importutils.NormalImport(((testmodname, None),))
+        module_imports = importutils.get_module_imports(
+            self.project.pycore, pymodule)
+        module_imports.add_import(importinfo)
+        offset = module_imports.get_changed_source().index(testmodname)
+        return code[:offset].count('\n') + 1

File rope/refactor/importutils/__init__.py

 from rope.refactor.importutils import module_imports
 from rope.refactor.importutils.importinfo import \
      (NormalImport, FromImport, get_module_name)
+
+
 class ImportTools(object):
 
     def __init__(self, pycore):

File rope/refactor/importutils/module_imports.py

             self.pymodule = pymodule
         self.pycore = pycore
         self.imports = []
+        self.pymodule = pymodule
         self.lines = self.pymodule.lines
 
     def visit_import(self, node, end_line):

File ropetest/contrib/autoimporttest.py

         self.assertEquals(set(['mod1', 'pkg.mod2']),
                           set(self.importer.get_modules('myvar')))
 
+    def test_trivial_insertion_line(self):
+        result = self.importer.find_insertion_line('')
+        self.assertEquals(1, result)
+
+    def test_insertion_line(self):
+        result = self.importer.find_insertion_line('import mod\n')
+        self.assertEquals(2, result)
+
+    def test_insertion_line_with_pydocs(self):
+        result = self.importer.find_insertion_line(
+            '"""docs\n\ndocs"""\nimport mod\n')
+        self.assertEquals(5, result)
+
+    def test_insertion_line_with_multiple_imports(self):
+        result = self.importer.find_insertion_line(
+            'import mod1\n\nimport mod2\n')
+        self.assertEquals(4, result)
+
 
 class AutoImportObservingTest(unittest.TestCase):