From 381fbeda6acbf9669c041807cda7b15e2feb17e5 Mon Sep 17 00:00:00 2001 From: Dave Halter Date: Thu, 14 May 2020 00:18:16 +0200 Subject: [PATCH] Make the diff nicer if there is no ending newline, fixes #1581 --- jedi/api/refactoring/__init__.py | 26 ++++++++++++++++++++++++-- test/test_api/test_refactoring.py | 14 ++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/jedi/api/refactoring/__init__.py b/jedi/api/refactoring/__init__.py index 44052cbb..61f6763c 100644 --- a/jedi/api/refactoring/__init__.py +++ b/jedi/api/refactoring/__init__.py @@ -25,11 +25,33 @@ class ChangedFile(object): def get_diff(self): old_lines = split_lines(self._module_node.get_code(), keepends=True) new_lines = split_lines(self.get_new_code(), keepends=True) + + # Add a newline at the end if it's missing. Otherwise the diff will be + # very weird. A `diff -u file1 file2` would show the string: + # + # \ No newline at end of file + # + # This is not necessary IMO, because Jedi does not really play with + # newlines and the ending newline does not really matter in Python + # files. ~dave + if old_lines[-1] != '': + old_lines[-1] += '\n' + if new_lines[-1] != '': + new_lines[-1] += '\n' + project_path = self._inference_state.project._path + if self._from_path is None: + from_p = '' + else: + from_p = relpath(self._from_path, project_path) + if self._to_path is None: + to_p = '' + else: + to_p = relpath(self._to_path, project_path) diff = difflib.unified_diff( old_lines, new_lines, - fromfile=relpath(self._from_path, project_path), - tofile=relpath(self._to_path, project_path), + fromfile=from_p, + tofile=to_p, ) # Apparently there's a space at the end of the diff - for whatever # reason. diff --git a/test/test_api/test_refactoring.py b/test/test_api/test_refactoring.py index a40acd13..bf03d879 100644 --- a/test/test_api/test_refactoring.py +++ b/test/test_api/test_refactoring.py @@ -62,3 +62,17 @@ def test_rename_none_path(Script): with pytest.raises(jedi.RefactoringError, match='on a Script with path=None'): refactoring.apply() assert refactoring + + +def test_diff_without_ending_newline(Script): + refactoring = Script('a = 1\nb\na').rename(1, 0, new_name='c') + assert refactoring.get_diff() == dedent('''\ + --- + +++ + @@ -1,3 +1,3 @@ + -a = 1 + +c = 1 + b + -a + +c + ''')