Skip to content

Commit

Permalink
Implement flake8-simplify SIM105 rule
Browse files Browse the repository at this point in the history
  • Loading branch information
messense committed Jan 4, 2023
1 parent aacfc9e commit 4ea61cc
Show file tree
Hide file tree
Showing 10 changed files with 123 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -957,6 +957,7 @@ For more, see [flake8-simplify](https://pypi.org/project/flake8-simplify/0.19.3/
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| SIM105 | UseContextlibSuppress | Use 'contextlib.suppress(..)' instead of try-except-pass | |
| SIM118 | KeyInDict | Use `key in dict` instead of `key in dict.keys()` | 🛠 |
| SIM222 | OrTrue | Use `True` instead of `... or True` | 🛠 |
| SIM223 | AndFalse | Use `False` instead of `... and False` | 🛠 |
Expand Down
24 changes: 24 additions & 0 deletions resources/test/fixtures/flake8_simplify/SIM105.py
@@ -0,0 +1,24 @@
def foo():
pass

try:
foo()
except ValueError: # SIM105
pass

try:
foo()
except (ValueError, OSError): # SIM105
pass

try:
foo()
except ValueError:
print('foo')
except OSError:
pass

try:
foo()
except:
pass
2 changes: 2 additions & 0 deletions ruff.schema.json
Expand Up @@ -895,6 +895,8 @@
"S107",
"SIM",
"SIM1",
"SIM10",
"SIM105",
"SIM11",
"SIM118",
"SIM2",
Expand Down
3 changes: 3 additions & 0 deletions src/checkers/ast.rs
Expand Up @@ -1272,6 +1272,9 @@ where
.into_iter(),
);
}
if self.settings.enabled.contains(&CheckCode::SIM105) {
flake8_simplify::plugins::use_contextlib_suppress(self, handlers, self.locator);
}
}
StmtKind::Assign { targets, value, .. } => {
if self.settings.enabled.contains(&CheckCode::E731) {
Expand Down
1 change: 1 addition & 0 deletions src/flake8_simplify/mod.rs
Expand Up @@ -12,6 +12,7 @@ mod tests {
use crate::registry::CheckCode;
use crate::settings;

#[test_case(CheckCode::SIM105, Path::new("SIM105.py"); "SIM105")]
#[test_case(CheckCode::SIM118, Path::new("SIM118.py"); "SIM118")]
#[test_case(CheckCode::SIM222, Path::new("SIM222.py"); "SIM222")]
#[test_case(CheckCode::SIM223, Path::new("SIM223.py"); "SIM223")]
Expand Down
2 changes: 2 additions & 0 deletions src/flake8_simplify/plugins/mod.rs
@@ -1,7 +1,9 @@
pub use bool_ops::{and_false, or_true};
pub use key_in_dict::{key_in_dict_compare, key_in_dict_for};
pub use use_contextlib_suppress::use_contextlib_suppress;
pub use yoda_conditions::yoda_conditions;

mod bool_ops;
mod key_in_dict;
mod use_contextlib_suppress;
mod yoda_conditions;
38 changes: 38 additions & 0 deletions src/flake8_simplify/plugins/use_contextlib_suppress.rs
@@ -0,0 +1,38 @@
use rustpython_ast::{Excepthandler, ExcepthandlerKind};

use crate::ast::helpers;
use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckKind};
use crate::source_code_locator::SourceCodeLocator;

/// SIM105
pub fn use_contextlib_suppress(
checker: &mut Checker,
handlers: &[Excepthandler],
locator: &SourceCodeLocator,
) {
if handlers.len() != 1 {
return;
}
let handler = &handlers[0];
let ExcepthandlerKind::ExceptHandler { body, .. } = &handler.node;
if body.len() == 1 {
let node = &body[0].node;
if matches!(node, rustpython_ast::StmtKind::Pass) {
let handler_names: Vec<_> = helpers::extract_handler_names(handlers)
.into_iter()
.flatten()
.collect();
let exception = if handler_names.is_empty() {
"Exception".to_string()
} else {
handler_names.join(", ")
};
let check = Check::new(
CheckKind::UseContextlibSuppress(exception),
helpers::except_range(handler, locator),
);
checker.add_check(check);
}
}
}
@@ -0,0 +1,35 @@
---
source: src/flake8_simplify/mod.rs
expression: checks
---
- kind:
UseContextlibSuppress: ValueError
location:
row: 6
column: 0
end_location:
row: 6
column: 6
fix: ~
parent: ~
- kind:
UseContextlibSuppress: "ValueError, OSError"
location:
row: 11
column: 0
end_location:
row: 11
column: 6
fix: ~
parent: ~
- kind:
UseContextlibSuppress: Exception
location:
row: 23
column: 0
end_location:
row: 23
column: 6
fix: ~
parent: ~

8 changes: 8 additions & 0 deletions src/registry.rs
Expand Up @@ -217,6 +217,7 @@ pub enum CheckCode {
YTT302,
YTT303,
// flake8-simplify
SIM105,
SIM118,
SIM222,
SIM223,
Expand Down Expand Up @@ -873,6 +874,7 @@ pub enum CheckKind {
UnaryPrefixIncrement,
UnreliableCallableCheck,
UnusedLoopControlVariable(String),
UseContextlibSuppress(String),
UselessComparison,
UselessContextlibSuppress,
UselessExpression,
Expand Down Expand Up @@ -1371,6 +1373,7 @@ impl CheckCode {
// flake8-blind-except
CheckCode::BLE001 => CheckKind::BlindExcept("Exception".to_string()),
// flake8-simplify
CheckCode::SIM105 => CheckKind::UseContextlibSuppress("..".to_string()),
CheckCode::SIM118 => CheckKind::KeyInDict("key".to_string(), "dict".to_string()),
CheckCode::SIM222 => CheckKind::OrTrue,
CheckCode::SIM223 => CheckKind::AndFalse,
Expand Down Expand Up @@ -1894,6 +1897,7 @@ impl CheckCode {
CheckCode::S106 => CheckCategory::Flake8Bandit,
CheckCode::S107 => CheckCategory::Flake8Bandit,
// flake8-simplify
CheckCode::SIM105 => CheckCategory::Flake8Simplify,
CheckCode::SIM118 => CheckCategory::Flake8Simplify,
CheckCode::SIM222 => CheckCategory::Flake8Simplify,
CheckCode::SIM223 => CheckCategory::Flake8Simplify,
Expand Down Expand Up @@ -2142,6 +2146,7 @@ impl CheckKind {
CheckKind::SysVersionCmpStr10 => &CheckCode::YTT302,
CheckKind::SysVersionSlice1Referenced => &CheckCode::YTT303,
// flake8-simplify
CheckKind::UseContextlibSuppress(..) => &CheckCode::SIM105,
CheckKind::KeyInDict(..) => &CheckCode::SIM118,
CheckKind::OrTrue => &CheckCode::SIM222,
CheckKind::AndFalse => &CheckCode::SIM223,
Expand Down Expand Up @@ -2652,6 +2657,9 @@ impl CheckKind {
CheckKind::FStringDocstring => "f-string used as docstring. This will be interpreted \
by python as a joined string rather than a docstring."
.to_string(),
CheckKind::UseContextlibSuppress(exception) => {
format!("Use 'contextlib.suppress({exception})' instead of try-except-pass")
}
CheckKind::UselessContextlibSuppress => {
"No arguments passed to `contextlib.suppress`. No exceptions will be suppressed \
and therefore this context manager is redundant"
Expand Down
10 changes: 9 additions & 1 deletion src/registry_gen.rs
Expand Up @@ -515,6 +515,8 @@ pub enum CheckCodePrefix {
S107,
SIM,
SIM1,
SIM10,
SIM105,
SIM11,
SIM118,
SIM2,
Expand Down Expand Up @@ -798,6 +800,7 @@ impl CheckCodePrefix {
CheckCode::YTT301,
CheckCode::YTT302,
CheckCode::YTT303,
CheckCode::SIM105,
CheckCode::SIM118,
CheckCode::SIM222,
CheckCode::SIM223,
Expand Down Expand Up @@ -2606,12 +2609,15 @@ impl CheckCodePrefix {
CheckCodePrefix::S106 => vec![CheckCode::S106],
CheckCodePrefix::S107 => vec![CheckCode::S107],
CheckCodePrefix::SIM => vec![
CheckCode::SIM105,
CheckCode::SIM118,
CheckCode::SIM222,
CheckCode::SIM223,
CheckCode::SIM300,
],
CheckCodePrefix::SIM1 => vec![CheckCode::SIM118],
CheckCodePrefix::SIM1 => vec![CheckCode::SIM105, CheckCode::SIM118],
CheckCodePrefix::SIM10 => vec![CheckCode::SIM105],
CheckCodePrefix::SIM105 => vec![CheckCode::SIM105],
CheckCodePrefix::SIM11 => vec![CheckCode::SIM118],
CheckCodePrefix::SIM118 => vec![CheckCode::SIM118],
CheckCodePrefix::SIM2 => vec![CheckCode::SIM222, CheckCode::SIM223],
Expand Down Expand Up @@ -3557,6 +3563,8 @@ impl CheckCodePrefix {
CheckCodePrefix::S107 => SuffixLength::Three,
CheckCodePrefix::SIM => SuffixLength::Zero,
CheckCodePrefix::SIM1 => SuffixLength::One,
CheckCodePrefix::SIM10 => SuffixLength::Two,
CheckCodePrefix::SIM105 => SuffixLength::Three,
CheckCodePrefix::SIM11 => SuffixLength::Two,
CheckCodePrefix::SIM118 => SuffixLength::Three,
CheckCodePrefix::SIM2 => SuffixLength::One,
Expand Down

0 comments on commit 4ea61cc

Please sign in to comment.