Skip to content

Commit

Permalink
fix: Don't merge comments while splitting delimiters
Browse files Browse the repository at this point in the history
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
  • Loading branch information
cobaltt7 committed Feb 22, 2024
1 parent d1d4fc5 commit ce3d055
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

<!-- Changes that affect Black's stable style -->

- Don't move comments along with delimiters, which could cause crashes (#4248)

### Preview style

<!-- Changes that affect Black's preview style -->
Expand Down
11 changes: 9 additions & 2 deletions src/black/linegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -1194,8 +1194,11 @@ def append_to_line(leaf: Leaf) -> Iterator[Line]:
for leaf_idx, leaf in enumerate(line.leaves):
yield from append_to_line(leaf)

for comment_after in line.comments_after(leaf):
yield from append_to_line(comment_after)
previous_leaf = line.leaves[leaf_idx - 1] if leaf_idx > 0 else None
previous_priority = previous_leaf and bt.delimiters.get(id(previous_leaf))
if previous_priority != delimiter_priority:
for comment_after in line.comments_after(leaf):
yield from append_to_line(comment_after)

lowest_depth = min(lowest_depth, leaf.bracket_depth)
if leaf.bracket_depth == lowest_depth:
Expand All @@ -1215,6 +1218,10 @@ def append_to_line(leaf: Leaf) -> Iterator[Line]:

leaf_priority = bt.delimiters.get(id(leaf))
if leaf_priority == delimiter_priority:
if leaf_idx + 1 < len(line.leaves):
for comment_after in line.comments_after(line.leaves[leaf_idx + 1]):
yield from append_to_line(comment_after)

yield current_line

current_line = Line(
Expand Down
18 changes: 18 additions & 0 deletions tests/data/cases/split_delimiter_comments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
a = (
1 + # type: ignore
2 # type: ignore
)
a = (
1 # type: ignore
+ 2 # type: ignore
)

# output
a = (
1 # type: ignore
+ 2 # type: ignore
)
a = (
1 # type: ignore
+ 2 # type: ignore
)

0 comments on commit ce3d055

Please sign in to comment.