Break `with` on end-of-line trailing comments (#7685)

## Summary

Ensures that:

```python
with (
    a  # comment
):
    pass
```

Retains its parentheses.

Closes https://github.com/astral-sh/ruff/issues/6750.

## Test Plan

`cargo test`
This commit is contained in:
Charlie Marsh 2023-09-27 20:16:40 -04:00 committed by GitHub
parent 58b50a6290
commit a6d79c03b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 118 additions and 12 deletions

View File

@ -108,6 +108,40 @@ with (
b # trailing b same line comment b # trailing b same line comment
): ... ): ...
with (
# comment
a
):
pass
with (
a # comment
):
pass
with (
a
# comment
):
pass
with (
# comment
a as b
):
pass
with (
a as b # comment
):
pass
with (
a as b
# comment
):
pass
with ( with (
[ [
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",

View File

@ -84,9 +84,9 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
})) }))
.fmt(f)?; .fmt(f)?;
} else if let [item] = item.items.as_slice() { } else if let [item] = item.items.as_slice() {
// This is similar to `maybe_parenthesize_expression`, but we're not dealing with an // This is similar to `maybe_parenthesize_expression`, but we're not
// expression here, it's a `WithItem`. // dealing with an expression here, it's a `WithItem`.
if comments.has_leading(item) || comments.has_trailing_own_line(item) { if comments.has_leading(item) || comments.has_trailing(item) {
optional_parentheses(&item.format()).fmt(f)?; optional_parentheses(&item.format()).fmt(f)?;
} else { } else {
item.format().fmt(f)?; item.format().fmt(f)?;

View File

@ -114,6 +114,40 @@ with (
b # trailing b same line comment b # trailing b same line comment
): ... ): ...
with (
# comment
a
):
pass
with (
a # comment
):
pass
with (
a
# comment
):
pass
with (
# comment
a as b
):
pass
with (
a as b # comment
):
pass
with (
a as b
# comment
):
pass
with ( with (
[ [
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
@ -297,10 +331,12 @@ with (
... # body ... # body
# body trailing own # body trailing own
with a as ( # a # as with (
# own line a as ( # a # as
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # own line
): # b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
) # b
):
pass pass
@ -372,13 +408,49 @@ with (
... ...
with ( with (
a (
# trailing own line comment a
) as ( # trailing as same line comment # trailing own line comment
b ) as ( # trailing as same line comment
): # trailing b same line comment b
) # trailing b same line comment
):
... ...
with (
# comment
a
):
pass
with (
a # comment
):
pass
with (
a
# comment
):
pass
with (
# comment
a as b
):
pass
with (
a as b # comment
):
pass
with (
a as b
# comment
):
pass
with ( with (
[ [
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",