Skip to content

Commit 2ab5832

Browse files
committed
Preserve CRLF if file already ends that way
1 parent abd3d0e commit 2ab5832

File tree

2 files changed

+10
-10
lines changed

2 files changed

+10
-10
lines changed

pre_commit_hooks/end_of_file_fixer.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,14 @@ 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(-2, os.SEEK_CUR)
43-
file_obj.truncate()
44-
file_obj.write(b'\n')
45-
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']:
42+
if remaining.startswith(sequence) and len(remaining) > len(sequence):
43+
file_obj.seek(position + len(sequence))
44+
file_obj.truncate()
45+
return 1
4646

4747
return 0
4848

tests/end_of_file_fixer_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
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', 1, b'foo\n'),
19-
(b'foo\r\n\r\n', 1, b'foo\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'),
2020
)
2121

2222

0 commit comments

Comments
 (0)