Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bugs in normalize_line(), and with a 2.7x speedup #2381

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
11 changes: 6 additions & 5 deletions isort/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,18 @@ def _infer_line_separator(contents: str) -> str:
return "\n"


_from_absolute_normalizer_pattern = re.compile(r"from[\t ]+(.+?)[\t ]+(c?import)[\t ]+")
_from_relative_normalizer_pattern = re.compile(r"from[\t ]*(\.+[^\t ]*?)[\t ]*(c?import)[\t ]+")


def normalize_line(raw_line: str) -> Tuple[str, str]:
"""Normalizes import related statements in the provided line.

Returns (normalized_line: str, raw_line: str)
"""
line = re.sub(r"from(\.+)cimport ", r"from \g<1> cimport ", raw_line)
line = re.sub(r"from(\.+)import ", r"from \g<1> import ", line)
line = _from_absolute_normalizer_pattern.sub(r"from \g<1> \g<2> ", raw_line)
line = _from_relative_normalizer_pattern.sub(r"from \g<1> \g<2> ", line)
line = line.replace("import*", "import *")
line = re.sub(r" (\.+)import ", r" \g<1> import ", line)
line = re.sub(r" (\.+)cimport ", r" \g<1> cimport ", line)
line = line.replace("\t", " ")
return line, raw_line


Expand Down
6 changes: 3 additions & 3 deletions tests/unit/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,13 @@ def test_fuzz_skip_line(line, in_quote, index, section_comments, needs_import):
("from..import a", "from .. import a"),
("import *", "import *"),
("import*", "import *"),
("from . import a", "from . import a"), # noqa: PT014
("from .import a", "from . import a"),
("from ..import a", "from .. import a"),
("from . cimport a", "from . cimport a"), # noqa: PT014
("from .cimport a", "from . cimport a"),
("from ..cimport a", "from .. cimport a"),
("from\t.\timport a", "from . import a"),
("from\t\t.\t\timport\t\ta", "from . import a"),
("from \t __future__ \t import \t annotations", "from __future__ import annotations"),
("from..x import y", "from ..x import y"),
],
)
def test_normalize_line(raw_line, expected):
Expand Down