Skip to content

Commit c695437

Browse files
committed
factor out helper should_suppress_clause
1 parent 77f5c3a commit c695437

File tree

1 file changed

+37
-13
lines changed
  • crates/ruff_python_formatter/src/statement

1 file changed

+37
-13
lines changed

crates/ruff_python_formatter/src/statement/clause.rs

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -556,18 +556,7 @@ where
556556

557557
impl<'ast> Format<PyFormatContext<'ast>> for FormatClause<'_, 'ast> {
558558
fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> {
559-
let source = f.context().source();
560-
if is_fix_fmt_skip_in_one_liners_enabled(f.context())
561-
&& let Some(last_child_in_clause) = self.format_header.header.last_child_in_clause()
562-
&& has_skip_comment(
563-
f.context().comments().trailing(last_child_in_clause),
564-
f.context().source(),
565-
)
566-
&& !source.contains_line_break(TextRange::new(
567-
self.format_header.header.range(source).unwrap().start(),
568-
last_child_in_clause.end(),
569-
))
570-
{
559+
if should_suppress_clause(&self, f)? {
571560
write_suppressed_clause(self, f)
572561
} else {
573562
write!(f, [self.format_header, self.format_body])
@@ -644,6 +633,39 @@ fn colon_range(after_keyword_or_condition: TextSize, source: &str) -> FormatResu
644633
}
645634
}
646635

636+
fn should_suppress_clause(
637+
clause: &FormatClause<'_, '_>,
638+
f: &mut Formatter<PyFormatContext<'_>>,
639+
) -> FormatResult<bool> {
640+
// Check if preview behavior is enabled
641+
if !is_fix_fmt_skip_in_one_liners_enabled(f.context()) {
642+
return Ok(false);
643+
};
644+
645+
let source = f.context().source();
646+
let Some(last_child_in_clause) = clause.format_header.header.last_child_in_clause() else {
647+
return Ok(false);
648+
};
649+
650+
let clause_start = clause
651+
.format_header
652+
.header
653+
.first_keyword_range(source)?
654+
.start();
655+
656+
let clause_range = TextRange::new(clause_start, last_child_in_clause.end());
657+
658+
// Only applies to clauses on a single line
659+
if source.contains_line_break(clause_range) {
660+
return Ok(false);
661+
};
662+
663+
Ok(has_skip_comment(
664+
f.context().comments().trailing(last_child_in_clause),
665+
f.context().source(),
666+
))
667+
}
668+
647669
#[cold]
648670
fn write_suppressed_clause(
649671
clause: &FormatClause,
@@ -655,7 +677,9 @@ fn write_suppressed_clause(
655677

656678
let comments = f.context().comments().clone();
657679

658-
let last_child = header.last_child_in_clause().unwrap();
680+
let last_child = header
681+
.last_child_in_clause()
682+
.expect("last child to exist if `should_suppress_clause` is `Ok(true)`");
659683
let range_end = last_child.end();
660684

661685
// Write the outer comments and format the node as verbatim

0 commit comments

Comments
 (0)