From 04de4f8042e6cf7cf81e8b060aeda7f2f04c48ec Mon Sep 17 00:00:00 2001 From: Edoardo Bezzeccheri Date: Wed, 7 May 2025 16:05:09 +0000 Subject: [PATCH] Using first line to determine EOL --- pre_commit_hooks/end_of_file_fixer.py | 11 ++++++++--- tests/end_of_file_fixer_test.py | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/pre_commit_hooks/end_of_file_fixer.py b/pre_commit_hooks/end_of_file_fixer.py index 2f397eb..0a72976 100644 --- a/pre_commit_hooks/end_of_file_fixer.py +++ b/pre_commit_hooks/end_of_file_fixer.py @@ -20,10 +20,15 @@ def fix_file(file_obj: IO[bytes]) -> int: last_character = file_obj.read(1) # last_character will be '' for an empty file if last_character not in {LF, CR} and last_character != b'': - # Check if file uses CRLF endings + # Look at first line to determine line ending file_obj.seek(0, os.SEEK_SET) - content = file_obj.read() - ending = CRLF if CRLF in content else LF + first_line = file_obj.readline() + if CRLF in first_line: + ending = CRLF + elif CR in first_line: + ending = CR + else: + ending = LF # Needs this seek for windows, otherwise IOError file_obj.seek(0, os.SEEK_END) file_obj.write(ending) diff --git a/tests/end_of_file_fixer_test.py b/tests/end_of_file_fixer_test.py index 05fdade..99f40b7 100644 --- a/tests/end_of_file_fixer_test.py +++ b/tests/end_of_file_fixer_test.py @@ -19,6 +19,7 @@ TESTS = ( (b'\xe2\x98\x83', 1, b'\xe2\x98\x83\n'), (b'foo\r\n', 0, b'foo\r\n'), (b'foo\r\nbar', 1, b'foo\r\nbar\r\n'), + (b'foo\rbar', 1, b'foo\rbar\r'), (b'foo\r\n\r\n\r\n', 1, b'foo\r\n'), (b'foo\r', 0, b'foo\r'), (b'foo\r\r\r\r', 1, b'foo\r'),