Skip to content

Commit

Permalink
Insert necessary padding in B014 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Sep 28, 2023
1 parent 9611f81 commit 66a45f2
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
Expand Up @@ -76,8 +76,15 @@ class MyError(Exception):
pass


# https://github.com/astral-sh/ruff/issues/6412
# Regression test for: https://github.com/astral-sh/ruff/issues/6412
try:
pass
except (ValueError, ValueError, TypeError):
pass


# Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739801758
try:
pas
except(re.error, re.error):
p
Expand Up @@ -10,6 +10,7 @@ use ruff_python_ast::call_path;
use ruff_python_ast::call_path::CallPath;

use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::registry::{AsRule, Rule};

/// ## What it does
Expand Down Expand Up @@ -112,6 +113,7 @@ fn type_pattern(elts: Vec<&Expr>) -> Expr {
.into()
}

/// B014
fn duplicate_handler_exceptions<'a>(
checker: &mut Checker,
expr: &'a Expr,
Expand Down Expand Up @@ -146,8 +148,14 @@ fn duplicate_handler_exceptions<'a>(
);
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(Fix::automatic(Edit::range_replacement(
if unique_elts.len() == 1 {
checker.generator().expr(unique_elts[0])
// Single exceptions don't require parentheses, but since we're _removing_
// parentheses, insert whitespace as needed.
if let [elt] = unique_elts.as_slice() {
pad(
checker.generator().expr(elt),
expr.range(),
checker.locator(),
)
} else {
// Multiple exceptions must always be parenthesized. This is done
// manually as the generator never parenthesizes lone tuples.
Expand All @@ -163,6 +171,7 @@ fn duplicate_handler_exceptions<'a>(
seen
}

/// B025
pub(crate) fn duplicate_exceptions(checker: &mut Checker, handlers: &[ExceptHandler]) {
let mut seen: FxHashSet<CallPath> = FxHashSet::default();
let mut duplicates: FxHashMap<CallPath, Vec<&Expr>> = FxHashMap::default();
Expand Down
Expand Up @@ -75,11 +75,31 @@ B014.py:82:8: B014 [*] Exception handler with duplicate exception: `ValueError`
= help: De-duplicate exceptions

Fix
79 79 | # https://github.com/astral-sh/ruff/issues/6412
79 79 | # Regression test for: https://github.com/astral-sh/ruff/issues/6412
80 80 | try:
81 81 | pass
82 |-except (ValueError, ValueError, TypeError):
82 |+except (ValueError, TypeError):
83 83 | pass
84 84 |
85 85 |

B014.py:89:7: B014 [*] Exception handler with duplicate exception: `re.error`
|
87 | try:
88 | pas
89 | except(re.error, re.error):
| ^^^^^^^^^^^^^^^^^^^^ B014
90 | p
|
= help: De-duplicate exceptions

Fix
86 86 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739801758
87 87 | try:
88 88 | pas
89 |-except(re.error, re.error):
89 |+except re.error:
90 90 | p


0 comments on commit 66a45f2

Please sign in to comment.