Skip to content

Commit

Permalink
Work around issue in libcst to preserve whitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
drdavella committed Sep 20, 2023
1 parent b73d1cc commit 9815610
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/codemodder/codemods/use_walrus_if.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,14 @@ def leave_Assign(self, original_node, updated_node):
return cst.RemoveFromParent()

return original_node

def leave_SimpleStatementLine(self, original_node, updated_node):
"""
This is a workaround for the fact that libcst doesn't preserve the whitespace in the parent node when all children are removed.
This feels like a bug in libCST but we'll work around it for now.
"""
if not updated_node.body:
return cst.FlattenSentinel(original_node.leading_lines)

return updated_node
2 changes: 1 addition & 1 deletion tests/codemods/test_walrus_if.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ def test_walrus_if_multiple(self, tmpdir):
if foo == "bar":
whatever(foo)
"""
# TODO: not sure why libcst isn't preserving empty lines
expected_output = """
if (val := do_something()) is not None:
do_something_else(val)
if (foo := hello()) == "bar":
whatever(foo)
"""
Expand Down

0 comments on commit 9815610

Please sign in to comment.