Skip to content

Commit

Permalink
Make the diff nicer if there is no ending newline, fixes davidhalter#…
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhalter committed May 13, 2020
1 parent 3104443 commit 381fbed
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
26 changes: 24 additions & 2 deletions jedi/api/refactoring/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,33 @@ def __init__(self, inference_state, from_path, to_path,
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.
Expand Down
14 changes: 14 additions & 0 deletions test/test_api/test_refactoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
''')

0 comments on commit 381fbed

Please sign in to comment.