mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-27 18:36:23 +00:00
[SIM115] Allow open followed by close (#7916)
This commit is contained in:
parent
7a072cc2ea
commit
f670f9b22c
2 changed files with 33 additions and 0 deletions
|
|
@ -127,12 +127,41 @@ fn is_open(checker: &mut Checker, func: &Expr) -> bool {
|
|||
}
|
||||
}
|
||||
|
||||
/// Return `true` if the current expression is followed by a `close` call.
|
||||
fn is_closed(semantic: &SemanticModel) -> bool {
|
||||
let Some(expr) = semantic.current_expression_grandparent() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let Expr::Call(ast::ExprCall {
|
||||
func, arguments, ..
|
||||
}) = expr
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if !arguments.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
attr.as_str() == "close"
|
||||
}
|
||||
|
||||
/// SIM115
|
||||
pub(crate) fn open_file_with_context_handler(checker: &mut Checker, func: &Expr) {
|
||||
if !is_open(checker, func) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ex) `open("foo.txt").close()`
|
||||
if is_closed(checker.semantic()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ex) `with open("foo.txt") as f: ...`
|
||||
if checker.semantic().current_statement().is_with_stmt() {
|
||||
return;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue