Skip to content

Commit

Permalink
Merge pull request #263 from asottile/first-line-ending
Browse files Browse the repository at this point in the history
use first line ending rather than most common
  • Loading branch information
asottile authored Jul 3, 2022
2 parents e955998 + ee3bd13 commit 1557a71
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
19 changes: 9 additions & 10 deletions reorder_python_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,15 +371,14 @@ def apply_import_sorting(
return pre_import_code + new_imports + rest


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


def fix_file_contents(
Expand All @@ -391,7 +390,7 @@ def fix_file_contents(
settings: Settings = Settings(),
) -> str:
# internally use `'\n` as the newline and normalize at the very end
nl = _most_common_line_ending(contents)
nl = _first_line_ending(contents)
contents = contents.replace('\r\n', '\n').replace('\r', '\n').rstrip()
if contents:
contents += '\n'
Expand Down
21 changes: 21 additions & 0 deletions tests/reorder_python_imports_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,27 @@ def test_fix_cr():
assert ret == s


def test_fix_mixed_uses_first_newline():
s = (
'"""foo"""\n'
'import os\r\n'
'import sys\r\n'
'x = 1\r\n'
)
ret = fix_file_contents(
s,
to_add=(),
to_remove=set(),
to_replace=Replacements.make([]),
)
assert ret == (
'"""foo"""\n'
'import os\n'
'import sys\n'
'x = 1\n'
)


@pytest.mark.parametrize(
('opt', 'expected'),
(
Expand Down

0 comments on commit 1557a71

Please sign in to comment.