Skip to content

Commit 24c5f07

Browse files
authored
Merge pull request #386 from pre-commit/line_endings_string_fixer
Fix crlf line endings for double-quote-string-fixer
2 parents e8e54f7 + 711b730 commit 24c5f07

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

pre_commit_hooks/string_fixer.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,13 @@ def handle_match(token_text): # type: (str) -> str
3131
def get_line_offsets_by_line_no(src): # type: (str) -> List[int]
3232
# Padded so we can index with line number
3333
offsets = [-1, 0]
34-
for line in src.splitlines():
35-
offsets.append(offsets[-1] + len(line) + 1)
34+
for line in src.splitlines(True):
35+
offsets.append(offsets[-1] + len(line))
3636
return offsets
3737

3838

3939
def fix_strings(filename): # type: (str) -> int
40-
with io.open(filename, encoding='UTF-8') as f:
40+
with io.open(filename, encoding='UTF-8', newline='') as f:
4141
contents = f.read()
4242
line_offsets = get_line_offsets_by_line_no(contents)
4343

@@ -58,8 +58,8 @@ def fix_strings(filename): # type: (str) -> int
5858

5959
new_contents = ''.join(splitcontents)
6060
if contents != new_contents:
61-
with io.open(filename, 'w', encoding='UTF-8') as write_handle:
62-
write_handle.write(new_contents)
61+
with io.open(filename, 'w', encoding='UTF-8', newline='') as f:
62+
f.write(new_contents)
6363
return 1
6464
else:
6565
return 0

tests/string_fixer_test.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,15 @@
4444

4545
@pytest.mark.parametrize(('input_s', 'output', 'expected_retval'), TESTS)
4646
def test_rewrite(input_s, output, expected_retval, tmpdir):
47-
path = tmpdir.join('file.txt')
47+
path = tmpdir.join('file.py')
4848
path.write(input_s)
4949
retval = main([path.strpath])
5050
assert path.read() == output
5151
assert retval == expected_retval
52+
53+
54+
def test_rewrite_crlf(tmpdir):
55+
f = tmpdir.join('f.py')
56+
f.write_binary(b'"foo"\r\n"bar"\r\n')
57+
assert main((f.strpath,))
58+
assert f.read_binary() == b"'foo'\r\n'bar'\r\n"

0 commit comments

Comments
 (0)