Skip to content

Commit 203735e

Browse files
committed
Edge case with mixed endings
Added case for which the file has mixed line endings. In this case, default into using LF for end of file line.
1 parent c881808 commit 203735e

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

pre_commit_hooks/end_of_file_fixer.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,13 @@ def fix_file(file_obj: IO[bytes]) -> int:
2020
last_character = file_obj.read(1)
2121
# last_character will be '' for an empty file
2222
if last_character not in {LF, CR} and last_character != b'':
23-
# Check if file uses CRLF endings
23+
# Check for consistent CRLF usage
2424
file_obj.seek(0, os.SEEK_SET)
2525
content = file_obj.read()
26-
ending = CRLF if CRLF in content else LF
26+
lf_count = content.count(LF)
27+
crlf_count = content.count(CRLF)
28+
# Use CRLF only if all line endings are CRLF
29+
ending = CRLF if crlf_count > 0 and crlf_count == lf_count else LF
2730
# Needs this seek for windows, otherwise IOError
2831
file_obj.seek(0, os.SEEK_END)
2932
file_obj.write(ending)

tests/end_of_file_fixer_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
(b'\xe2\x98\x83', 1, b'\xe2\x98\x83\n'),
2020
(b'foo\r\n', 0, b'foo\r\n'),
2121
(b'foo\r\nbar', 1, b'foo\r\nbar\r\n'),
22+
(b'foo\nbar\r\nbaz', 1, b'foo\nbar\r\nbaz\n'),
2223
(b'foo\r\n\r\n\r\n', 1, b'foo\r\n'),
2324
(b'foo\r', 0, b'foo\r'),
2425
(b'foo\r\r\r\r', 1, b'foo\r'),

0 commit comments

Comments
 (0)