Avoid auto-fixing UP032 if comments are present around format call arguments (#6342)

This commit is contained in:
Harutaka Kawamura 2023-08-05 00:37:23 +09:00 committed by GitHub
parent 9bb21283ca
commit 08dd87e04d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 6 deletions

View file

@ -198,3 +198,7 @@ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
).format(a=1)
"{}".format(**c)
"{}".format(
1 # comment
)

View file

@ -9,7 +9,7 @@ use ruff_python_parser::{lexer, Mode, Tok};
use ruff_text_size::TextRange;
use rustc_hash::FxHashMap;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::str::{leading_quote, trailing_quote};
use ruff_source_file::Locator;
@ -42,14 +42,16 @@ use crate::rules::pyupgrade::helpers::curly_escape;
#[violation]
pub struct FString;
impl AlwaysAutofixableViolation for FString {
impl Violation for FString {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("Use f-string instead of `format` call")
}
fn autofix_title(&self) -> String {
"Convert to f-string".to_string()
fn autofix_title(&self) -> Option<String> {
Some("Convert to f-string".to_string())
}
}
@ -316,7 +318,7 @@ pub(crate) fn f_strings(
return;
}
let Expr::Call(ast::ExprCall { func, .. }) = expr else {
let Expr::Call(ast::ExprCall { func, arguments, .. }) = expr else {
return;
};
@ -420,7 +422,19 @@ pub(crate) fn f_strings(
}
let mut diagnostic = Diagnostic::new(FString, expr.range());
if checker.patch(diagnostic.kind.rule()) {
// Avoid autofix if there are comments within the call:
// ```
// "{}".format(
// 0, # 0
// )
// ```
if checker.patch(diagnostic.kind.rule())
&& !checker
.indexer()
.comment_ranges()
.intersects(arguments.range())
{
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
contents,
expr.range(),

View file

@ -945,4 +945,15 @@ UP032_0.py:129:1: UP032 [*] Use f-string instead of `format` call
131 131 | ###
132 132 | # Non-errors
UP032_0.py:202:1: UP032 Use f-string instead of `format` call
|
200 | "{}".format(**c)
201 |
202 | / "{}".format(
203 | | 1 # comment
204 | | )
| |_^ UP032
|
= help: Convert to f-string