[flake8-bandit] Check for builtins instead of builtin (S102, PTH123) (#15443)

## Summary

Resolves #15442.

## Test Plan

`cargo nextest run` and `cargo insta test`.
This commit is contained in:
InSync 2025-01-13 07:45:31 +07:00 committed by GitHub
parent d1666fbbee
commit 4f37fdeff2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 44 additions and 9 deletions

View file

@ -3,3 +3,13 @@ def fn():
exec('x = 2')
exec('y = 3')
## https://github.com/astral-sh/ruff/issues/15442
def _():
from builtins import exec
exec('') # Error
def _():
from builtin import exec
exec('') # No error

View file

@ -34,3 +34,16 @@ splitext(p)
with open(p) as fp:
fp.read()
open(p).close()
# https://github.com/astral-sh/ruff/issues/15442
def _():
from builtins import open
with open(p) as _: ... # Error
def _():
from builtin import open
with open(p) as _: ... # No error

View file

@ -33,11 +33,7 @@ impl Violation for ExecBuiltin {
/// S102
pub(crate) fn exec_used(checker: &mut Checker, func: &Expr) {
if checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["" | "builtin", "exec"]))
{
if checker.semantic().match_builtin_expr(func, "exec") {
checker
.diagnostics
.push(Diagnostic::new(ExecBuiltin, func.range()));

View file

@ -1,6 +1,5 @@
---
source: crates/ruff_linter/src/rules/flake8_bandit/mod.rs
snapshot_kind: text
---
S102.py:3:5: S102 Use of `exec` detected
|
@ -19,3 +18,13 @@ S102.py:5:1: S102 Use of `exec` detected
5 | exec('y = 3')
| ^^^^ S102
|
S102.py:11:5: S102 Use of `exec` detected
|
9 | def _():
10 | from builtins import exec
11 | exec('') # Error
| ^^^^ S102
12 |
13 | def _():
|

View file

@ -97,8 +97,8 @@ pub(crate) fn replaceable_by_pathlib(checker: &mut Checker, call: &ExprCall) {
// PTH205
["os", "path", "getctime"] => Some(OsPathGetctime.into()),
// PTH123
["" | "builtin", "open"] => {
// `closefd` and `openener` are not supported by pathlib, so check if they are
["" | "builtins", "open"] => {
// `closefd` and `opener` are not supported by pathlib, so check if they are
// are set to non-default values.
// https://github.com/astral-sh/ruff/issues/7620
// Signature as of Python 3.11 (https://docs.python.org/3/library/functions.html#open):

View file

@ -1,6 +1,5 @@
---
source: crates/ruff_linter/src/rules/flake8_use_pathlib/mod.rs
snapshot_kind: text
---
import_from.py:9:5: PTH100 `os.path.abspath()` should be replaced by `Path.resolve()`
|
@ -268,3 +267,11 @@ import_from.py:36:1: PTH123 `open()` should be replaced by `Path.open()`
36 | open(p).close()
| ^^^^ PTH123
|
import_from.py:43:10: PTH123 `open()` should be replaced by `Path.open()`
|
41 | from builtins import open
42 |
43 | with open(p) as _: ... # Error
| ^^^^ PTH123
|