From 644011fb14b1fb9db2b237db7dbb531f7789dbd4 Mon Sep 17 00:00:00 2001 From: konsti Date: Wed, 11 Oct 2023 13:30:34 +0200 Subject: [PATCH] Formatter quoting for f-strings with triple quotes (#7826) **Summary** Quoting of f-strings can change if they are triple quoted and only contain single quotes inside. Fixes #6841 **Test Plan** New fixtures --------- Co-authored-by: Dhruv Manilawala --- .../test/fixtures/ruff/expression/fstring.py | 5 +++++ crates/ruff_python_formatter/src/expression/string.rs | 11 ++++++++++- .../snapshots/format@expression__fstring.py.snap | 10 ++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py index f808f11e94..017d243f1f 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py @@ -57,3 +57,8 @@ result_f = ( ), 2 ) + +# https://github.com/astral-sh/ruff/issues/6841 +x = f'''a{""}b''' +y = f'''c{1}d"""e''' +z = f'''a{""}b''' f'''c{1}d"""e''' diff --git a/crates/ruff_python_formatter/src/expression/string.rs b/crates/ruff_python_formatter/src/expression/string.rs index b7078459cf..7e0b0cb06b 100644 --- a/crates/ruff_python_formatter/src/expression/string.rs +++ b/crates/ruff_python_formatter/src/expression/string.rs @@ -48,10 +48,19 @@ impl<'a> AnyString<'a> { match self { Self::Constant(_) => Quoting::CanChange, Self::FString(f_string) => { + let unprefixed = locator + .slice(f_string.range) + .trim_start_matches(|c| c != '"' && c != '\''); + let triple_quoted = + unprefixed.starts_with(r#"""""#) || unprefixed.starts_with(r#"'''"#); if f_string.values.iter().any(|value| match value { Expr::FormattedValue(ast::ExprFormattedValue { range, .. }) => { let string_content = locator.slice(*range); - string_content.contains(['"', '\'']) + if triple_quoted { + string_content.contains(r#"""""#) || string_content.contains("'''") + } else { + string_content.contains(['"', '\'']) + } } _ => false, }) { diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap index 37fa5a5e40..5d39862c2d 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap @@ -63,6 +63,11 @@ result_f = ( ), 2 ) + +# https://github.com/astral-sh/ruff/issues/6841 +x = f'''a{""}b''' +y = f'''c{1}d"""e''' +z = f'''a{""}b''' f'''c{1}d"""e''' ``` ## Output @@ -124,6 +129,11 @@ result_f = ( ), 2, ) + +# https://github.com/astral-sh/ruff/issues/6841 +x = f"""a{""}b""" +y = f'''c{1}d"""e''' +z = f"""a{""}b""" f'''c{1}d"""e''' ```