Skip to content

Commit

Permalink
Merge pull request #1458 from PyCQA/issue/1454/fix-endless-import-sor…
Browse files Browse the repository at this point in the history
…ting

Fix issue #1454: Endless import sorting for indendent imports with se…
  • Loading branch information
timothycrosley authored Sep 4, 2020
2 parents 95f32e4 + 6ac179a commit 5d984fc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
15 changes: 9 additions & 6 deletions isort/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ def process(
contains_imports: bool = False
in_top_comment: bool = False
first_import_section: bool = True
section_comments = [f"# {heading}" for heading in config.import_headings.values()]
indent: str = ""
isort_off: bool = False
code_sorting: Union[bool, str] = False
Expand Down Expand Up @@ -146,11 +145,11 @@ def process(
if (
(index == 0 or (index in (1, 2) and not contains_imports))
and stripped_line.startswith("#")
and stripped_line not in section_comments
and stripped_line not in config.section_comments
):
in_top_comment = True
elif in_top_comment:
if not line.startswith("#") or stripped_line in section_comments:
if not line.startswith("#") or stripped_line in config.section_comments:
in_top_comment = False
first_comment_index_end = index - 1

Expand Down Expand Up @@ -210,8 +209,13 @@ def process(
else:
code_sorting_section += line
line = ""
elif stripped_line in config.section_comments and not import_section:
import_section += line
elif stripped_line in config.section_comments:
if import_section and not contains_imports:
output_stream.write(import_section)
import_section = line
not_imports = False
else:
import_section += line
indent = line[: -len(line.lstrip())]
elif not (stripped_line or contains_imports):
not_imports = True
Expand Down Expand Up @@ -337,7 +341,6 @@ def process(
line_separator=line_separator,
ignore_whitespace=config.ignore_whitespace,
)

output_stream.write(sorted_import_section)
if not line and not indent and next_import_section:
output_stream.write(line_separator)
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,3 +926,26 @@ def test_empty_float_to_top_shouldnt_error_issue_1453():
""",
show_diff=True,
)


def test_import_sorting_shouldnt_be_endless_with_headers_issue_1454():
"""isort should never enter an endless sorting loop.
See: https://github.com/PyCQA/isort/issues/1454
"""
assert isort.check_code(
"""
# standard library imports
import sys
try:
# Comment about local lib
# related third party imports
from local_lib import stuff
except ImportError as e:
pass
""",
known_third_party=["local_lib"],
import_heading_thirdparty="related third party imports",
show_diff=True,
)

0 comments on commit 5d984fc

Please sign in to comment.