Fix handling of newlines in empty files (#7473)

This commit is contained in:
Micha Reiser 2023-09-18 08:08:10 +02:00 committed by GitHub
parent b66bfa6570
commit 0346e781d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 90 additions and 15 deletions

View file

@ -1,5 +1,6 @@
use ruff_formatter::write;
use ruff_python_ast::ModModule;
use ruff_python_trivia::lines_after;
use crate::comments::SourceComment;
use crate::prelude::*;
@ -11,16 +12,27 @@ pub struct FormatModModule;
impl FormatNodeRule<ModModule> for FormatModModule {
fn fmt_fields(&self, item: &ModModule, f: &mut PyFormatter) -> FormatResult<()> {
let ModModule { range: _, body } = item;
let ModModule { range, body } = item;
write!(
f,
[
body.format().with_options(SuiteKind::TopLevel),
// Trailing newline at the end of the file
hard_line_break()
]
)
if body.is_empty() {
// Only preserve an empty line if the source contains an empty line too.
if !f.context().comments().has_leading(item)
&& lines_after(range.end(), f.context().source()) != 0
{
empty_line().fmt(f)
} else {
Ok(())
}
} else {
write!(
f,
[
body.format().with_options(SuiteKind::TopLevel),
// Trailing newline at the end of the file
hard_line_break()
]
)
}
}
fn fmt_dangling_comments(