Skip to content

Commit f56bc19

Browse files
authored
Place 'r' prefix before 'f' for raw format strings (#8464)
## Summary Currently, `UP032` applied to raw strings results in format strings with the prefix 'fr'. This gets changed to 'rf' by Ruff format (or Black). In order to avoid that, this PR uses the prefix 'rf' to begin with. ## Test Plan Updated the expectation on an existing test.
1 parent 7c12eaf commit f56bc19

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -191,15 +191,21 @@ fn try_convert_to_f_string(
191191
summary: &mut FormatSummaryValues,
192192
locator: &Locator,
193193
) -> Result<Option<String>> {
194+
let contents = locator.slice(range);
195+
194196
// Strip the unicode prefix. It's redundant in Python 3, and invalid when used
195197
// with f-strings.
196-
let contents = locator.slice(range);
197198
let contents = if contents.starts_with('U') || contents.starts_with('u') {
198199
&contents[1..]
199200
} else {
200201
contents
201202
};
202203

204+
// Temporarily strip the raw prefix, if present. It will be prepended to the result, before the
205+
// 'f', to match the prefix order both the Ruff formatter (and Black) use when formatting code.
206+
let raw = contents.starts_with('R') || contents.starts_with('r');
207+
let contents = if raw { &contents[1..] } else { contents };
208+
203209
// Remove the leading and trailing quotes.
204210
let leading_quote = leading_quote(contents).context("Unable to identify leading quote")?;
205211
let trailing_quote = trailing_quote(contents).context("Unable to identify trailing quote")?;
@@ -291,7 +297,10 @@ fn try_convert_to_f_string(
291297
}
292298

293299
// Construct the format string.
294-
let mut contents = String::with_capacity(1 + converted.len());
300+
let mut contents = String::with_capacity(usize::from(raw) + 1 + converted.len());
301+
if raw {
302+
contents.push('r');
303+
}
295304
contents.push('f');
296305
contents.push_str(leading_quote);
297306
contents.push_str(&converted);

crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP032_0.py.snap

+1-1
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ UP032_0.py:37:1: UP032 [*] Use f-string instead of `format` call
353353
35 35 | "foo{}".format(1)
354354
36 36 |
355355
37 |-r"foo{}".format(1)
356-
37 |+fr"foo{1}"
356+
37 |+rf"foo{1}"
357357
38 38 |
358358
39 39 | x = "{a}".format(a=1)
359359
40 40 |

0 commit comments

Comments
 (0)