From a3924392e21e6a10f30dfa926c677ef26e36998f Mon Sep 17 00:00:00 2001 From: XueHua-s <97370135+XueHua-s@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:52:29 +0800 Subject: [PATCH 1/3] Preserve multiline strings after semicolon continuations --- isort/_parse_utils.py | 82 ++++++++++++++++++++++++---------- isort/core.py | 40 ++++++++++++----- isort/identify.py | 6 ++- isort/output.py | 4 +- isort/parse.py | 34 +++++++------- tests/unit/test_identify.py | 21 +++++++++ tests/unit/test_regressions.py | 41 +++++++++++++++++ 7 files changed, 173 insertions(+), 55 deletions(-) diff --git a/isort/_parse_utils.py b/isort/_parse_utils.py index fd0f8a3ed..dca9c3672 100644 --- a/isort/_parse_utils.py +++ b/isort/_parse_utils.py @@ -5,6 +5,7 @@ from enum import StrEnum from typing import NamedTuple +from .comments import parse as parse_comments from .settings import Config @@ -44,29 +45,41 @@ class SkipLineResult(NamedTuple): in_quote: str +def _scan_quotes_and_parentheses(line: str, in_quote: str) -> tuple[str, int]: + """Return the quote state and change in parenthesis depth outside strings and comments.""" + parentheses = 0 + char_index = 0 + while char_index < len(line): + char = line[char_index] + if char == "\\": + char_index += 1 + elif in_quote: + if line[char_index : char_index + len(in_quote)] == in_quote: + in_quote = "" + elif char in ("'", '"'): + long_quote = line[char_index : char_index + 3] + if long_quote in ('"""', "'''"): + in_quote = long_quote + char_index += 2 + else: + in_quote = char + elif char == "#": + break + elif char == "(": + parentheses += 1 + elif char == ")": + parentheses -= 1 + char_index += 1 + return in_quote, parentheses + + # Ignore DeepSource cyclomatic complexity check for this function. # skipcq: PY-R1000 def skip_line(line: str, in_quote: str, needs_import: bool = True) -> SkipLineResult: """Determine if a given line should be skipped.""" should_skip = bool(in_quote) if '"' in line or "'" in line: - char_index = 0 - while char_index < len(line): - if line[char_index] == "\\": - char_index += 1 - elif in_quote: - if line[char_index : char_index + len(in_quote)] == in_quote: - in_quote = "" - elif line[char_index] in ("'", '"'): - long_quote = line[char_index : char_index + 3] - if long_quote in ('"""', "'''"): - in_quote = long_quote - char_index += 2 - else: - in_quote = line[char_index] - elif line[char_index] == "#": - break - char_index += 1 + in_quote, _ = _scan_quotes_and_parentheses(line, in_quote) code = line.split("#", maxsplit=1)[0] if ";" in code and needs_import: @@ -90,12 +103,14 @@ class ImportContinuationResult(NamedTuple): final_line: str complete_import_string: str extra_lines: list[ExtraLine] + should_skip: bool + in_quote: str def collect_import_continuation( line: str, import_string: str, - get_next_line: Callable[[], tuple[str, str | None]], + get_next_line: Callable[[], str], line_separator: str = "\n", ) -> ImportContinuationResult: r"""Collect continuation lines for a multi-line import statement. @@ -104,33 +119,52 @@ def collect_import_continuation( and backslash-continued imports ``import Y, \\`` + newline + `` Z``. """ extra_lines: list[ExtraLine] = [] + should_skip = False + in_quote = "" if "(" in line.split("#", 1)[0]: while not line.split("#", maxsplit=1)[0].strip().endswith(")"): try: - line, comment = get_next_line() + line, comment = parse_comments(get_next_line()) except StopIteration: break extra_lines.append(ExtraLine(line=line, comment=comment)) import_string += line_separator + line else: + seen_semicolon = False while line.strip().endswith("\\"): try: - line, comment = get_next_line() + raw_line = get_next_line() except StopIteration: break + line, comment = parse_comments(raw_line) + seen_semicolon |= ";" in line + parentheses = 0 + if seen_semicolon: + in_quote, parentheses = _scan_quotes_and_parentheses(raw_line, in_quote) + if in_quote and parentheses <= 0: + return ImportContinuationResult( + raw_line, import_string, extra_lines, True, in_quote + ) line = line.lstrip() # Still need to check for parentheses after an escaped line - if "(" in line.split("#")[0] and ")" not in line.split("#")[0]: + track_parentheses = seen_semicolon and parentheses > 0 + if track_parentheses or ("(" in line.split("#")[0] and ")" not in line.split("#")[0]): extra_lines.append(ExtraLine(line=line, comment=comment)) import_string += line_separator + line + should_skip |= bool(in_quote) - while not line.split("#")[0].strip().endswith(")"): + while parentheses > 0 if track_parentheses else not line.strip().endswith(")"): try: - line, comment = get_next_line() + raw_line = get_next_line() except StopIteration: break + if track_parentheses: + in_quote, change = _scan_quotes_and_parentheses(raw_line, in_quote) + parentheses += change + should_skip |= bool(in_quote) + line, comment = parse_comments(raw_line) extra_lines.append(ExtraLine(line=line, comment=comment)) import_string += line_separator + line else: @@ -147,6 +181,8 @@ def collect_import_continuation( final_line=line, complete_import_string=import_string, extra_lines=extra_lines, + should_skip=should_skip, + in_quote=in_quote, ) diff --git a/isort/core.py b/isort/core.py index b3f057d6f..99e51bf3a 100644 --- a/isort/core.py +++ b/isort/core.py @@ -78,18 +78,23 @@ def _float_to_top( new_input = "" current = "" isort_off = False + in_quote = "" verbose_output: list[str] = [] made_changes = False for line in chain(input_stream, (None,)): stripped_line = line.strip() if line is not None else "" + if line is not None and not isort_off: + in_quote = _scan_quotes(line, stripped_line, in_quote) if isort_off and line is not None: if stripped_line == "# isort: on": isort_off = False new_input += line - elif ( - line is None - or stripped_line in ("# isort: split", "# isort: off") - or line.rstrip().endswith("# isort: split") + elif line is None or ( + not in_quote + and ( + stripped_line in ("# isort: split", "# isort: off") + or line.rstrip().endswith("# isort: split") + ) ): if stripped_line == "# isort: off": isort_off = True @@ -394,25 +399,32 @@ def process( new_indent = line[: -len(line.lstrip())] import_statement = line stripped_line = line.strip().split("#")[0] - while stripped_line.endswith("\\") or ( - "(" in stripped_line and ")" not in stripped_line + seen_semicolon = False + while not in_quote and ( + stripped_line.endswith("\\") + or ("(" in stripped_line and ")" not in stripped_line) ): if stripped_line.endswith("\\"): - while stripped_line and stripped_line.endswith("\\"): + while not in_quote and stripped_line.endswith("\\"): line = input_stream.readline() stripped_line = line.strip().split("#")[0] + seen_semicolon |= ";" in stripped_line + if seen_semicolon: + in_quote = _scan_quotes(line, stripped_line, in_quote) import_statement += line else: - while ")" not in stripped_line: + while not in_quote and ")" not in stripped_line: line = input_stream.readline() if not line: # end of file without closing parenthesis raise ExistingSyntaxErrors("Parenthesis is not closed") stripped_line = line.strip().split("#")[0] + if seen_semicolon: + in_quote = _scan_quotes(line, stripped_line, in_quote) import_statement += line - # The second clause keeps a per-line ``isort: skip`` import exactly + # The skip-comment check keeps a per-line ``isort: skip`` import exactly # where it is: when earlier imports have already been collected into # the current section, the skipped statement is treated as a section # boundary so those imports can't be sorted above it. Without it, a @@ -420,9 +432,13 @@ def process( # always floated to the top) makes isort splice the sorted block # ahead of the skipped line and relocate it below the block. See #2092. if ( - import_statement.lstrip().startswith("from") - and "import" not in import_statement - ) or (contains_imports and _has_skip_comment(import_statement)): + in_quote + or ( + import_statement.lstrip().startswith("from") + and "import" not in import_statement + ) + or (contains_imports and _has_skip_comment(import_statement)) + ): line = import_statement not_imports = True else: diff --git a/isort/identify.py b/isort/identify.py index f1a4a8c1d..d7f76d325 100644 --- a/isort/identify.py +++ b/isort/identify.py @@ -119,12 +119,14 @@ def imports( file_path=file_path, ) - _, import_string, _ = collect_import_continuation( + _, import_string, _, skip_continuation, in_quote = collect_import_continuation( line, import_string, # We can disregard `index` here because it is no longer accessed after this line. - lambda: parse_comments(next(indexed_input)[1]), + lambda: next(indexed_input)[1], ) + if skip_continuation: + continue if type_of_import is _ImportType.FROM: import_string = normalize_from_import_string(import_string) diff --git a/isort/output.py b/isort/output.py index c4553ab61..653dc381e 100644 --- a/isort/output.py +++ b/isort/output.py @@ -204,9 +204,11 @@ def sorted_imports( if parsed.place_imports: new_out_lines = [] + in_quote = "" for index, line in enumerate(formatted_output): new_out_lines.append(line) - if line in parsed.import_placements: + _, in_quote = _parse_utils.skip_line(line, in_quote=in_quote, needs_import=False) + if not in_quote and line in parsed.import_placements: new_out_lines.extend(parsed.place_imports[parsed.import_placements[line]]) if ( len(formatted_output) <= (index + 1) diff --git a/isort/parse.py b/isort/parse.py index de90d1c84..4ea1a51ee 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -133,9 +133,11 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte statement_index = index (skipping_line, in_quote) = skip_line(line, in_quote=in_quote) - if ( - line in config.section_comments or line in config.section_comments_end - ) and not skipping_line: + if skipping_line: + out_lines.append(line) + continue + + if line in config.section_comments or line in config.section_comments_end: if import_index == -1: # pragma: no branch import_index = index - 1 continue @@ -149,10 +151,6 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte place_imports[section] = [] import_placements[line] = section - if skipping_line: - out_lines.append(line) - continue - lstripped_line = line.lstrip() if ( config.float_to_top @@ -230,17 +228,25 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte if type_of_import is _ImportType.FROM and len(line_parts) == 2 and comments: nested_comments[line_parts[-1]] = comments[0] - def _get_next_line() -> tuple[str, str | None]: + def _get_next_line() -> str: nonlocal index if index >= line_count: raise StopIteration - result = parse_comments(in_lines[index]) + result = in_lines[index] index += 1 return result - line, import_string, extra_lines = collect_import_continuation( - line, import_string, _get_next_line, line_separator + line, import_string, extra_lines, skip_continuation, in_quote = ( + collect_import_continuation(line, import_string, _get_next_line, line_separator) ) + # A semicolon introduced by the continuation means the original lines must + # be preserved, whether or not they open a string that spans later lines. + if skip_continuation or ( + ";" in import_string.split("#")[0] and ";" not in statement.split("#")[0] + ): + out_lines.append(raw_line) + out_lines.extend(in_lines[statement_index:index]) + continue for extra_line in extra_lines: raw_lines.append(extra_line.line) # If during parsing of the continuation lines we encounter a comment, we record it. @@ -254,12 +260,6 @@ def _get_next_line() -> tuple[str, str | None]: ): nested_comments[stripped_line] = extra_line.comment - # Preserve original formatting when semicolons appear in import_string but not statement - if ";" in import_string.split("#")[0] and ";" not in statement.split("#")[0]: - out_lines.append(raw_lines[0]) - out_lines.extend(in_lines[statement_index:index]) - continue - if import_index == -1: import_index = statement_index - 1 diff --git a/tests/unit/test_identify.py b/tests/unit/test_identify.py index 52006d499..f8bdbe4b5 100644 --- a/tests/unit/test_identify.py +++ b/tests/unit/test_identify.py @@ -9,6 +9,27 @@ def imports_in_code(code: str, **kwargs: Any) -> list[identify.Import]: return list(identify.imports(StringIO(code), **kwargs)) +def test_find_imports_skips_string_after_semicolon_continuation_issue_2837() -> None: + source = '''\ +from package import \\ + name; text = """ +import z +import a +""" + +import c +''' + assert imports_in_code(source) == [Import(7, False, "c")] + + continued = source.replace('text = """', 'text = \\\n """') + assert imports_in_code(continued) == [Import(8, False, "c")] + + parenthesized = source.replace('text = """', 'text = (\n """', 1).replace( + '\n"""\n', '\n"""\n )\n' + ) + assert imports_in_code(parenthesized) == [Import(9, False, "c")] + + def test_top_only() -> None: imports_in_function = """ import abc diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index 4781b5522..47b0aa9a4 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -3034,6 +3034,47 @@ def test_semicolon_continuation_keeps_hash_inside_string_issue_1918() -> None: assert isort.code(source) == source +@pytest.mark.parametrize("float_to_top", [False, True]) +@pytest.mark.parametrize( + ("string_start", "string_end"), + [ + ('"""', '"""'), + ("r'''( # string content\n# isort: split\n# isort: off", "''' # closing comment"), + ('"#"; text = b"""', '"""'), + ('\\\n """', '"""'), + ('(\n """', '"""\n )'), + ('("""', '"""\n )'), + ('("""', '# text before the close""")'), + ('"""\n# isort: imports-THIRDPARTY', '"""'), + ], +) +def test_semicolon_continuation_preserves_multiline_string_issue_2837( + float_to_top: bool, string_start: str, string_end: str +) -> None: + literal = ( + "from package import \\\n" + f" name; text = {string_start}\n" + "import z\n" + "import a\n" + f"{string_end}\n\n" + ) + source = literal + "import d # trailing import comment\nimport c\n" + expected = literal + "import c\nimport d # trailing import comment\n" + + assert isort.code(source, float_to_top=float_to_top) == expected + assert isort.code(expected, float_to_top=float_to_top) == expected + + +def test_semicolon_continuation_preserves_duplicate_placement_marker_issue_2837() -> None: + marker = "# isort: imports-THIRDPARTY\n" + literal = f'from package import \\\n name; text = """\nimport z\n{marker}import a\n"""\n' + source = marker + "\n" + literal + "\nimport d\nimport c\n" + expected = marker + "import c\nimport d\n\n" + literal + + assert isort.code(source, float_to_top=True) == expected + assert isort.code(expected, float_to_top=True) == expected + + def test_straight_continuation_keeps_leading_comment_above_import_issue_1918() -> None: """Moving a leading comment must not leave the import below the code it feeds. From 5182b74017c5bea17c25d384f8e32eda5e491739 Mon Sep 17 00:00:00 2001 From: XueHua-s <97370135+XueHua-s@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:05:07 +0800 Subject: [PATCH 2/3] Simplify continuation scanning and handle end of input --- isort/_parse_utils.py | 131 +++++++++++++++++++++++++----------------- isort/core.py | 106 +++++++++++++++++++--------------- isort/identify.py | 11 +++- isort/parse.py | 5 +- 4 files changed, 150 insertions(+), 103 deletions(-) diff --git a/isort/_parse_utils.py b/isort/_parse_utils.py index dca9c3672..f22c9c6f6 100644 --- a/isort/_parse_utils.py +++ b/isort/_parse_utils.py @@ -100,6 +100,8 @@ class ExtraLine(NamedTuple): class ImportContinuationResult(NamedTuple): + """Collected import text and any quote state that the caller must carry forward.""" + final_line: str complete_import_string: str extra_lines: list[ExtraLine] @@ -107,75 +109,96 @@ class ImportContinuationResult(NamedTuple): in_quote: str +def _collect_parenthesized_continuation( + line: str, + import_string: str, + get_next_line: Callable[[], str | None], + line_separator: str, + parentheses: int | None = None, + in_quote: str = "", +) -> ImportContinuationResult: + """Collect through the closing parenthesis of an import or mixed statement.""" + extra_lines: list[ExtraLine] = [] + should_skip = bool(in_quote) + + # Mixed statements track bracket depth, since their strings may contain parentheses. + while ( + parentheses > 0 + if parentheses is not None + else not line.split("#", 1)[0].strip().endswith(")") + ): + raw_line = get_next_line() + if raw_line is None: + break + if parentheses is not None: + in_quote, change = _scan_quotes_and_parentheses(raw_line, in_quote) + parentheses += change + should_skip |= bool(in_quote) + line, comment = parse_comments(raw_line) + extra_lines.append(ExtraLine(line=line, comment=comment)) + import_string += line_separator + line + + return ImportContinuationResult(line, import_string, extra_lines, should_skip, in_quote) + + def collect_import_continuation( line: str, import_string: str, - get_next_line: Callable[[], str], + get_next_line: Callable[[], str | None], line_separator: str = "\n", ) -> ImportContinuationResult: r"""Collect continuation lines for a multi-line import statement. Handles both parenthesised imports ``from X import (`` + newline + `` Y, Z)`` and backslash-continued imports ``import Y, \\`` + newline + `` Z``. + The line reader returns None at the end of input. """ + if "(" in line.split("#", 1)[0]: + return _collect_parenthesized_continuation( + line, import_string, get_next_line, line_separator + ) + extra_lines: list[ExtraLine] = [] should_skip = False in_quote = "" + seen_semicolon = False - if "(" in line.split("#", 1)[0]: - while not line.split("#", maxsplit=1)[0].strip().endswith(")"): - try: - line, comment = parse_comments(get_next_line()) - except StopIteration: - break - extra_lines.append(ExtraLine(line=line, comment=comment)) + while line.strip().endswith("\\"): + raw_line = get_next_line() + if raw_line is None: + break + line, comment = parse_comments(raw_line) + seen_semicolon |= ";" in line + parentheses = 0 + if seen_semicolon: + in_quote, parentheses = _scan_quotes_and_parentheses(raw_line, in_quote) + if in_quote and parentheses <= 0: + return ImportContinuationResult( + raw_line, import_string, extra_lines, True, in_quote + ) + + line = line.lstrip() + extra_lines.append(ExtraLine(line=line, comment=comment)) + if parentheses > 0 or ("(" in line and ")" not in line): + continuation = _collect_parenthesized_continuation( + line, + import_string + line_separator + line, + get_next_line, + line_separator, + parentheses if parentheses > 0 else None, + in_quote, + ) + line = continuation.final_line + import_string = continuation.complete_import_string + extra_lines.extend(continuation.extra_lines) + should_skip |= continuation.should_skip + in_quote = continuation.in_quote + elif import_string.strip().endswith((" import", " cimport")) or line.strip().startswith( + ("import ", "cimport ") + ): import_string += line_separator + line - else: - seen_semicolon = False - while line.strip().endswith("\\"): - try: - raw_line = get_next_line() - except StopIteration: - break - line, comment = parse_comments(raw_line) - seen_semicolon |= ";" in line - parentheses = 0 - if seen_semicolon: - in_quote, parentheses = _scan_quotes_and_parentheses(raw_line, in_quote) - if in_quote and parentheses <= 0: - return ImportContinuationResult( - raw_line, import_string, extra_lines, True, in_quote - ) - line = line.lstrip() - - # Still need to check for parentheses after an escaped line - track_parentheses = seen_semicolon and parentheses > 0 - if track_parentheses or ("(" in line.split("#")[0] and ")" not in line.split("#")[0]): - extra_lines.append(ExtraLine(line=line, comment=comment)) - import_string += line_separator + line - should_skip |= bool(in_quote) - - while parentheses > 0 if track_parentheses else not line.strip().endswith(")"): - try: - raw_line = get_next_line() - except StopIteration: - break - if track_parentheses: - in_quote, change = _scan_quotes_and_parentheses(raw_line, in_quote) - parentheses += change - should_skip |= bool(in_quote) - line, comment = parse_comments(raw_line) - extra_lines.append(ExtraLine(line=line, comment=comment)) - import_string += line_separator + line - else: - if import_string.strip().endswith( - (" import", " cimport") - ) or line.strip().startswith(("import ", "cimport ")): - extra_lines.append(ExtraLine(line=line, comment=comment)) - import_string += line_separator + line - else: - extra_lines.append(ExtraLine(line=line, comment=comment)) - import_string = import_string.rstrip().rstrip("\\") + " " + line.lstrip() + else: + import_string = import_string.rstrip().rstrip("\\") + " " + line return ImportContinuationResult( final_line=line, diff --git a/isort/core.py b/isort/core.py index 99e51bf3a..787e5304e 100644 --- a/isort/core.py +++ b/isort/core.py @@ -64,17 +64,54 @@ def _has_skip_comment(import_statement: str) -> bool: class _FloatToTopResult(NamedTuple): + """Input and diagnostics produced by the float-to-top preprocessing pass.""" + input_stream: TextIO verbose_output: list[str] made_changes: bool +def _sort_float_to_top_section( + source: str, + add_imports: list[str], + boundary: str | None, + config: Config, + extension: str, +) -> tuple[str, list[str], bool]: + """Sort one float-to-top section and preserve its spacing before the next boundary.""" + before = source + if add_imports: + line_separator = parse._infer_line_separator(boundary, config.line_ending) + source += line_separator + line_separator.join(add_imports) + parsed = parse.file_contents(source, config=config) + + extra_space = "" + while before.endswith(parsed.line_separator): + extra_space += parsed.line_separator + before = before[: -len(parsed.line_separator)] + extra_space = extra_space.replace(parsed.line_separator, "", 1) + sorted_output = output.sorted_imports( + parsed, + Config(config=config, lines_before_imports=-1), + extension, + import_type="import", + ) + changed = _has_changed( + before=before, + after=sorted_output, + line_separator=parsed.line_separator, + ignore_whitespace=config.ignore_whitespace, + ) + return sorted_output + extra_space, parsed.verbose_output, changed + + def _float_to_top( input_stream: TextIO, add_imports: list[str], config: Config, extension: str, ) -> _FloatToTopResult: + """Move imports to the top of each section that permits sorting.""" new_input = "" current = "" isort_off = False @@ -82,53 +119,32 @@ def _float_to_top( verbose_output: list[str] = [] made_changes = False for line in chain(input_stream, (None,)): - stripped_line = line.strip() if line is not None else "" - if line is not None and not isort_off: + if line is not None: + stripped_line = line.strip() + if isort_off: + if stripped_line == "# isort: on": + isort_off = False + new_input += line + continue + in_quote = _scan_quotes(line, stripped_line, in_quote) - if isort_off and line is not None: - if stripped_line == "# isort: on": - isort_off = False - new_input += line - elif line is None or ( - not in_quote - and ( - stripped_line in ("# isort: split", "# isort: off") - or line.rstrip().endswith("# isort: split") + if in_quote or ( + stripped_line != "# isort: off" and not stripped_line.endswith("# isort: split") + ): + current += line + continue + isort_off = stripped_line == "# isort: off" + + if current: + sorted_section, section_verbose, section_changed = _sort_float_to_top_section( + current, add_imports, line, config, extension ) - ): - if stripped_line == "# isort: off": - isort_off = True - if current: - before = current - if add_imports: - line_separator = parse._infer_line_separator(line, config.line_ending) - current += line_separator + line_separator.join(add_imports) - add_imports = [] - parsed = parse.file_contents(current, config=config) - verbose_output += parsed.verbose_output - extra_space = "" - while before.endswith(parsed.line_separator): - extra_space += parsed.line_separator - before = before[: -len(parsed.line_separator)] - extra_space = extra_space.replace(parsed.line_separator, "", 1) - sorted_output = output.sorted_imports( - parsed, - Config(config=config, lines_before_imports=-1), - extension, - import_type="import", - ) - made_changes = made_changes or _has_changed( - before=before, - after=sorted_output, - line_separator=parsed.line_separator, - ignore_whitespace=config.ignore_whitespace, - ) - new_input += sorted_output - new_input += extra_space - current = "" - new_input += line or "" - else: - current += line or "" + new_input += sorted_section + verbose_output += section_verbose + made_changes |= section_changed + add_imports = [] + current = "" + new_input += line or "" return _FloatToTopResult( input_stream=StringIO(new_input), diff --git a/isort/identify.py b/isort/identify.py index d7f76d325..3d8ff5e2c 100644 --- a/isort/identify.py +++ b/isort/identify.py @@ -61,6 +61,14 @@ def imports( in_quote = "" indexed_input = enumerate(input_stream) + + def _get_next_line() -> str | None: + """Consume a continuation line without changing the import's starting index.""" + try: + return next(indexed_input)[1] + except StopIteration: + return None + for index, raw_line in indexed_input: (skipping_line, in_quote) = skip_line(raw_line, in_quote=in_quote) @@ -122,8 +130,7 @@ def imports( _, import_string, _, skip_continuation, in_quote = collect_import_continuation( line, import_string, - # We can disregard `index` here because it is no longer accessed after this line. - lambda: next(indexed_input)[1], + _get_next_line, ) if skip_continuation: continue diff --git a/isort/parse.py b/isort/parse.py index 4ea1a51ee..9ea371527 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -228,10 +228,11 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte if type_of_import is _ImportType.FROM and len(line_parts) == 2 and comments: nested_comments[line_parts[-1]] = comments[0] - def _get_next_line() -> str: + def _get_next_line() -> str | None: + """Read the next physical line and advance the parser's position.""" nonlocal index if index >= line_count: - raise StopIteration + return None result = in_lines[index] index += 1 return result From 78f535316f318c1d77143f46cdfe2afff3132de5 Mon Sep 17 00:00:00 2001 From: XueHua-s <97370135+XueHua-s@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:15:37 +0800 Subject: [PATCH 3/3] Share newline inference across the parsers --- isort/_parse_utils.py | 13 +++++++++++++ isort/core.py | 7 ++++--- isort/literal.py | 4 ++-- isort/parse.py | 15 ++------------- tests/unit/test_parse.py | 5 +++-- 5 files changed, 24 insertions(+), 20 deletions(-) diff --git a/isort/_parse_utils.py b/isort/_parse_utils.py index f22c9c6f6..349a0febc 100644 --- a/isort/_parse_utils.py +++ b/isort/_parse_utils.py @@ -9,6 +9,19 @@ from .settings import Config +def infer_line_separator(contents: str | None, configured: str) -> str: + """Use the configured newline or infer it from the source, defaulting to LF.""" + if configured: + return configured + if contents is None: + return "\n" + if "\r\n" in contents: + return "\r\n" + if "\r" in contents: + return "\r" + return "\n" + + class NormalizeLineResult(NamedTuple): normalized_line: str raw_line: str diff --git a/isort/core.py b/isort/core.py index 787e5304e..0390fd873 100644 --- a/isort/core.py +++ b/isort/core.py @@ -8,6 +8,7 @@ from isort.settings import DEFAULT_CONFIG, Config from . import output, parse +from ._parse_utils import infer_line_separator from .exceptions import ExistingSyntaxErrors, FileSkipComment from .format import format_natural, remove_whitespace from .settings import FILE_SKIP_COMMENTS @@ -81,7 +82,7 @@ def _sort_float_to_top_section( """Sort one float-to-top section and preserve its spacing before the next boundary.""" before = source if add_imports: - line_separator = parse._infer_line_separator(boundary, config.line_ending) + line_separator = infer_line_separator(boundary, config.line_ending) source += line_separator + line_separator.join(add_imports) parsed = parse.file_contents(source, config=config) @@ -253,7 +254,7 @@ def process( not_imports = True end_of_file = True line = "" - line_separator = parse._infer_line_separator(line, line_separator) + line_separator = infer_line_separator(line, line_separator) if code_sorting and code_sorting_section: if is_reexport: @@ -287,7 +288,7 @@ def process( output_stream.truncate() else: stripped_line = line.strip() - line_separator = parse._infer_line_separator(line, line_separator) + line_separator = infer_line_separator(line, line_separator) for file_skip_comment in FILE_SKIP_COMMENTS: if file_skip_comment in line: diff --git a/isort/literal.py b/isort/literal.py index 57027d25e..439505629 100644 --- a/isort/literal.py +++ b/isort/literal.py @@ -2,12 +2,12 @@ from collections.abc import Callable from typing import Any +from isort._parse_utils import infer_line_separator from isort.exceptions import ( AssignmentsFormatMismatch, LiteralParsingFailure, LiteralSortTypeMismatch, ) -from isort.parse import _infer_line_separator from isort.settings import DEFAULT_CONFIG, Config type_mapping: dict[str, tuple[type, Callable[[Any, Config, int, bool, str], str]]] = {} @@ -67,7 +67,7 @@ def assignment(code: str, sort_type: str, extension: str, config: Config = DEFAU if type(value) is not expected_type: raise LiteralSortTypeMismatch(type(value), expected_type) - line_separator = _infer_line_separator(code, config.line_ending) + line_separator = infer_line_separator(code, config.line_ending) prefix_length = len(f"{variable_name} {operator} ") variable_value = sort_function( diff --git a/isort/parse.py b/isort/parse.py index 9ea371527..e9c5b312c 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -11,6 +11,7 @@ _ImportType, collect_import_continuation, import_type, + infer_line_separator, normalize_from_import_string, normalize_line, skip_line, @@ -37,18 +38,6 @@ ) -def _infer_line_separator(contents: str | None, configured: str) -> str: - if configured: - return configured - if contents is None: - return "\n" - if "\r\n" in contents: - return "\r\n" - if "\r" in contents: - return "\r" - return "\n" - - ParsedImports = TypedDict( "ParsedImports", { @@ -85,7 +74,7 @@ class ParsedContent(NamedTuple): # skipcq: PY-R1000 def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedContent: """Parses a python file taking out and categorizing imports.""" - line_separator: str = _infer_line_separator(contents, config.line_ending) + line_separator: str = infer_line_separator(contents, config.line_ending) # ``str.splitlines`` also treats characters such as form feed as line # boundaries, even though Python's universal-newline handling does not. # Normalize actual newline sequences explicitly so those characters stay diff --git a/tests/unit/test_parse.py b/tests/unit/test_parse.py index 54247c158..185b60485 100644 --- a/tests/unit/test_parse.py +++ b/tests/unit/test_parse.py @@ -69,8 +69,9 @@ def test_file_contents_splits_only_on_newlines(line_separator: str) -> None: @given(contents=st.text()) -def test_fuzz__infer_line_separator(contents: str) -> None: - parse._infer_line_separator(contents=contents, configured="\n") +def test_fuzz_infer_line_separator(contents: str) -> None: + """An explicit line ending takes precedence over any source text.""" + assert _parse_utils.infer_line_separator(contents, configured="\n") == "\n" @given(import_string=st.text())