From 0489bbc54ced7edae1bff606e3cae024a53bb77c Mon Sep 17 00:00:00 2001 From: Chris Pryer <14341145+cnpryer@users.noreply.github.com> Date: Fri, 1 Sep 2023 08:52:59 -0400 Subject: [PATCH] Match Black's formatting of trailing comments containing NBSP (#7030) --- .../src/comments/format.rs | 19 ++++++++++--------- .../format@trailing_comments.py.snap | 4 ++-- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/crates/ruff_python_formatter/src/comments/format.rs b/crates/ruff_python_formatter/src/comments/format.rs index e682924284d56..6a6cb33768e16 100644 --- a/crates/ruff_python_formatter/src/comments/format.rs +++ b/crates/ruff_python_formatter/src/comments/format.rs @@ -474,18 +474,19 @@ fn normalize_comment<'a>( if content.starts_with('\u{A0}') { let trimmed = content.trim_start_matches('\u{A0}'); - // Black adds a space before the non-breaking space if part of a type pragma. if trimmed.trim_start().starts_with("type:") { - return Ok(Cow::Owned(std::format!("# \u{A0}{trimmed}"))); - } - - // Black replaces the non-breaking space with a space if followed by a space. - if trimmed.starts_with(' ') { - return Ok(Cow::Owned(std::format!("# {trimmed}"))); + // Black adds a space before the non-breaking space if part of a type pragma. + Ok(Cow::Owned(std::format!("# {content}"))) + } else if trimmed.starts_with(' ') { + // Black replaces the non-breaking space with a space if followed by a space. + Ok(Cow::Owned(std::format!("# {trimmed}"))) + } else { + // Otherwise we replace the first non-breaking space with a regular space. + Ok(Cow::Owned(std::format!("# {}", &content["\u{A0}".len()..]))) } + } else { + Ok(Cow::Owned(std::format!("# {}", content.trim_start()))) } - - Ok(Cow::Owned(std::format!("# {}", content.trim_start()))) } /// A helper for stripping '#' from comments. diff --git a/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap index 982bb00711926..7e6a4bdc161e4 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@trailing_comments.py.snap @@ -65,11 +65,11 @@ i = "" #   type: Add space before leading NBSP followed by spaces i = "" # type: A space is added i = "" #   type: Add space before leading NBSP followed by a space i = "" #  type: Add space before leading NBSP -i = "" #  type: Add space before two leading NBSP +i = "" #   type: Add space before two leading NBSP # A noqa as `#\u{A0}\u{A0}noqa` becomes `# \u{A0}noqa` -i = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # noqa +i = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" #  noqa ```