Skip to content
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

[flake8-use-pathlib] Catch redundant joins in PTH201 and avoid syntax errors #15177

Merged
merged 2 commits into from
Dec 30, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -1,15 +1,70 @@
from pathlib import Path, PurePath
from pathlib import Path as pth


# match
_ = Path(".")
_ = pth(".")
_ = PurePath(".")
_ = Path("")

Path('', )

Path(
'',
)

Path( # Comment before argument
'',
)

Path(
'', # EOL comment
)

Path(
'' # Comment in the middle of implicitly concatenated string
".",
)

Path(
'' # Comment before comma
,
)

Path(
'',
) / "bare"

Path( # Comment before argument
'',
) / ("parenthesized")

Path(
'', # EOL comment
) / ( ("double parenthesized" ) )

( Path(
'' # Comment in the middle of implicitly concatenated string
".",
) )/ (("parenthesized path call")
# Comment between closing parentheses
)

Path(
'' # Comment before comma
,
) / "multiple" / (
"frag" # Comment
'ment'
)


# no match
_ = Path()
print(".")
Path("file.txt")
Path(".", "folder")
PurePath(".", "folder")

Path()
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -983,7 +983,7 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
flake8_use_pathlib::rules::replaceable_by_pathlib(checker, call);
}
if checker.enabled(Rule::PathConstructorCurrentDirectory) {
flake8_use_pathlib::rules::path_constructor_current_directory(checker, expr, func);
flake8_use_pathlib::rules::path_constructor_current_directory(checker, call);
}
if checker.enabled(Rule::OsSepSplit) {
flake8_use_pathlib::rules::os_sep_split(checker, call);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use std::ops::Range;

use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_ast::parenthesize::parenthesized_range;
use ruff_python_ast::{AstNode, Expr, ExprBinOp, ExprCall, ExprStringLiteral, Operator};
use ruff_text_size::{Ranged, TextRange};

use crate::checkers::ast::Checker;
use crate::fix::edits::{remove_argument, Parentheses};

/// ## What it does
/// Checks for `pathlib.Path` objects that are initialized with the current
Expand Down Expand Up @@ -43,9 +48,25 @@ impl AlwaysFixableViolation for PathConstructorCurrentDirectory {
}

/// PTH201
pub(crate) fn path_constructor_current_directory(checker: &mut Checker, expr: &Expr, func: &Expr) {
if !checker
.semantic()
pub(crate) fn path_constructor_current_directory(checker: &mut Checker, call: &ExprCall) {
let (semantic, locator, source, comment_ranges) = (
checker.semantic(),
checker.locator(),
checker.source(),
checker.comment_ranges(),
);

let applicability = |range| {
if comment_ranges.intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
}
};

let (func, arguments) = (&call.func, &call.arguments);

if !semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["pathlib", "Path" | "PurePath"])
Expand All @@ -54,21 +75,81 @@ pub(crate) fn path_constructor_current_directory(checker: &mut Checker, expr: &E
return;
}

let Expr::Call(ExprCall { arguments, .. }) = expr else {
if !arguments.keywords.is_empty() {
return;
}

let [Expr::StringLiteral(ExprStringLiteral {
value,
range: argument_range,
})] = &*arguments.args
else {
return;
};

if !arguments.keywords.is_empty() {
if !matches!(value.to_str(), "" | ".") {
return;
}

let [Expr::StringLiteral(ast::ExprStringLiteral { value, range })] = &*arguments.args else {
return;
let fix = match parent_and_next_path_fragment_range(checker) {
Some((parent_range, next_fragment_range)) => {
let next_fragment_expr = locator.slice(next_fragment_range);
let call_expr = locator.slice(call.range);

let relative_argument_range: Range<usize> = {
let range = argument_range - call.start();
range.start().into()..range.end().into()
};

let mut new_call_expr = call_expr.to_string();
new_call_expr.replace_range(relative_argument_range, next_fragment_expr);

let edit = Edit::range_replacement(new_call_expr, parent_range);

Fix::applicable_edit(edit, applicability(parent_range))
}
None => {
let Ok(edit) =
remove_argument(argument_range, arguments, Parentheses::Preserve, source)
else {
unreachable!("Cannot remove argument");
};

Fix::applicable_edit(edit, applicability(call.range))
}
};

let diagnostic = Diagnostic::new(PathConstructorCurrentDirectory, *argument_range);

checker.diagnostics.push(diagnostic.with_fix(fix));
}

fn parent_and_next_path_fragment_range(checker: &Checker) -> Option<(TextRange, TextRange)> {
let (semantic, comment_ranges, source) = (
checker.semantic(),
checker.comment_ranges(),
checker.source(),
);

let parent = semantic.current_expression_parent()?;

let Expr::BinOp(parent @ ExprBinOp { op, right, .. }) = parent else {
return None;
};

if matches!(value.to_str(), "" | ".") {
let mut diagnostic = Diagnostic::new(PathConstructorCurrentDirectory, *range);
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(*range)));
checker.diagnostics.push(diagnostic);
let original_range = right.range();

match op {
Operator::Div => {
let parenthesized_range = parenthesized_range(
right.into(),
parent.as_any_node_ref(),
comment_ranges,
source,
);

Some((parent.range, parenthesized_range.unwrap_or(original_range)))
}
_ => None,
}
}
Loading
Loading