Skip to content

Commit

Permalink
Merge pull request #1861 from legau/linesbef
Browse files Browse the repository at this point in the history
Fix lines_before_imports appending lines after comments
  • Loading branch information
timothycrosley committed Dec 4, 2021
2 parents 54d9c9b + 8c3f257 commit 4e23fcf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
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

0 comments on commit 4e23fcf

Please sign in to comment.