diff --git a/isort/core.py b/isort/core.py index 472d914d..1f56f713 100644 --- a/isort/core.py +++ b/isort/core.py @@ -340,10 +340,12 @@ def process( ): cimport_statement = True - if cimport_statement != cimports or ( + if cimport_statement != cimports: + indent = new_indent + if ( new_indent != indent and import_section - and (not did_contain_imports or len(new_indent) < len(indent)) + and (not did_contain_imports and len(new_indent) < len(indent)) ): indent = new_indent if import_section: @@ -421,7 +423,7 @@ def process( if indent: import_section = "".join( - line[len(indent) :] for line in import_section.splitlines(keepends=True) + line[len(line) - len(line.lstrip()) :] for line in import_section.splitlines(keepends=True) ) parsed_content = parse.file_contents(import_section, config=config) diff --git a/tests/unit/test_isort.py b/tests/unit/test_isort.py index c241e325..3a7d5525 100644 --- a/tests/unit/test_isort.py +++ b/tests/unit/test_isort.py @@ -5689,6 +5689,22 @@ def test_reexport_not_last_line() -> None: assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output +def test_strip_leading_characters_with_odd_indentation() -> None: + """ Test to ensure that isort doesn't strip away leading character + with odd indentation + """ + test_input = """ +#!/usr/bin/env python3 + +if True: +#this comment breaks + # this is another comment + import sys + """ + + assert isort.code(test_input) == test_input + + def test_reexport_multiline_import() -> None: test_input = """from m import ( bar,