diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index c16f5628c..61948871d 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -97,13 +97,19 @@ def _get_location(self, stmt): def _remove_imports(self, imports): lines = self.pymodule.source_code.splitlines(True) after_removing = [] + first_import_line = self._first_import_line() last_index = 0 for stmt in imports: start, end = stmt.get_old_location() - after_removing.extend(lines[last_index:start - 1]) + blank_lines = 0 + if start != first_import_line: + for lineno in range(start - 2, last_index - 1, -1): + if lines[lineno].strip() == '': + blank_lines += 1 + else: + break + after_removing.extend(lines[last_index:start - 1 - blank_lines]) last_index = end - 1 - for i in range(start, end): - after_removing.append('') after_removing.extend(lines[last_index:]) return after_removing diff --git a/ropetest/refactor/importutilstest.py b/ropetest/refactor/importutilstest.py index 73f52b822..a6e6651a7 100644 --- a/ropetest/refactor/importutilstest.py +++ b/ropetest/refactor/importutilstest.py @@ -865,6 +865,17 @@ def test_sorting_imports_moving_to_top_and_module_docs2(self): 'import mod\n\n\ndef f():\n print(mod)\n', self.import_tools.sort_imports(pymod)) + def test_get_changed_source_preserves_blank_lines(self): + self.mod.write( + '__author__ = "author"\n\nimport aaa\n\nimport bbb\n\n' + 'def f():\n print(mod)\n') + pymod = self.project.get_module('mod') + module_with_imports = self.import_tools.module_imports(pymod) + self.assertEquals( + 'import aaa\n\nimport bbb\n\n__author__ = "author"\n\n' + 'def f():\n print(mod)\n', + module_with_imports.get_changed_source()) + def test_sorting_future_imports(self): self.mod.write('import os\nfrom __future__ import devision\n') pymod = self.project.get_module('mod')