From 2ab5832ce1914a85155c334c56a6946881e9dfac Mon Sep 17 00:00:00 2001 From: mtkennerly Date: Sat, 13 Oct 2018 19:00:22 -0400 Subject: [PATCH] Preserve CRLF if file already ends that way --- pre_commit_hooks/end_of_file_fixer.py | 16 ++++++++-------- tests/end_of_file_fixer_test.py | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pre_commit_hooks/end_of_file_fixer.py b/pre_commit_hooks/end_of_file_fixer.py index 9b94ab3..37ebbb5 100644 --- a/pre_commit_hooks/end_of_file_fixer.py +++ b/pre_commit_hooks/end_of_file_fixer.py @@ -35,14 +35,14 @@ def fix_file(file_obj): last_character = file_obj.read(1) # Our current position is at the end of the file just before any amount of - # newlines. If we read two characters and get two newlines back we know - # there are extraneous newlines at the ned of the file. Then backtrack and - # trim the end off. - if len(file_obj.read(2)) == 2: - file_obj.seek(-2, os.SEEK_CUR) - file_obj.truncate() - file_obj.write(b'\n') - return 1 + # newlines. If we find extraneous newlines, then backtrack and trim them. + position = file_obj.tell() + remaining = file_obj.read() + for sequence in [b'\n', b'\r\n']: + if remaining.startswith(sequence) and len(remaining) > len(sequence): + file_obj.seek(position + len(sequence)) + file_obj.truncate() + return 1 return 0 diff --git a/tests/end_of_file_fixer_test.py b/tests/end_of_file_fixer_test.py index 0766636..deedeab 100644 --- a/tests/end_of_file_fixer_test.py +++ b/tests/end_of_file_fixer_test.py @@ -15,8 +15,8 @@ TESTS = ( (b'foo', 1, b'foo\n'), (b'foo\n\n\n', 1, b'foo\n'), (b'\xe2\x98\x83', 1, b'\xe2\x98\x83\n'), - (b'foo\r\n', 1, b'foo\n'), - (b'foo\r\n\r\n', 1, b'foo\n'), + (b'foo\r\n', 0, b'foo\r\n'), + (b'foo\r\n\r\n\r\n', 1, b'foo\r\n'), )