Skip to content

Commit

Permalink
fix: prevent autoimport from importing same package many times
Browse files Browse the repository at this point in the history
  • Loading branch information
lyz-code committed Aug 20, 2021
1 parent eb6f61c commit c79b8a0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/autoimport/model.py
Expand Up @@ -239,11 +239,14 @@ def _move_imports_to_top(self) -> None:
def _fix_flake_import_errors(self) -> None:
"""Fix python source code to correct missed or unused import statements."""
error_messages = autoflake.check(self._join_code())
fixed_packages = []

for message in error_messages:
if isinstance(message, (UndefinedName, UndefinedExport)):
object_name = message.message_args[0]
self._add_package(object_name)
if object_name not in fixed_packages:
self._add_package(object_name)
fixed_packages.append(object_name)
elif isinstance(message, UnusedImport):
import_name = message.message_args[0]
self._remove_unused_imports(import_name)
Expand Down
26 changes: 26 additions & 0 deletions tests/unit/test_services.py
Expand Up @@ -801,3 +801,29 @@ def test_fix_respects_leading_comments_with_new_lines() -> None:
result = fix_code(source)

assert result == desired_source


def test_fix_imports_dependency_only_once() -> None:
"""
Given: Code with a line that uses a package three times.
When: Fix code is run.
Then: The dependency is imported only once
"""
source = dedent(
"""\
def f(x):
return os.getcwd() + os.getcwd() + os.getcwd()
"""
)
desired_source = dedent(
"""\
import os
def f(x):
return os.getcwd() + os.getcwd() + os.getcwd()
"""
)

result = fix_code(source)

assert result == desired_source

0 comments on commit c79b8a0

Please sign in to comment.