From 6ac179a14662f606530ecc46965b52cfc66f6ece Mon Sep 17 00:00:00 2001 From: Timothy Crosley Date: Thu, 3 Sep 2020 20:36:03 -0700 Subject: [PATCH] Fix issue #1454: Endless import sorting for indendent imports with section heading and preceding comment. --- isort/core.py | 15 +++++++++------ tests/unit/test_regressions.py | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/isort/core.py b/isort/core.py index 08adc239c..f3197b99d 100644 --- a/isort/core.py +++ b/isort/core.py @@ -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 @@ -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 @@ -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 @@ -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) diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index 5feaef6fb..752adc343 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -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, + )