Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix lines_before_imports appending lines after comments #1861

Merged
merged 1 commit into from Dec 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions isort/core.py
Expand Up @@ -72,6 +72,7 @@ def process(
stripped_line: str = ""
end_of_file: bool = False
verbose_output: List[str] = []
lines_before: List[str] = []

if config.float_to_top:
new_input = ""
Expand Down Expand Up @@ -333,6 +334,15 @@ def process(
not_imports = True

if not_imports:

if not was_in_quote and config.lines_before_imports > -1:
if line.strip() == "":
lines_before += line
continue
if not import_section:
output_stream.write("".join(lines_before))
lines_before = []

raw_import_section: str = import_section
if (
add_imports
Expand Down
22 changes: 18 additions & 4 deletions tests/unit/test_isort.py
Expand Up @@ -1716,14 +1716,28 @@ 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\nfrom c import d\nfoo = 'bar'\n"
test_input = """from a import b

foo = 'bar'
"""

ln = "\n"

# default case is no line added before the import
assert isort.code(test_input) == ("from a import b\nfrom c import d\n\nfoo = 'bar'\n")
assert isort.code(test_input) == (test_input)

# test again with a custom number of lines before the import section
assert isort.code(test_input, lines_before_imports=2) == (
"\n\nfrom a import b\nfrom c import d\n\nfoo = 'bar'\n"
assert isort.code(test_input, lines_before_imports=2) == 2 * ln + test_input

comment = "# Comment\n"

# test with a comment above
assert isort.code(comment + ln + test_input, lines_before_imports=0) == comment + test_input

# test with comments with empty lines
assert (
isort.code(comment + ln + comment + 3 * ln + test_input, lines_before_imports=1)
== comment + ln + comment + 1 * ln + test_input
)


Expand Down