diff options
author | Timothy Edmund Crosley <timothy.crosley@gmail.com> | 2020-08-22 01:12:58 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-08-22 01:12:58 -0700 |
commit | f960ee88fe25a3f89ebcf990234138c1bff9b082 (patch) | |
tree | 8d65f3741bed88bde6159b8fb9d9117d4b265c5f | |
parent | 8bd4d3f9ae73f3a79fb63cc4baa63123fa739ff5 (diff) | |
parent | 681fdd37c3fb8aa11481f77652c9aaee248dbbdb (diff) | |
download | isort-f960ee88fe25a3f89ebcf990234138c1bff9b082.tar.gz |
Merge pull request #1390 from sztamas/issue/1389/ensure_new_line_before_comments-bug
Issue/1389/ensure new line before comments bug
-rw-r--r-- | isort/output.py | 24 | ||||
-rw-r--r-- | tests/test_isort.py | 1 |
2 files changed, 17 insertions, 8 deletions
diff --git a/isort/output.py b/isort/output.py index 2a918323..5732ae53 100644 --- a/isort/output.py +++ b/isort/output.py @@ -139,12 +139,6 @@ def sorted_imports( for line in new_section_output: comments = getattr(line, "comments", ()) if comments: - if ( - config.ensure_newline_before_comments - and section_output - and section_output[-1] - ): - section_output.append("") section_output.extend(comments) section_output.append(str(line)) @@ -173,6 +167,9 @@ def sorted_imports( else: pending_lines_before = pending_lines_before or not no_lines_before + if config.ensure_newline_before_comments: + output = _ensure_newline_before_comment(output) + while output and output[-1].strip() == "": output.pop() # pragma: no cover while output and output[0].strip() == "": @@ -297,8 +294,6 @@ def _with_from_imports( comments = parsed.categorized_comments["from"].pop(module, ()) above_comments = parsed.categorized_comments["above"]["from"].pop(module, None) if above_comments: - if new_section_output and config.ensure_newline_before_comments: - new_section_output.append("") new_section_output.extend(above_comments) if "*" in from_imports and config.combine_star: @@ -551,3 +546,16 @@ class _LineWithComments(str): instance = super().__new__(cls, value) # type: ignore instance.comments = comments return instance + + +def _ensure_newline_before_comment(output): + new_output: List[str] = [] + + def is_comment(line): + return line and line.startswith("#") + + for line, prev_line in zip(output, [None] + output): + if is_comment(line) and prev_line != "" and not is_comment(prev_line): + new_output.append("") + new_output.append(line) + return new_output diff --git a/tests/test_isort.py b/tests/test_isort.py index 36260d07..bcbc0f3a 100644 --- a/tests/test_isort.py +++ b/tests/test_isort.py @@ -3816,6 +3816,7 @@ def test_isort_keeps_comments_issue_691() -> None: def test_isort_ensures_blank_line_between_import_and_comment() -> None: config = { "ensure_newline_before_comments": True, + "lines_between_sections": 0, "known_one": ["one"], "known_two": ["two"], "known_three": ["three"], |