From a3b5529bb3fd0bc1d10dd5f1c451625d384075ff Mon Sep 17 00:00:00 2001 From: Zsolt Dollenstein Date: Wed, 11 Dec 2024 20:30:33 +0000 Subject: [PATCH] rename: fix renaming toplevel names (#1260) For toplevel module names imported via `import foo`, the rename codemod would fail to change these. This PR fixes that. --- libcst/codemod/commands/rename.py | 2 +- libcst/codemod/commands/tests/test_rename.py | 22 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/libcst/codemod/commands/rename.py b/libcst/codemod/commands/rename.py index f09c41fb..ee196582 100644 --- a/libcst/codemod/commands/rename.py +++ b/libcst/codemod/commands/rename.py @@ -347,7 +347,7 @@ def gen_replacement(self, original_name: str) -> str: module_as_name[0] + ".", module_as_name[1] + ".", 1 ) - if original_name == self.old_mod_or_obj: + if self.old_module and original_name == self.old_mod_or_obj: return self.new_mod_or_obj elif original_name == self.old_name: return ( diff --git a/libcst/codemod/commands/tests/test_rename.py b/libcst/codemod/commands/tests/test_rename.py index 4b88ee29..6e8ef936 100644 --- a/libcst/codemod/commands/tests/test_rename.py +++ b/libcst/codemod/commands/tests/test_rename.py @@ -850,3 +850,25 @@ def test_import_parent_module_asname(self) -> None: z.c(z.c.d) """ self.assertCodemod(before, after, old_name="a.b.c", new_name="z.c") + + def test_push_down_toplevel_names(self) -> None: + before = """ + import foo + foo.baz() + """ + after = """ + import quux.foo + quux.foo.baz() + """ + self.assertCodemod(before, after, old_name="foo", new_name="quux.foo") + + def test_push_down_toplevel_names_with_asname(self) -> None: + before = """ + import foo as bar + bar.baz() + """ + after = """ + import quux.foo + quux.foo.baz() + """ + self.assertCodemod(before, after, old_name="foo", new_name="quux.foo")