Skip to content

Commit

Permalink
Fix a minor issue in incremental formatting where trailing comments o…
Browse files Browse the repository at this point in the history
…n unchanged lines might have their leading space normalized.

This is also required for the new async handling introduced in psf#3609

PiperOrigin-RevId: 517517272
  • Loading branch information
yilei authored and Copybara-Service committed Mar 17, 2023
1 parent 23c77ee commit 4b5d62b
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/pyink/ink.py
Expand Up @@ -161,7 +161,7 @@ def _convert_unchanged_line_by_line(node: Node, lines_set: Set[int]):
assert False, "Unexpected empty nodes in the match_stmt"
continue
if not _get_line_range(nodes_to_ignore).intersection(lines_set):
_convert_nodes_to_standardalone_comment(nodes_to_ignore)
_convert_nodes_to_standardalone_comment(nodes_to_ignore, newline=leaf)
elif leaf.parent and leaf.parent.type == syms.suite:
# The `suite` node is defined as:
# suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
Expand All @@ -185,7 +185,7 @@ def _convert_unchanged_line_by_line(node: Node, lines_set: Set[int]):
):
nodes_to_ignore.insert(0, grandparent.prev_sibling)
if not _get_line_range(nodes_to_ignore).intersection(lines_set):
_convert_nodes_to_standardalone_comment(nodes_to_ignore)
_convert_nodes_to_standardalone_comment(nodes_to_ignore, newline=leaf)
else:
ancestor = _furthest_ancestor_with_last_leaf(leaf)
# Consider multiple decorators as a whole block, as their
Expand Down Expand Up @@ -236,7 +236,7 @@ def _convert_node_to_standalone_comment(node: LN):
)


def _convert_nodes_to_standardalone_comment(nodes: Sequence[LN]):
def _convert_nodes_to_standardalone_comment(nodes: Sequence[LN], *, newline: Leaf):
"""Convert nodes to STANDALONE_COMMENT by modifying the tree inline."""
if not nodes:
return
Expand All @@ -247,6 +247,10 @@ def _convert_nodes_to_standardalone_comment(nodes: Sequence[LN]):
prefix = first_leaf.prefix
first_leaf.prefix = ""
value = "".join(str(node) for node in nodes)
# The prefix comment on the NEWLINE leaf is the trailing comment of the statement.
if newline.prefix:
value += newline.prefix
newline.prefix = ""
index = nodes[0].remove()
for node in nodes[1:]:
node.remove()
Expand Down

0 comments on commit 4b5d62b

Please sign in to comment.