Skip to content

Commit

Permalink
Fix an incremental formatting bug where it interacts poorly with fmt …
Browse files Browse the repository at this point in the history
…on/off pairs on unchanged lines.

PiperOrigin-RevId: 501849192
  • Loading branch information
yilei authored and copybara-github committed Jan 13, 2023
1 parent 412775f commit 2f5a0a5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ All notable changes to Pyink are recorded here.

## Unreleased

* Nothing notable unreleased.
* Fixed a bug in incremental formatting (`--pyink_lines=`) where pairs of
`# fmt: off/on` are used outside of the line ranges.

## 22.12.0

Expand Down
16 changes: 16 additions & 0 deletions src/pyink/ink.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ def convert_unchanged_lines(src_node: Node, lines: Collection[Tuple[int, int]]):
_convert_unchanged_line_by_line(src_node, lines_set)


def _contains_standalone_comment(node: LN) -> bool:
if isinstance(node, Leaf):
return node.type == STANDALONE_COMMENT
else:
for child in node.children:
if _contains_standalone_comment(child):
return True
return False


class _TopLevelStatementsVisitor(Visitor[None]):
"""A node visitor that converts unchanged top-level statements to STANDALONE_COMMENT.
Expand All @@ -102,6 +112,12 @@ def visit_simple_stmt(self, node: Node) -> Iterator[None]:

def visit_suite(self, node: Node) -> Iterator[None]:
yield from []
# If there is a STANDALONE_COMMENT node, it means parts of the node tree
# have fmt on/off/skip markers. Those STANDALONE_COMMENT nodes can't
# be simply converted by calling str(node). So we just don't convert
# here.
if _contains_standalone_comment(node):
return
# Find the semantic parent of this suite. For `async_stmt` and
# `async_funcdef`, the ASYNC token is defined on a separate level by the
# grammar.
Expand Down

0 comments on commit 2f5a0a5

Please sign in to comment.