Fix \r and \r\n handling in t- and f-string debug texts (#18673)

This commit is contained in:
Micha Reiser 2025-06-15 07:53:06 +02:00 committed by GitHub
parent 5e02d839d5
commit 8237d4670c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 79 additions and 4 deletions

View file

@ -196,6 +196,24 @@ impl Transformer for Normalizer {
transformer::walk_expr(self, expr);
}
fn visit_interpolated_string_element(
&self,
interpolated_string_element: &mut InterpolatedStringElement,
) {
let InterpolatedStringElement::Interpolation(interpolation) = interpolated_string_element
else {
return;
};
let Some(debug) = &mut interpolation.debug_text else {
return;
};
// Changing the newlines to the configured newline is okay because Python normalizes all newlines to `\n`
debug.leading = debug.leading.replace("\r\n", "\n").replace('\r', "\n");
debug.trailing = debug.trailing.replace("\r\n", "\n").replace('\r', "\n");
}
fn visit_string_literal(&self, string_literal: &mut ast::StringLiteral) {
static STRIP_DOC_TESTS: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(

View file

@ -0,0 +1,27 @@
---
source: crates/ruff_python_formatter/tests/fixtures.rs
input_file: crates/ruff_python_formatter/resources/test/fixtures/ruff/f-string-carriage-return-newline.py
---
## Input
```python
# Regression test for https://github.com/astral-sh/ruff/issues/18667
f"{
1=
}"
t"{
1=
}"
```
## Output
```python
# Regression test for https://github.com/astral-sh/ruff/issues/18667
f"{
1=
}"
t"{
1=
}"
```