Skip to content

Commit cb2bc2e

Browse files
authored
Merge pull request #327 from mtkennerly/bugfix/eol-crlf
Fix #326: Handle CRLF in end-of-file-fixer
2 parents e01bc2c + e694a6c commit cb2bc2e

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

pre_commit_hooks/end_of_file_fixer.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ def fix_file(file_obj):
1515
return 0
1616
last_character = file_obj.read(1)
1717
# last_character will be '' for an empty file
18-
if last_character != b'\n' and last_character != b'':
18+
if last_character not in {b'\n', b'\r'} and last_character != b'':
1919
# Needs this seek for windows, otherwise IOError
2020
file_obj.seek(0, os.SEEK_END)
2121
file_obj.write(b'\n')
2222
return 1
2323

24-
while last_character == b'\n':
24+
while last_character in {b'\n', b'\r'}:
2525
# Deal with the beginning of the file
2626
if file_obj.tell() == 1:
2727
# If we've reached the beginning of the file and it is all
@@ -35,13 +35,16 @@ def fix_file(file_obj):
3535
last_character = file_obj.read(1)
3636

3737
# Our current position is at the end of the file just before any amount of
38-
# newlines. If we read two characters and get two newlines back we know
39-
# there are extraneous newlines at the ned of the file. Then backtrack and
40-
# trim the end off.
41-
if len(file_obj.read(2)) == 2:
42-
file_obj.seek(-1, os.SEEK_CUR)
43-
file_obj.truncate()
44-
return 1
38+
# newlines. If we find extraneous newlines, then backtrack and trim them.
39+
position = file_obj.tell()
40+
remaining = file_obj.read()
41+
for sequence in (b'\n', b'\r\n', b'\r'):
42+
if remaining == sequence:
43+
return 0
44+
elif remaining.startswith(sequence):
45+
file_obj.seek(position + len(sequence))
46+
file_obj.truncate()
47+
return 1
4548

4649
return 0
4750

tests/end_of_file_fixer_test.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
(b'foo', 1, b'foo\n'),
1616
(b'foo\n\n\n', 1, b'foo\n'),
1717
(b'\xe2\x98\x83', 1, b'\xe2\x98\x83\n'),
18+
(b'foo\r\n', 0, b'foo\r\n'),
19+
(b'foo\r\n\r\n\r\n', 1, b'foo\r\n'),
20+
(b'foo\r', 0, b'foo\r'),
21+
(b'foo\r\r\r\r', 1, b'foo\r'),
1822
)
1923

2024

0 commit comments

Comments
 (0)