Skip to content

[pyupgrade] Better messages and diagnostic range (UP015) #15872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions crates/ruff_linter/src/rules/pyupgrade/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,25 @@ mod tests {
Ok(())
}

#[test_case(Rule::RedundantOpenModes, Path::new("UP015.py"))]
#[test_case(Rule::RedundantOpenModes, Path::new("UP015_1.py"))]
fn preview_rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"preview__{}_{}",
rule_code.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_messages!(snapshot, diagnostics);
Ok(())
}

#[test]
fn up007_preview() -> Result<()> {
let diagnostics = test_path(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ use anyhow::Result;
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_codegen::Stylist;
use ruff_python_parser::{TokenKind, Tokens};
use ruff_python_stdlib::open_mode::OpenMode;
use ruff_text_size::{Ranged, TextSize};

use crate::checkers::ast::Checker;

/// ## What it does
/// Checks for redundant `open` mode parameters.
/// Checks for redundant `open` mode arguments.
///
/// ## Why is this bad?
/// Redundant `open` mode parameters are unnecessary and should be removed to
/// Redundant `open` mode arguments are unnecessary and should be removed to
/// avoid confusion.
///
/// ## Example
Expand All @@ -40,18 +39,18 @@ impl AlwaysFixableViolation for RedundantOpenModes {
fn message(&self) -> String {
let RedundantOpenModes { replacement } = self;
if replacement.is_empty() {
"Unnecessary open mode parameters".to_string()
"Unnecessary mode argument".to_string()
} else {
format!("Unnecessary open mode parameters, use \"{replacement}\"")
format!("Unnecessary modes, use `{replacement}`")
}
}

fn fix_title(&self) -> String {
let RedundantOpenModes { replacement } = self;
if replacement.is_empty() {
"Remove open mode parameters".to_string()
"Remove mode argument".to_string()
} else {
format!("Replace with \"{replacement}\"")
format!("Replace with `{replacement}`")
}
}
}
Expand All @@ -71,68 +70,71 @@ pub(crate) fn redundant_open_modes(checker: &mut Checker, call: &ast::ExprCall)
return;
}

let Some(mode_param) = call.arguments.find_argument_value("mode", 1) else {
let Some(mode_arg) = call.arguments.find_argument_value("mode", 1) else {
return;
};
let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &mode_param else {
let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &mode_arg else {
return;
};
let Ok(mode) = OpenMode::from_chars(value.chars()) else {
return;
};
let reduced = mode.reduce();
if reduced != mode {
checker.diagnostics.push(create_diagnostic(
call,
mode_param,
reduced,
checker.tokens(),
checker.stylist(),
));
checker
.diagnostics
.push(create_diagnostic(call, mode_arg, reduced, checker));
}
}

fn create_diagnostic(
call: &ast::ExprCall,
mode_param: &Expr,
mode_arg: &Expr,
mode: OpenMode,
tokens: &Tokens,
stylist: &Stylist,
checker: &Checker,
) -> Diagnostic {
let range = if checker.settings.preview.is_enabled() {
mode_arg.range()
} else {
call.range
};

let mut diagnostic = Diagnostic::new(
RedundantOpenModes {
replacement: mode.to_string(),
},
call.range(),
range,
);

if mode.is_empty() {
diagnostic
.try_set_fix(|| create_remove_param_fix(call, mode_param, tokens).map(Fix::safe_edit));
diagnostic.try_set_fix(|| {
create_remove_argument_fix(call, mode_arg, checker.tokens()).map(Fix::safe_edit)
});
} else {
let stylist = checker.stylist();
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
format!("{}{mode}{}", stylist.quote(), stylist.quote()),
mode_param.range(),
mode_arg.range(),
)));
}

diagnostic
}

fn create_remove_param_fix(
fn create_remove_argument_fix(
call: &ast::ExprCall,
mode_param: &Expr,
mode_arg: &Expr,
tokens: &Tokens,
) -> Result<Edit> {
// Find the last comma before mode_param and create a deletion fix
// starting from the comma and ending after mode_param.
// Find the last comma before mode_arg and create a deletion fix
// starting from the comma and ending after mode_arg.
let mut fix_start: Option<TextSize> = None;
let mut fix_end: Option<TextSize> = None;
let mut is_first_arg: bool = false;
let mut delete_first_arg: bool = false;

for token in tokens.in_range(call.range()) {
if token.start() == mode_param.start() {
if token.start() == mode_arg.start() {
if is_first_arg {
delete_first_arg = true;
continue;
Expand Down
Loading
Loading