Skip to content

Commit 1557a71

Browse files
authored
Merge pull request #263 from asottile/first-line-ending
use first line ending rather than most common
2 parents e955998 + ee3bd13 commit 1557a71

2 files changed

Lines changed: 30 additions & 10 deletions

File tree

reorder_python_imports.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -371,15 +371,14 @@ def apply_import_sorting(
371371
return pre_import_code + new_imports + rest
372372

373373

374-
def _most_common_line_ending(s: str) -> str:
375-
# initialize in case there's no line endings at all
376-
counts = collections.Counter({'\n': 0})
377-
for line in s.splitlines(True):
378-
for ending in ('\r\n', '\r', '\n'):
379-
if line.endswith(ending):
380-
counts[ending] += 1
381-
break
382-
return counts.most_common(1)[0][0]
374+
def _first_line_ending(s: str) -> str:
375+
sio = io.StringIO(s, newline='')
376+
line = sio.readline()
377+
for nl in ('\r\n', '\r'):
378+
if line.endswith(nl):
379+
return nl
380+
else:
381+
return '\n'
383382

384383

385384
def fix_file_contents(
@@ -391,7 +390,7 @@ def fix_file_contents(
391390
settings: Settings = Settings(),
392391
) -> str:
393392
# internally use `'\n` as the newline and normalize at the very end
394-
nl = _most_common_line_ending(contents)
393+
nl = _first_line_ending(contents)
395394
contents = contents.replace('\r\n', '\n').replace('\r', '\n').rstrip()
396395
if contents:
397396
contents += '\n'

tests/reorder_python_imports_test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,27 @@ def test_fix_cr():
829829
assert ret == s
830830

831831

832+
def test_fix_mixed_uses_first_newline():
833+
s = (
834+
'"""foo"""\n'
835+
'import os\r\n'
836+
'import sys\r\n'
837+
'x = 1\r\n'
838+
)
839+
ret = fix_file_contents(
840+
s,
841+
to_add=(),
842+
to_remove=set(),
843+
to_replace=Replacements.make([]),
844+
)
845+
assert ret == (
846+
'"""foo"""\n'
847+
'import os\n'
848+
'import sys\n'
849+
'x = 1\n'
850+
)
851+
852+
832853
@pytest.mark.parametrize(
833854
('opt', 'expected'),
834855
(

0 commit comments

Comments
 (0)