Preview Style: Format module level docstring (#9725)

Co-authored-by: Micha Reiser <micha@reiser.io>
This commit is contained in:
Shaygan Hooshyari 2024-02-05 16:03:34 +01:00 committed by GitHub
parent 80fc02e7d5
commit b47f85eb69
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 30 additions and 143 deletions

View file

@ -74,3 +74,10 @@ pub(crate) const fn is_hex_codes_in_unicode_sequences_enabled(context: &PyFormat
pub(crate) const fn is_multiline_string_handling_enabled(context: &PyFormatContext) -> bool {
context.is_preview()
}
/// Returns `true` if the [`multiline_string_handling`](https://github.com/astral-sh/ruff/pull/9725) preview style is enabled.
/// Black does not [`format docstrings`](https://github.com/psf/black/issues/3493) so we keep this
/// preview for compatibility with Black.
pub(crate) const fn is_format_module_docstring_enabled(context: &PyFormatContext) -> bool {
context.is_preview()
}

View file

@ -15,7 +15,8 @@ use crate::expression::expr_string_literal::ExprStringLiteralKind;
use crate::prelude::*;
use crate::preview::{
is_blank_line_after_nested_stub_class_enabled, is_dummy_implementations_enabled,
is_module_docstring_newlines_enabled, is_no_blank_line_before_class_docstring_enabled,
is_format_module_docstring_enabled, is_module_docstring_newlines_enabled,
is_no_blank_line_before_class_docstring_enabled,
};
use crate::statement::stmt_expr::FormatStmtExpr;
use crate::verbatim::{
@ -140,7 +141,17 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
SuiteChildStatement::Other(first)
}
}
SuiteKind::TopLevel => SuiteChildStatement::Other(first),
SuiteKind::TopLevel => {
if is_format_module_docstring_enabled(f.context()) {
if let Some(docstring) = DocstringStmt::try_from_statement(first, self.kind) {
SuiteChildStatement::Docstring(docstring)
} else {
SuiteChildStatement::Other(first)
}
} else {
SuiteChildStatement::Other(first)
}
}
};
let first_comments = comments.leading_dangling_trailing(first);