mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-28 21:05:08 +00:00
Avoid hard line break after dangling open-parenthesis comments (#6380)
## Summary Given: ```python [ # comment first, second, third ] # another comment ``` We were adding a hard line break as part of the formatting of `# comment`, which led to the following formatting: ```python [first, second, third] # comment # another comment ``` Closes https://github.com/astral-sh/ruff/issues/6367.
This commit is contained in:
parent
63692b3798
commit
b763973357
6 changed files with 82 additions and 18 deletions
|
@ -227,6 +227,57 @@ impl Format<PyFormatContext<'_>> for FormatDanglingComments<'_> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Formats the dangling comments within a parenthesized expression, for example:
|
||||
/// ```python
|
||||
/// [ # comment
|
||||
/// 1,
|
||||
/// 2,
|
||||
/// 3,
|
||||
/// ]
|
||||
/// ```
|
||||
pub(crate) fn dangling_open_parenthesis_comments(
|
||||
comments: &[SourceComment],
|
||||
) -> FormatDanglingOpenParenthesisComments {
|
||||
FormatDanglingOpenParenthesisComments { comments }
|
||||
}
|
||||
|
||||
pub(crate) struct FormatDanglingOpenParenthesisComments<'a> {
|
||||
comments: &'a [SourceComment],
|
||||
}
|
||||
|
||||
impl Format<PyFormatContext<'_>> for FormatDanglingOpenParenthesisComments<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> {
|
||||
let mut comments = self
|
||||
.comments
|
||||
.iter()
|
||||
.filter(|comment| comment.is_unformatted());
|
||||
|
||||
if let Some(comment) = comments.next() {
|
||||
debug_assert!(
|
||||
comment.line_position().is_end_of_line(),
|
||||
"Expected dangling comment to be at the end of the line"
|
||||
);
|
||||
|
||||
write!(
|
||||
f,
|
||||
[line_suffix(&format_args![
|
||||
space(),
|
||||
space(),
|
||||
format_comment(comment)
|
||||
])]
|
||||
)?;
|
||||
comment.mark_formatted();
|
||||
|
||||
debug_assert!(
|
||||
comments.next().is_none(),
|
||||
"Expected at most one dangling comment"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats the content of the passed comment.
|
||||
///
|
||||
/// * Adds a whitespace between `#` and the comment text except if the first character is a `#`, `:`, `'`, or `!`
|
||||
|
|
|
@ -95,8 +95,9 @@ use std::rc::Rc;
|
|||
use ruff_python_ast::{Mod, Ranged};
|
||||
|
||||
pub(crate) use format::{
|
||||
dangling_comments, dangling_node_comments, leading_alternate_branch_comments, leading_comments,
|
||||
leading_node_comments, trailing_comments, trailing_node_comments,
|
||||
dangling_comments, dangling_node_comments, dangling_open_parenthesis_comments,
|
||||
leading_alternate_branch_comments, leading_comments, leading_node_comments, trailing_comments,
|
||||
trailing_node_comments,
|
||||
};
|
||||
use ruff_formatter::{SourceCode, SourceCodeSlice};
|
||||
use ruff_python_ast::node::AnyNodeRef;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue