Fix formatting of single with-item with trailing comment (#14005)

This commit is contained in:
Micha Reiser 2024-11-01 09:08:06 +01:00 committed by GitHub
parent 20b8a43017
commit cf0f5e1318
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 276 additions and 14 deletions

View file

@ -71,7 +71,10 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
match layout {
WithItemsLayout::SingleWithTarget(single) => {
optional_parentheses(&single.format()).fmt(f)
optional_parentheses(&single.format().with_options(
WithItemLayout::ParenthesizedContextManagers { single: true },
))
.fmt(f)
}
WithItemsLayout::SingleWithoutTarget(single) => single
@ -93,7 +96,11 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
for item in &with_stmt.items {
joiner.entry_with_line_separator(
item,
&item.format(),
&item.format().with_options(
WithItemLayout::ParenthesizedContextManagers {
single: with_stmt.items.len() == 1,
},
),
soft_line_break_or_space(),
);
}
@ -114,9 +121,22 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
WithItemsLayout::Parenthesized => parenthesized(
"(",
&format_with(|f: &mut PyFormatter| {
f.join_comma_separated(with_stmt.body.first().unwrap().start())
.nodes(&with_stmt.items)
.finish()
let mut joiner = f.join_comma_separated(
with_stmt.body.first().unwrap().start(),
);
for item in &with_stmt.items {
joiner.entry(
item,
&item.format().with_options(
WithItemLayout::ParenthesizedContextManagers {
single: with_stmt.items.len() == 1,
},
),
);
}
joiner.finish()
}),
")",
)