mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-18 17:41:12 +00:00

## Summary Builds on #6170 to break `global` and `nonlocal` statements, such that we get: ```python def f(): global \ analyze_featuremap_layer, \ analyze_featuremapcompression_layer, \ analyze_latencies_post, \ analyze_motions_layer, \ analyze_size_model ``` Instead of: ```python def f(): global analyze_featuremap_layer, analyze_featuremapcompression_layer, analyze_latencies_post, analyze_motions_layer, analyze_size_model ``` Notably, we avoid applying this formatting if the statement ends in a comment. Otherwise, the comment would _need_ to be placed after the last item, like: ```python def f(): global \ analyze_featuremap_layer, \ analyze_featuremapcompression_layer, \ analyze_latencies_post, \ analyze_motions_layer, \ analyze_size_model # noqa ``` To me, this seems wrong (and would break the `# noqa` comment). Ideally, the items would be parenthesized, and the comment would be on the inner parenthesis, like: ```python def f(): global ( # noqa analyze_featuremap_layer, analyze_featuremapcompression_layer, analyze_latencies_post, analyze_motions_layer, analyze_size_model ) ``` But that's not valid syntax.
53 lines
1.7 KiB
Rust
53 lines
1.7 KiB
Rust
use ruff_formatter::{format_args, write};
|
|
use ruff_python_ast::node::AstNode;
|
|
use ruff_python_ast::StmtGlobal;
|
|
|
|
use crate::prelude::*;
|
|
use crate::FormatNodeRule;
|
|
|
|
#[derive(Default)]
|
|
pub struct FormatStmtGlobal;
|
|
|
|
impl FormatNodeRule<StmtGlobal> for FormatStmtGlobal {
|
|
fn fmt_fields(&self, item: &StmtGlobal, f: &mut PyFormatter) -> FormatResult<()> {
|
|
// Join the `global` names, breaking across continuation lines if necessary, unless the
|
|
// `global` statement has a trailing comment, in which case, breaking the names would
|
|
// move the comment "off" of the `global` statement.
|
|
if f.context()
|
|
.comments()
|
|
.has_trailing_comments(item.as_any_node_ref())
|
|
{
|
|
let joined = format_with(|f| {
|
|
f.join_with(format_args![text(","), space()])
|
|
.entries(item.names.iter().formatted())
|
|
.finish()
|
|
});
|
|
|
|
write!(f, [text("global"), space(), &joined])
|
|
} else {
|
|
let joined = format_with(|f| {
|
|
f.join_with(&format_args![
|
|
text(","),
|
|
space(),
|
|
if_group_breaks(&text("\\")),
|
|
soft_line_break(),
|
|
])
|
|
.entries(item.names.iter().formatted())
|
|
.finish()
|
|
});
|
|
|
|
write!(
|
|
f,
|
|
[
|
|
text("global"),
|
|
space(),
|
|
&group(&format_args!(
|
|
if_group_breaks(&text("\\")),
|
|
soft_line_break(),
|
|
&soft_block_indent(&joined)
|
|
))
|
|
]
|
|
)
|
|
}
|
|
}
|
|
}
|