Skip to content

Commit d123abe

Browse files
committed
simplify add_imports by handling blank-only files earlier
1 parent f962c00 commit d123abe

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

reorder_python_imports.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -153,17 +153,9 @@ def _inner() -> Generator[CodePartition, None, None]:
153153

154154

155155
def add_imports(
156-
partitions: Iterable[CodePartition],
156+
partitions: list[CodePartition],
157157
to_add: tuple[str, ...] = (),
158158
) -> list[CodePartition]:
159-
partitions = list(partitions)
160-
if not _partitions_to_src(partitions).strip():
161-
return partitions
162-
163-
# If we don't have a trailing newline, this refactor is wrong
164-
if not partitions[-1].src.endswith('\n'):
165-
partitions[-1] = partitions[-1]._replace(src=partitions[-1].src + '\n')
166-
167159
return partitions + [
168160
CodePartition(CodeType.IMPORT, imp_statement.strip() + '\n')
169161
for imp_statement in to_add
@@ -400,7 +392,11 @@ def fix_file_contents(
400392
) -> str:
401393
# internally use `'\n` as the newline and normalize at the very end
402394
nl = _most_common_line_ending(contents)
403-
contents = contents.replace('\r\n', '\n').replace('\r', '\n')
395+
contents = contents.replace('\r\n', '\n').replace('\r', '\n').rstrip()
396+
if contents:
397+
contents += '\n'
398+
else:
399+
return ''
404400

405401
partitioned = partition_source(contents)
406402
partitioned = combine_trailing_code_chunks(partitioned)

tests/reorder_python_imports_test.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,15 @@ def test_add_import_trivial():
346346
) == ''
347347

348348

349+
def test_add_imports_empty_file():
350+
assert fix_file_contents(
351+
'\n\n',
352+
to_add=('from __future__ import absolute_import',),
353+
to_remove=set(),
354+
to_replace=Replacements.make([]),
355+
) == ''
356+
357+
349358
def test_add_import_import_already_there():
350359
assert fix_file_contents(
351360
'from __future__ import absolute_import\n',

0 commit comments

Comments
 (0)