From 8082ca4f5a9048375df0f69738b242d8b0b902d7 Mon Sep 17 00:00:00 2001 From: Zsolt Dollenstein Date: Tue, 25 Jul 2023 15:28:31 +0100 Subject: [PATCH] Don't insert duplicate imports --- libcst/codemod/commands/rename.py | 28 ++++++++--------- libcst/codemod/commands/tests/test_rename.py | 32 ++++++++++++++++++++ 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/libcst/codemod/commands/rename.py b/libcst/codemod/commands/rename.py index 472d1e616..4bd0ee3dc 100644 --- a/libcst/codemod/commands/rename.py +++ b/libcst/codemod/commands/rename.py @@ -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) diff --git a/libcst/codemod/commands/tests/test_rename.py b/libcst/codemod/commands/tests/test_rename.py index 2c9daed11..2f8971192 100644 --- a/libcst/codemod/commands/tests/test_rename.py +++ b/libcst/codemod/commands/tests/test_rename.py @@ -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