Skip to content

Commit

Permalink
Don't insert duplicate imports
Browse files Browse the repository at this point in the history
  • Loading branch information
zsol committed Jul 25, 2023
1 parent ef1801a commit 05caa23
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 15 deletions.
28 changes: 13 additions & 15 deletions libcst/codemod/commands/rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,28 +128,26 @@ def leave_Import(
):
# Might, be in use elsewhere in the code, so schedule a potential removal, and add another alias.
new_names.append(import_alias)
self.scheduled_removals.add(original_node)
new_names.append(
cst.ImportAlias(
name=cst.Name(
value=self.gen_replacement_module(import_alias_full_name)
)
)
)
replacement_module = self.gen_replacement_module(import_alias_full_name)
self.bypass_import = True
if replacement_module != import_alias_name.value:
self.scheduled_removals.add(original_node)
new_names.append(
cst.ImportAlias(name=cst.Name(value=replacement_module))
)
elif isinstance(
import_alias_name, cst.Attribute
) and self.old_name.startswith(import_alias_full_name + "."):
# Same idea as above.
new_names.append(import_alias)
self.scheduled_removals.add(original_node)
new_name_node: Union[
cst.Attribute, cst.Name
] = self.gen_name_or_attr_node(
self.gen_replacement_module(import_alias_full_name)
)
new_names.append(cst.ImportAlias(name=new_name_node))
replacement_module = self.gen_replacement_module(import_alias_full_name)
self.bypass_import = True
if replacement_module != import_alias_full_name:
self.scheduled_removals.add(original_node)
new_name_node: Union[
cst.Attribute, cst.Name
] = self.gen_name_or_attr_node(replacement_module)
new_names.append(cst.ImportAlias(name=new_name_node))
else:
new_names.append(import_alias)

Expand Down
32 changes: 32 additions & 0 deletions libcst/codemod/commands/tests/test_rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,38 @@ class Fooo(module_2.Class_2):
new_name="a.b.module_3.Class_3",
)

def test_import_same_module(self) -> None:
before = """
import logging
logging.warn(1)
"""
after = """
import logging
logging.warning(1)
"""
self.assertCodemod(
before,
after,
old_name="logging.warn",
new_name="logging.warning",
)

def test_import_same_dotted_module(self) -> None:
before = """
import a.b
a.b.warn(1)
"""
after = """
import a.b
a.b.warning(1)
"""
self.assertCodemod(
before,
after,
old_name="a.b.warn",
new_name="a.b.warning",
)

def test_rename_local_variable(self) -> None:
before = """
x = 5
Expand Down

0 comments on commit 05caa23

Please sign in to comment.