Commits

Anonymous committed ad09dc9

autoimport: added AutoImport.get_name_locations()

  • Participants
  • Parent commits 98eae55

Comments (0)

Files changed (2)

File rope/contrib/autoimport.py

                 result.append(module)
         return result
 
+    def get_name_locations(self, name):
+        """Return a list of ``(resource, lineno)`` tuples"""
+        result = []
+        pycore = self.project.pycore
+        for module in self.names:
+            if name in self.names[module]:
+                try:
+                    pymodule = pycore.get_module(module)
+                    if name in pymodule:
+                        pyname = pymodule[name]
+                        module, lineno = pyname.get_definition_location()
+                        if module is not None:
+                            resource = module.get_module().get_resource()
+                            if resource is not None and lineno is not None:
+                                result.append((resource, lineno))
+                except exceptions.ModuleNotFoundError:
+                    pass
+        return result
+
     def generate_cache(self, resources=None, underlined=False,
                        task_handle=taskhandle.NullTaskHandle()):
         """Generate global name cache for project files

File ropetest/contrib/autoimporttest.py

         self.importer.update_resource(self.mod1, underlined=True)
         self.assertEquals(['mod1'], self.importer.get_modules('_myvar'))
 
+    def test_name_locations(self):
+        self.mod1.write('myvar = None\n')
+        self.importer.update_resource(self.mod1)
+        self.assertEquals([(self.mod1, 1)],
+                          self.importer.get_name_locations('myvar'))
+
+    def test_name_locations_with_multiple_occurrences(self):
+        self.mod1.write('myvar = None\n')
+        self.mod2.write('\nmyvar = None\n')
+        self.importer.update_resource(self.mod1)
+        self.importer.update_resource(self.mod2)
+        self.assertEquals(set([(self.mod1, 1), (self.mod2, 2)]),
+                          set(self.importer.get_name_locations('myvar')))
+
 
 class AutoImportObservingTest(unittest.TestCase):