Support fmt: skip on compound statements (#6593)

This commit is contained in:
Micha Reiser 2023-08-17 08:05:41 +02:00 committed by GitHub
parent 4dc32a00d0
commit fa7442da2f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 1385 additions and 625 deletions

View file

@ -1,11 +1,13 @@
use crate::comments::{leading_alternate_branch_comments, trailing_comments, SourceComment};
use ruff_formatter::{format_args, write};
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::{ElifElseClause, StmtIf};
use crate::comments::SourceComment;
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::prelude::*;
use crate::statement::clause::{clause_header, ClauseHeader};
use crate::FormatNodeRule;
use ruff_formatter::write;
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::{ElifElseClause, StmtIf};
#[derive(Default)]
pub struct FormatStmtIf;
@ -25,11 +27,15 @@ impl FormatNodeRule<StmtIf> for FormatStmtIf {
write!(
f,
[
text("if"),
space(),
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks),
text(":"),
trailing_comments(trailing_colon_comment),
clause_header(
ClauseHeader::If(item),
trailing_colon_comment,
&format_args![
text("if"),
space(),
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks),
],
),
block_indent(&body.format())
]
)?;
@ -70,26 +76,28 @@ pub(crate) fn format_elif_else_clause(
let trailing_colon_comment = comments.dangling_comments(item);
let leading_comments = comments.leading_comments(item);
leading_alternate_branch_comments(leading_comments, last_node).fmt(f)?;
if let Some(test) = test {
write!(
f,
[
text("elif"),
space(),
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks),
]
)?;
} else {
text("else").fmt(f)?;
}
write!(
f,
[
text(":"),
trailing_comments(trailing_colon_comment),
clause_header(
ClauseHeader::ElifElse(item),
trailing_colon_comment,
&format_with(|f| {
if let Some(test) = test {
write!(
f,
[
text("elif"),
space(),
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks),
]
)
} else {
text("else").fmt(f)
}
}),
)
.with_leading_comments(leading_comments, last_node),
block_indent(&body.format())
]
)