From 510c49cd51b448b4e6e99fd88d19c0fae4383b7c Mon Sep 17 00:00:00 2001 From: Zsolt Dollenstein Date: Mon, 2 Dec 2024 16:02:13 +0000 Subject: [PATCH] rename: don't eat commas unnecessarily #1254 was a bit too aggressive in removing commas. They shouldn't be removed if there are parenthesis around the imported names. --- libcst/codemod/commands/rename.py | 2 +- libcst/codemod/commands/tests/test_rename.py | 32 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/libcst/codemod/commands/rename.py b/libcst/codemod/commands/rename.py index 9ad4334d..f09c41fb 100644 --- a/libcst/codemod/commands/rename.py +++ b/libcst/codemod/commands/rename.py @@ -252,7 +252,7 @@ def leave_ImportFrom( # This import might be in use elsewhere in the code, so schedule a potential removal. self.scheduled_removals.add(original_node) new_names.append(import_alias) - if isinstance(new_names[-1].comma, cst.Comma): + if isinstance(new_names[-1].comma, cst.Comma) and updated_node.rpar is None: new_names[-1] = new_names[-1].with_changes( comma=cst.MaybeSentinel.DEFAULT ) diff --git a/libcst/codemod/commands/tests/test_rename.py b/libcst/codemod/commands/tests/test_rename.py index 8245a34c..4b88ee29 100644 --- a/libcst/codemod/commands/tests/test_rename.py +++ b/libcst/codemod/commands/tests/test_rename.py @@ -450,6 +450,38 @@ class Foo(b): new_name="f.d", ) + def test_comma_import_from_parens(self) -> None: + before = """ + from a import ( + b, + c, + d, + ) + from x import (y,) + + class Foo(b): + bar: c.bar + baz: d.baz + """ + after = """ + from a import ( + b, + c, + ) + from x import (y,) + from f import d + + class Foo(b): + bar: c.bar + baz: d.baz + """ + self.assertCodemod( + before, + after, + old_name="a.d", + new_name="f.d", + ) + def test_no_removal_of_import_in_use(self) -> None: before = """ import a