diff --git a/CHANGELOG.md b/CHANGELOG.md index ebfb1f38e..b820a0325 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Find out more about isort's release policy [here](https://pycqa.github.io/isort/ - Fixed #1461: Quiet config option not respected by file API in some circumstances. - Fixed #1482: pylama integration is not working correctly out-of-the-box. - Fixed #1492: --check does not work with stdin source. + - Fixed #1499: isort gets confused by single line, multi-line style comments when using float-to-top. ### 5.5.3 [Hotfix] September 20, 2020 - Fixed #1488: in rare cases isort can mangle `yield from` or `raise from` statements. diff --git a/isort/parse.py b/isort/parse.py index 613f7fa76..d9ab60e2c 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -200,12 +200,16 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte if skipping_line: out_lines.append(line) continue - elif ( + + lstripped_line = line.lstrip() + if ( config.float_to_top and import_index == -1 and line and not in_quote - and not line.strip().startswith("#") + and not lstripped_line.startswith("#") + and not lstripped_line.startswith("'''") + and not lstripped_line.startswith('"""') ): import_index = index - 1 while import_index and not in_lines[import_index - 1]: diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index 4869d444f..5c609d200 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -1081,3 +1081,80 @@ def generator_function(): from \\ """ assert isort.check_code(raise_from_at_file_end_ignored, show_diff=True) + + +def test_isort_float_to_top_correctly_identifies_single_line_comments_1499(): + """Test to ensure isort correctly handles the case where float to top is used + to push imports to the top and the top comment is a multiline type but only + one line. + See: https://github.com/PyCQA/isort/issues/1499 + """ + assert ( + isort.code( + '''#!/bin/bash +"""My comment""" +def foo(): + pass + +import a + +def bar(): + pass +''', + float_to_top=True, + ) + == ( + '''#!/bin/bash +"""My comment""" +import a + + +def foo(): + pass + + +def bar(): + pass +''' + ) + ) + assert ( + isort.code( + """#!/bin/bash +'''My comment''' +def foo(): + pass + +import a + +def bar(): + pass +""", + float_to_top=True, + ) + == ( + """#!/bin/bash +'''My comment''' +import a + + +def foo(): + pass + + +def bar(): + pass +""" + ) + ) + + assert isort.check_code( + """#!/bin/bash +'''My comment''' +import a + +x = 1 +""", + float_to_top=True, + show_diff=True, + )