Skip to content

Commit

Permalink
Keep trailing newline in module level docstring
Browse files Browse the repository at this point in the history
  • Loading branch information
Glyphack committed Jan 31, 2024
1 parent 2501c76 commit 52d01bd
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 491 deletions.
4 changes: 3 additions & 1 deletion crates/ruff_python_formatter/src/other/string_literal.rs
@@ -1,6 +1,7 @@
use ruff_python_ast::StringLiteral;
use ruff_text_size::Ranged;

use crate::context::NodeLevel;
use crate::prelude::*;
use crate::preview::is_hex_codes_in_unicode_sequences_enabled;
use crate::string::{docstring, Quoting, StringPart};
Expand Down Expand Up @@ -66,7 +67,8 @@ impl Format<PyFormatContext<'_>> for FormatStringLiteral<'_> {
);

if self.layout.is_docstring() {
docstring::format(&normalized, f)
let is_top_level = matches!(f.context().node_level(), NodeLevel::TopLevel(_));
docstring::format(&normalized, f, is_top_level)
} else {
normalized.fmt(f)
}
Expand Down
17 changes: 16 additions & 1 deletion crates/ruff_python_formatter/src/string/docstring.rs
Expand Up @@ -5,6 +5,7 @@
use std::{borrow::Cow, collections::VecDeque};

use ruff_python_parser::ParseError;
use ruff_source_file::NewlineWithTrailingNewline;
use {once_cell::sync::Lazy, regex::Regex};
use {
ruff_formatter::{write, FormatOptions, IndentStyle, LineWidth, Printed},
Expand Down Expand Up @@ -102,7 +103,11 @@ use super::{NormalizedString, QuoteChar};
/// line c
/// """
/// ```
pub(crate) fn format(normalized: &NormalizedString, f: &mut PyFormatter) -> FormatResult<()> {
pub(crate) fn format(
normalized: &NormalizedString,
f: &mut PyFormatter,
is_module: bool,
) -> FormatResult<()> {
let docstring = &normalized.text;

// Black doesn't change the indentation of docstrings that contain an escaped newline
Expand Down Expand Up @@ -201,6 +206,16 @@ pub(crate) fn format(normalized: &NormalizedString, f: &mut PyFormatter) -> Form
let trim_end = docstring
.as_ref()
.trim_end_matches(|c: char| c.is_whitespace() && c != '\n');

// When there is a trailing newline, we want to keep it for module docstrings
if ({
let ref this = trim_end;
this.ends_with(&['\r', '\n'][..])
}) && is_module
{
hard_line_break().fmt(f)?;
}

if needs_chaperone_space(normalized, trim_end) {
space().fmt(f)?;
}
Expand Down

This file was deleted.

0 comments on commit 52d01bd

Please sign in to comment.