Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions pre_commit_hooks/end_of_file_fixer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
from collections.abc import Sequence
from typing import IO

LF = b'\n'
CR = b'\r'
CRLF = b'\r\n'


def fix_file(file_obj: IO[bytes]) -> int:
# Test for newline at end of file
Expand All @@ -15,13 +19,20 @@ def fix_file(file_obj: IO[bytes]) -> int:
return 0
last_character = file_obj.read(1)
# last_character will be '' for an empty file
if last_character not in {b'\n', b'\r'} and last_character != b'':
if last_character not in {LF, CR} and last_character != b'':
# Check for consistent CRLF usage
file_obj.seek(0, os.SEEK_SET)
content = file_obj.read()
lf_count = content.count(LF)
crlf_count = content.count(CRLF)
# Use CRLF only if all line endings are CRLF
ending = CRLF if crlf_count > 0 and crlf_count == lf_count else LF
# Needs this seek for windows, otherwise IOError
file_obj.seek(0, os.SEEK_END)
file_obj.write(b'\n')
file_obj.write(ending)
return 1

while last_character in {b'\n', b'\r'}:
while last_character in {LF, CR}:
# Deal with the beginning of the file
if file_obj.tell() == 1:
# If we've reached the beginning of the file and it is all
Expand All @@ -38,7 +49,7 @@ def fix_file(file_obj: IO[bytes]) -> int:
# 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', b'\r'):
for sequence in (LF, CRLF, CR):
if remaining == sequence:
return 0
elif remaining.startswith(sequence):
Expand Down
2 changes: 2 additions & 0 deletions tests/end_of_file_fixer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
(b'foo\n\n\n', 1, b'foo\n'),
(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\nbar\r\nbaz', 1, b'foo\nbar\r\nbaz\n'),
(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'),
Expand Down