Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 127 additions & 55 deletions isort/_parse_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,23 @@
from enum import StrEnum
from typing import NamedTuple

from .comments import parse as parse_comments
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
Expand Down Expand Up @@ -44,29 +58,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:
Expand All @@ -87,66 +113,112 @@ 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]
should_skip: bool
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[[], tuple[str, str | None]],
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.
"""
extra_lines: list[ExtraLine] = []

if "(" in line.split("#", 1)[0]:
while not line.split("#", maxsplit=1)[0].strip().endswith(")"):
try:
line, comment = get_next_line()
except StopIteration:
break
extra_lines.append(ExtraLine(line=line, comment=comment))
return _collect_parenthesized_continuation(
line, import_string, get_next_line, line_separator
)

extra_lines: list[ExtraLine] = []
should_skip = False
in_quote = ""
seen_semicolon = False

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:
while line.strip().endswith("\\"):
try:
line, comment = get_next_line()
except StopIteration:
break
line = line.lstrip()

# Still need to check for parentheses after an escaped line
if "(" in line.split("#")[0] and ")" not in line.split("#")[0]:
extra_lines.append(ExtraLine(line=line, comment=comment))
import_string += line_separator + line

while not line.split("#")[0].strip().endswith(")"):
try:
line, comment = get_next_line()
except StopIteration:
break
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,
complete_import_string=import_string,
extra_lines=extra_lines,
should_skip=should_skip,
in_quote=in_quote,
)


Expand Down
Loading