Skip to content

Commit

Permalink
Place 'r' prefix before 'f' for raw format strings (#8464)
Browse files Browse the repository at this point in the history
## 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.
  • Loading branch information
deepyaman authored Nov 3, 2023
1 parent 7c12eaf commit f56bc19
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
13 changes: 11 additions & 2 deletions crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,15 +191,21 @@ fn try_convert_to_f_string(
summary: &mut FormatSummaryValues,
locator: &Locator,
) -> Result<Option<String>> {
let contents = locator.slice(range);

// Strip the unicode prefix. It's redundant in Python 3, and invalid when used
// with f-strings.
let contents = locator.slice(range);
let contents = if contents.starts_with('U') || contents.starts_with('u') {
&contents[1..]
} else {
contents
};

// Temporarily strip the raw prefix, if present. It will be prepended to the result, before the
// 'f', to match the prefix order both the Ruff formatter (and Black) use when formatting code.
let raw = contents.starts_with('R') || contents.starts_with('r');
let contents = if raw { &contents[1..] } else { contents };

// Remove the leading and trailing quotes.
let leading_quote = leading_quote(contents).context("Unable to identify leading quote")?;
let trailing_quote = trailing_quote(contents).context("Unable to identify trailing quote")?;
Expand Down Expand Up @@ -291,7 +297,10 @@ fn try_convert_to_f_string(
}

// Construct the format string.
let mut contents = String::with_capacity(1 + converted.len());
let mut contents = String::with_capacity(usize::from(raw) + 1 + converted.len());
if raw {
contents.push('r');
}
contents.push('f');
contents.push_str(leading_quote);
contents.push_str(&converted);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ UP032_0.py:37:1: UP032 [*] Use f-string instead of `format` call
35 35 | "foo{}".format(1)
36 36 |
37 |-r"foo{}".format(1)
37 |+fr"foo{1}"
37 |+rf"foo{1}"
38 38 |
39 39 | x = "{a}".format(a=1)
40 40 |
Expand Down

0 comments on commit f56bc19

Please sign in to comment.