fix: Don't remove comments along with parens (#4218)

Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
This commit is contained in:
cobalt 2024-02-12 08:27:50 -06:00 committed by GitHub
parent 35e9776919
commit 8af439407c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 122 additions and 0 deletions

View File

@ -10,6 +10,9 @@
<!-- Changes that affect Black's stable style -->
- Fixed a bug where comments where mistakenly removed along with redundant parentheses
(#4218)
### Preview style
<!-- Changes that affect Black's preview style -->

View File

@ -1553,6 +1553,9 @@ def maybe_make_parens_invisible_in_atom(
not is_type_ignore_comment_string(middle.prefix.strip())
):
first.value = ""
if first.prefix.strip():
# Preserve comments before first paren
middle.prefix = first.prefix + middle.prefix
last.value = ""
maybe_make_parens_invisible_in_atom(
middle,
@ -1564,6 +1567,9 @@ def maybe_make_parens_invisible_in_atom(
# Strip the invisible parens from `middle` by replacing
# it with the child in-between the invisible parens
middle.replace(middle.children[1])
if middle.children[-1].prefix.strip():
# Preserve comments before last paren
last.prefix = middle.children[-1].prefix + last.prefix
return False

View File

@ -0,0 +1,113 @@
if (
True
# sdf
):
print("hw")
if ((
True
# sdf
)):
print("hw")
if ((
# type: ignore
True
)):
print("hw")
if ((
True
# type: ignore
)):
print("hw")
if (
# a long comment about
# the condition below
(a or b)
):
pass
def return_true():
return (
(
True # this comment gets removed accidentally
)
)
def return_true():
return (True) # this comment gets removed accidentally
if (
# huh comment
(True)
):
...
if (
# huh
(
# comment
True
)
):
...
# output
if (
True
# sdf
):
print("hw")
if (
True
# sdf
):
print("hw")
if (
# type: ignore
True
):
print("hw")
if (
True
# type: ignore
):
print("hw")
if (
# a long comment about
# the condition below
a
or b
):
pass
def return_true():
return True # this comment gets removed accidentally
def return_true():
return True # this comment gets removed accidentally
if (
# huh comment
True
):
...
if (
# huh
# comment
True
):
...