mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-04 02:38:25 +00:00
Avoid auto-fixing UP031 if there are comments within the right-hand side (#6364)
This commit is contained in:
parent
1ac2699b5e
commit
501f537cb8
3 changed files with 32 additions and 5 deletions
|
@ -106,3 +106,7 @@ print('Hello %(arg)s' % bar['bop'])
|
|||
"""
|
||||
% (x,)
|
||||
)
|
||||
|
||||
"%s" % (
|
||||
x, # comment
|
||||
)
|
||||
|
|
|
@ -7,7 +7,7 @@ use ruff_python_literal::cformat::{
|
|||
use ruff_python_parser::{lexer, AsMode, Tok};
|
||||
use ruff_text_size::TextRange;
|
||||
|
||||
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_python_ast::whitespace::indentation;
|
||||
|
@ -43,14 +43,16 @@ use crate::rules::pyupgrade::helpers::curly_escape;
|
|||
#[violation]
|
||||
pub struct PrintfStringFormatting;
|
||||
|
||||
impl AlwaysAutofixableViolation for PrintfStringFormatting {
|
||||
impl Violation for PrintfStringFormatting {
|
||||
const AUTOFIX: AutofixKind = AutofixKind::Sometimes;
|
||||
|
||||
#[derive_message_formats]
|
||||
fn message(&self) -> String {
|
||||
format!("Use format specifiers instead of percent format")
|
||||
}
|
||||
|
||||
fn autofix_title(&self) -> String {
|
||||
"Replace with format specifiers".to_string()
|
||||
fn autofix_title(&self) -> Option<String> {
|
||||
Some("Replace with format specifiers".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -467,7 +469,15 @@ pub(crate) fn printf_string_formatting(
|
|||
contents.push_str(&format!(".format{params_string}"));
|
||||
|
||||
let mut diagnostic = Diagnostic::new(PrintfStringFormatting, expr.range());
|
||||
if checker.patch(diagnostic.kind.rule()) {
|
||||
// Avoid autofix if there are comments within the right-hand side:
|
||||
// ```
|
||||
// "%s" % (
|
||||
// 0, # 0
|
||||
// )
|
||||
// ```
|
||||
if checker.patch(diagnostic.kind.rule())
|
||||
&& !checker.indexer().comment_ranges().intersects(right.range())
|
||||
{
|
||||
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
|
||||
contents,
|
||||
expr.range(),
|
||||
|
|
|
@ -893,5 +893,18 @@ UP031_0.py:104:5: UP031 [*] Use format specifiers instead of percent format
|
|||
105 |+ foo {}
|
||||
106 |+ """.format(x)
|
||||
108 107 | )
|
||||
109 108 |
|
||||
110 109 | "%s" % (
|
||||
|
||||
UP031_0.py:110:1: UP031 Use format specifiers instead of percent format
|
||||
|
|
||||
108 | )
|
||||
109 |
|
||||
110 | / "%s" % (
|
||||
111 | | x, # comment
|
||||
112 | | )
|
||||
| |_^ UP031
|
||||
|
|
||||
= help: Replace with format specifiers
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue