From 043261fb6bb1c3a16ebc760e9c89207d58f2d378 Mon Sep 17 00:00:00 2001 From: Rouven Bauer Date: Sun, 21 Aug 2022 21:27:15 +0200 Subject: [PATCH] Fix `lines_before_import` sometimes being ignored The config option `lines_before_import` was ignored if the file only contained imports + optionally a leading comment. --- isort/core.py | 2 +- isort/output.py | 13 +++++++------ tests/unit/test_isort.py | 12 ++++++------ 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/isort/core.py b/isort/core.py index bff28458..708a1c01 100644 --- a/isort/core.py +++ b/isort/core.py @@ -363,7 +363,7 @@ def process( if not_imports: if not was_in_quote and config.lines_before_imports > -1: - if line.strip() == "": + if line.strip() == "" and not end_of_file: lines_before += line continue if not import_section: diff --git a/isort/output.py b/isort/output.py index 3dbcdc48..2b1266a9 100644 --- a/isort/output.py +++ b/isort/output.py @@ -183,6 +183,13 @@ def sorted_imports( ] == [""]: formatted_output.pop(imports_tail) + if config.lines_before_imports != -1: + lines_before_imports = config.lines_before_imports + if config.profile == "black" and extension == "pyi": # special case for black + lines_before_imports = 1 + formatted_output[:0] = ["" for line in range(lines_before_imports)] + imports_tail += lines_before_imports + if len(formatted_output) > imports_tail: next_construct = "" tail = formatted_output[imports_tail:] @@ -218,12 +225,6 @@ def sorted_imports( else: formatted_output[imports_tail:0] = [""] - if config.lines_before_imports != -1: - lines_before_imports = config.lines_before_imports - if config.profile == "black" and extension == "pyi": # special case for black - lines_before_imports = 1 - formatted_output[:0] = ["" for line in range(lines_before_imports)] - if parsed.place_imports: new_out_lines = [] for index, line in enumerate(formatted_output): diff --git a/tests/unit/test_isort.py b/tests/unit/test_isort.py index 199d565f..15c50283 100644 --- a/tests/unit/test_isort.py +++ b/tests/unit/test_isort.py @@ -1715,12 +1715,12 @@ def test_order_by_type() -> None: ) -def test_custom_lines_before_import_section() -> None: - """Test the case where the number of lines to output after imports has been explicitly set.""" - test_input = """from a import b - -foo = 'bar' -""" +@pytest.mark.parametrize("has_body", [True, False]) +def test_custom_lines_before_import_section(has_body: bool) -> None: + """Test the case where the number of lines to output before imports has been explicitly set.""" + test_input = "from a import b\n" + if has_body: + test_input += "\nfoo = 'bar'\n" ln = "\n"