Skip to content

Commit

Permalink
Remove multiple trailing lines in comments
Browse files Browse the repository at this point in the history
Previously, rustfmt would remove one blank, trailing line in a comment
every time it ran, so formatting was not idempotent if a comment had
multiple trailing lines. Comments are only reformatted in this way if
`comment::rewrite_comment_inner` is called, which is enabled by any of the
config options `normalize_comments`, `wrap_comments`, or
`format_code_in_doc_comments` (for doc comments only). Absent those
config options, no trailing line reformatting occurs at all.

In this commit, when the existing condition that detects a blank, trailing
line is true, any preceding blank lines are removed from the reformatted
comment. A source/target "system test" was added to prevent regression.

Signed-off-by: Ross Williams <[email protected]>
  • Loading branch information
overhacked committed May 11, 2024
1 parent d5f1200 commit fd95d0f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,13 @@ impl<'a> CommentRewrite<'a> {
} else if self.is_prev_line_multi_line && !line.is_empty() {
self.result.push(' ')
} else if is_last && line.is_empty() {
// trailing blank lines are unwanted
// Trailing blank lines are unwanted; if the last line is blank, look for additional,
// preceding blank lines to remove, also.
let trailing_line = self.comment_line_separator.trim_end_matches(' ');
while self.result.ends_with(trailing_line) {
self.result
.truncate(self.result.len() - trailing_line.len());
}
if !self.closer.is_empty() {
self.result.push_str(&self.indent_str);
}
Expand Down
21 changes: 21 additions & 0 deletions tests/source/comment_trailing_lines.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// rustfmt-wrap_comments: true

//! Module comment with multiple trailing lines
//!
//!

/// Doc comment with multiple trailing lines
///
///
pub mod foo {}

/// Doc comment with one trailing line
///
pub mod bar {}

/*
* Block comment with multiple trailing lines
*
*
*/
pub mod block {}
14 changes: 14 additions & 0 deletions tests/target/comment_trailing_lines.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// rustfmt-wrap_comments: true

//! Module comment with multiple trailing lines

/// Doc comment with multiple trailing lines
pub mod foo {}

/// Doc comment with one trailing line
pub mod bar {}

/*
* Block comment with multiple trailing lines
*/
pub mod block {}

0 comments on commit fd95d0f

Please sign in to comment.