diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index f075ab456e9ba..29c9fd8cf6b8f 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -56,33 +56,35 @@ prior to merging. There are four phases to adding a new lint rule: -1. Define the rule in `src/registry.rs`. -2. Define the _logic_ for triggering the rule in `src/checkers/ast.rs` (for AST-based checks), +1. Define the violation in `src/violations.rs` (e.g., `ModuleImportNotAtTopOfFile`). +2. Map the violation to a code in `src/registry.rs` (e.g., `E402`). +3. Define the _logic_ for triggering the violation in `src/checkers/ast.rs` (for AST-based checks), `src/checkers/tokens.rs` (for token-based checks), or `src/checkers/lines.rs` (for text-based checks). -3. Add a test fixture. -4. Update the generated files (documentation and generated code). +4. Add a test fixture. +5. Update the generated files (documentation and generated code). -To define the rule, open up `src/registry.rs`. You'll need to define both a `CheckCode` and -`CheckKind`. As an example, you can grep for `E402` and `ModuleImportNotAtTopOfFile`, and follow the -pattern implemented therein. +To define the violation, open up `src/violations.rs`, and define a new struct using the +`define_violation!` macro. There are plenty of examples in that file, so feel free to pattern-match +against the existing structs. -To trigger the rule, you'll likely want to augment the logic in `src/checkers/ast.rs`, which defines -the Python AST visitor, responsible for iterating over the abstract syntax tree and collecting -lint-rule violations as it goes. If you need to inspect the AST, you can run -`cargo +nightly dev print-ast` with a Python file. Grep for the `Check::new` invocations to -understand how other, similar rules are implemented. +To trigger the violation, you'll likely want to augment the logic in `src/checkers/ast.rs`, which +defines the Python AST visitor, responsible for iterating over the abstract syntax tree and +collecting diagnostics as it goes. + +If you need to inspect the AST, you can run `cargo +nightly dev print-ast` with a Python file. Grep +for the `Check::new` invocations to understand how other, similar rules are implemented. To add a test fixture, create a file under `resources/test/fixtures/[plugin-name]`, named to match -the `CheckCode` you defined earlier (e.g., `E402.py`). This file should contain a variety of +the code you defined earlier (e.g., `E402.py`). This file should contain a variety of violations and non-violations designed to evaluate and demonstrate the behavior of your lint rule. Run `cargo +nightly dev generate-all` to generate the code for your new fixture. Then run Ruff locally with (e.g.) `cargo run resources/test/fixtures/pycodestyle/E402.py --no-cache --select E402`. Once you're satisfied with the output, codify the behavior as a snapshot test by adding a new -`test_case` macro in the relevant `src/[plugin-name]/mod.rs` file. Then, run `cargo test`. Your -test will fail, but you'll be prompted to follow-up with `cargo insta review`. Accept the generated -snapshot, then commit the snapshot file alongside the rest of your changes. +`test_case` macro in the relevant `src/[plugin-name]/mod.rs` file. Then, run `cargo test --all`. +Your test will fail, but you'll be prompted to follow-up with `cargo insta review`. Accept the +generated snapshot, then commit the snapshot file alongside the rest of your changes. Finally, regenerate the documentation and generated code with `cargo +nightly dev generate-all`. diff --git a/README.md b/README.md index 27177d666787c..587df1f57ecba 100644 --- a/README.md +++ b/README.md @@ -919,7 +919,7 @@ For more, see [flake8-pytest-style](https://pypi.org/project/flake8-pytest-style | PT006 | ParametrizeNamesWrongType | Wrong name(s) type in `@pytest.mark.parametrize`, expected `tuple` | 🛠 | | PT007 | ParametrizeValuesWrongType | Wrong values type in `@pytest.mark.parametrize` expected `list` of `tuple` | | | PT008 | PatchWithLambda | Use `return_value=` instead of patching with `lambda` | | -| PT009 | UnittestAssertion | Use a regular `assert` instead of unittest-style `...` | | +| PT009 | UnittestAssertion | Use a regular `assert` instead of unittest-style `...` | 🛠 | | PT010 | RaisesWithoutException | set the expected exception in `pytest.raises()` | | | PT011 | RaisesTooBroad | `pytest.raises(...)` is too broad, set the `match` parameter or use a more specific exception | | | PT012 | RaisesWithMultipleStatements | `pytest.raises()` block should contain a single simple statement | | @@ -985,7 +985,7 @@ For more, see [flake8-simplify](https://pypi.org/project/flake8-simplify/0.19.3/ | SIM208 | DoubleNegation | Use `expr` instead of `not (not expr)` | 🛠 | | SIM210 | IfExprWithTrueFalse | Use `bool(expr)` instead of `True if expr else False` | 🛠 | | SIM211 | IfExprWithFalseTrue | Use `not expr` instead of `False if expr else True` | 🛠 | -| SIM212 | IfExprWithTwistedArms | Use `expr2 if expr2 else expr1` instead of `expr1 if not expr2 else expr2` | 🛠 | +| SIM212 | IfExprWithTwistedArms | Use `body if body else else` instead of `else if not body else body` | 🛠 | | SIM220 | AAndNotA | Use `False` instead of `... and not ...` | 🛠 | | SIM221 | AOrNotA | Use `True` instead of `... or not ...` | 🛠 | | SIM222 | OrTrue | Use `True` instead of `... or True` | 🛠 | diff --git a/resources/test/fixtures/flake8_pytest_style/PT009.py b/resources/test/fixtures/flake8_pytest_style/PT009.py index 0b02f989aa403..e99d8e06a84ff 100644 --- a/resources/test/fixtures/flake8_pytest_style/PT009.py +++ b/resources/test/fixtures/flake8_pytest_style/PT009.py @@ -1,9 +1,76 @@ -import pytest +import unittest -def test_xxx(): - assert 1 == 1 # OK no parameters +class Test(unittest.TestCase): + def test_xxx(self): + assert 1 == 1 # OK no parameters + def test_assert_true(self): + expr = 1 + msg = "Must be True" + self.assertTrue(expr) # Error + self.assertTrue(expr=expr) # Error + self.assertTrue(expr, msg) # Error + self.assertTrue(expr=expr, msg=msg) # Error + self.assertTrue(msg=msg, expr=expr) # Error + self.assertTrue(*(expr, msg)) # Error, unfixable + self.assertTrue(**{"expr": expr, "msg": msg}) # Error, unfixable + self.assertTrue(msg=msg, expr=expr, unexpected_arg=False) # Error, unfixable + self.assertTrue(msg=msg) # Error, unfixable -def test_xxx(): - self.assertEqual(1, 1) # Error + def test_assert_false(self): + self.assertFalse(True) # Error + + def test_assert_equal(self): + self.assertEqual(1, 2) # Error + + def test_assert_not_equal(self): + self.assertNotEqual(1, 1) # Error + + def test_assert_greater(self): + self.assertGreater(1, 2) # Error + + def test_assert_greater_equal(self): + self.assertGreaterEqual(1, 2) # Error + + def test_assert_less(self): + self.assertLess(2, 1) # Error + + def test_assert_less_equal(self): + self.assertLessEqual(1, 2) # Error + + def test_assert_in(self): + self.assertIn(1, [2, 3]) # Error + + def test_assert_not_in(self): + self.assertNotIn(2, [2, 3]) # Error + + def test_assert_is_none(self): + self.assertIsNone(0) # Error + + def test_assert_is_not_none(self): + self.assertIsNotNone(0) # Error + + def test_assert_is(self): + self.assertIs([], []) # Error + + def test_assert_is_not(self): + self.assertIsNot(1, 1) # Error + + def test_assert_is_instance(self): + self.assertIsInstance(1, str) # Error + + def test_assert_is_not_instance(self): + self.assertNotIsInstance(1, int) # Error + + def test_assert_regex(self): + self.assertRegex("abc", r"def") # Error + + def test_assert_not_regex(self): + self.assertNotRegex("abc", r"abc") # Error + + def test_assert_regexp_matches(self): + self.assertRegexpMatches("abc", r"def") # Error + + def test_assert_not_regexp_matches(self): + self.assertNotRegex("abc", r"abc") # Error diff --git a/resources/test/fixtures/isort/split.py b/resources/test/fixtures/isort/split.py index 7554a90b8d499..acdc032fe5203 100644 --- a/resources/test/fixtures/isort/split.py +++ b/resources/test/fixtures/isort/split.py @@ -3,7 +3,10 @@ # isort: split -import a -import b import c import d + +# isort: split + +import a +import b diff --git a/src/checkers/ast.rs b/src/checkers/ast.rs index 54583eff93e70..bd342d70ea9e7 100644 --- a/src/checkers/ast.rs +++ b/src/checkers/ast.rs @@ -30,7 +30,7 @@ use crate::python::builtins::{BUILTINS, MAGIC_GLOBALS}; use crate::python::future::ALL_FEATURE_NAMES; use crate::python::typing; use crate::python::typing::SubscriptKind; -use crate::registry::{Check, CheckCode, CheckKind, DeferralKeyword}; +use crate::registry::{Check, CheckCode, DeferralKeyword}; use crate::settings::types::PythonVersion; use crate::settings::{flags, Settings}; use crate::source_code_locator::SourceCodeLocator; @@ -42,7 +42,8 @@ use crate::{ flake8_debugger, flake8_errmsg, flake8_implicit_str_concat, flake8_import_conventions, flake8_pie, flake8_print, flake8_pytest_style, flake8_return, flake8_simplify, flake8_tidy_imports, flake8_unused_arguments, mccabe, noqa, pandas_vet, pep8_naming, - pycodestyle, pydocstyle, pyflakes, pygrep_hooks, pylint, pyupgrade, ruff, visibility, + pycodestyle, pydocstyle, pyflakes, pygrep_hooks, pylint, pyupgrade, ruff, violations, + visibility, }; const GLOBAL_SCOPE_INDEX: usize = 0; @@ -312,7 +313,7 @@ where if !exists { if self.settings.enabled.contains(&CheckCode::PLE0117) { self.checks.push(Check::new( - CheckKind::NonlocalWithoutBinding(name.to_string()), + violations::NonlocalWithoutBinding(name.to_string()), *range, )); } @@ -573,7 +574,7 @@ where ScopeKind::Class(_) | ScopeKind::Module ) { self.checks.push(Check::new( - CheckKind::ReturnOutsideFunction, + violations::ReturnOutsideFunction, Range::from_located(stmt), )); } @@ -656,7 +657,7 @@ where if self.settings.enabled.contains(&CheckCode::E401) { if names.len() > 1 { self.checks.push(Check::new( - CheckKind::MultipleImportsOnOneLine, + violations::MultipleImportsOnOneLine, Range::from_located(stmt), )); } @@ -665,7 +666,7 @@ where if self.settings.enabled.contains(&CheckCode::E402) { if self.seen_import_boundary && stmt.location.column() == 0 { self.checks.push(Check::new( - CheckKind::ModuleImportNotAtTopOfFile, + violations::ModuleImportNotAtTopOfFile, Range::from_located(stmt), )); } @@ -886,7 +887,7 @@ where if self.settings.enabled.contains(&CheckCode::E402) { if self.seen_import_boundary && stmt.location.column() == 0 { self.checks.push(Check::new( - CheckKind::ModuleImportNotAtTopOfFile, + violations::ModuleImportNotAtTopOfFile, Range::from_located(stmt), )); } @@ -965,7 +966,9 @@ where if self.settings.enabled.contains(&CheckCode::F407) { if !ALL_FEATURE_NAMES.contains(&&*alias.node.name) { self.checks.push(Check::new( - CheckKind::FutureFeatureNotDefined(alias.node.name.to_string()), + violations::FutureFeatureNotDefined( + alias.node.name.to_string(), + ), Range::from_located(alias), )); } @@ -974,7 +977,7 @@ where if self.settings.enabled.contains(&CheckCode::F404) && !self.futures_allowed { self.checks.push(Check::new( - CheckKind::LateFutureImport, + violations::LateFutureImport, Range::from_located(stmt), )); } @@ -994,10 +997,12 @@ where [*(self.scope_stack.last().expect("No current scope found"))]; if !matches!(scope.kind, ScopeKind::Module) { self.checks.push(Check::new( - CheckKind::ImportStarNotPermitted(helpers::format_import_from( - level.as_ref(), - module.as_deref(), - )), + violations::ImportStarNotPermitted( + helpers::format_import_from( + level.as_ref(), + module.as_deref(), + ), + ), Range::from_located(stmt), )); } @@ -1005,7 +1010,7 @@ where if self.settings.enabled.contains(&CheckCode::F403) { self.checks.push(Check::new( - CheckKind::ImportStarUsed(helpers::format_import_from( + violations::ImportStarUsed(helpers::format_import_from( level.as_ref(), module.as_deref(), )), @@ -1804,7 +1809,7 @@ where Err(e) => { if self.settings.enabled.contains(&CheckCode::F521) { self.checks.push(Check::new( - CheckKind::StringDotFormatInvalidFormat( + violations::StringDotFormatInvalidFormat( pyflakes::format::error_to_string(&e), ), location, @@ -2355,7 +2360,9 @@ where } } if self.settings.enabled.contains(&CheckCode::PT009) { - if let Some(check) = flake8_pytest_style::plugins::unittest_assertion(func) { + if let Some(check) = flake8_pytest_style::plugins::unittest_assertion( + self, expr, func, args, keywords, + ) { self.checks.push(check); } } @@ -2394,7 +2401,7 @@ where let scope = self.current_scope(); if matches!(scope.kind, ScopeKind::Class(_) | ScopeKind::Module) { self.checks.push(Check::new( - CheckKind::YieldOutsideFunction(DeferralKeyword::Yield), + violations::YieldOutsideFunction(DeferralKeyword::Yield), Range::from_located(expr), )); } @@ -2405,7 +2412,7 @@ where let scope = self.current_scope(); if matches!(scope.kind, ScopeKind::Class(_) | ScopeKind::Module) { self.checks.push(Check::new( - CheckKind::YieldOutsideFunction(DeferralKeyword::YieldFrom), + violations::YieldOutsideFunction(DeferralKeyword::YieldFrom), Range::from_located(expr), )); } @@ -2416,7 +2423,7 @@ where let scope = self.current_scope(); if matches!(scope.kind, ScopeKind::Class(_) | ScopeKind::Module) { self.checks.push(Check::new( - CheckKind::YieldOutsideFunction(DeferralKeyword::Await), + violations::YieldOutsideFunction(DeferralKeyword::Await), Range::from_located(expr), )); } @@ -2467,7 +2474,7 @@ where }) => { if self.settings.enabled.contains(&CheckCode::F509) { self.checks.push(Check::new( - CheckKind::PercentFormatUnsupportedFormatCharacter(c), + violations::PercentFormatUnsupportedFormatCharacter(c), location, )); } @@ -2475,7 +2482,7 @@ where Err(e) => { if self.settings.enabled.contains(&CheckCode::F501) { self.checks.push(Check::new( - CheckKind::PercentFormatInvalidFormat(e.to_string()), + violations::PercentFormatInvalidFormat(e.to_string()), location, )); } @@ -3081,7 +3088,7 @@ where if self.bindings[*index].used.is_none() { if self.settings.enabled.contains(&CheckCode::F841) { let mut check = Check::new( - CheckKind::UnusedVariable(name.to_string()), + violations::UnusedVariable(name.to_string()), name_range, ); if self.patch(&CheckCode::F841) { @@ -3367,7 +3374,7 @@ impl<'a> Checker<'a> { overridden = Some((*scope_index, *existing_binding_index)); if self.settings.enabled.contains(&CheckCode::F402) { self.checks.push(Check::new( - CheckKind::ImportShadowedByLoopVar( + violations::ImportShadowedByLoopVar( name.to_string(), existing.range.location.row(), ), @@ -3387,7 +3394,7 @@ impl<'a> Checker<'a> { overridden = Some((*scope_index, *existing_binding_index)); if self.settings.enabled.contains(&CheckCode::F811) { self.checks.push(Check::new( - CheckKind::RedefinedWhileUnused( + violations::RedefinedWhileUnused( name.to_string(), existing.range.location.row(), ), @@ -3513,7 +3520,7 @@ impl<'a> Checker<'a> { from_list.sort(); self.checks.push(Check::new( - CheckKind::ImportStarUsage(id.to_string(), from_list), + violations::ImportStarUsage(id.to_string(), from_list), Range::from_located(expr), )); } @@ -3544,7 +3551,7 @@ impl<'a> Checker<'a> { } self.checks.push(Check::new( - CheckKind::UndefinedName(id.clone()), + violations::UndefinedName(id.clone()), Range::from_located(expr), )); } @@ -3715,7 +3722,7 @@ impl<'a> Checker<'a> { && self.settings.enabled.contains(&CheckCode::F821) { self.checks.push(Check::new( - CheckKind::UndefinedName(id.to_string()), + violations::UndefinedName(id.to_string()), Range::from_located(expr), )); } @@ -3776,7 +3783,7 @@ impl<'a> Checker<'a> { } else { if self.settings.enabled.contains(&CheckCode::F722) { self.checks.push(Check::new( - CheckKind::ForwardAnnotationSyntaxError(expression.to_string()), + violations::ForwardAnnotationSyntaxError(expression.to_string()), range, )); } @@ -3882,7 +3889,7 @@ impl<'a> Checker<'a> { let binding = &self.bindings[*index]; if matches!(binding.kind, BindingKind::Global) { checks.push(Check::new( - CheckKind::GlobalVariableNotAssigned((*name).to_string()), + violations::GlobalVariableNotAssigned((*name).to_string()), binding.range, )); } @@ -3911,7 +3918,7 @@ impl<'a> Checker<'a> { for &name in names { if !scope.values.contains_key(name) { checks.push(Check::new( - CheckKind::UndefinedExport(name.to_string()), + violations::UndefinedExport(name.to_string()), all_binding.range, )); } @@ -3949,7 +3956,7 @@ impl<'a> Checker<'a> { if let Some(indices) = self.redefinitions.get(index) { for index in indices { checks.push(Check::new( - CheckKind::RedefinedWhileUnused( + violations::RedefinedWhileUnused( (*name).to_string(), binding.range.location.row(), ), @@ -3980,7 +3987,7 @@ impl<'a> Checker<'a> { for &name in names { if !scope.values.contains_key(name) { checks.push(Check::new( - CheckKind::ImportStarUsage( + violations::ImportStarUsage( name.to_string(), from_list.clone(), ), @@ -4095,7 +4102,7 @@ impl<'a> Checker<'a> { let multiple = unused_imports.len() > 1; for (full_name, range) in unused_imports { let mut check = Check::new( - CheckKind::UnusedImport(full_name.to_string(), ignore_init, multiple), + violations::UnusedImport(full_name.to_string(), ignore_init, multiple), *range, ); if matches!(child.node, StmtKind::ImportFrom { .. }) @@ -4117,7 +4124,7 @@ impl<'a> Checker<'a> { let multiple = unused_imports.len() > 1; for (full_name, range) in unused_imports { let mut check = Check::new( - CheckKind::UnusedImport(full_name.to_string(), ignore_init, multiple), + violations::UnusedImport(full_name.to_string(), ignore_init, multiple), *range, ); if matches!(child.node, StmtKind::ImportFrom { .. }) diff --git a/src/checkers/noqa.rs b/src/checkers/noqa.rs index 42af3c73e4494..f650bfbd506f7 100644 --- a/src/checkers/noqa.rs +++ b/src/checkers/noqa.rs @@ -7,10 +7,10 @@ use rustpython_parser::ast::Location; use crate::ast::types::Range; use crate::autofix::Fix; -use crate::noqa; use crate::noqa::{is_file_exempt, Directive}; use crate::registry::{Check, CheckCode, CheckKind, UnusedCodes, CODE_REDIRECTS}; use crate::settings::{flags, Settings}; +use crate::{noqa, violations}; pub fn check_noqa( checks: &mut Vec, @@ -42,7 +42,7 @@ pub fn check_noqa( // Remove any ignored checks. for (index, check) in checks.iter().enumerate() { - if check.kind == CheckKind::BlanketNOQA { + if matches!(check.kind, CheckKind::BlanketNOQA(..)) { continue; } @@ -101,7 +101,7 @@ pub fn check_noqa( Directive::All(spaces, start, end) => { if matches.is_empty() { let mut check = Check::new( - CheckKind::UnusedNOQA(None), + violations::UnusedNOQA(None), Range::new(Location::new(row + 1, start), Location::new(row + 1, end)), ); if matches!(autofix, flags::Autofix::Enabled) @@ -152,7 +152,7 @@ pub fn check_noqa( && unmatched_codes.is_empty()) { let mut check = Check::new( - CheckKind::UnusedNOQA(Some(UnusedCodes { + violations::UnusedNOQA(Some(UnusedCodes { disabled: disabled_codes .iter() .map(|code| (*code).to_string()) diff --git a/src/commands.rs b/src/commands.rs index f3babf2913c16..eb34b9082c24c 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -22,11 +22,11 @@ use crate::iterators::par_iter; use crate::linter::{add_noqa_to_path, lint_path, lint_stdin, Diagnostics}; use crate::logging::LogLevel; use crate::message::Message; -use crate::registry::{CheckCode, CheckKind}; +use crate::registry::CheckCode; use crate::resolver::{FileDiscovery, PyprojectDiscovery}; use crate::settings::flags; use crate::settings::types::SerializationFormat; -use crate::{cache, fs, one_time_warning, packages, resolver}; +use crate::{cache, fs, one_time_warning, packages, resolver, violations}; /// Run the linter over a collection of files. pub fn run( @@ -119,7 +119,7 @@ pub fn run( let settings = resolver.resolve(path, pyproject_strategy); if settings.enabled.contains(&CheckCode::E902) { Diagnostics::new(vec![Message { - kind: CheckKind::IOError(message), + kind: violations::IOError(message).into(), location: Location::default(), end_location: Location::default(), fix: None, diff --git a/src/directives.rs b/src/directives.rs index 8e954c8c9ea9a..27c9eef777f87 100644 --- a/src/directives.rs +++ b/src/directives.rs @@ -104,6 +104,7 @@ pub fn extract_isort_directives(lxr: &[LexResult]) -> IsortDirectives { continue; }; + let comment_text = comment_text.trim_end(); if comment_text == "# isort: split" { splits.push(start.row()); } else if comment_text == "# isort: skip_file" { diff --git a/src/eradicate/checks.rs b/src/eradicate/checks.rs index a47604a769a23..678e73bc840ff 100644 --- a/src/eradicate/checks.rs +++ b/src/eradicate/checks.rs @@ -3,9 +3,9 @@ use rustpython_ast::Location; use crate::ast::types::Range; use crate::autofix::Fix; use crate::eradicate::detection::comment_contains_code; -use crate::registry::{CheckCode, CheckKind}; +use crate::registry::CheckCode; use crate::settings::flags; -use crate::{Check, Settings, SourceCodeLocator}; +use crate::{violations, Check, Settings, SourceCodeLocator}; fn is_standalone_comment(line: &str) -> bool { for char in line.chars() { @@ -32,7 +32,7 @@ pub fn commented_out_code( // Verify that the comment is on its own line, and that it contains code. if is_standalone_comment(&line) && comment_contains_code(&line, &settings.task_tags[..]) { - let mut check = Check::new(CheckKind::CommentedOutCode, Range::new(start, end)); + let mut check = Check::new(violations::CommentedOutCode, Range::new(start, end)); if matches!(autofix, flags::Autofix::Enabled) && settings.fixable.contains(&CheckCode::ERA001) { diff --git a/src/eradicate/snapshots/ruff__eradicate__tests__ERA001_ERA001.py.snap b/src/eradicate/snapshots/ruff__eradicate__tests__ERA001_ERA001.py.snap index 45a288af610b8..e248cbb69909d 100644 --- a/src/eradicate/snapshots/ruff__eradicate__tests__ERA001_ERA001.py.snap +++ b/src/eradicate/snapshots/ruff__eradicate__tests__ERA001_ERA001.py.snap @@ -2,7 +2,8 @@ source: src/eradicate/mod.rs expression: checks --- -- kind: CommentedOutCode +- kind: + CommentedOutCode: ~ location: row: 1 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 0 parent: ~ -- kind: CommentedOutCode +- kind: + CommentedOutCode: ~ location: row: 2 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 3 column: 0 parent: ~ -- kind: CommentedOutCode +- kind: + CommentedOutCode: ~ location: row: 3 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 4 column: 0 parent: ~ -- kind: CommentedOutCode +- kind: + CommentedOutCode: ~ location: row: 5 column: 0 @@ -66,7 +70,8 @@ expression: checks row: 6 column: 0 parent: ~ -- kind: CommentedOutCode +- kind: + CommentedOutCode: ~ location: row: 12 column: 4 diff --git a/src/flake8_2020/plugins.rs b/src/flake8_2020/plugins.rs index 821df3532a3de..1c3dc61d048f9 100644 --- a/src/flake8_2020/plugins.rs +++ b/src/flake8_2020/plugins.rs @@ -4,7 +4,8 @@ use rustpython_ast::{Cmpop, Constant, Expr, ExprKind, Located}; use crate::ast::helpers::match_module_member; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; fn is_sys(checker: &Checker, expr: &Expr, target: &str) -> bool { match_module_member( @@ -35,14 +36,14 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) { && checker.settings.enabled.contains(&CheckCode::YTT303) { checker.checks.push(Check::new( - CheckKind::SysVersionSlice1Referenced, + violations::SysVersionSlice1Referenced, Range::from_located(value), )); } else if *i == BigInt::from(3) && checker.settings.enabled.contains(&CheckCode::YTT101) { checker.checks.push(Check::new( - CheckKind::SysVersionSlice3Referenced, + violations::SysVersionSlice3Referenced, Range::from_located(value), )); } @@ -55,14 +56,14 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) { } => { if *i == BigInt::from(2) && checker.settings.enabled.contains(&CheckCode::YTT102) { checker.checks.push(Check::new( - CheckKind::SysVersion2Referenced, + violations::SysVersion2Referenced, Range::from_located(value), )); } else if *i == BigInt::from(0) && checker.settings.enabled.contains(&CheckCode::YTT301) { checker.checks.push(Check::new( - CheckKind::SysVersion0Referenced, + violations::SysVersion0Referenced, Range::from_located(value), )); } @@ -99,7 +100,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: & && checker.settings.enabled.contains(&CheckCode::YTT201) { checker.checks.push(Check::new( - CheckKind::SysVersionInfo0Eq3Referenced, + violations::SysVersionInfo0Eq3Referenced, Range::from_located(left), )); } @@ -119,7 +120,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: & { if checker.settings.enabled.contains(&CheckCode::YTT203) { checker.checks.push(Check::new( - CheckKind::SysVersionInfo1CmpInt, + violations::SysVersionInfo1CmpInt, Range::from_located(left), )); } @@ -145,7 +146,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: & { if checker.settings.enabled.contains(&CheckCode::YTT204) { checker.checks.push(Check::new( - CheckKind::SysVersionInfoMinorCmpInt, + violations::SysVersionInfoMinorCmpInt, Range::from_located(left), )); } @@ -171,13 +172,13 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: & if s.len() == 1 { if checker.settings.enabled.contains(&CheckCode::YTT302) { checker.checks.push(Check::new( - CheckKind::SysVersionCmpStr10, + violations::SysVersionCmpStr10, Range::from_located(left), )); } } else if checker.settings.enabled.contains(&CheckCode::YTT103) { checker.checks.push(Check::new( - CheckKind::SysVersionCmpStr3, + violations::SysVersionCmpStr3, Range::from_located(left), )); } @@ -195,7 +196,7 @@ pub fn name_or_attribute(checker: &mut Checker, expr: &Expr) { &checker.import_aliases, ) { checker.checks.push(Check::new( - CheckKind::SixPY3Referenced, + violations::SixPY3Referenced, Range::from_located(expr), )); } diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT101_YTT101.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT101_YTT101.py.snap index 117a97d742e7a..d0bbbe626079b 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT101_YTT101.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT101_YTT101.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionSlice3Referenced +- kind: + SysVersionSlice3Referenced: ~ location: row: 6 column: 6 @@ -11,7 +12,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: SysVersionSlice3Referenced +- kind: + SysVersionSlice3Referenced: ~ location: row: 7 column: 6 @@ -20,7 +22,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: SysVersionSlice3Referenced +- kind: + SysVersionSlice3Referenced: ~ location: row: 8 column: 6 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT102_YTT102.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT102_YTT102.py.snap index e3e22a12c7bef..95154733f4179 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT102_YTT102.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT102_YTT102.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersion2Referenced +- kind: + SysVersion2Referenced: ~ location: row: 4 column: 11 @@ -11,7 +12,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: SysVersion2Referenced +- kind: + SysVersion2Referenced: ~ location: row: 5 column: 11 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT103_YTT103.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT103_YTT103.py.snap index 058ca50aee845..33f8316362763 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT103_YTT103.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT103_YTT103.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionCmpStr3 +- kind: + SysVersionCmpStr3: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: SysVersionCmpStr3 +- kind: + SysVersionCmpStr3: ~ location: row: 5 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SysVersionCmpStr3 +- kind: + SysVersionCmpStr3: ~ location: row: 6 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SysVersionCmpStr3 +- kind: + SysVersionCmpStr3: ~ location: row: 7 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SysVersionCmpStr3 +- kind: + SysVersionCmpStr3: ~ location: row: 8 column: 0 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT201_YTT201.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT201_YTT201.py.snap index 5938845bea221..914a98438b6ef 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT201_YTT201.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT201_YTT201.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionInfo0Eq3Referenced +- kind: + SysVersionInfo0Eq3Referenced: ~ location: row: 7 column: 6 @@ -11,7 +12,8 @@ expression: checks column: 25 fix: ~ parent: ~ -- kind: SysVersionInfo0Eq3Referenced +- kind: + SysVersionInfo0Eq3Referenced: ~ location: row: 8 column: 6 @@ -20,7 +22,8 @@ expression: checks column: 21 fix: ~ parent: ~ -- kind: SysVersionInfo0Eq3Referenced +- kind: + SysVersionInfo0Eq3Referenced: ~ location: row: 9 column: 6 @@ -29,7 +32,8 @@ expression: checks column: 25 fix: ~ parent: ~ -- kind: SysVersionInfo0Eq3Referenced +- kind: + SysVersionInfo0Eq3Referenced: ~ location: row: 10 column: 6 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT202_YTT202.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT202_YTT202.py.snap index fb796f299aade..92f02b2706d6b 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT202_YTT202.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT202_YTT202.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SixPY3Referenced +- kind: + SixPY3Referenced: ~ location: row: 4 column: 3 @@ -11,7 +12,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: SixPY3Referenced +- kind: + SixPY3Referenced: ~ location: row: 6 column: 3 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT203_YTT203.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT203_YTT203.py.snap index 16f7567ad2478..2923a2f4761df 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT203_YTT203.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT203_YTT203.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionInfo1CmpInt +- kind: + SysVersionInfo1CmpInt: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: SysVersionInfo1CmpInt +- kind: + SysVersionInfo1CmpInt: ~ location: row: 5 column: 0 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT204_YTT204.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT204_YTT204.py.snap index 9b645f776dcca..9454114a1158a 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT204_YTT204.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT204_YTT204.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionInfoMinorCmpInt +- kind: + SysVersionInfoMinorCmpInt: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: SysVersionInfoMinorCmpInt +- kind: + SysVersionInfoMinorCmpInt: ~ location: row: 5 column: 0 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT301_YTT301.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT301_YTT301.py.snap index 4e77544721b0f..62ea74015991a 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT301_YTT301.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT301_YTT301.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersion0Referenced +- kind: + SysVersion0Referenced: ~ location: row: 4 column: 11 @@ -11,7 +12,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: SysVersion0Referenced +- kind: + SysVersion0Referenced: ~ location: row: 5 column: 11 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT302_YTT302.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT302_YTT302.py.snap index 71088f79a9bdc..c969663a0654e 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT302_YTT302.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT302_YTT302.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionCmpStr10 +- kind: + SysVersionCmpStr10: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: SysVersionCmpStr10 +- kind: + SysVersionCmpStr10: ~ location: row: 5 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SysVersionCmpStr10 +- kind: + SysVersionCmpStr10: ~ location: row: 6 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SysVersionCmpStr10 +- kind: + SysVersionCmpStr10: ~ location: row: 7 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SysVersionCmpStr10 +- kind: + SysVersionCmpStr10: ~ location: row: 8 column: 0 diff --git a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT303_YTT303.py.snap b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT303_YTT303.py.snap index 3cc403d19cda1..29553b8758803 100644 --- a/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT303_YTT303.py.snap +++ b/src/flake8_2020/snapshots/ruff__flake8_2020__tests__YTT303_YTT303.py.snap @@ -2,7 +2,8 @@ source: src/flake8_2020/mod.rs expression: checks --- -- kind: SysVersionSlice1Referenced +- kind: + SysVersionSlice1Referenced: ~ location: row: 4 column: 6 @@ -11,7 +12,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: SysVersionSlice1Referenced +- kind: + SysVersionSlice1Referenced: ~ location: row: 5 column: 6 diff --git a/src/flake8_annotations/plugins.rs b/src/flake8_annotations/plugins.rs index 1726ffd903d2d..0e82759ddfc3e 100644 --- a/src/flake8_annotations/plugins.rs +++ b/src/flake8_annotations/plugins.rs @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::docstrings::definition::{Definition, DefinitionKind}; use crate::flake8_annotations::fixes; use crate::flake8_annotations::helpers::match_function_def; -use crate::registry::{CheckCode, CheckKind}; +use crate::registry::CheckCode; use crate::visibility::Visibility; -use crate::{visibility, Check}; +use crate::{violations, visibility, Check}; #[derive(Default)] struct ReturnStatementVisitor<'a> { @@ -58,7 +58,7 @@ where { if checker.match_typing_expr(annotation, "Any") { checker.checks.push(Check::new( - CheckKind::DynamicallyTypedExpression(func()), + violations::DynamicallyTypedExpression(func()), Range::from_located(annotation), )); }; @@ -94,7 +94,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V { if checker.settings.enabled.contains(&CheckCode::ANN001) { checker.checks.push(Check::new( - CheckKind::MissingTypeFunctionArgument(arg.node.arg.to_string()), + violations::MissingTypeFunctionArgument(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -117,7 +117,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V { if checker.settings.enabled.contains(&CheckCode::ANN002) { checker.checks.push(Check::new( - CheckKind::MissingTypeArgs(arg.node.arg.to_string()), + violations::MissingTypeArgs(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -140,7 +140,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V { if checker.settings.enabled.contains(&CheckCode::ANN003) { checker.checks.push(Check::new( - CheckKind::MissingTypeKwargs(arg.node.arg.to_string()), + violations::MissingTypeKwargs(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -166,7 +166,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V Visibility::Public => { if checker.settings.enabled.contains(&CheckCode::ANN201) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypePublicFunction(name.to_string()), + violations::MissingReturnTypePublicFunction(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } @@ -174,7 +174,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V Visibility::Private => { if checker.settings.enabled.contains(&CheckCode::ANN202) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypePrivateFunction(name.to_string()), + violations::MissingReturnTypePrivateFunction(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } @@ -212,7 +212,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V { if checker.settings.enabled.contains(&CheckCode::ANN001) { checker.checks.push(Check::new( - CheckKind::MissingTypeFunctionArgument(arg.node.arg.to_string()), + violations::MissingTypeFunctionArgument(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -236,7 +236,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V { if checker.settings.enabled.contains(&CheckCode::ANN002) { checker.checks.push(Check::new( - CheckKind::MissingTypeArgs(arg.node.arg.to_string()), + violations::MissingTypeArgs(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -260,7 +260,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V { if checker.settings.enabled.contains(&CheckCode::ANN003) { checker.checks.push(Check::new( - CheckKind::MissingTypeKwargs(arg.node.arg.to_string()), + violations::MissingTypeKwargs(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -275,14 +275,14 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V if visibility::is_classmethod(checker, cast::decorator_list(stmt)) { if checker.settings.enabled.contains(&CheckCode::ANN102) { checker.checks.push(Check::new( - CheckKind::MissingTypeCls(arg.node.arg.to_string()), + violations::MissingTypeCls(arg.node.arg.to_string()), Range::from_located(arg), )); } } else { if checker.settings.enabled.contains(&CheckCode::ANN101) { checker.checks.push(Check::new( - CheckKind::MissingTypeSelf(arg.node.arg.to_string()), + violations::MissingTypeSelf(arg.node.arg.to_string()), Range::from_located(arg), )); } @@ -308,14 +308,14 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V if visibility::is_classmethod(checker, cast::decorator_list(stmt)) { if checker.settings.enabled.contains(&CheckCode::ANN206) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypeClassMethod(name.to_string()), + violations::MissingReturnTypeClassMethod(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } } else if visibility::is_staticmethod(checker, cast::decorator_list(stmt)) { if checker.settings.enabled.contains(&CheckCode::ANN205) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypeStaticMethod(name.to_string()), + violations::MissingReturnTypeStaticMethod(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } @@ -327,7 +327,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V && has_any_typed_arg) { let mut check = Check::new( - CheckKind::MissingReturnTypeSpecialMethod(name.to_string()), + violations::MissingReturnTypeSpecialMethod(name.to_string()), helpers::identifier_range(stmt, checker.locator), ); if checker.patch(check.kind.code()) { @@ -344,7 +344,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V } else if visibility::is_magic(stmt) { if checker.settings.enabled.contains(&CheckCode::ANN204) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypeSpecialMethod(name.to_string()), + violations::MissingReturnTypeSpecialMethod(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } @@ -353,7 +353,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V Visibility::Public => { if checker.settings.enabled.contains(&CheckCode::ANN201) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypePublicFunction(name.to_string()), + violations::MissingReturnTypePublicFunction(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } @@ -361,7 +361,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V Visibility::Private => { if checker.settings.enabled.contains(&CheckCode::ANN202) { checker.checks.push(Check::new( - CheckKind::MissingReturnTypePrivateFunction(name.to_string()), + violations::MissingReturnTypePrivateFunction(name.to_string()), helpers::identifier_range(stmt, checker.locator), )); } diff --git a/src/flake8_bandit/checks/assert_used.rs b/src/flake8_bandit/checks/assert_used.rs index 2cb5a3c4a791b..0f540f7b51d6e 100644 --- a/src/flake8_bandit/checks/assert_used.rs +++ b/src/flake8_bandit/checks/assert_used.rs @@ -1,9 +1,10 @@ use rustpython_ast::{Located, StmtKind}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// S101 pub fn assert_used(stmt: &Located) -> Check { - Check::new(CheckKind::AssertUsed, Range::from_located(stmt)) + Check::new(violations::AssertUsed, Range::from_located(stmt)) } diff --git a/src/flake8_bandit/checks/bad_file_permissions.rs b/src/flake8_bandit/checks/bad_file_permissions.rs index ce6a4d4f91228..5077d4610cb4b 100644 --- a/src/flake8_bandit/checks/bad_file_permissions.rs +++ b/src/flake8_bandit/checks/bad_file_permissions.rs @@ -5,7 +5,8 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword, Operator}; use crate::ast::helpers::{compose_call_path, match_module_member, SimpleCallArgs}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const WRITE_WORLD: u16 = 0o2; const EXECUTE_GROUP: u16 = 0o10; @@ -97,7 +98,7 @@ pub fn bad_file_permissions( if let Some(int_value) = get_int_value(mode_arg) { if (int_value & WRITE_WORLD > 0) || (int_value & EXECUTE_GROUP > 0) { return Some(Check::new( - CheckKind::BadFilePermissions(int_value), + violations::BadFilePermissions(int_value), Range::from_located(mode_arg), )); } diff --git a/src/flake8_bandit/checks/exec_used.rs b/src/flake8_bandit/checks/exec_used.rs index e206e821a7a24..e92ec22e0be54 100644 --- a/src/flake8_bandit/checks/exec_used.rs +++ b/src/flake8_bandit/checks/exec_used.rs @@ -1,7 +1,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// S102 pub fn exec_used(expr: &Expr, func: &Expr) -> Option { @@ -11,5 +12,5 @@ pub fn exec_used(expr: &Expr, func: &Expr) -> Option { if id != "exec" { return None; } - Some(Check::new(CheckKind::ExecUsed, Range::from_located(expr))) + Some(Check::new(violations::ExecUsed, Range::from_located(expr))) } diff --git a/src/flake8_bandit/checks/hardcoded_bind_all_interfaces.rs b/src/flake8_bandit/checks/hardcoded_bind_all_interfaces.rs index c160425899021..093df44d0802d 100644 --- a/src/flake8_bandit/checks/hardcoded_bind_all_interfaces.rs +++ b/src/flake8_bandit/checks/hardcoded_bind_all_interfaces.rs @@ -1,10 +1,11 @@ use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// S104 pub fn hardcoded_bind_all_interfaces(value: &str, range: &Range) -> Option { if value == "0.0.0.0" { - Some(Check::new(CheckKind::HardcodedBindAllInterfaces, *range)) + Some(Check::new(violations::HardcodedBindAllInterfaces, *range)) } else { None } diff --git a/src/flake8_bandit/checks/hardcoded_password_default.rs b/src/flake8_bandit/checks/hardcoded_password_default.rs index e37e4d1155890..8173dd653e9da 100644 --- a/src/flake8_bandit/checks/hardcoded_password_default.rs +++ b/src/flake8_bandit/checks/hardcoded_password_default.rs @@ -2,7 +2,8 @@ use rustpython_ast::{ArgData, Arguments, Expr, Located}; use crate::ast::types::Range; use crate::flake8_bandit::helpers::{matches_password_name, string_literal}; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn check_password_kwarg(arg: &Located, default: &Expr) -> Option { let string = string_literal(default)?; @@ -11,7 +12,7 @@ fn check_password_kwarg(arg: &Located, default: &Expr) -> Option return None; } Some(Check::new( - CheckKind::HardcodedPasswordDefault(string.to_string()), + violations::HardcodedPasswordDefault(string.to_string()), Range::from_located(default), )) } diff --git a/src/flake8_bandit/checks/hardcoded_password_func_arg.rs b/src/flake8_bandit/checks/hardcoded_password_func_arg.rs index 448cb257090f8..5f1bfceae79c3 100644 --- a/src/flake8_bandit/checks/hardcoded_password_func_arg.rs +++ b/src/flake8_bandit/checks/hardcoded_password_func_arg.rs @@ -2,7 +2,8 @@ use rustpython_ast::Keyword; use crate::ast::types::Range; use crate::flake8_bandit::helpers::{matches_password_name, string_literal}; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// S106 pub fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec { @@ -15,7 +16,7 @@ pub fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec { return None; } Some(Check::new( - CheckKind::HardcodedPasswordFuncArg(string.to_string()), + violations::HardcodedPasswordFuncArg(string.to_string()), Range::from_located(keyword), )) }) diff --git a/src/flake8_bandit/checks/hardcoded_password_string.rs b/src/flake8_bandit/checks/hardcoded_password_string.rs index 8b31e71a8e4cd..b8fb070887773 100644 --- a/src/flake8_bandit/checks/hardcoded_password_string.rs +++ b/src/flake8_bandit/checks/hardcoded_password_string.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; use crate::flake8_bandit::helpers::{matches_password_name, string_literal}; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn is_password_target(target: &Expr) -> bool { let target_name = match &target.node { @@ -34,7 +35,7 @@ pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) - return None; } Some(Check::new( - CheckKind::HardcodedPasswordString(string.to_string()), + violations::HardcodedPasswordString(string.to_string()), Range::from_located(comp), )) }) @@ -47,7 +48,7 @@ pub fn assign_hardcoded_password_string(value: &Expr, targets: &[Expr]) -> Optio for target in targets { if is_password_target(target) { return Some(Check::new( - CheckKind::HardcodedPasswordString(string.to_string()), + violations::HardcodedPasswordString(string.to_string()), Range::from_located(value), )); } diff --git a/src/flake8_bandit/checks/hardcoded_tmp_directory.rs b/src/flake8_bandit/checks/hardcoded_tmp_directory.rs index d082a4aab8304..d744d96ba9bc9 100644 --- a/src/flake8_bandit/checks/hardcoded_tmp_directory.rs +++ b/src/flake8_bandit/checks/hardcoded_tmp_directory.rs @@ -1,13 +1,14 @@ use rustpython_ast::Expr; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// S108 pub fn hardcoded_tmp_directory(expr: &Expr, value: &str, prefixes: &[String]) -> Option { if prefixes.iter().any(|prefix| value.starts_with(prefix)) { Some(Check::new( - CheckKind::HardcodedTempFile(value.to_string()), + violations::HardcodedTempFile(value.to_string()), Range::from_located(expr), )) } else { diff --git a/src/flake8_bandit/checks/hashlib_insecure_hash_functions.rs b/src/flake8_bandit/checks/hashlib_insecure_hash_functions.rs index 5d27c0fdc4d10..63f85317e666a 100644 --- a/src/flake8_bandit/checks/hashlib_insecure_hash_functions.rs +++ b/src/flake8_bandit/checks/hashlib_insecure_hash_functions.rs @@ -4,7 +4,8 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::helpers::{match_module_member, SimpleCallArgs}; use crate::ast::types::Range; use crate::flake8_bandit::helpers::string_literal; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const WEAK_HASHES: [&str; 4] = ["md4", "md5", "sha", "sha1"]; @@ -41,7 +42,7 @@ pub fn hashlib_insecure_hash_functions( if WEAK_HASHES.contains(&hash_func_name.to_lowercase().as_str()) { return Some(Check::new( - CheckKind::HashlibInsecureHashFunction(hash_func_name.to_string()), + violations::HashlibInsecureHashFunction(hash_func_name.to_string()), Range::from_located(name_arg), )); } @@ -56,7 +57,7 @@ pub fn hashlib_insecure_hash_functions( } return Some(Check::new( - CheckKind::HashlibInsecureHashFunction((*func_name).to_string()), + violations::HashlibInsecureHashFunction((*func_name).to_string()), Range::from_located(func), )); } diff --git a/src/flake8_bandit/checks/request_with_no_cert_validation.rs b/src/flake8_bandit/checks/request_with_no_cert_validation.rs index 8dd9fef4f721e..9ccb6287fc3a5 100644 --- a/src/flake8_bandit/checks/request_with_no_cert_validation.rs +++ b/src/flake8_bandit/checks/request_with_no_cert_validation.rs @@ -4,7 +4,8 @@ use rustpython_parser::ast::Constant; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path, SimpleCallArgs}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const REQUESTS_HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"]; const HTTPX_METHODS: [&str; 11] = [ @@ -41,7 +42,7 @@ pub fn request_with_no_cert_validation( } = &verify_arg.node { return Some(Check::new( - CheckKind::RequestWithNoCertValidation("requests".to_string()), + violations::RequestWithNoCertValidation("requests".to_string()), Range::from_located(verify_arg), )); } @@ -58,7 +59,7 @@ pub fn request_with_no_cert_validation( } = &verify_arg.node { return Some(Check::new( - CheckKind::RequestWithNoCertValidation("httpx".to_string()), + violations::RequestWithNoCertValidation("httpx".to_string()), Range::from_located(verify_arg), )); } diff --git a/src/flake8_bandit/checks/request_without_timeout.rs b/src/flake8_bandit/checks/request_without_timeout.rs index 18d258d7efddc..16d977554ab8f 100644 --- a/src/flake8_bandit/checks/request_without_timeout.rs +++ b/src/flake8_bandit/checks/request_without_timeout.rs @@ -4,7 +4,8 @@ use rustpython_parser::ast::Constant; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path, SimpleCallArgs}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"]; @@ -29,13 +30,13 @@ pub fn request_without_timeout( _ => None, } { return Some(Check::new( - CheckKind::RequestWithoutTimeout(Some(timeout)), + violations::RequestWithoutTimeout(Some(timeout)), Range::from_located(timeout_arg), )); } } else { return Some(Check::new( - CheckKind::RequestWithoutTimeout(None), + violations::RequestWithoutTimeout(None), Range::from_located(func), )); } diff --git a/src/flake8_bandit/checks/unsafe_yaml_load.rs b/src/flake8_bandit/checks/unsafe_yaml_load.rs index 9c3e6e51f05e6..94919911d8307 100644 --- a/src/flake8_bandit/checks/unsafe_yaml_load.rs +++ b/src/flake8_bandit/checks/unsafe_yaml_load.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Expr, ExprKind, Keyword}; use crate::ast::helpers::{match_module_member, SimpleCallArgs}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// S506 pub fn unsafe_yaml_load( @@ -35,13 +36,13 @@ pub fn unsafe_yaml_load( _ => None, }; return Some(Check::new( - CheckKind::UnsafeYAMLLoad(loader), + violations::UnsafeYAMLLoad(loader), Range::from_located(loader_arg), )); } } else { return Some(Check::new( - CheckKind::UnsafeYAMLLoad(None), + violations::UnsafeYAMLLoad(None), Range::from_located(func), )); } diff --git a/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S101_S101.py.snap b/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S101_S101.py.snap index 1d0f97bb52f41..051679a50ecad 100644 --- a/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S101_S101.py.snap +++ b/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S101_S101.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bandit/mod.rs expression: checks --- -- kind: AssertUsed +- kind: + AssertUsed: ~ location: row: 2 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: AssertUsed +- kind: + AssertUsed: ~ location: row: 8 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: AssertUsed +- kind: + AssertUsed: ~ location: row: 11 column: 4 diff --git a/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S102_S102.py.snap b/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S102_S102.py.snap index 315e8d0d091de..fa644e15d1c4d 100644 --- a/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S102_S102.py.snap +++ b/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S102_S102.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bandit/mod.rs expression: checks --- -- kind: ExecUsed +- kind: + ExecUsed: ~ location: row: 3 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: ExecUsed +- kind: + ExecUsed: ~ location: row: 5 column: 0 diff --git a/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S104_S104.py.snap b/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S104_S104.py.snap index f5780261fc636..0891f38bc87c9 100644 --- a/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S104_S104.py.snap +++ b/src/flake8_bandit/snapshots/ruff__flake8_bandit__tests__S104_S104.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bandit/mod.rs expression: checks --- -- kind: HardcodedBindAllInterfaces +- kind: + HardcodedBindAllInterfaces: ~ location: row: 9 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: HardcodedBindAllInterfaces +- kind: + HardcodedBindAllInterfaces: ~ location: row: 10 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: HardcodedBindAllInterfaces +- kind: + HardcodedBindAllInterfaces: ~ location: row: 14 column: 5 @@ -29,7 +32,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: HardcodedBindAllInterfaces +- kind: + HardcodedBindAllInterfaces: ~ location: row: 18 column: 8 diff --git a/src/flake8_blind_except/plugins.rs b/src/flake8_blind_except/plugins.rs index 03c4d97846e94..e31e5413226f3 100644 --- a/src/flake8_blind_except/plugins.rs +++ b/src/flake8_blind_except/plugins.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind, Stmt, StmtKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// BLE001 pub fn blind_except( @@ -36,7 +37,7 @@ pub fn blind_except( } }) { checker.checks.push(Check::new( - CheckKind::BlindExcept(id.to_string()), + violations::BlindExcept(id.to_string()), Range::from_located(type_), )); } diff --git a/src/flake8_boolean_trap/plugins.rs b/src/flake8_boolean_trap/plugins.rs index 3c37db9fe6e0e..a73b4cb168be7 100644 --- a/src/flake8_boolean_trap/plugins.rs +++ b/src/flake8_boolean_trap/plugins.rs @@ -4,6 +4,7 @@ use rustpython_parser::ast::{Constant, Expr}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::{Check, CheckKind}; +use crate::violations; const FUNC_NAME_ALLOWLIST: &[&str] = &[ "assertEqual", @@ -76,7 +77,7 @@ pub fn check_positional_boolean_in_def(checker: &mut Checker, arguments: &Argume continue; } checker.checks.push(Check::new( - CheckKind::BooleanPositionalArgInFunctionDefinition, + violations::BooleanPositionalArgInFunctionDefinition, Range::from_located(arg), )); } @@ -90,7 +91,7 @@ pub fn check_boolean_default_value_in_function_definition( add_if_boolean( checker, arg, - CheckKind::BooleanDefaultValueInFunctionDefinition, + violations::BooleanDefaultValueInFunctionDefinition.into(), ); } } @@ -107,7 +108,7 @@ pub fn check_boolean_positional_value_in_function_call( add_if_boolean( checker, arg, - CheckKind::BooleanPositionalValueInFunctionCall, + violations::BooleanPositionalValueInFunctionCall.into(), ); } } diff --git a/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT001_FBT.py.snap b/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT001_FBT.py.snap index f661f67f415a5..ead0efe6ce325 100644 --- a/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT001_FBT.py.snap +++ b/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT001_FBT.py.snap @@ -2,7 +2,8 @@ source: src/flake8_boolean_trap/mod.rs expression: checks --- -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 4 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 5 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 31 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 10 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 36 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 11 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 41 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 14 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 37 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 15 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 42 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 18 column: 4 @@ -65,7 +72,8 @@ expression: checks column: 40 fix: ~ parent: ~ -- kind: BooleanPositionalArgInFunctionDefinition +- kind: + BooleanPositionalArgInFunctionDefinition: ~ location: row: 19 column: 4 diff --git a/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT002_FBT.py.snap b/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT002_FBT.py.snap index e4f8bc28d7afb..2bc213aebe307 100644 --- a/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT002_FBT.py.snap +++ b/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT002_FBT.py.snap @@ -2,7 +2,8 @@ source: src/flake8_boolean_trap/mod.rs expression: checks --- -- kind: BooleanDefaultValueInFunctionDefinition +- kind: + BooleanDefaultValueInFunctionDefinition: ~ location: row: 12 column: 30 @@ -11,7 +12,8 @@ expression: checks column: 34 fix: ~ parent: ~ -- kind: BooleanDefaultValueInFunctionDefinition +- kind: + BooleanDefaultValueInFunctionDefinition: ~ location: row: 13 column: 42 @@ -20,7 +22,8 @@ expression: checks column: 46 fix: ~ parent: ~ -- kind: BooleanDefaultValueInFunctionDefinition +- kind: + BooleanDefaultValueInFunctionDefinition: ~ location: row: 14 column: 40 @@ -29,7 +32,8 @@ expression: checks column: 44 fix: ~ parent: ~ -- kind: BooleanDefaultValueInFunctionDefinition +- kind: + BooleanDefaultValueInFunctionDefinition: ~ location: row: 15 column: 45 diff --git a/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT003_FBT.py.snap b/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT003_FBT.py.snap index 0dd0c9ad6c1b7..f1d8e4e1acb29 100644 --- a/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT003_FBT.py.snap +++ b/src/flake8_boolean_trap/snapshots/ruff__flake8_boolean_trap__tests__FBT003_FBT.py.snap @@ -2,7 +2,8 @@ source: src/flake8_boolean_trap/mod.rs expression: checks --- -- kind: BooleanPositionalValueInFunctionCall +- kind: + BooleanPositionalValueInFunctionCall: ~ location: row: 42 column: 10 @@ -11,7 +12,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: BooleanPositionalValueInFunctionCall +- kind: + BooleanPositionalValueInFunctionCall: ~ location: row: 57 column: 10 @@ -20,7 +22,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: BooleanPositionalValueInFunctionCall +- kind: + BooleanPositionalValueInFunctionCall: ~ location: row: 57 column: 16 diff --git a/src/flake8_bugbear/plugins/abstract_base_class.rs b/src/flake8_bugbear/plugins/abstract_base_class.rs index ebeaf4e61b106..c00fc60a31bc2 100644 --- a/src/flake8_bugbear/plugins/abstract_base_class.rs +++ b/src/flake8_bugbear/plugins/abstract_base_class.rs @@ -4,7 +4,8 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword, Stmt, StmtKind}; use crate::ast::helpers::match_module_member; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; fn is_abc_class( bases: &[Expr], @@ -118,7 +119,7 @@ pub fn abstract_base_class( .any(|d| is_overload(d, &checker.from_imports, &checker.import_aliases)) { checker.checks.push(Check::new( - CheckKind::EmptyMethodWithoutAbstractDecorator(name.to_string()), + violations::EmptyMethodWithoutAbstractDecorator(name.to_string()), Range::from_located(stmt), )); } @@ -126,7 +127,7 @@ pub fn abstract_base_class( if checker.settings.enabled.contains(&CheckCode::B024) { if !has_abstract_method { checker.checks.push(Check::new( - CheckKind::AbstractBaseClassWithoutAbstractMethod(name.to_string()), + violations::AbstractBaseClassWithoutAbstractMethod(name.to_string()), Range::from_located(stmt), )); } diff --git a/src/flake8_bugbear/plugins/assert_false.rs b/src/flake8_bugbear/plugins/assert_false.rs index f6664d1dc7460..93fcc02fc4cc3 100644 --- a/src/flake8_bugbear/plugins/assert_false.rs +++ b/src/flake8_bugbear/plugins/assert_false.rs @@ -3,8 +3,9 @@ use rustpython_ast::{Constant, Expr, ExprContext, ExprKind, Location, Stmt, Stmt use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; +use crate::violations; fn assertion_error(msg: Option<&Expr>) -> Stmt { Stmt::new( @@ -45,7 +46,7 @@ pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option return; }; - let mut check = Check::new(CheckKind::DoNotAssertFalse, Range::from_located(test)); + let mut check = Check::new(violations::DoNotAssertFalse, Range::from_located(test)); if checker.patch(check.kind.code()) { let mut generator: SourceCodeGenerator = checker.style.into(); generator.unparse_stmt(&assertion_error(msg)); diff --git a/src/flake8_bugbear/plugins/assert_raises_exception.rs b/src/flake8_bugbear/plugins/assert_raises_exception.rs index 4fa7a41ec29aa..635affbcc4a6f 100644 --- a/src/flake8_bugbear/plugins/assert_raises_exception.rs +++ b/src/flake8_bugbear/plugins/assert_raises_exception.rs @@ -3,7 +3,8 @@ use rustpython_ast::{ExprKind, Stmt, Withitem}; use crate::ast::helpers::match_module_member; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B017 pub fn assert_raises_exception(checker: &mut Checker, stmt: &Stmt, items: &[Withitem]) { @@ -34,7 +35,7 @@ pub fn assert_raises_exception(checker: &mut Checker, stmt: &Stmt, items: &[With } checker.checks.push(Check::new( - CheckKind::NoAssertRaisesException, + violations::NoAssertRaisesException, Range::from_located(stmt), )); } diff --git a/src/flake8_bugbear/plugins/assignment_to_os_environ.rs b/src/flake8_bugbear/plugins/assignment_to_os_environ.rs index f9ea3a06e5a84..95d814b8fd683 100644 --- a/src/flake8_bugbear/plugins/assignment_to_os_environ.rs +++ b/src/flake8_bugbear/plugins/assignment_to_os_environ.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B003 pub fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) { @@ -23,7 +24,7 @@ pub fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) { return; } checker.checks.push(Check::new( - CheckKind::AssignmentToOsEnviron, + violations::AssignmentToOsEnviron, Range::from_located(target), )); } diff --git a/src/flake8_bugbear/plugins/cached_instance_method.rs b/src/flake8_bugbear/plugins/cached_instance_method.rs index 98586c816fb15..86cc21e93266a 100644 --- a/src/flake8_bugbear/plugins/cached_instance_method.rs +++ b/src/flake8_bugbear/plugins/cached_instance_method.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::types::{Range, ScopeKind}; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn is_cache_func(checker: &Checker, expr: &Expr) -> bool { let call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases); @@ -34,7 +35,7 @@ pub fn cached_instance_method(checker: &mut Checker, decorator_list: &[Expr]) { }, ) { checker.checks.push(Check::new( - CheckKind::CachedInstanceMethod, + violations::CachedInstanceMethod, Range::from_located(decorator), )); } diff --git a/src/flake8_bugbear/plugins/cannot_raise_literal.rs b/src/flake8_bugbear/plugins/cannot_raise_literal.rs index 8c3e69b99e725..55a4adb1cb29c 100644 --- a/src/flake8_bugbear/plugins/cannot_raise_literal.rs +++ b/src/flake8_bugbear/plugins/cannot_raise_literal.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B016 pub fn cannot_raise_literal(checker: &mut Checker, expr: &Expr) { @@ -10,7 +11,7 @@ pub fn cannot_raise_literal(checker: &mut Checker, expr: &Expr) { return; }; checker.checks.push(Check::new( - CheckKind::CannotRaiseLiteral, + violations::CannotRaiseLiteral, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/duplicate_exceptions.rs b/src/flake8_bugbear/plugins/duplicate_exceptions.rs index 6251d7f2f3395..34d6d8872aade 100644 --- a/src/flake8_bugbear/plugins/duplicate_exceptions.rs +++ b/src/flake8_bugbear/plugins/duplicate_exceptions.rs @@ -6,8 +6,9 @@ use crate::ast::helpers; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; use crate::source_code_generator::SourceCodeGenerator; +use crate::violations; fn type_pattern(elts: Vec<&Expr>) -> Expr { Expr::new( @@ -44,7 +45,7 @@ fn duplicate_handler_exceptions<'a>( // TODO(charlie): Handle "BaseException" and redundant exception aliases. if !duplicates.is_empty() { let mut check = Check::new( - CheckKind::DuplicateHandlerException( + violations::DuplicateHandlerException( duplicates .into_iter() .map(|call_path| call_path.join(".")) @@ -108,7 +109,7 @@ pub fn duplicate_exceptions(checker: &mut Checker, handlers: &[Excepthandler]) { for (name, exprs) in duplicates { for expr in exprs { checker.checks.push(Check::new( - CheckKind::DuplicateTryBlockException(name.join(".")), + violations::DuplicateTryBlockException(name.join(".")), Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/f_string_docstring.rs b/src/flake8_bugbear/plugins/f_string_docstring.rs index 86dc439973323..56ebd1dc231b6 100644 --- a/src/flake8_bugbear/plugins/f_string_docstring.rs +++ b/src/flake8_bugbear/plugins/f_string_docstring.rs @@ -2,7 +2,8 @@ use rustpython_ast::{ExprKind, Stmt, StmtKind}; use crate::ast::helpers; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B021 pub fn f_string_docstring(checker: &mut Checker, body: &[Stmt]) { @@ -16,7 +17,7 @@ pub fn f_string_docstring(checker: &mut Checker, body: &[Stmt]) { return; }; checker.checks.push(Check::new( - CheckKind::FStringDocstring, + violations::FStringDocstring, helpers::identifier_range(stmt, checker.locator), )); } diff --git a/src/flake8_bugbear/plugins/function_call_argument_default.rs b/src/flake8_bugbear/plugins/function_call_argument_default.rs index 8d972208a2a9b..ac98bb82925e4 100644 --- a/src/flake8_bugbear/plugins/function_call_argument_default.rs +++ b/src/flake8_bugbear/plugins/function_call_argument_default.rs @@ -10,6 +10,7 @@ use crate::ast::visitor::Visitor; use crate::checkers::ast::Checker; use crate::flake8_bugbear::plugins::mutable_argument_default::is_mutable_func; use crate::registry::{Check, CheckKind}; +use crate::violations; const IMMUTABLE_FUNCS: [(&str, &str); 7] = [ ("", "tuple"), @@ -58,7 +59,7 @@ where && !is_nan_or_infinity(func, args) { self.checks.push(( - CheckKind::FunctionCallArgumentDefault(compose_call_path(expr)), + violations::FunctionCallArgumentDefault(compose_call_path(expr)).into(), Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/function_uses_loop_variable.rs b/src/flake8_bugbear/plugins/function_uses_loop_variable.rs index ccb4e1bc03f0f..e5d2aa35f89b7 100644 --- a/src/flake8_bugbear/plugins/function_uses_loop_variable.rs +++ b/src/flake8_bugbear/plugins/function_uses_loop_variable.rs @@ -6,7 +6,8 @@ use crate::ast::types::{Node, Range}; use crate::ast::visitor; use crate::ast::visitor::Visitor; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; #[derive(Default)] struct LoadedNamesVisitor<'a> { @@ -212,7 +213,7 @@ where if !checker.flake8_bugbear_seen.contains(&expr) { checker.flake8_bugbear_seen.push(expr); checker.checks.push(Check::new( - CheckKind::FunctionUsesLoopVariable(name.to_string()), + violations::FunctionUsesLoopVariable(name.to_string()), range, )); } diff --git a/src/flake8_bugbear/plugins/getattr_with_constant.rs b/src/flake8_bugbear/plugins/getattr_with_constant.rs index 9c4e5b8604966..05c86e222573c 100644 --- a/src/flake8_bugbear/plugins/getattr_with_constant.rs +++ b/src/flake8_bugbear/plugins/getattr_with_constant.rs @@ -5,8 +5,9 @@ use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::python::identifiers::IDENTIFIER_REGEX; use crate::python::keyword::KWLIST; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; +use crate::violations; fn attribute(value: &Expr, attr: &str) -> Expr { Expr::new( @@ -44,7 +45,7 @@ pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar return; } - let mut check = Check::new(CheckKind::GetAttrWithConstant, Range::from_located(expr)); + let mut check = Check::new(violations::GetAttrWithConstant, Range::from_located(expr)); if checker.patch(check.kind.code()) { let mut generator: SourceCodeGenerator = checker.style.into(); generator.unparse_expr(&attribute(obj, value), 0); diff --git a/src/flake8_bugbear/plugins/jump_statement_in_finally.rs b/src/flake8_bugbear/plugins/jump_statement_in_finally.rs index f713e2ea1d1a5..6715568bae647 100644 --- a/src/flake8_bugbear/plugins/jump_statement_in_finally.rs +++ b/src/flake8_bugbear/plugins/jump_statement_in_finally.rs @@ -2,13 +2,14 @@ use rustpython_ast::{Stmt, StmtKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn walk_stmt(checker: &mut Checker, body: &[Stmt], f: fn(&Stmt) -> bool) { for stmt in body { if f(stmt) { checker.checks.push(Check::new( - CheckKind::JumpStatementInFinally(match &stmt.node { + violations::JumpStatementInFinally(match &stmt.node { StmtKind::Break { .. } => "break".to_string(), StmtKind::Continue { .. } => "continue".to_string(), StmtKind::Return { .. } => "return".to_string(), diff --git a/src/flake8_bugbear/plugins/loop_variable_overrides_iterator.rs b/src/flake8_bugbear/plugins/loop_variable_overrides_iterator.rs index ccd2838df7928..f078257abce30 100644 --- a/src/flake8_bugbear/plugins/loop_variable_overrides_iterator.rs +++ b/src/flake8_bugbear/plugins/loop_variable_overrides_iterator.rs @@ -5,7 +5,8 @@ use crate::ast::types::Range; use crate::ast::visitor; use crate::ast::visitor::Visitor; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; #[derive(Default)] struct NameFinder<'a> { @@ -56,7 +57,7 @@ pub fn loop_variable_overrides_iterator(checker: &mut Checker, target: &Expr, it for (name, expr) in target_names { if iter_names.contains_key(name) { checker.checks.push(Check::new( - CheckKind::LoopVariableOverridesIterator(name.to_string()), + violations::LoopVariableOverridesIterator(name.to_string()), Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/mutable_argument_default.rs b/src/flake8_bugbear/plugins/mutable_argument_default.rs index 3085175404dd9..6b2c74ce5f418 100644 --- a/src/flake8_bugbear/plugins/mutable_argument_default.rs +++ b/src/flake8_bugbear/plugins/mutable_argument_default.rs @@ -4,7 +4,8 @@ use rustpython_ast::{Arguments, Constant, Expr, ExprKind, Operator}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const MUTABLE_FUNCS: &[(&str, &str)] = &[ ("", "dict"), @@ -165,7 +166,7 @@ pub fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) { }) { checker.checks.push(Check::new( - CheckKind::MutableArgumentDefault, + violations::MutableArgumentDefault, Range::from_located(default), )); } diff --git a/src/flake8_bugbear/plugins/raise_without_from_inside_except.rs b/src/flake8_bugbear/plugins/raise_without_from_inside_except.rs index 0ddd886202ef3..a1ca215adf99a 100644 --- a/src/flake8_bugbear/plugins/raise_without_from_inside_except.rs +++ b/src/flake8_bugbear/plugins/raise_without_from_inside_except.rs @@ -4,7 +4,8 @@ use crate::ast::types::Range; use crate::ast::visitor::Visitor; use crate::checkers::ast::Checker; use crate::python::string::is_lower; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; struct RaiseVisitor { checks: Vec, @@ -20,7 +21,7 @@ impl<'a> Visitor<'a> for RaiseVisitor { ExprKind::Name { id, .. } if is_lower(id) => {} _ => { self.checks.push(Check::new( - CheckKind::RaiseWithoutFromInsideExcept, + violations::RaiseWithoutFromInsideExcept, Range::from_located(stmt), )); } diff --git a/src/flake8_bugbear/plugins/redundant_tuple_in_exception_handler.rs b/src/flake8_bugbear/plugins/redundant_tuple_in_exception_handler.rs index a02ac662ee6f5..0661640e10ea7 100644 --- a/src/flake8_bugbear/plugins/redundant_tuple_in_exception_handler.rs +++ b/src/flake8_bugbear/plugins/redundant_tuple_in_exception_handler.rs @@ -3,8 +3,9 @@ use rustpython_ast::{Excepthandler, ExcepthandlerKind, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; +use crate::violations; /// B013 pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[Excepthandler]) { @@ -19,7 +20,7 @@ pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[E continue; }; let mut check = Check::new( - CheckKind::RedundantTupleInExceptionHandler(elt.to_string()), + violations::RedundantTupleInExceptionHandler(elt.to_string()), Range::from_located(type_), ); if checker.patch(check.kind.code()) { diff --git a/src/flake8_bugbear/plugins/setattr_with_constant.rs b/src/flake8_bugbear/plugins/setattr_with_constant.rs index e8fd62217cf92..6a06612d76495 100644 --- a/src/flake8_bugbear/plugins/setattr_with_constant.rs +++ b/src/flake8_bugbear/plugins/setattr_with_constant.rs @@ -5,9 +5,10 @@ use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::python::identifiers::IDENTIFIER_REGEX; use crate::python::keyword::KWLIST; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_style::SourceCodeStyleDetector; +use crate::violations; fn assignment(obj: &Expr, name: &str, value: &Expr, stylist: &SourceCodeStyleDetector) -> String { let stmt = Stmt::new( @@ -60,7 +61,7 @@ pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar // (i.e., it's directly within an `StmtKind::Expr`). if let StmtKind::Expr { value: child } = &checker.current_stmt().node { if expr == child.as_ref() { - let mut check = Check::new(CheckKind::SetAttrWithConstant, Range::from_located(expr)); + let mut check = Check::new(violations::SetAttrWithConstant, Range::from_located(expr)); if checker.patch(check.kind.code()) { check.amend(Fix::replacement( assignment(obj, name, value, checker.style), diff --git a/src/flake8_bugbear/plugins/star_arg_unpacking_after_keyword_arg.rs b/src/flake8_bugbear/plugins/star_arg_unpacking_after_keyword_arg.rs index 03765992d9320..286056e90b033 100644 --- a/src/flake8_bugbear/plugins/star_arg_unpacking_after_keyword_arg.rs +++ b/src/flake8_bugbear/plugins/star_arg_unpacking_after_keyword_arg.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind, Keyword}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B026 pub fn star_arg_unpacking_after_keyword_arg( @@ -21,7 +22,7 @@ pub fn star_arg_unpacking_after_keyword_arg( continue; } checker.checks.push(Check::new( - CheckKind::StarArgUnpackingAfterKeywordArg, + violations::StarArgUnpackingAfterKeywordArg, Range::from_located(arg), )); } diff --git a/src/flake8_bugbear/plugins/strip_with_multi_characters.rs b/src/flake8_bugbear/plugins/strip_with_multi_characters.rs index 3f67df1c429e4..9a59c054db981 100644 --- a/src/flake8_bugbear/plugins/strip_with_multi_characters.rs +++ b/src/flake8_bugbear/plugins/strip_with_multi_characters.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B005 pub fn strip_with_multi_characters(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { @@ -26,7 +27,7 @@ pub fn strip_with_multi_characters(checker: &mut Checker, expr: &Expr, func: &Ex if value.len() > 1 && value.chars().unique().count() != value.len() { checker.checks.push(Check::new( - CheckKind::StripWithMultiCharacters, + violations::StripWithMultiCharacters, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/unary_prefix_increment.rs b/src/flake8_bugbear/plugins/unary_prefix_increment.rs index ba440513ce6e2..01c247c4a8f4f 100644 --- a/src/flake8_bugbear/plugins/unary_prefix_increment.rs +++ b/src/flake8_bugbear/plugins/unary_prefix_increment.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind, Unaryop}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B002 pub fn unary_prefix_increment(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand: &Expr) { @@ -16,7 +17,7 @@ pub fn unary_prefix_increment(checker: &mut Checker, expr: &Expr, op: &Unaryop, return; } checker.checks.push(Check::new( - CheckKind::UnaryPrefixIncrement, + violations::UnaryPrefixIncrement, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/unreliable_callable_check.rs b/src/flake8_bugbear/plugins/unreliable_callable_check.rs index 67fc2d959b429..96a44ae730d58 100644 --- a/src/flake8_bugbear/plugins/unreliable_callable_check.rs +++ b/src/flake8_bugbear/plugins/unreliable_callable_check.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B004 pub fn unreliable_callable_check(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { @@ -26,7 +27,7 @@ pub fn unreliable_callable_check(checker: &mut Checker, expr: &Expr, func: &Expr return; } checker.checks.push(Check::new( - CheckKind::UnreliableCallableCheck, + violations::UnreliableCallableCheck, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/unused_loop_control_variable.rs b/src/flake8_bugbear/plugins/unused_loop_control_variable.rs index f86185cc7beb0..93120d2b6e46c 100644 --- a/src/flake8_bugbear/plugins/unused_loop_control_variable.rs +++ b/src/flake8_bugbear/plugins/unused_loop_control_variable.rs @@ -6,7 +6,8 @@ use crate::ast::visitor; use crate::ast::visitor::Visitor; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// Identify all `ExprKind::Name` nodes in an AST. struct NameFinder<'a> { @@ -62,7 +63,7 @@ pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body: } let mut check = Check::new( - CheckKind::UnusedLoopControlVariable(name.to_string()), + violations::UnusedLoopControlVariable(name.to_string()), Range::from_located(expr), ); if checker.patch(check.kind.code()) { diff --git a/src/flake8_bugbear/plugins/useless_comparison.rs b/src/flake8_bugbear/plugins/useless_comparison.rs index 333ba121b1956..f3e33aa99bccc 100644 --- a/src/flake8_bugbear/plugins/useless_comparison.rs +++ b/src/flake8_bugbear/plugins/useless_comparison.rs @@ -2,12 +2,13 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; pub fn useless_comparison(checker: &mut Checker, expr: &Expr) { if matches!(expr.node, ExprKind::Compare { .. }) { checker.checks.push(Check::new( - CheckKind::UselessComparison, + violations::UselessComparison, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/useless_contextlib_suppress.rs b/src/flake8_bugbear/plugins/useless_contextlib_suppress.rs index 67ab2f501ac3e..8ff9d2620f33c 100644 --- a/src/flake8_bugbear/plugins/useless_contextlib_suppress.rs +++ b/src/flake8_bugbear/plugins/useless_contextlib_suppress.rs @@ -3,7 +3,8 @@ use rustpython_ast::Expr; use crate::ast::helpers::{collect_call_paths, match_call_path}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B005 pub fn useless_contextlib_suppress(checker: &mut Checker, expr: &Expr, args: &[Expr]) { @@ -15,7 +16,7 @@ pub fn useless_contextlib_suppress(checker: &mut Checker, expr: &Expr, args: &[E ) && args.is_empty() { checker.checks.push(Check::new( - CheckKind::UselessContextlibSuppress, + violations::UselessContextlibSuppress, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/plugins/useless_expression.rs b/src/flake8_bugbear/plugins/useless_expression.rs index 94741e35095ec..ea9d82cda9e12 100644 --- a/src/flake8_bugbear/plugins/useless_expression.rs +++ b/src/flake8_bugbear/plugins/useless_expression.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Constant, ExprKind, Stmt, StmtKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; // B018 pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) { @@ -11,7 +12,7 @@ pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) { match &value.node { ExprKind::List { .. } | ExprKind::Dict { .. } | ExprKind::Set { .. } => { checker.checks.push(Check::new( - CheckKind::UselessExpression, + violations::UselessExpression, Range::from_located(value), )); } @@ -19,7 +20,7 @@ pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) { Constant::Str { .. } | Constant::Ellipsis => {} _ => { checker.checks.push(Check::new( - CheckKind::UselessExpression, + violations::UselessExpression, Range::from_located(value), )); } diff --git a/src/flake8_bugbear/plugins/zip_without_explicit_strict.rs b/src/flake8_bugbear/plugins/zip_without_explicit_strict.rs index f7942de92c896..260212fa4fd66 100644 --- a/src/flake8_bugbear/plugins/zip_without_explicit_strict.rs +++ b/src/flake8_bugbear/plugins/zip_without_explicit_strict.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind, Keyword}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// B905 pub fn zip_without_explicit_strict( @@ -23,7 +24,7 @@ pub fn zip_without_explicit_strict( }) { checker.checks.push(Check::new( - CheckKind::ZipWithoutExplicitStrict, + violations::ZipWithoutExplicitStrict, Range::from_located(expr), )); } diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B002_B002.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B002_B002.py.snap index a01149f18f3be..8569db84b7888 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B002_B002.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B002_B002.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: UnaryPrefixIncrement +- kind: + UnaryPrefixIncrement: ~ location: row: 15 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: UnaryPrefixIncrement +- kind: + UnaryPrefixIncrement: ~ location: row: 20 column: 11 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B003_B003.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B003_B003.py.snap index 9fbc60f875be2..f5b9d6749d24f 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B003_B003.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B003_B003.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: AssignmentToOsEnviron +- kind: + AssignmentToOsEnviron: ~ location: row: 9 column: 0 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B004_B004.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B004_B004.py.snap index 983a27224578c..996565f536629 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B004_B004.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B004_B004.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: UnreliableCallableCheck +- kind: + UnreliableCallableCheck: ~ location: row: 3 column: 7 @@ -11,7 +12,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: UnreliableCallableCheck +- kind: + UnreliableCallableCheck: ~ location: row: 5 column: 7 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B005_B005.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B005_B005.py.snap index 7f2faff061a41..b6b25c7cfbac2 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B005_B005.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B005_B005.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: StripWithMultiCharacters +- kind: + StripWithMultiCharacters: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: StripWithMultiCharacters +- kind: + StripWithMultiCharacters: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: StripWithMultiCharacters +- kind: + StripWithMultiCharacters: ~ location: row: 10 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 25 fix: ~ parent: ~ -- kind: StripWithMultiCharacters +- kind: + StripWithMultiCharacters: ~ location: row: 13 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 18 fix: ~ parent: ~ -- kind: StripWithMultiCharacters +- kind: + StripWithMultiCharacters: ~ location: row: 16 column: 0 @@ -47,7 +52,8 @@ expression: checks column: 25 fix: ~ parent: ~ -- kind: StripWithMultiCharacters +- kind: + StripWithMultiCharacters: ~ location: row: 19 column: 0 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B006_B006_B008.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B006_B006_B008.py.snap index 77e5aa23e9661..1e61bddb7f022 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B006_B006_B008.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B006_B006_B008.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 60 column: 24 @@ -11,7 +12,8 @@ expression: checks column: 33 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 64 column: 29 @@ -20,7 +22,8 @@ expression: checks column: 31 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 68 column: 19 @@ -29,7 +32,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 72 column: 19 @@ -38,7 +42,8 @@ expression: checks column: 44 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 76 column: 31 @@ -47,7 +52,8 @@ expression: checks column: 56 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 80 column: 25 @@ -56,7 +62,8 @@ expression: checks column: 44 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 85 column: 45 @@ -65,7 +72,8 @@ expression: checks column: 69 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 89 column: 45 @@ -74,7 +82,8 @@ expression: checks column: 72 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 93 column: 44 @@ -83,7 +92,8 @@ expression: checks column: 68 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 97 column: 32 @@ -92,7 +102,8 @@ expression: checks column: 34 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 170 column: 19 @@ -101,7 +112,8 @@ expression: checks column: 48 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 203 column: 26 @@ -110,7 +122,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 204 column: 34 @@ -119,7 +132,8 @@ expression: checks column: 36 fix: ~ parent: ~ -- kind: MutableArgumentDefault +- kind: + MutableArgumentDefault: ~ location: row: 205 column: 61 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B009_B009_B010.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B009_B009_B010.py.snap index d353c3e21fe25..dd67028f70d7f 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B009_B009_B010.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B009_B009_B010.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: GetAttrWithConstant +- kind: + GetAttrWithConstant: ~ location: row: 18 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 18 column: 19 parent: ~ -- kind: GetAttrWithConstant +- kind: + GetAttrWithConstant: ~ location: row: 19 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 19 column: 23 parent: ~ -- kind: GetAttrWithConstant +- kind: + GetAttrWithConstant: ~ location: row: 20 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 20 column: 22 parent: ~ -- kind: GetAttrWithConstant +- kind: + GetAttrWithConstant: ~ location: row: 21 column: 0 @@ -66,7 +70,8 @@ expression: checks row: 21 column: 23 parent: ~ -- kind: GetAttrWithConstant +- kind: + GetAttrWithConstant: ~ location: row: 22 column: 14 @@ -82,7 +87,8 @@ expression: checks row: 22 column: 31 parent: ~ -- kind: GetAttrWithConstant +- kind: + GetAttrWithConstant: ~ location: row: 23 column: 3 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B010_B009_B010.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B010_B009_B010.py.snap index aaff7454d0000..6bfc63c3f6842 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B010_B009_B010.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B010_B009_B010.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: SetAttrWithConstant +- kind: + SetAttrWithConstant: ~ location: row: 37 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 37 column: 25 parent: ~ -- kind: SetAttrWithConstant +- kind: + SetAttrWithConstant: ~ location: row: 38 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 38 column: 29 parent: ~ -- kind: SetAttrWithConstant +- kind: + SetAttrWithConstant: ~ location: row: 39 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 39 column: 28 parent: ~ -- kind: SetAttrWithConstant +- kind: + SetAttrWithConstant: ~ location: row: 40 column: 0 @@ -66,7 +70,8 @@ expression: checks row: 40 column: 29 parent: ~ -- kind: SetAttrWithConstant +- kind: + SetAttrWithConstant: ~ location: row: 41 column: 0 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B011_B011.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B011_B011.py.snap index b86b2a31220e0..445be230fe3ae 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B011_B011.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B011_B011.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: DoNotAssertFalse +- kind: + DoNotAssertFalse: ~ location: row: 8 column: 7 @@ -18,7 +19,8 @@ expression: checks row: 8 column: 12 parent: ~ -- kind: DoNotAssertFalse +- kind: + DoNotAssertFalse: ~ location: row: 10 column: 7 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B015_B015.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B015_B015.py.snap index cc532803a8f92..79deb155e9746 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B015_B015.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B015_B015.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: UselessComparison +- kind: + UselessComparison: ~ location: row: 3 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: UselessComparison +- kind: + UselessComparison: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: UselessComparison +- kind: + UselessComparison: ~ location: row: 17 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: UselessComparison +- kind: + UselessComparison: ~ location: row: 24 column: 4 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B016_B016.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B016_B016.py.snap index 6c33cc8e98209..b574d5a066b51 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B016_B016.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B016_B016.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: CannotRaiseLiteral +- kind: + CannotRaiseLiteral: ~ location: row: 6 column: 6 @@ -11,7 +12,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: CannotRaiseLiteral +- kind: + CannotRaiseLiteral: ~ location: row: 7 column: 6 @@ -20,7 +22,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: CannotRaiseLiteral +- kind: + CannotRaiseLiteral: ~ location: row: 8 column: 6 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B017_B017.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B017_B017.py.snap index 5dd754b5dad39..55d60e43f7187 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B017_B017.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B017_B017.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: NoAssertRaisesException +- kind: + NoAssertRaisesException: ~ location: row: 22 column: 8 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B018_B018.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B018_B018.py.snap index d3f09d89f6384..eba7b5260706c 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B018_B018.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B018_B018.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 11 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 12 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 5 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 13 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 14 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 15 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 16 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 17 column: 4 @@ -65,7 +72,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 18 column: 4 @@ -74,7 +82,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 19 column: 4 @@ -83,7 +92,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 20 column: 4 @@ -92,7 +102,8 @@ expression: checks column: 18 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 24 column: 4 @@ -101,7 +112,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 27 column: 4 @@ -110,7 +122,8 @@ expression: checks column: 5 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 39 column: 4 @@ -119,7 +132,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 40 column: 4 @@ -128,7 +142,8 @@ expression: checks column: 5 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 41 column: 4 @@ -137,7 +152,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 42 column: 4 @@ -146,7 +162,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 43 column: 4 @@ -155,7 +172,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 44 column: 4 @@ -164,7 +182,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 45 column: 4 @@ -173,7 +192,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 46 column: 4 @@ -182,7 +202,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 47 column: 4 @@ -191,7 +212,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 48 column: 4 @@ -200,7 +222,8 @@ expression: checks column: 18 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 52 column: 4 @@ -209,7 +232,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: UselessExpression +- kind: + UselessExpression: ~ location: row: 55 column: 4 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B019_B019.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B019_B019.py.snap index f3decc8342420..442118373ef1c 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B019_B019.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B019_B019.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 78 column: 5 @@ -11,7 +12,8 @@ expression: checks column: 20 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 82 column: 5 @@ -20,7 +22,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 86 column: 5 @@ -29,7 +32,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 90 column: 5 @@ -38,7 +42,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 94 column: 5 @@ -47,7 +52,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 98 column: 5 @@ -56,7 +62,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 102 column: 5 @@ -65,7 +72,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: CachedInstanceMethod +- kind: + CachedInstanceMethod: ~ location: row: 106 column: 5 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B021_B021.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B021_B021.py.snap index 4f5dd6f917c02..480a313dd540e 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B021_B021.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B021_B021.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 3 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 14 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 22 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 30 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 38 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 46 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 54 column: 4 @@ -65,7 +72,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 62 column: 4 @@ -74,7 +82,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 70 column: 4 @@ -83,7 +92,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: FStringDocstring +- kind: + FStringDocstring: ~ location: row: 74 column: 4 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B022_B022.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B022_B022.py.snap index d19c1dd14eecf..bfae86f7ef97b 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B022_B022.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B022_B022.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: UselessContextlibSuppress +- kind: + UselessContextlibSuppress: ~ location: row: 9 column: 5 @@ -11,7 +12,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: UselessContextlibSuppress +- kind: + UselessContextlibSuppress: ~ location: row: 12 column: 5 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B026_B026.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B026_B026.py.snap index 5d0460a1028d1..1d44bb1c153e7 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B026_B026.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B026_B026.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 16 column: 15 @@ -11,7 +12,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 17 column: 15 @@ -20,7 +22,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 18 column: 26 @@ -29,7 +32,8 @@ expression: checks column: 34 fix: ~ parent: ~ -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 19 column: 37 @@ -38,7 +42,8 @@ expression: checks column: 40 fix: ~ parent: ~ -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 20 column: 15 @@ -47,7 +52,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 20 column: 25 @@ -56,7 +62,8 @@ expression: checks column: 33 fix: ~ parent: ~ -- kind: StarArgUnpackingAfterKeywordArg +- kind: + StarArgUnpackingAfterKeywordArg: ~ location: row: 21 column: 25 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B904_B904.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B904_B904.py.snap index d67f8c71be92b..c9aab2c24f5ec 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B904_B904.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B904_B904.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: RaiseWithoutFromInsideExcept +- kind: + RaiseWithoutFromInsideExcept: ~ location: row: 10 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: RaiseWithoutFromInsideExcept +- kind: + RaiseWithoutFromInsideExcept: ~ location: row: 11 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 21 fix: ~ parent: ~ -- kind: RaiseWithoutFromInsideExcept +- kind: + RaiseWithoutFromInsideExcept: ~ location: row: 16 column: 4 diff --git a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B905_B905.py.snap b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B905_B905.py.snap index 77f1486fbc7c7..e670b111b1ff3 100644 --- a/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B905_B905.py.snap +++ b/src/flake8_bugbear/snapshots/ruff__flake8_bugbear__tests__B905_B905.py.snap @@ -2,7 +2,8 @@ source: src/flake8_bugbear/mod.rs expression: checks --- -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 5 fix: ~ parent: ~ -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 2 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 3 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 4 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 4 column: 15 @@ -47,7 +52,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 5 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: ZipWithoutExplicitStrict +- kind: + ZipWithoutExplicitStrict: ~ location: row: 6 column: 0 diff --git a/src/flake8_builtins/checks.rs b/src/flake8_builtins/checks.rs index a817215096c49..e0631d3de8e38 100644 --- a/src/flake8_builtins/checks.rs +++ b/src/flake8_builtins/checks.rs @@ -4,6 +4,7 @@ use crate::ast::types::Range; use crate::flake8_builtins::types::ShadowingType; use crate::python::builtins::BUILTINS; use crate::registry::{Check, CheckKind}; +use crate::violations; /// Check builtin name shadowing. pub fn builtin_shadowing( @@ -12,11 +13,17 @@ pub fn builtin_shadowing( node_type: ShadowingType, ) -> Option { if BUILTINS.contains(&name) { - Some(Check::new( + Some(Check::new::( match node_type { - ShadowingType::Variable => CheckKind::BuiltinVariableShadowing(name.to_string()), - ShadowingType::Argument => CheckKind::BuiltinArgumentShadowing(name.to_string()), - ShadowingType::Attribute => CheckKind::BuiltinAttributeShadowing(name.to_string()), + ShadowingType::Variable => { + violations::BuiltinVariableShadowing(name.to_string()).into() + } + ShadowingType::Argument => { + violations::BuiltinArgumentShadowing(name.to_string()).into() + } + ShadowingType::Attribute => { + violations::BuiltinAttributeShadowing(name.to_string()).into() + } }, Range::from_located(located), )) diff --git a/src/flake8_comprehensions/checks.rs b/src/flake8_comprehensions/checks.rs index 1a9c5a408d083..173ec9809079f 100644 --- a/src/flake8_comprehensions/checks.rs +++ b/src/flake8_comprehensions/checks.rs @@ -6,8 +6,9 @@ use rustpython_ast::{ use crate::ast::types::Range; use crate::flake8_comprehensions::fixes; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; fn function_name(func: &Expr) -> Option<&str> { if let ExprKind::Name { id, .. } = &func.node { @@ -58,7 +59,7 @@ pub fn unnecessary_generator_list( ) -> Option { let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?; if let ExprKind::GeneratorExp { .. } = argument { - let mut check = Check::new(CheckKind::UnnecessaryGeneratorList, location); + let mut check = Check::new(violations::UnnecessaryGeneratorList, location); if fix { match fixes::fix_unnecessary_generator_list(locator, expr) { Ok(fix) => { @@ -84,7 +85,7 @@ pub fn unnecessary_generator_set( ) -> Option { let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; if let ExprKind::GeneratorExp { .. } = argument { - let mut check = Check::new(CheckKind::UnnecessaryGeneratorSet, location); + let mut check = Check::new(violations::UnnecessaryGeneratorSet, location); if fix { match fixes::fix_unnecessary_generator_set(locator, expr) { Ok(fix) => { @@ -112,7 +113,7 @@ pub fn unnecessary_generator_dict( if let ExprKind::GeneratorExp { elt, .. } = argument { match &elt.node { ExprKind::Tuple { elts, .. } if elts.len() == 2 => { - let mut check = Check::new(CheckKind::UnnecessaryGeneratorDict, location); + let mut check = Check::new(violations::UnnecessaryGeneratorDict, location); if fix { match fixes::fix_unnecessary_generator_dict(locator, expr) { Ok(fix) => { @@ -141,7 +142,7 @@ pub fn unnecessary_list_comprehension_set( ) -> Option { let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; if let ExprKind::ListComp { .. } = &argument { - let mut check = Check::new(CheckKind::UnnecessaryListComprehensionSet, location); + let mut check = Check::new(violations::UnnecessaryListComprehensionSet, location); if fix { match fixes::fix_unnecessary_list_comprehension_set(locator, expr) { Ok(fix) => { @@ -175,7 +176,7 @@ pub fn unnecessary_list_comprehension_dict( if elts.len() != 2 { return None; } - let mut check = Check::new(CheckKind::UnnecessaryListComprehensionDict, location); + let mut check = Check::new(violations::UnnecessaryListComprehensionDict, location); if fix { match fixes::fix_unnecessary_list_comprehension_dict(locator, expr) { Ok(fix) => { @@ -203,7 +204,10 @@ pub fn unnecessary_literal_set( ExprKind::Tuple { .. } => "tuple", _ => return None, }; - let mut check = Check::new(CheckKind::UnnecessaryLiteralSet(kind.to_string()), location); + let mut check = Check::new( + violations::UnnecessaryLiteralSet(kind.to_string()), + location, + ); if fix { match fixes::fix_unnecessary_literal_set(locator, expr) { Ok(fix) => { @@ -239,7 +243,7 @@ pub fn unnecessary_literal_dict( return None; } let mut check = Check::new( - CheckKind::UnnecessaryLiteralDict(kind.to_string()), + violations::UnnecessaryLiteralDict(kind.to_string()), location, ); if fix { @@ -277,7 +281,7 @@ pub fn unnecessary_collection_call( _ => return None, }; let mut check = Check::new( - CheckKind::UnnecessaryCollectionCall(id.to_string()), + violations::UnnecessaryCollectionCall(id.to_string()), location, ); if fix { @@ -307,7 +311,7 @@ pub fn unnecessary_literal_within_tuple_call( _ => return None, }; let mut check = Check::new( - CheckKind::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()), + violations::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()), location, ); if fix { @@ -337,7 +341,7 @@ pub fn unnecessary_literal_within_list_call( _ => return None, }; let mut check = Check::new( - CheckKind::UnnecessaryLiteralWithinListCall(argument_kind.to_string()), + violations::UnnecessaryLiteralWithinListCall(argument_kind.to_string()), location, ); if fix { @@ -364,7 +368,7 @@ pub fn unnecessary_list_call( if !matches!(argument, ExprKind::ListComp { .. }) { return None; } - let mut check = Check::new(CheckKind::UnnecessaryListCall, location); + let mut check = Check::new(violations::UnnecessaryListCall, location); if fix { match fixes::fix_unnecessary_list_call(locator, expr) { Ok(fix) => { @@ -397,7 +401,7 @@ pub fn unnecessary_call_around_sorted( } let mut check = Check::new( - CheckKind::UnnecessaryCallAroundSorted(outer.to_string()), + violations::UnnecessaryCallAroundSorted(outer.to_string()), location, ); if fix { @@ -419,7 +423,7 @@ pub fn unnecessary_double_cast_or_process( ) -> Option { fn new_check(inner: &str, outer: &str, location: Range) -> Check { Check::new( - CheckKind::UnnecessaryDoubleCastOrProcess(inner.to_string(), outer.to_string()), + violations::UnnecessaryDoubleCastOrProcess(inner.to_string(), outer.to_string()), location, ) } @@ -490,7 +494,7 @@ pub fn unnecessary_subscript_reversal( return None; }; Some(Check::new( - CheckKind::UnnecessarySubscriptReversal(id.to_string()), + violations::UnnecessarySubscriptReversal(id.to_string()), location, )) } @@ -522,7 +526,7 @@ pub fn unnecessary_comprehension( _ => return None, }; let mut check = Check::new( - CheckKind::UnnecessaryComprehension(expr_kind.to_string()), + violations::UnnecessaryComprehension(expr_kind.to_string()), location, ); if fix { @@ -539,7 +543,7 @@ pub fn unnecessary_comprehension( /// C417 pub fn unnecessary_map(func: &Expr, args: &[Expr], location: Range) -> Option { fn new_check(kind: &str, location: Range) -> Check { - Check::new(CheckKind::UnnecessaryMap(kind.to_string()), location) + Check::new(violations::UnnecessaryMap(kind.to_string()), location) } let id = function_name(func)?; match id { diff --git a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C400_C400.py.snap b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C400_C400.py.snap index 1a9d0c1ef2a4e..58048f7e20d3e 100644 --- a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C400_C400.py.snap +++ b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C400_C400.py.snap @@ -2,7 +2,8 @@ source: src/flake8_comprehensions/mod.rs expression: checks --- -- kind: UnnecessaryGeneratorList +- kind: + UnnecessaryGeneratorList: ~ location: row: 1 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 1 column: 29 parent: ~ -- kind: UnnecessaryGeneratorList +- kind: + UnnecessaryGeneratorList: ~ location: row: 2 column: 4 diff --git a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C401_C401.py.snap b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C401_C401.py.snap index bc541bfba5c22..4901aa9876e46 100644 --- a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C401_C401.py.snap +++ b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C401_C401.py.snap @@ -2,7 +2,8 @@ source: src/flake8_comprehensions/mod.rs expression: checks --- -- kind: UnnecessaryGeneratorSet +- kind: + UnnecessaryGeneratorSet: ~ location: row: 1 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 1 column: 28 parent: ~ -- kind: UnnecessaryGeneratorSet +- kind: + UnnecessaryGeneratorSet: ~ location: row: 2 column: 4 diff --git a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C402_C402.py.snap b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C402_C402.py.snap index 94833c1e0c9bd..f7a4026a799f4 100644 --- a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C402_C402.py.snap +++ b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C402_C402.py.snap @@ -2,7 +2,8 @@ source: src/flake8_comprehensions/mod.rs expression: checks --- -- kind: UnnecessaryGeneratorDict +- kind: + UnnecessaryGeneratorDict: ~ location: row: 1 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 1 column: 30 parent: ~ -- kind: UnnecessaryGeneratorDict +- kind: + UnnecessaryGeneratorDict: ~ location: row: 2 column: 0 diff --git a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C403_C403.py.snap b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C403_C403.py.snap index 6317dd53e0c51..344166adbedfb 100644 --- a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C403_C403.py.snap +++ b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C403_C403.py.snap @@ -2,7 +2,8 @@ source: src/flake8_comprehensions/mod.rs expression: checks --- -- kind: UnnecessaryListComprehensionSet +- kind: + UnnecessaryListComprehensionSet: ~ location: row: 1 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 1 column: 30 parent: ~ -- kind: UnnecessaryListComprehensionSet +- kind: + UnnecessaryListComprehensionSet: ~ location: row: 2 column: 4 diff --git a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C404_C404.py.snap b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C404_C404.py.snap index 0a030aee01d95..18d42461fdcad 100644 --- a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C404_C404.py.snap +++ b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C404_C404.py.snap @@ -2,7 +2,8 @@ source: src/flake8_comprehensions/mod.rs expression: checks --- -- kind: UnnecessaryListComprehensionDict +- kind: + UnnecessaryListComprehensionDict: ~ location: row: 1 column: 0 diff --git a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C411_C411.py.snap b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C411_C411.py.snap index b38f781c32511..9069948bbbb50 100644 --- a/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C411_C411.py.snap +++ b/src/flake8_comprehensions/snapshots/ruff__flake8_comprehensions__tests__C411_C411.py.snap @@ -2,7 +2,8 @@ source: src/flake8_comprehensions/mod.rs expression: checks --- -- kind: UnnecessaryListCall +- kind: + UnnecessaryListCall: ~ location: row: 2 column: 0 diff --git a/src/flake8_datetimez/plugins.rs b/src/flake8_datetimez/plugins.rs index 4e35c242cdafb..80da2f6a72c5b 100644 --- a/src/flake8_datetimez/plugins.rs +++ b/src/flake8_datetimez/plugins.rs @@ -5,7 +5,8 @@ use crate::ast::helpers::{ }; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; pub fn call_datetime_without_tzinfo( checker: &mut Checker, @@ -23,7 +24,7 @@ pub fn call_datetime_without_tzinfo( if args.len() < 8 && !has_non_none_keyword(keywords, "tzinfo") { checker .checks - .push(Check::new(CheckKind::CallDatetimeWithoutTzinfo, location)); + .push(Check::new(violations::CallDatetimeWithoutTzinfo, location)); return; } @@ -31,7 +32,7 @@ pub fn call_datetime_without_tzinfo( if args.len() >= 8 && is_const_none(&args[7]) { checker .checks - .push(Check::new(CheckKind::CallDatetimeWithoutTzinfo, location)); + .push(Check::new(violations::CallDatetimeWithoutTzinfo, location)); } } @@ -46,7 +47,7 @@ pub fn call_datetime_today(checker: &mut Checker, func: &Expr, location: Range) ) { checker .checks - .push(Check::new(CheckKind::CallDatetimeToday, location)); + .push(Check::new(violations::CallDatetimeToday, location)); } } @@ -61,7 +62,7 @@ pub fn call_datetime_utcnow(checker: &mut Checker, func: &Expr, location: Range) ) { checker .checks - .push(Check::new(CheckKind::CallDatetimeUtcnow, location)); + .push(Check::new(violations::CallDatetimeUtcnow, location)); } } @@ -75,7 +76,7 @@ pub fn call_datetime_utcfromtimestamp(checker: &mut Checker, func: &Expr, locati &checker.from_imports, ) { checker.checks.push(Check::new( - CheckKind::CallDatetimeUtcfromtimestamp, + violations::CallDatetimeUtcfromtimestamp, location, )); } @@ -102,7 +103,7 @@ pub fn call_datetime_now_without_tzinfo( // no args / no args unqualified if args.is_empty() && keywords.is_empty() { checker.checks.push(Check::new( - CheckKind::CallDatetimeNowWithoutTzinfo, + violations::CallDatetimeNowWithoutTzinfo, location, )); return; @@ -111,7 +112,7 @@ pub fn call_datetime_now_without_tzinfo( // none args if !args.is_empty() && is_const_none(&args[0]) { checker.checks.push(Check::new( - CheckKind::CallDatetimeNowWithoutTzinfo, + violations::CallDatetimeNowWithoutTzinfo, location, )); return; @@ -120,7 +121,7 @@ pub fn call_datetime_now_without_tzinfo( // wrong keywords / none keyword if !keywords.is_empty() && !has_non_none_keyword(keywords, "tz") { checker.checks.push(Check::new( - CheckKind::CallDatetimeNowWithoutTzinfo, + violations::CallDatetimeNowWithoutTzinfo, location, )); } @@ -148,7 +149,7 @@ pub fn call_datetime_fromtimestamp( if args.len() < 2 && keywords.is_empty() { checker .checks - .push(Check::new(CheckKind::CallDatetimeFromtimestamp, location)); + .push(Check::new(violations::CallDatetimeFromtimestamp, location)); return; } @@ -156,7 +157,7 @@ pub fn call_datetime_fromtimestamp( if args.len() > 1 && is_const_none(&args[1]) { checker .checks - .push(Check::new(CheckKind::CallDatetimeFromtimestamp, location)); + .push(Check::new(violations::CallDatetimeFromtimestamp, location)); return; } @@ -164,7 +165,7 @@ pub fn call_datetime_fromtimestamp( if !keywords.is_empty() && !has_non_none_keyword(keywords, "tz") { checker .checks - .push(Check::new(CheckKind::CallDatetimeFromtimestamp, location)); + .push(Check::new(violations::CallDatetimeFromtimestamp, location)); } } @@ -198,7 +199,7 @@ pub fn call_datetime_strptime_without_zone( let (Some(grandparent), Some(parent)) = (checker.current_expr_grandparent(), checker.current_expr_parent()) else { checker.checks.push(Check::new( - CheckKind::CallDatetimeStrptimeWithoutZone, + violations::CallDatetimeStrptimeWithoutZone, location, )); return; @@ -221,7 +222,7 @@ pub fn call_datetime_strptime_without_zone( } checker.checks.push(Check::new( - CheckKind::CallDatetimeStrptimeWithoutZone, + violations::CallDatetimeStrptimeWithoutZone, location, )); } @@ -232,7 +233,7 @@ pub fn call_date_today(checker: &mut Checker, func: &Expr, location: Range) { if match_call_path(&call_path, "datetime.date", "today", &checker.from_imports) { checker .checks - .push(Check::new(CheckKind::CallDateToday, location)); + .push(Check::new(violations::CallDateToday, location)); } } @@ -247,6 +248,6 @@ pub fn call_date_fromtimestamp(checker: &mut Checker, func: &Expr, location: Ran ) { checker .checks - .push(Check::new(CheckKind::CallDateFromtimestamp, location)); + .push(Check::new(violations::CallDateFromtimestamp, location)); } } diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ001_DTZ001.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ001_DTZ001.py.snap index 5f7b0b7da5647..715194954fa30 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ001_DTZ001.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ001_DTZ001.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeWithoutTzinfo +- kind: + CallDatetimeWithoutTzinfo: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 38 fix: ~ parent: ~ -- kind: CallDatetimeWithoutTzinfo +- kind: + CallDatetimeWithoutTzinfo: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 47 fix: ~ parent: ~ -- kind: CallDatetimeWithoutTzinfo +- kind: + CallDatetimeWithoutTzinfo: ~ location: row: 13 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 37 fix: ~ parent: ~ -- kind: CallDatetimeWithoutTzinfo +- kind: + CallDatetimeWithoutTzinfo: ~ location: row: 16 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 42 fix: ~ parent: ~ -- kind: CallDatetimeWithoutTzinfo +- kind: + CallDatetimeWithoutTzinfo: ~ location: row: 21 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ002_DTZ002.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ002_DTZ002.py.snap index 525ce1451389c..2ff1d1ce92c74 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ002_DTZ002.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ002_DTZ002.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeToday +- kind: + CallDatetimeToday: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 25 fix: ~ parent: ~ -- kind: CallDatetimeToday +- kind: + CallDatetimeToday: ~ location: row: 9 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ003_DTZ003.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ003_DTZ003.py.snap index 54bcea1312dc7..fded301a70d43 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ003_DTZ003.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ003_DTZ003.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeUtcnow +- kind: + CallDatetimeUtcnow: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: CallDatetimeUtcnow +- kind: + CallDatetimeUtcnow: ~ location: row: 9 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ004_DTZ004.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ004_DTZ004.py.snap index 9be1a8af4751d..8752839367f35 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ004_DTZ004.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ004_DTZ004.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeUtcfromtimestamp +- kind: + CallDatetimeUtcfromtimestamp: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 40 fix: ~ parent: ~ -- kind: CallDatetimeUtcfromtimestamp +- kind: + CallDatetimeUtcfromtimestamp: ~ location: row: 9 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ005_DTZ005.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ005_DTZ005.py.snap index 0fe77d5667a72..09d04c3438000 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ005_DTZ005.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ005_DTZ005.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeNowWithoutTzinfo +- kind: + CallDatetimeNowWithoutTzinfo: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: CallDatetimeNowWithoutTzinfo +- kind: + CallDatetimeNowWithoutTzinfo: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 48 fix: ~ parent: ~ -- kind: CallDatetimeNowWithoutTzinfo +- kind: + CallDatetimeNowWithoutTzinfo: ~ location: row: 10 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 27 fix: ~ parent: ~ -- kind: CallDatetimeNowWithoutTzinfo +- kind: + CallDatetimeNowWithoutTzinfo: ~ location: row: 13 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: CallDatetimeNowWithoutTzinfo +- kind: + CallDatetimeNowWithoutTzinfo: ~ location: row: 18 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ006_DTZ006.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ006_DTZ006.py.snap index 628d6630437a0..25ed8950a8d87 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ006_DTZ006.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ006_DTZ006.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeFromtimestamp +- kind: + CallDatetimeFromtimestamp: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 37 fix: ~ parent: ~ -- kind: CallDatetimeFromtimestamp +- kind: + CallDatetimeFromtimestamp: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 64 fix: ~ parent: ~ -- kind: CallDatetimeFromtimestamp +- kind: + CallDatetimeFromtimestamp: ~ location: row: 10 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 43 fix: ~ parent: ~ -- kind: CallDatetimeFromtimestamp +- kind: + CallDatetimeFromtimestamp: ~ location: row: 13 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 46 fix: ~ parent: ~ -- kind: CallDatetimeFromtimestamp +- kind: + CallDatetimeFromtimestamp: ~ location: row: 18 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ007_DTZ007.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ007_DTZ007.py.snap index e021390a92513..309257b12abca 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ007_DTZ007.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ007_DTZ007.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDatetimeStrptimeWithoutZone +- kind: + CallDatetimeStrptimeWithoutZone: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 53 fix: ~ parent: ~ -- kind: CallDatetimeStrptimeWithoutZone +- kind: + CallDatetimeStrptimeWithoutZone: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 52 fix: ~ parent: ~ -- kind: CallDatetimeStrptimeWithoutZone +- kind: + CallDatetimeStrptimeWithoutZone: ~ location: row: 10 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 52 fix: ~ parent: ~ -- kind: CallDatetimeStrptimeWithoutZone +- kind: + CallDatetimeStrptimeWithoutZone: ~ location: row: 13 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 52 fix: ~ parent: ~ -- kind: CallDatetimeStrptimeWithoutZone +- kind: + CallDatetimeStrptimeWithoutZone: ~ location: row: 35 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ011_DTZ011.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ011_DTZ011.py.snap index 4267ffcdc16c0..edea49b52a740 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ011_DTZ011.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ011_DTZ011.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDateToday +- kind: + CallDateToday: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 21 fix: ~ parent: ~ -- kind: CallDateToday +- kind: + CallDateToday: ~ location: row: 9 column: 0 diff --git a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ012_DTZ012.py.snap b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ012_DTZ012.py.snap index 05efd44f9c339..317c897862b63 100644 --- a/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ012_DTZ012.py.snap +++ b/src/flake8_datetimez/snapshots/ruff__flake8_datetimez__tests__DTZ012_DTZ012.py.snap @@ -2,7 +2,8 @@ source: src/flake8_datetimez/mod.rs expression: checks --- -- kind: CallDateFromtimestamp +- kind: + CallDateFromtimestamp: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 33 fix: ~ parent: ~ -- kind: CallDateFromtimestamp +- kind: + CallDateFromtimestamp: ~ location: row: 9 column: 0 diff --git a/src/flake8_debugger/checks.rs b/src/flake8_debugger/checks.rs index f1225294b6b66..2f34c8d3e7ac6 100644 --- a/src/flake8_debugger/checks.rs +++ b/src/flake8_debugger/checks.rs @@ -4,7 +4,8 @@ use rustpython_ast::{Expr, Stmt}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::types::Range; use crate::flake8_debugger::types::DebuggerUsingType; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const DEBUGGERS: &[(&str, &str)] = &[ ("pdb", "set_trace"), @@ -31,7 +32,7 @@ pub fn debugger_call( .any(|(module, member)| match_call_path(&call_path, module, member, from_imports)) { Some(Check::new( - CheckKind::Debugger(DebuggerUsingType::Call(call_path.join("."))), + violations::Debugger(DebuggerUsingType::Call(call_path.join("."))), Range::from_located(expr), )) } else { @@ -53,7 +54,7 @@ pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option< .find(|(module_name, member)| module_name == &module && member == &name) { return Some(Check::new( - CheckKind::Debugger(DebuggerUsingType::Import(format!("{module_name}.{member}"))), + violations::Debugger(DebuggerUsingType::Import(format!("{module_name}.{member}"))), Range::from_located(stmt), )); } @@ -62,7 +63,7 @@ pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option< .any(|(module_name, ..)| module_name == &name) { return Some(Check::new( - CheckKind::Debugger(DebuggerUsingType::Import(name.to_string())), + violations::Debugger(DebuggerUsingType::Import(name.to_string())), Range::from_located(stmt), )); } diff --git a/src/flake8_errmsg/plugins.rs b/src/flake8_errmsg/plugins.rs index 35d1f5a9424c2..d00f306aa4d54 100644 --- a/src/flake8_errmsg/plugins.rs +++ b/src/flake8_errmsg/plugins.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// EM101, EM102, EM103 pub fn string_in_exception(checker: &mut Checker, exc: &Expr) { @@ -17,7 +18,7 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) { if checker.settings.enabled.contains(&CheckCode::EM101) { if string.len() > checker.settings.flake8_errmsg.max_string_length { checker.checks.push(Check::new( - CheckKind::RawStringInException, + violations::RawStringInException, Range::from_located(first), )); } @@ -27,7 +28,7 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) { ExprKind::JoinedStr { .. } => { if checker.settings.enabled.contains(&CheckCode::EM102) { checker.checks.push(Check::new( - CheckKind::FStringInException, + violations::FStringInException, Range::from_located(first), )); } @@ -38,7 +39,7 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) { if let ExprKind::Attribute { value, attr, .. } = &func.node { if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) { checker.checks.push(Check::new( - CheckKind::DotFormatInException, + violations::DotFormatInException, Range::from_located(first), )); } diff --git a/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__custom.snap b/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__custom.snap index 2a4e9671c47e7..5482c577d7649 100644 --- a/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__custom.snap +++ b/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__custom.snap @@ -2,7 +2,8 @@ source: src/flake8_errmsg/mod.rs expression: checks --- -- kind: RawStringInException +- kind: + RawStringInException: ~ location: row: 5 column: 23 @@ -11,7 +12,8 @@ expression: checks column: 53 fix: ~ parent: ~ -- kind: FStringInException +- kind: + FStringInException: ~ location: row: 14 column: 23 @@ -20,7 +22,8 @@ expression: checks column: 56 fix: ~ parent: ~ -- kind: DotFormatInException +- kind: + DotFormatInException: ~ location: row: 18 column: 23 diff --git a/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__defaults.snap b/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__defaults.snap index c2331e8421c04..3ca1c73c5fa3d 100644 --- a/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__defaults.snap +++ b/src/flake8_errmsg/snapshots/ruff__flake8_errmsg__tests__defaults.snap @@ -2,7 +2,8 @@ source: src/flake8_errmsg/mod.rs expression: checks --- -- kind: RawStringInException +- kind: + RawStringInException: ~ location: row: 5 column: 23 @@ -11,7 +12,8 @@ expression: checks column: 53 fix: ~ parent: ~ -- kind: RawStringInException +- kind: + RawStringInException: ~ location: row: 9 column: 23 @@ -20,7 +22,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: FStringInException +- kind: + FStringInException: ~ location: row: 14 column: 23 @@ -29,7 +32,8 @@ expression: checks column: 56 fix: ~ parent: ~ -- kind: DotFormatInException +- kind: + DotFormatInException: ~ location: row: 18 column: 23 diff --git a/src/flake8_implicit_str_concat/checks.rs b/src/flake8_implicit_str_concat/checks.rs index cc12907160377..136627641e0c2 100644 --- a/src/flake8_implicit_str_concat/checks.rs +++ b/src/flake8_implicit_str_concat/checks.rs @@ -3,8 +3,9 @@ use rustpython_ast::{Constant, Expr, ExprKind, Location, Operator}; use rustpython_parser::lexer::{LexResult, Tok}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; /// ISC001, ISC002 pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec { @@ -15,7 +16,7 @@ pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec if matches!(a_tok, Tok::String { .. }) && matches!(b_tok, Tok::String { .. }) { if a_end.row() == b_start.row() { checks.push(Check::new( - CheckKind::SingleLineImplicitStringConcatenation, + violations::SingleLineImplicitStringConcatenation, Range { location: *a_start, end_location: *b_end, @@ -30,7 +31,7 @@ pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec }); if contents.trim_end().ends_with('\\') { checks.push(Check::new( - CheckKind::MultiLineImplicitStringConcatenation, + violations::MultiLineImplicitStringConcatenation, Range { location: *a_start, end_location: *b_end, @@ -63,7 +64,7 @@ pub fn explicit(expr: &Expr) -> Option { } ) { return Some(Check::new( - CheckKind::ExplicitStringConcatenation, + violations::ExplicitStringConcatenation, Range::from_located(expr), )); } diff --git a/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap b/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap index 70e347bf1d159..712c221d59cae 100644 --- a/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap +++ b/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC001_ISC.py.snap @@ -2,7 +2,8 @@ source: src/flake8_implicit_str_concat/mod.rs expression: checks --- -- kind: SingleLineImplicitStringConcatenation +- kind: + SingleLineImplicitStringConcatenation: ~ location: row: 1 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: SingleLineImplicitStringConcatenation +- kind: + SingleLineImplicitStringConcatenation: ~ location: row: 1 column: 8 diff --git a/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC002_ISC.py.snap b/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC002_ISC.py.snap index 688edf4bb8d32..c5463841f8542 100644 --- a/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC002_ISC.py.snap +++ b/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC002_ISC.py.snap @@ -2,7 +2,8 @@ source: src/flake8_implicit_str_concat/mod.rs expression: checks --- -- kind: MultiLineImplicitStringConcatenation +- kind: + MultiLineImplicitStringConcatenation: ~ location: row: 5 column: 4 diff --git a/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap b/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap index a1eaa682e4d8f..81a5b4a9096e4 100644 --- a/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap +++ b/src/flake8_implicit_str_concat/snapshots/ruff__flake8_implicit_str_concat__tests__ISC003_ISC.py.snap @@ -2,7 +2,8 @@ source: src/flake8_implicit_str_concat/mod.rs expression: checks --- -- kind: ExplicitStringConcatenation +- kind: + ExplicitStringConcatenation: ~ location: row: 3 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: ExplicitStringConcatenation +- kind: + ExplicitStringConcatenation: ~ location: row: 9 column: 2 @@ -20,7 +22,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: ExplicitStringConcatenation +- kind: + ExplicitStringConcatenation: ~ location: row: 14 column: 2 @@ -29,7 +32,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: ExplicitStringConcatenation +- kind: + ExplicitStringConcatenation: ~ location: row: 19 column: 2 diff --git a/src/flake8_import_conventions/checks.rs b/src/flake8_import_conventions/checks.rs index 5baae84634ea0..6577e15e5843b 100644 --- a/src/flake8_import_conventions/checks.rs +++ b/src/flake8_import_conventions/checks.rs @@ -2,7 +2,8 @@ use rustc_hash::FxHashMap; use rustpython_ast::Stmt; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// ICN001 pub fn check_conventional_import( @@ -24,7 +25,7 @@ pub fn check_conventional_import( } if !is_valid_import { return Some(Check::new( - CheckKind::ImportAliasIsNotConventional( + violations::ImportAliasIsNotConventional( name.to_string(), expected_alias.to_string(), ), diff --git a/src/flake8_pie/plugins.rs b/src/flake8_pie/plugins.rs index d5cdc6ac1ae60..06029d509845a 100644 --- a/src/flake8_pie/plugins.rs +++ b/src/flake8_pie/plugins.rs @@ -6,7 +6,8 @@ use crate::ast::types::Range; use crate::autofix::helpers::delete_stmt; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// PIE790 pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) { @@ -26,8 +27,10 @@ pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) { } ) { if matches!(pass_stmt.node, StmtKind::Pass) { - let mut check = - Check::new(CheckKind::NoUnnecessaryPass, Range::from_located(pass_stmt)); + let mut check = Check::new( + violations::NoUnnecessaryPass, + Range::from_located(pass_stmt), + ); if checker.patch(&CheckCode::PIE790) { match delete_stmt(pass_stmt, None, &[], checker.locator) { Ok(fix) => { @@ -76,7 +79,7 @@ pub fn dupe_class_field_definitions(checker: &mut Checker, bases: &[Expr], body: if seen_targets.contains(target) { let mut check = Check::new( - CheckKind::DupeClassFieldDefinitions(target.to_string()), + violations::DupeClassFieldDefinitions(target.to_string()), Range::from_located(stmt), ); if checker.patch(&CheckCode::PIE794) { @@ -97,7 +100,8 @@ pub fn prefer_list_builtin(checker: &mut Checker, expr: &Expr) { if args.args.is_empty() { if let ExprKind::List { elts, .. } = &body.node { if elts.is_empty() { - let mut check = Check::new(CheckKind::PreferListBuiltin, Range::from_located(expr)); + let mut check = + Check::new(violations::PreferListBuiltin, Range::from_located(expr)); if checker.patch(&CheckCode::PIE807) { check.amend(Fix::replacement( "list".to_string(), diff --git a/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE790_PIE790.py.snap b/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE790_PIE790.py.snap index 2288dabfa94ff..422b7b7ef91c9 100644 --- a/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE790_PIE790.py.snap +++ b/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE790_PIE790.py.snap @@ -2,7 +2,8 @@ source: src/flake8_pie/mod.rs expression: checks --- -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 4 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 5 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 9 column: 4 @@ -34,7 +36,8 @@ expression: checks row: 10 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 14 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 14 column: 10 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 21 column: 4 @@ -66,7 +70,8 @@ expression: checks row: 22 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 28 column: 4 @@ -82,7 +87,8 @@ expression: checks row: 29 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 35 column: 4 @@ -98,7 +104,8 @@ expression: checks row: 36 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 42 column: 4 @@ -114,7 +121,8 @@ expression: checks row: 43 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 50 column: 4 @@ -130,7 +138,8 @@ expression: checks row: 51 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 58 column: 4 @@ -146,7 +155,8 @@ expression: checks row: 59 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 65 column: 4 @@ -162,7 +172,8 @@ expression: checks row: 66 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 74 column: 4 @@ -178,7 +189,8 @@ expression: checks row: 75 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 79 column: 4 @@ -194,7 +206,8 @@ expression: checks row: 80 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 83 column: 4 @@ -210,7 +223,8 @@ expression: checks row: 84 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 87 column: 4 @@ -226,7 +240,8 @@ expression: checks row: 88 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 92 column: 4 @@ -242,7 +257,8 @@ expression: checks row: 93 column: 0 parent: ~ -- kind: NoUnnecessaryPass +- kind: + NoUnnecessaryPass: ~ location: row: 96 column: 4 diff --git a/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE807_PIE807.py.snap b/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE807_PIE807.py.snap index 20e2b61da9740..2f34e8fa737f3 100644 --- a/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE807_PIE807.py.snap +++ b/src/flake8_pie/snapshots/ruff__flake8_pie__tests__PIE807_PIE807.py.snap @@ -2,7 +2,8 @@ source: src/flake8_pie/mod.rs expression: checks --- -- kind: PreferListBuiltin +- kind: + PreferListBuiltin: ~ location: row: 3 column: 43 @@ -18,7 +19,8 @@ expression: checks row: 3 column: 53 parent: ~ -- kind: PreferListBuiltin +- kind: + PreferListBuiltin: ~ location: row: 7 column: 35 @@ -34,7 +36,8 @@ expression: checks row: 7 column: 45 parent: ~ -- kind: PreferListBuiltin +- kind: + PreferListBuiltin: ~ location: row: 11 column: 27 diff --git a/src/flake8_print/plugins/print_call.rs b/src/flake8_print/plugins/print_call.rs index 9621f5860eb0f..df50a0f945137 100644 --- a/src/flake8_print/plugins/print_call.rs +++ b/src/flake8_print/plugins/print_call.rs @@ -5,7 +5,8 @@ use crate::ast::helpers::{collect_call_paths, dealias_call_path, is_const_none, use crate::ast::types::Range; use crate::autofix::helpers; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// T201, T203 pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) { @@ -27,9 +28,9 @@ pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) { } } } - Check::new(CheckKind::PrintFound, Range::from_located(func)) + Check::new(violations::PrintFound, Range::from_located(func)) } else if match_call_path(&call_path, "pprint", "pprint", &checker.from_imports) { - Check::new(CheckKind::PPrintFound, Range::from_located(func)) + Check::new(violations::PPrintFound, Range::from_located(func)) } else { return; } diff --git a/src/flake8_print/snapshots/ruff__flake8_print__tests__T201_T201.py.snap b/src/flake8_print/snapshots/ruff__flake8_print__tests__T201_T201.py.snap index 934b904593457..d77696ac2d638 100644 --- a/src/flake8_print/snapshots/ruff__flake8_print__tests__T201_T201.py.snap +++ b/src/flake8_print/snapshots/ruff__flake8_print__tests__T201_T201.py.snap @@ -2,7 +2,8 @@ source: src/flake8_print/mod.rs expression: checks --- -- kind: PrintFound +- kind: + PrintFound: ~ location: row: 4 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 5 column: 0 parent: ~ -- kind: PrintFound +- kind: + PrintFound: ~ location: row: 5 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 6 column: 0 parent: ~ -- kind: PrintFound +- kind: + PrintFound: ~ location: row: 6 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 7 column: 0 parent: ~ -- kind: PrintFound +- kind: + PrintFound: ~ location: row: 7 column: 0 diff --git a/src/flake8_print/snapshots/ruff__flake8_print__tests__T203_T203.py.snap b/src/flake8_print/snapshots/ruff__flake8_print__tests__T203_T203.py.snap index a897c14d84ae0..c3d6dc321049e 100644 --- a/src/flake8_print/snapshots/ruff__flake8_print__tests__T203_T203.py.snap +++ b/src/flake8_print/snapshots/ruff__flake8_print__tests__T203_T203.py.snap @@ -2,7 +2,8 @@ source: src/flake8_print/mod.rs expression: checks --- -- kind: PPrintFound +- kind: + PPrintFound: ~ location: row: 3 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 4 column: 0 parent: ~ -- kind: PPrintFound +- kind: + PPrintFound: ~ location: row: 7 column: 0 diff --git a/src/flake8_pytest_style/plugins/assertion.rs b/src/flake8_pytest_style/plugins/assertion.rs index 18bd0296a024a..c472bc61c15fa 100644 --- a/src/flake8_pytest_style/plugins/assertion.rs +++ b/src/flake8_pytest_style/plugins/assertion.rs @@ -1,12 +1,17 @@ use rustpython_ast::{ - Boolop, Excepthandler, ExcepthandlerKind, Expr, ExprKind, Stmt, StmtKind, Unaryop, + Boolop, Excepthandler, ExcepthandlerKind, Expr, ExprKind, Keyword, Stmt, StmtKind, Unaryop, }; use super::helpers::is_falsy_constant; +use super::unittest_assert::UnittestAssert; +use crate::ast::helpers::unparse_stmt; use crate::ast::types::Range; use crate::ast::visitor; use crate::ast::visitor::Visitor; -use crate::registry::{Check, CheckKind}; +use crate::autofix::Fix; +use crate::checkers::ast::Checker; +use crate::registry::Check; +use crate::violations; /// Visitor that tracks assert statements and checks if they reference /// the exception name. @@ -47,7 +52,7 @@ where if let Some(current_assert) = self.current_assert { if id.as_str() == self.exception_name { self.errors.push(Check::new( - CheckKind::AssertInExcept(id.to_string()), + violations::AssertInExcept(id.to_string()), Range::from_located(current_assert), )); } @@ -58,42 +63,6 @@ where } } -const UNITTEST_ASSERT_NAMES: &[&str] = &[ - "assertAlmostEqual", - "assertAlmostEquals", - "assertDictEqual", - "assertEqual", - "assertEquals", - "assertFalse", - "assertGreater", - "assertGreaterEqual", - "assertIn", - "assertIs", - "assertIsInstance", - "assertIsNone", - "assertIsNot", - "assertIsNotNone", - "assertItemsEqual", - "assertLess", - "assertLessEqual", - "assertMultiLineEqual", - "assertNotAlmostEqual", - "assertNotAlmostEquals", - "assertNotContains", - "assertNotEqual", - "assertNotEquals", - "assertNotIn", - "assertNotIsInstance", - "assertNotRegexpMatches", - "assertRaises", - "assertRaisesMessage", - "assertRaisesRegexp", - "assertRegexpMatches", - "assertSetEqual", - "assertTrue", - "assert_", -]; - /// Check if the test expression is a composite condition. /// For example, `a and b` or `not (a or b)`. The latter is equivalent /// to `not a and not b` by De Morgan's laws. @@ -120,14 +89,30 @@ fn check_assert_in_except(name: &str, body: &[Stmt]) -> Vec { } /// PT009 -pub fn unittest_assertion(call: &Expr) -> Option { - match &call.node { +pub fn unittest_assertion( + checker: &Checker, + call: &Expr, + func: &Expr, + args: &[Expr], + keywords: &[Keyword], +) -> Option { + match &func.node { ExprKind::Attribute { attr, .. } => { - if UNITTEST_ASSERT_NAMES.contains(&attr.as_str()) { - Some(Check::new( - CheckKind::UnittestAssertion(attr.to_string()), - Range::from_located(call), - )) + if let Ok(unittest_assert) = UnittestAssert::try_from(attr.as_str()) { + let mut check = Check::new( + violations::UnittestAssertion(unittest_assert.to_string()), + Range::from_located(func), + ); + if checker.patch(check.kind.code()) { + if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) { + check.amend(Fix::replacement( + unparse_stmt(&stmt, checker.style), + call.location, + call.end_location.unwrap(), + )); + } + } + Some(check) } else { None } @@ -140,7 +125,7 @@ pub fn unittest_assertion(call: &Expr) -> Option { pub fn assert_falsy(assert_stmt: &Stmt, test_expr: &Expr) -> Option { if is_falsy_constant(test_expr) { Some(Check::new( - CheckKind::AssertAlwaysFalse, + violations::AssertAlwaysFalse, Range::from_located(assert_stmt), )) } else { @@ -168,7 +153,7 @@ pub fn assert_in_exception_handler(handlers: &[Excepthandler]) -> Vec { pub fn composite_condition(assert_stmt: &Stmt, test_expr: &Expr) -> Option { if is_composite_condition(test_expr) { Some(Check::new( - CheckKind::CompositeAssertion, + violations::CompositeAssertion, Range::from_located(assert_stmt), )) } else { diff --git a/src/flake8_pytest_style/plugins/fail.rs b/src/flake8_pytest_style/plugins/fail.rs index 6af19fdfb626c..0e2a161c4599d 100644 --- a/src/flake8_pytest_style/plugins/fail.rs +++ b/src/flake8_pytest_style/plugins/fail.rs @@ -4,7 +4,8 @@ use super::helpers::{is_empty_or_null_string, is_pytest_fail}; use crate::ast::helpers::SimpleCallArgs; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; pub fn fail_call(checker: &mut Checker, call: &Expr, args: &[Expr], keywords: &[Keyword]) { if is_pytest_fail(call, checker) { @@ -14,13 +15,13 @@ pub fn fail_call(checker: &mut Checker, call: &Expr, args: &[Expr], keywords: &[ if let Some(msg) = msg { if is_empty_or_null_string(msg) { checker.checks.push(Check::new( - CheckKind::FailWithoutMessage, + violations::FailWithoutMessage, Range::from_located(call), )); } } else { checker.checks.push(Check::new( - CheckKind::FailWithoutMessage, + violations::FailWithoutMessage, Range::from_located(call), )); } diff --git a/src/flake8_pytest_style/plugins/fixture.rs b/src/flake8_pytest_style/plugins/fixture.rs index 6b893ce910a11..cc5f94fd2fecd 100644 --- a/src/flake8_pytest_style/plugins/fixture.rs +++ b/src/flake8_pytest_style/plugins/fixture.rs @@ -10,7 +10,8 @@ use crate::ast::visitor; use crate::ast::visitor::Visitor; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; #[derive(Default)] /// Visitor that skips functions @@ -79,7 +80,7 @@ fn pytest_fixture_parentheses( actual: &str, ) { let mut check = Check::new( - CheckKind::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()), + violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()), Range::from_located(decorator), ); if checker.patch(check.kind.code()) { @@ -112,7 +113,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E if checker.settings.enabled.contains(&CheckCode::PT002) && !args.is_empty() { checker.checks.push(Check::new( - CheckKind::FixturePositionalArgs(func_name.to_string()), + violations::FixturePositionalArgs(func_name.to_string()), Range::from_located(decorator), )); } @@ -125,7 +126,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E if let Some(scope_keyword) = scope_keyword { if keyword_is_literal(scope_keyword, "function") { checker.checks.push(Check::new( - CheckKind::ExtraneousScopeFunction, + violations::ExtraneousScopeFunction, Range::from_located(scope_keyword), )); } @@ -156,7 +157,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo && func_name.starts_with('_') { checker.checks.push(Check::new( - CheckKind::IncorrectFixtureNameUnderscore(func_name.to_string()), + violations::IncorrectFixtureNameUnderscore(func_name.to_string()), Range::from_located(func), )); } else if checker.settings.enabled.contains(&CheckCode::PT004) @@ -165,7 +166,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo && !func_name.starts_with('_') { checker.checks.push(Check::new( - CheckKind::MissingFixtureNameUnderscore(func_name.to_string()), + violations::MissingFixtureNameUnderscore(func_name.to_string()), Range::from_located(func), )); } @@ -176,7 +177,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo if let ExprKind::Yield { .. } = value.node { if visitor.yield_statements.len() == 1 { let mut check = Check::new( - CheckKind::UselessYieldFixture(func_name.to_string()), + violations::UselessYieldFixture(func_name.to_string()), Range::from_located(stmt), ); if checker.patch(check.kind.code()) { @@ -203,7 +204,7 @@ fn check_test_function_args(checker: &mut Checker, args: &Arguments) { let name = arg.node.arg.to_string(); if name.starts_with('_') { checker.checks.push(Check::new( - CheckKind::FixtureParamWithoutValue(name), + violations::FixtureParamWithoutValue(name), Range::from_located(arg), )); } @@ -214,7 +215,7 @@ fn check_test_function_args(checker: &mut Checker, args: &Arguments) { fn check_fixture_decorator_name(checker: &mut Checker, decorator: &Expr) { if is_pytest_yield_fixture(decorator, checker) { checker.checks.push(Check::new( - CheckKind::DeprecatedYieldFixture, + violations::DeprecatedYieldFixture, Range::from_located(decorator), )); } @@ -234,7 +235,7 @@ fn check_fixture_addfinalizer(checker: &mut Checker, args: &Arguments, body: &[S if let Some(addfinalizer) = visitor.addfinalizer_call { checker.checks.push(Check::new( - CheckKind::FixtureFinalizerCallback, + violations::FixtureFinalizerCallback, Range::from_located(addfinalizer), )); } @@ -248,7 +249,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) { if checker.settings.enabled.contains(&CheckCode::PT024) { if name == "asyncio" { checker.checks.push(Check::new( - CheckKind::UnnecessaryAsyncioMarkOnFixture, + violations::UnnecessaryAsyncioMarkOnFixture, Range::from_located(mark), )); } @@ -257,7 +258,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) { if checker.settings.enabled.contains(&CheckCode::PT025) { if name == "usefixtures" { checker.checks.push(Check::new( - CheckKind::ErroneousUseFixturesOnFixture, + violations::ErroneousUseFixturesOnFixture, Range::from_located(mark), )); } diff --git a/src/flake8_pytest_style/plugins/imports.rs b/src/flake8_pytest_style/plugins/imports.rs index 876518181921a..b75fe22236c52 100644 --- a/src/flake8_pytest_style/plugins/imports.rs +++ b/src/flake8_pytest_style/plugins/imports.rs @@ -1,7 +1,8 @@ use rustpython_ast::Stmt; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn is_pytest_or_subpackage(imported_name: &str) -> bool { imported_name == "pytest" || imported_name.starts_with("pytest.") @@ -13,7 +14,7 @@ pub fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option(checker: &Checker, decorators: &'a [Expr]) -> Option<&'a Expr> { decorators @@ -80,7 +81,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) { match names_type { types::ParametrizeNameType::Tuple => { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(names_type), + violations::ParametrizeNamesWrongType(names_type), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -110,7 +111,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) { } types::ParametrizeNameType::List => { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(names_type), + violations::ParametrizeNamesWrongType(names_type), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -152,7 +153,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) { types::ParametrizeNameType::Tuple => {} types::ParametrizeNameType::List => { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(names_type), + violations::ParametrizeNamesWrongType(names_type), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -174,7 +175,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) { } types::ParametrizeNameType::CSV => { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(names_type), + violations::ParametrizeNamesWrongType(names_type), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -201,7 +202,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) { types::ParametrizeNameType::List => {} types::ParametrizeNameType::Tuple => { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(names_type), + violations::ParametrizeNamesWrongType(names_type), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -223,7 +224,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) { } types::ParametrizeNameType::CSV => { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(names_type), + violations::ParametrizeNamesWrongType(names_type), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -257,7 +258,7 @@ fn check_values(checker: &mut Checker, expr: &Expr) { ExprKind::List { elts, .. } => { if values_type != types::ParametrizeValuesType::List { checker.checks.push(Check::new( - CheckKind::ParametrizeValuesWrongType(values_type, values_row_type), + violations::ParametrizeValuesWrongType(values_type, values_row_type), Range::from_located(expr), )); } @@ -266,7 +267,7 @@ fn check_values(checker: &mut Checker, expr: &Expr) { ExprKind::Tuple { elts, .. } => { if values_type != types::ParametrizeValuesType::Tuple { checker.checks.push(Check::new( - CheckKind::ParametrizeValuesWrongType(values_type, values_row_type), + violations::ParametrizeValuesWrongType(values_type, values_row_type), Range::from_located(expr), )); } @@ -278,7 +279,7 @@ fn check_values(checker: &mut Checker, expr: &Expr) { fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) { let mut check = Check::new( - CheckKind::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV), + violations::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV), Range::from_located(expr), ); @@ -305,7 +306,7 @@ fn handle_value_rows( ExprKind::Tuple { .. } => { if values_row_type != types::ParametrizeValuesRowType::Tuple { checker.checks.push(Check::new( - CheckKind::ParametrizeValuesWrongType(values_type, values_row_type), + violations::ParametrizeValuesWrongType(values_type, values_row_type), Range::from_located(elt), )); } @@ -313,7 +314,7 @@ fn handle_value_rows( ExprKind::List { .. } => { if values_row_type != types::ParametrizeValuesRowType::List { checker.checks.push(Check::new( - CheckKind::ParametrizeValuesWrongType(values_type, values_row_type), + violations::ParametrizeValuesWrongType(values_type, values_row_type), Range::from_located(elt), )); } diff --git a/src/flake8_pytest_style/plugins/patch.rs b/src/flake8_pytest_style/plugins/patch.rs index 98c6a48f8d55a..58b6f07c3a85d 100644 --- a/src/flake8_pytest_style/plugins/patch.rs +++ b/src/flake8_pytest_style/plugins/patch.rs @@ -5,7 +5,8 @@ use crate::ast::helpers::{collect_arg_names, compose_call_path, SimpleCallArgs}; use crate::ast::types::Range; use crate::ast::visitor; use crate::ast::visitor::Visitor; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const PATCH_NAMES: &[&str] = &[ "mocker.patch", @@ -72,7 +73,7 @@ fn check_patch_call( if !visitor.uses_args { return Some(Check::new( - CheckKind::PatchWithLambda, + violations::PatchWithLambda, Range::from_located(call), )); } diff --git a/src/flake8_pytest_style/plugins/raises.rs b/src/flake8_pytest_style/plugins/raises.rs index bb3d2b23e1db2..77d89a3a97f40 100644 --- a/src/flake8_pytest_style/plugins/raises.rs +++ b/src/flake8_pytest_style/plugins/raises.rs @@ -8,7 +8,8 @@ use crate::ast::helpers::{ }; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; fn is_pytest_raises( func: &Expr, @@ -33,7 +34,7 @@ pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: if checker.settings.enabled.contains(&CheckCode::PT010) { if args.is_empty() && keywords.is_empty() { checker.checks.push(Check::new( - CheckKind::RaisesWithoutException, + violations::RaisesWithoutException, Range::from_located(func), )); } @@ -91,7 +92,7 @@ pub fn complex_raises(checker: &mut Checker, stmt: &Stmt, items: &[Withitem], bo if is_too_complex { checker.checks.push(Check::new( - CheckKind::RaisesWithMultipleStatements, + violations::RaisesWithMultipleStatements, Range::from_located(stmt), )); } @@ -118,7 +119,7 @@ fn exception_needs_match(checker: &mut Checker, exception: &Expr) { if is_broad_exception { checker.checks.push(Check::new( - CheckKind::RaisesTooBroad(call_path.join(".")), + violations::RaisesTooBroad(call_path.join(".")), Range::from_located(exception), )); } diff --git a/src/flake8_pytest_style/plugins/unittest_assert.rs b/src/flake8_pytest_style/plugins/unittest_assert.rs new file mode 100644 index 0000000000000..fa6380d0e12af --- /dev/null +++ b/src/flake8_pytest_style/plugins/unittest_assert.rs @@ -0,0 +1,404 @@ +use std::hash::BuildHasherDefault; + +use anyhow::{anyhow, bail, Result}; +use rustc_hash::FxHashMap; +use rustpython_ast::{ + Cmpop, Constant, Expr, ExprContext, ExprKind, Keyword, Stmt, StmtKind, Unaryop, +}; + +use crate::ast::helpers::{create_expr, create_stmt}; + +pub enum UnittestAssert { + AlmostEqual, + AlmostEquals, + DictEqual, + Equal, + Equals, + False, + Greater, + GreaterEqual, + In, + Is, + IsInstance, + IsNone, + IsNot, + IsNotNone, + ItemsEqual, + Less, + LessEqual, + MultiLineEqual, + NotAlmostEqual, + NotAlmostEquals, + NotContains, + NotEqual, + NotEquals, + NotIn, + NotIsInstance, + NotRegex, + NotRegexpMatches, + Raises, + RaisesMessage, + RaisesRegexp, + Regex, + RegexpMatches, + SetEqual, + True, + Underscore, +} + +impl std::fmt::Display for UnittestAssert { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + UnittestAssert::AlmostEqual => write!(f, "assertAlmostEqual"), + UnittestAssert::AlmostEquals => write!(f, "assertAlmostEquals"), + UnittestAssert::DictEqual => write!(f, "assertDictEqual"), + UnittestAssert::Equal => write!(f, "assertEqual"), + UnittestAssert::Equals => write!(f, "assertEquals"), + UnittestAssert::False => write!(f, "assertFalse"), + UnittestAssert::Greater => write!(f, "assertGreater"), + UnittestAssert::GreaterEqual => write!(f, "assertGreaterEqual"), + UnittestAssert::In => write!(f, "assertIn"), + UnittestAssert::Is => write!(f, "assertIs"), + UnittestAssert::IsInstance => write!(f, "assertIsInstance"), + UnittestAssert::IsNone => write!(f, "assertIsNone"), + UnittestAssert::IsNot => write!(f, "assertIsNot"), + UnittestAssert::IsNotNone => write!(f, "assertIsNotNone"), + UnittestAssert::ItemsEqual => write!(f, "assertItemsEqual"), + UnittestAssert::Less => write!(f, "assertLess"), + UnittestAssert::LessEqual => write!(f, "assertLessEqual"), + UnittestAssert::MultiLineEqual => write!(f, "assertMultiLineEqual"), + UnittestAssert::NotAlmostEqual => write!(f, "assertNotAlmostEqual"), + UnittestAssert::NotAlmostEquals => write!(f, "assertNotAlmostEquals"), + UnittestAssert::NotContains => write!(f, "assertNotContains"), + UnittestAssert::NotEqual => write!(f, "assertNotEqual"), + UnittestAssert::NotEquals => write!(f, "assertNotEquals"), + UnittestAssert::NotIn => write!(f, "assertNotIn"), + UnittestAssert::NotIsInstance => write!(f, "assertNotIsInstance"), + UnittestAssert::NotRegex => write!(f, "assertNotRegex"), + UnittestAssert::NotRegexpMatches => write!(f, "assertNotRegexpMatches"), + UnittestAssert::Raises => write!(f, "assertRaises"), + UnittestAssert::RaisesMessage => write!(f, "assertRaisesMessage"), + UnittestAssert::RaisesRegexp => write!(f, "assertRaisesRegexp"), + UnittestAssert::Regex => write!(f, "assertRegex"), + UnittestAssert::RegexpMatches => write!(f, "assertRegexpMatches"), + UnittestAssert::SetEqual => write!(f, "assertSetEqual"), + UnittestAssert::True => write!(f, "assertTrue"), + UnittestAssert::Underscore => write!(f, "assert_"), + } + } +} + +impl TryFrom<&str> for UnittestAssert { + type Error = String; + + fn try_from(value: &str) -> Result { + match value { + "assertAlmostEqual" => Ok(UnittestAssert::AlmostEqual), + "assertAlmostEquals" => Ok(UnittestAssert::AlmostEquals), + "assertDictEqual" => Ok(UnittestAssert::DictEqual), + "assertEqual" => Ok(UnittestAssert::Equal), + "assertEquals" => Ok(UnittestAssert::Equals), + "assertFalse" => Ok(UnittestAssert::False), + "assertGreater" => Ok(UnittestAssert::Greater), + "assertGreaterEqual" => Ok(UnittestAssert::GreaterEqual), + "assertIn" => Ok(UnittestAssert::In), + "assertIs" => Ok(UnittestAssert::Is), + "assertIsInstance" => Ok(UnittestAssert::IsInstance), + "assertIsNone" => Ok(UnittestAssert::IsNone), + "assertIsNot" => Ok(UnittestAssert::IsNot), + "assertIsNotNone" => Ok(UnittestAssert::IsNotNone), + "assertItemsEqual" => Ok(UnittestAssert::ItemsEqual), + "assertLess" => Ok(UnittestAssert::Less), + "assertLessEqual" => Ok(UnittestAssert::LessEqual), + "assertMultiLineEqual" => Ok(UnittestAssert::MultiLineEqual), + "assertNotAlmostEqual" => Ok(UnittestAssert::NotAlmostEqual), + "assertNotAlmostEquals" => Ok(UnittestAssert::NotAlmostEquals), + "assertNotContains" => Ok(UnittestAssert::NotContains), + "assertNotEqual" => Ok(UnittestAssert::NotEqual), + "assertNotEquals" => Ok(UnittestAssert::NotEquals), + "assertNotIn" => Ok(UnittestAssert::NotIn), + "assertNotIsInstance" => Ok(UnittestAssert::NotIsInstance), + "assertNotRegex" => Ok(UnittestAssert::NotRegex), + "assertNotRegexpMatches" => Ok(UnittestAssert::NotRegexpMatches), + "assertRaises" => Ok(UnittestAssert::Raises), + "assertRaisesMessage" => Ok(UnittestAssert::RaisesMessage), + "assertRaisesRegexp" => Ok(UnittestAssert::RaisesRegexp), + "assertRegex" => Ok(UnittestAssert::Regex), + "assertRegexpMatches" => Ok(UnittestAssert::RegexpMatches), + "assertSetEqual" => Ok(UnittestAssert::SetEqual), + "assertTrue" => Ok(UnittestAssert::True), + "assert_" => Ok(UnittestAssert::Underscore), + _ => Err(format!("Unknown unittest assert method: {value}")), + } + } +} + +fn assert(expr: &Expr, msg: Option<&Expr>) -> Stmt { + create_stmt(StmtKind::Assert { + test: Box::new(expr.clone()), + msg: msg.map(|msg| Box::new(msg.clone())), + }) +} + +fn compare(left: &Expr, cmpop: Cmpop, right: &Expr) -> Expr { + create_expr(ExprKind::Compare { + left: Box::new(left.clone()), + ops: vec![cmpop], + comparators: vec![right.clone()], + }) +} + +pub struct Arguments<'a> { + positional: Vec<&'a str>, + keyword: Vec<&'a str>, +} + +impl<'a> Arguments<'a> { + pub fn new(positional: Vec<&'a str>, keyword: Vec<&'a str>) -> Self { + Self { + positional, + keyword, + } + } + + pub fn contains(&self, arg: &str) -> bool { + self.positional.contains(&arg) || self.keyword.contains(&arg) + } +} + +impl UnittestAssert { + pub fn arguments(&self) -> Arguments { + match self { + UnittestAssert::AlmostEqual => { + Arguments::new(vec!["first", "second"], vec!["places", "msg", "delta"]) + } + UnittestAssert::AlmostEquals => { + Arguments::new(vec!["first", "second"], vec!["places", "msg", "delta"]) + } + UnittestAssert::DictEqual => Arguments::new(vec!["d1", "d2"], vec!["msg"]), + UnittestAssert::Equal => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::Equals => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::False => Arguments::new(vec!["expr"], vec!["msg"]), + UnittestAssert::Greater => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::GreaterEqual => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::In => Arguments::new(vec!["member", "container"], vec!["msg"]), + UnittestAssert::Is => Arguments::new(vec!["expr1", "expr2"], vec!["msg"]), + UnittestAssert::IsInstance => Arguments::new(vec!["obj", "cls"], vec!["msg"]), + UnittestAssert::IsNone => Arguments::new(vec!["expr"], vec!["msg"]), + UnittestAssert::IsNot => Arguments::new(vec!["expr1", "expr2"], vec!["msg"]), + UnittestAssert::IsNotNone => Arguments::new(vec!["expr"], vec!["msg"]), + UnittestAssert::ItemsEqual => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::Less => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::LessEqual => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::MultiLineEqual => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::NotAlmostEqual => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::NotAlmostEquals => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::NotContains => Arguments::new(vec!["container", "member"], vec!["msg"]), + UnittestAssert::NotEqual => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::NotEquals => Arguments::new(vec!["first", "second"], vec!["msg"]), + UnittestAssert::NotIn => Arguments::new(vec!["member", "container"], vec!["msg"]), + UnittestAssert::NotIsInstance => Arguments::new(vec!["obj", "cls"], vec!["msg"]), + UnittestAssert::NotRegex => Arguments::new(vec!["text", "regex"], vec!["msg"]), + UnittestAssert::NotRegexpMatches => Arguments::new(vec!["text", "regex"], vec!["msg"]), + UnittestAssert::Raises => Arguments::new(vec!["exception"], vec!["msg"]), + UnittestAssert::RaisesMessage => Arguments::new(vec!["exception", "msg"], vec!["msg"]), + UnittestAssert::RaisesRegexp => Arguments::new(vec!["exception", "regex"], vec!["msg"]), + UnittestAssert::Regex => Arguments::new(vec!["text", "regex"], vec!["msg"]), + UnittestAssert::RegexpMatches => Arguments::new(vec!["text", "regex"], vec!["msg"]), + UnittestAssert::SetEqual => Arguments::new(vec!["set1", "set2"], vec!["msg"]), + UnittestAssert::True => Arguments::new(vec!["expr"], vec!["msg"]), + UnittestAssert::Underscore => Arguments::new(vec!["expr"], vec!["msg"]), + } + } + + /// Create a map from argument name to value. + pub fn args_map<'a>( + &'a self, + args: &'a [Expr], + keywords: &'a [Keyword], + ) -> Result> { + if args + .iter() + .any(|arg| matches!(arg.node, ExprKind::Starred { .. })) + || keywords.iter().any(|kw| kw.node.arg.is_none()) + { + bail!("Contains variable-length arguments. Cannot autofix.".to_string()); + } + + let mut args_map: FxHashMap<&str, &Expr> = FxHashMap::with_capacity_and_hasher( + args.len() + keywords.len(), + BuildHasherDefault::default(), + ); + let arguments = self.arguments(); + for (arg, value) in arguments.positional.iter().zip(args.iter()) { + args_map.insert(arg, value); + } + for kw in keywords { + let arg = kw.node.arg.as_ref().unwrap(); + if !arguments.contains((*arg).as_str()) { + bail!("Unexpected keyword argument `{arg}`"); + } + args_map.insert(kw.node.arg.as_ref().unwrap().as_str(), &kw.node.value); + } + Ok(args_map) + } + + pub fn generate_assert(&self, args: &[Expr], keywords: &[Keyword]) -> Result { + let args = self.args_map(args, keywords)?; + match self { + UnittestAssert::True | UnittestAssert::False => { + let expr = args + .get("expr") + .ok_or_else(|| anyhow!("Missing argument `expr`"))?; + let msg = args.get("msg").copied(); + let bool = create_expr(ExprKind::Constant { + value: Constant::Bool(matches!(self, UnittestAssert::True)), + kind: None, + }); + let expr = compare(expr, Cmpop::Is, &bool); + Ok(assert(&expr, msg)) + } + UnittestAssert::Equal + | UnittestAssert::Equals + | UnittestAssert::NotEqual + | UnittestAssert::NotEquals + | UnittestAssert::Greater + | UnittestAssert::GreaterEqual + | UnittestAssert::Less + | UnittestAssert::LessEqual => { + let first = args + .get("first") + .ok_or_else(|| anyhow!("Missing argument `first`"))?; + let second = args + .get("second") + .ok_or_else(|| anyhow!("Missing argument `second`"))?; + let msg = args.get("msg").copied(); + let cmpop = match self { + UnittestAssert::Equal | UnittestAssert::Equals => Cmpop::Eq, + UnittestAssert::NotEqual | UnittestAssert::NotEquals => Cmpop::NotEq, + UnittestAssert::Greater => Cmpop::Gt, + UnittestAssert::GreaterEqual => Cmpop::GtE, + UnittestAssert::Less => Cmpop::Lt, + UnittestAssert::LessEqual => Cmpop::LtE, + _ => unreachable!(), + }; + let expr = compare(first, cmpop, second); + Ok(assert(&expr, msg)) + } + UnittestAssert::Is | UnittestAssert::IsNot => { + let expr1 = args + .get("expr1") + .ok_or_else(|| anyhow!("Missing argument `expr1`"))?; + let expr2 = args + .get("expr2") + .ok_or_else(|| anyhow!("Missing argument `expr2`"))?; + let msg = args.get("msg").copied(); + let cmpop = if matches!(self, UnittestAssert::Is) { + Cmpop::Is + } else { + Cmpop::IsNot + }; + let expr = compare(expr1, cmpop, expr2); + Ok(assert(&expr, msg)) + } + UnittestAssert::In | UnittestAssert::NotIn => { + let member = args + .get("member") + .ok_or_else(|| anyhow!("Missing argument `member`"))?; + let container = args + .get("container") + .ok_or_else(|| anyhow!("Missing argument `container`"))?; + let msg = args.get("msg").copied(); + let cmpop = if matches!(self, UnittestAssert::In) { + Cmpop::In + } else { + Cmpop::NotIn + }; + let expr = compare(member, cmpop, container); + Ok(assert(&expr, msg)) + } + UnittestAssert::IsNone | UnittestAssert::IsNotNone => { + let expr = args + .get("expr") + .ok_or_else(|| anyhow!("Missing argument `expr`"))?; + let msg = args.get("msg").copied(); + let cmpop = if matches!(self, UnittestAssert::IsNone) { + Cmpop::Is + } else { + Cmpop::IsNot + }; + let expr = compare( + expr, + cmpop, + &create_expr(ExprKind::Constant { + value: Constant::None, + kind: None, + }), + ); + Ok(assert(&expr, msg)) + } + UnittestAssert::IsInstance | UnittestAssert::NotIsInstance => { + let obj = args + .get("obj") + .ok_or_else(|| anyhow!("Missing argument `obj`"))?; + let cls = args + .get("cls") + .ok_or_else(|| anyhow!("Missing argument `cls`"))?; + let msg = args.get("msg").copied(); + let isinstance = create_expr(ExprKind::Call { + func: Box::new(create_expr(ExprKind::Name { + id: "isinstance".to_string(), + ctx: ExprContext::Load, + })), + args: vec![(**obj).clone(), (**cls).clone()], + keywords: vec![], + }); + if matches!(self, UnittestAssert::IsInstance) { + Ok(assert(&isinstance, msg)) + } else { + let expr = create_expr(ExprKind::UnaryOp { + op: Unaryop::Not, + operand: Box::new(isinstance), + }); + Ok(assert(&expr, msg)) + } + } + UnittestAssert::Regex + | UnittestAssert::RegexpMatches + | UnittestAssert::NotRegex + | UnittestAssert::NotRegexpMatches => { + let regex = args + .get("regex") + .ok_or_else(|| anyhow!("Missing argument `regex`"))?; + let text = args + .get("text") + .ok_or_else(|| anyhow!("Missing argument `text`"))?; + let msg = args.get("msg").copied(); + let re_search = create_expr(ExprKind::Call { + func: Box::new(create_expr(ExprKind::Attribute { + value: Box::new(create_expr(ExprKind::Name { + id: "re".to_string(), + ctx: ExprContext::Load, + })), + attr: "search".to_string(), + ctx: ExprContext::Load, + })), + args: vec![(**regex).clone(), (**text).clone()], + keywords: vec![], + }); + if matches!(self, UnittestAssert::Regex | UnittestAssert::RegexpMatches) { + Ok(assert(&re_search, msg)) + } else { + Ok(assert( + &create_expr(ExprKind::UnaryOp { + op: Unaryop::Not, + operand: Box::new(re_search), + }), + msg, + )) + } + } + _ => bail!("Cannot autofix `{self}`"), + } + } +} diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT003.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT003.snap index adcd97da632c0..a246054a6f257 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT003.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT003.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: ExtraneousScopeFunction +- kind: + ExtraneousScopeFunction: ~ location: row: 14 column: 16 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT008.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT008.snap index e0416492096d1..f9fda39d939e9 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT008.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT008.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 35 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 36 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 37 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 38 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 40 column: 0 @@ -47,7 +52,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 41 column: 0 @@ -56,7 +62,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 42 column: 0 @@ -65,7 +72,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 43 column: 0 @@ -74,7 +82,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 45 column: 0 @@ -83,7 +92,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 46 column: 0 @@ -92,7 +102,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 47 column: 0 @@ -101,7 +112,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PatchWithLambda +- kind: + PatchWithLambda: ~ location: row: 48 column: 0 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT009.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT009.snap index 6c3673efc2b08..5ea90e5595c09 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT009.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT009.snap @@ -3,13 +3,451 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- - kind: - UnittestAssertion: assertEqual + UnittestAssertion: assertTrue + location: + row: 11 + column: 8 + end_location: + row: 11 + column: 23 + fix: + content: assert expr is True + location: + row: 11 + column: 8 + end_location: + row: 11 + column: 29 + parent: ~ +- kind: + UnittestAssertion: assertTrue location: - row: 9 - column: 4 + row: 12 + column: 8 end_location: - row: 9 - column: 20 + row: 12 + column: 23 + fix: + content: assert expr is True + location: + row: 12 + column: 8 + end_location: + row: 12 + column: 34 + parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 13 + column: 8 + end_location: + row: 13 + column: 23 + fix: + content: assert expr is True + location: + row: 13 + column: 8 + end_location: + row: 13 + column: 34 + parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 14 + column: 8 + end_location: + row: 14 + column: 23 + fix: + content: "assert expr is True, msg" + location: + row: 14 + column: 8 + end_location: + row: 14 + column: 43 + parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 15 + column: 8 + end_location: + row: 15 + column: 23 + fix: + content: "assert expr is True, msg" + location: + row: 15 + column: 8 + end_location: + row: 15 + column: 43 + parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 16 + column: 8 + end_location: + row: 16 + column: 23 + fix: ~ + parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 17 + column: 8 + end_location: + row: 17 + column: 23 fix: ~ parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 18 + column: 8 + end_location: + row: 18 + column: 23 + fix: ~ + parent: ~ +- kind: + UnittestAssertion: assertTrue + location: + row: 19 + column: 8 + end_location: + row: 19 + column: 23 + fix: ~ + parent: ~ +- kind: + UnittestAssertion: assertFalse + location: + row: 22 + column: 8 + end_location: + row: 22 + column: 24 + fix: + content: assert True is False + location: + row: 22 + column: 8 + end_location: + row: 22 + column: 30 + parent: ~ +- kind: + UnittestAssertion: assertEqual + location: + row: 25 + column: 8 + end_location: + row: 25 + column: 24 + fix: + content: assert 1 == 2 + location: + row: 25 + column: 8 + end_location: + row: 25 + column: 30 + parent: ~ +- kind: + UnittestAssertion: assertNotEqual + location: + row: 28 + column: 8 + end_location: + row: 28 + column: 27 + fix: + content: assert 1 != 1 + location: + row: 28 + column: 8 + end_location: + row: 28 + column: 33 + parent: ~ +- kind: + UnittestAssertion: assertGreater + location: + row: 31 + column: 8 + end_location: + row: 31 + column: 26 + fix: + content: assert 1 > 2 + location: + row: 31 + column: 8 + end_location: + row: 31 + column: 32 + parent: ~ +- kind: + UnittestAssertion: assertGreaterEqual + location: + row: 34 + column: 8 + end_location: + row: 34 + column: 31 + fix: + content: assert 1 >= 2 + location: + row: 34 + column: 8 + end_location: + row: 34 + column: 37 + parent: ~ +- kind: + UnittestAssertion: assertLess + location: + row: 37 + column: 8 + end_location: + row: 37 + column: 23 + fix: + content: assert 2 < 1 + location: + row: 37 + column: 8 + end_location: + row: 37 + column: 29 + parent: ~ +- kind: + UnittestAssertion: assertLessEqual + location: + row: 40 + column: 8 + end_location: + row: 40 + column: 28 + fix: + content: assert 1 <= 2 + location: + row: 40 + column: 8 + end_location: + row: 40 + column: 34 + parent: ~ +- kind: + UnittestAssertion: assertIn + location: + row: 43 + column: 8 + end_location: + row: 43 + column: 21 + fix: + content: "assert 1 in [2, 3]" + location: + row: 43 + column: 8 + end_location: + row: 43 + column: 32 + parent: ~ +- kind: + UnittestAssertion: assertNotIn + location: + row: 46 + column: 8 + end_location: + row: 46 + column: 24 + fix: + content: "assert 2 not in [2, 3]" + location: + row: 46 + column: 8 + end_location: + row: 46 + column: 35 + parent: ~ +- kind: + UnittestAssertion: assertIsNone + location: + row: 49 + column: 8 + end_location: + row: 49 + column: 25 + fix: + content: assert 0 is None + location: + row: 49 + column: 8 + end_location: + row: 49 + column: 28 + parent: ~ +- kind: + UnittestAssertion: assertIsNotNone + location: + row: 52 + column: 8 + end_location: + row: 52 + column: 28 + fix: + content: assert 0 is not None + location: + row: 52 + column: 8 + end_location: + row: 52 + column: 31 + parent: ~ +- kind: + UnittestAssertion: assertIs + location: + row: 55 + column: 8 + end_location: + row: 55 + column: 21 + fix: + content: "assert [] is []" + location: + row: 55 + column: 8 + end_location: + row: 55 + column: 29 + parent: ~ +- kind: + UnittestAssertion: assertIsNot + location: + row: 58 + column: 8 + end_location: + row: 58 + column: 24 + fix: + content: assert 1 is not 1 + location: + row: 58 + column: 8 + end_location: + row: 58 + column: 30 + parent: ~ +- kind: + UnittestAssertion: assertIsInstance + location: + row: 61 + column: 8 + end_location: + row: 61 + column: 29 + fix: + content: "assert isinstance(1, str)" + location: + row: 61 + column: 8 + end_location: + row: 61 + column: 37 + parent: ~ +- kind: + UnittestAssertion: assertNotIsInstance + location: + row: 64 + column: 8 + end_location: + row: 64 + column: 32 + fix: + content: "assert not isinstance(1, int)" + location: + row: 64 + column: 8 + end_location: + row: 64 + column: 40 + parent: ~ +- kind: + UnittestAssertion: assertRegex + location: + row: 67 + column: 8 + end_location: + row: 67 + column: 24 + fix: + content: "assert re.search(\"def\", \"abc\")" + location: + row: 67 + column: 8 + end_location: + row: 67 + column: 39 + parent: ~ +- kind: + UnittestAssertion: assertNotRegex + location: + row: 70 + column: 8 + end_location: + row: 70 + column: 27 + fix: + content: "assert not re.search(\"abc\", \"abc\")" + location: + row: 70 + column: 8 + end_location: + row: 70 + column: 42 + parent: ~ +- kind: + UnittestAssertion: assertRegexpMatches + location: + row: 73 + column: 8 + end_location: + row: 73 + column: 32 + fix: + content: "assert re.search(\"def\", \"abc\")" + location: + row: 73 + column: 8 + end_location: + row: 73 + column: 47 + parent: ~ +- kind: + UnittestAssertion: assertNotRegex + location: + row: 76 + column: 8 + end_location: + row: 76 + column: 27 + fix: + content: "assert not re.search(\"abc\", \"abc\")" + location: + row: 76 + column: 8 + end_location: + row: 76 + column: 42 + parent: ~ diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT010.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT010.snap index bb39536fc61b4..152b3879ee6d1 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT010.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT010.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: RaisesWithoutException +- kind: + RaisesWithoutException: ~ location: row: 5 column: 9 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT012.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT012.snap index 99ce08605213a..33d3744c63b6c 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT012.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT012.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 28 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 34 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 38 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 42 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 46 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 50 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 54 column: 4 @@ -65,7 +72,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: RaisesWithMultipleStatements +- kind: + RaisesWithMultipleStatements: ~ location: row: 60 column: 4 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT013.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT013.snap index 85467ed1cf9ee..c7ee1d187f8a6 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT013.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT013.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: IncorrectPytestImport +- kind: + IncorrectPytestImport: ~ location: row: 11 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 27 fix: ~ parent: ~ -- kind: IncorrectPytestImport +- kind: + IncorrectPytestImport: ~ location: row: 12 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 26 fix: ~ parent: ~ -- kind: IncorrectPytestImport +- kind: + IncorrectPytestImport: ~ location: row: 13 column: 0 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT015.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT015.snap index f1f4cd82a7eef..dcff99bb6f7ef 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT015.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT015.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 9 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 10 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 16 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 11 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 12 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 13 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 14 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 15 column: 4 @@ -65,7 +72,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 16 column: 4 @@ -74,7 +82,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 17 column: 4 @@ -83,7 +92,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 18 column: 4 @@ -92,7 +102,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 19 column: 4 @@ -101,7 +112,8 @@ expression: checks column: 16 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 20 column: 4 @@ -110,7 +122,8 @@ expression: checks column: 18 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 21 column: 4 @@ -119,7 +132,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 22 column: 4 @@ -128,7 +142,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 23 column: 4 @@ -137,7 +152,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 24 column: 4 @@ -146,7 +162,8 @@ expression: checks column: 21 fix: ~ parent: ~ -- kind: AssertAlwaysFalse +- kind: + AssertAlwaysFalse: ~ location: row: 25 column: 4 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT016.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT016.snap index 500722b562ba2..a320d57990147 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT016.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT016.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: FailWithoutMessage +- kind: + FailWithoutMessage: ~ location: row: 13 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: FailWithoutMessage +- kind: + FailWithoutMessage: ~ location: row: 14 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: FailWithoutMessage +- kind: + FailWithoutMessage: ~ location: row: 15 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: FailWithoutMessage +- kind: + FailWithoutMessage: ~ location: row: 16 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: FailWithoutMessage +- kind: + FailWithoutMessage: ~ location: row: 17 column: 4 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT018.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT018.snap index 291b06b1a32fb..60b2c24cf9258 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT018.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT018.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 12 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 39 fix: ~ parent: ~ -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 13 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 59 fix: ~ parent: ~ -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 14 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 43 fix: ~ parent: ~ -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 15 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 60 fix: ~ parent: ~ -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 16 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 44 fix: ~ parent: ~ -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 17 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 63 fix: ~ parent: ~ -- kind: CompositeAssertion +- kind: + CompositeAssertion: ~ location: row: 18 column: 4 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT020.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT020.snap index b6fbe4c300523..af62f8c9f7b7b 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT020.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT020.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: DeprecatedYieldFixture +- kind: + DeprecatedYieldFixture: ~ location: row: 14 column: 1 @@ -11,7 +12,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: DeprecatedYieldFixture +- kind: + DeprecatedYieldFixture: ~ location: row: 19 column: 1 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT021.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT021.snap index 3e7b95662ea67..e3dd5274d4920 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT021.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT021.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: FixtureFinalizerCallback +- kind: + FixtureFinalizerCallback: ~ location: row: 49 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 42 fix: ~ parent: ~ -- kind: FixtureFinalizerCallback +- kind: + FixtureFinalizerCallback: ~ location: row: 56 column: 4 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT024.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT024.snap index 13bd018a5f077..376e8ab14ec59 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT024.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT024.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: UnnecessaryAsyncioMarkOnFixture +- kind: + UnnecessaryAsyncioMarkOnFixture: ~ location: row: 14 column: 1 @@ -11,7 +12,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: UnnecessaryAsyncioMarkOnFixture +- kind: + UnnecessaryAsyncioMarkOnFixture: ~ location: row: 20 column: 1 @@ -20,7 +22,8 @@ expression: checks column: 20 fix: ~ parent: ~ -- kind: UnnecessaryAsyncioMarkOnFixture +- kind: + UnnecessaryAsyncioMarkOnFixture: ~ location: row: 27 column: 1 @@ -29,7 +32,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: UnnecessaryAsyncioMarkOnFixture +- kind: + UnnecessaryAsyncioMarkOnFixture: ~ location: row: 33 column: 1 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT025.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT025.snap index bd22d9ec23455..daf4eed5f527b 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT025.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT025.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: ErroneousUseFixturesOnFixture +- kind: + ErroneousUseFixturesOnFixture: ~ location: row: 9 column: 1 @@ -11,7 +12,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: ErroneousUseFixturesOnFixture +- kind: + ErroneousUseFixturesOnFixture: ~ location: row: 16 column: 1 diff --git a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT026.snap b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT026.snap index 30996a6681e99..c4e1f6f23ec15 100644 --- a/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT026.snap +++ b/src/flake8_pytest_style/snapshots/ruff__flake8_pytest_style__tests__PT026.snap @@ -2,7 +2,8 @@ source: src/flake8_pytest_style/mod.rs expression: checks --- -- kind: UseFixturesWithoutParameters +- kind: + UseFixturesWithoutParameters: ~ location: row: 19 column: 1 @@ -18,7 +19,8 @@ expression: checks row: 19 column: 26 parent: ~ -- kind: UseFixturesWithoutParameters +- kind: + UseFixturesWithoutParameters: ~ location: row: 24 column: 1 diff --git a/src/flake8_quotes/checks.rs b/src/flake8_quotes/checks.rs index 6f9a9e155508f..5d1910296e3d9 100644 --- a/src/flake8_quotes/checks.rs +++ b/src/flake8_quotes/checks.rs @@ -2,8 +2,9 @@ use rustpython_ast::Location; use crate::ast::types::Range; use crate::flake8_quotes::settings::{Quote, Settings}; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; fn good_single(quote: &Quote) -> char { match quote { @@ -72,7 +73,7 @@ pub fn quotes( } Some(Check::new( - CheckKind::BadQuotesDocstring(settings.docstring_quotes.clone()), + violations::BadQuotesDocstring(settings.docstring_quotes.clone()), Range::new(start, end), )) } else if is_multiline { @@ -87,7 +88,7 @@ pub fn quotes( } Some(Check::new( - CheckKind::BadQuotesMultilineString(settings.multiline_quotes.clone()), + violations::BadQuotesMultilineString(settings.multiline_quotes.clone()), Range::new(start, end), )) } else { @@ -102,7 +103,7 @@ pub fn quotes( && !string_contents.contains(bad_single(&settings.inline_quotes)) { return Some(Check::new( - CheckKind::AvoidQuoteEscape, + violations::AvoidQuoteEscape, Range::new(start, end), )); } @@ -112,7 +113,7 @@ pub fn quotes( // If we're not using the preferred type, only allow use to avoid escapes. if !string_contents.contains(good_single(&settings.inline_quotes)) { return Some(Check::new( - CheckKind::BadQuotesInlineString(settings.inline_quotes.clone()), + violations::BadQuotesInlineString(settings.inline_quotes.clone()), Range::new(start, end), )); } diff --git a/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__doubles_doubles_escaped.py.snap b/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__doubles_doubles_escaped.py.snap index cd7ac17eaf005..a9dc42ea2452d 100644 --- a/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__doubles_doubles_escaped.py.snap +++ b/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__doubles_doubles_escaped.py.snap @@ -2,7 +2,8 @@ source: src/flake8_quotes/mod.rs expression: checks --- -- kind: AvoidQuoteEscape +- kind: + AvoidQuoteEscape: ~ location: row: 1 column: 25 diff --git a/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__singles_singles_escaped.py.snap b/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__singles_singles_escaped.py.snap index cd7ac17eaf005..a9dc42ea2452d 100644 --- a/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__singles_singles_escaped.py.snap +++ b/src/flake8_quotes/snapshots/ruff__flake8_quotes__tests__singles_singles_escaped.py.snap @@ -2,7 +2,8 @@ source: src/flake8_quotes/mod.rs expression: checks --- -- kind: AvoidQuoteEscape +- kind: + AvoidQuoteEscape: ~ location: row: 1 column: 25 diff --git a/src/flake8_return/plugins.rs b/src/flake8_return/plugins.rs index 25fcc0693789b..3f2adad95aa8c 100644 --- a/src/flake8_return/plugins.rs +++ b/src/flake8_return/plugins.rs @@ -8,8 +8,8 @@ use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::flake8_return::helpers::result_exists; use crate::flake8_return::visitor::{ReturnVisitor, Stack}; -use crate::registry::{Branch, CheckCode, CheckKind}; -use crate::Check; +use crate::registry::{Branch, CheckCode}; +use crate::{violations, Check}; /// RET501 fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) { @@ -26,7 +26,7 @@ fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) { ) { continue; } - let mut check = Check::new(CheckKind::UnnecessaryReturnNone, Range::from_located(stmt)); + let mut check = Check::new(violations::UnnecessaryReturnNone, Range::from_located(stmt)); if checker.patch(&CheckCode::RET501) { check.amend(Fix::replacement( "return".to_string(), @@ -44,7 +44,7 @@ fn implicit_return_value(checker: &mut Checker, stack: &Stack) { if expr.is_some() { continue; } - let mut check = Check::new(CheckKind::ImplicitReturnValue, Range::from_located(stmt)); + let mut check = Check::new(violations::ImplicitReturnValue, Range::from_located(stmt)); if checker.patch(&CheckCode::RET502) { check.amend(Fix::replacement( "return None".to_string(), @@ -62,7 +62,7 @@ fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) { StmtKind::If { body, orelse, .. } => { if body.is_empty() || orelse.is_empty() { checker.checks.push(Check::new( - CheckKind::ImplicitReturn, + violations::ImplicitReturn, Range::from_located(last_stmt), )); return; @@ -100,7 +100,7 @@ fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) { | StmtKind::Raise { .. } | StmtKind::Try { .. } => {} _ => { - let mut check = Check::new(CheckKind::ImplicitReturn, Range::from_located(last_stmt)); + let mut check = Check::new(violations::ImplicitReturn, Range::from_located(last_stmt)); if checker.patch(&CheckCode::RET503) { let mut content = String::new(); content.push_str(&indentation(checker, last_stmt)); @@ -191,7 +191,7 @@ fn unnecessary_assign(checker: &mut Checker, stack: &Stack, expr: &Expr) { if !stack.refs.contains_key(id.as_str()) { checker.checks.push(Check::new( - CheckKind::UnnecessaryAssign, + violations::UnnecessaryAssign, Range::from_located(expr), )); return; @@ -208,7 +208,7 @@ fn unnecessary_assign(checker: &mut Checker, stack: &Stack, expr: &Expr) { } checker.checks.push(Check::new( - CheckKind::UnnecessaryAssign, + violations::UnnecessaryAssign, Range::from_located(expr), )); } @@ -223,7 +223,7 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) -> if matches!(child.node, StmtKind::Return { .. }) { if checker.settings.enabled.contains(&CheckCode::RET505) { checker.checks.push(Check::new( - CheckKind::SuperfluousElseReturn(branch), + violations::SuperfluousElseReturn(branch), Range::from_located(stmt), )); } @@ -232,7 +232,7 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) -> if matches!(child.node, StmtKind::Break) { if checker.settings.enabled.contains(&CheckCode::RET508) { checker.checks.push(Check::new( - CheckKind::SuperfluousElseBreak(branch), + violations::SuperfluousElseBreak(branch), Range::from_located(stmt), )); } @@ -241,7 +241,7 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) -> if matches!(child.node, StmtKind::Raise { .. }) { if checker.settings.enabled.contains(&CheckCode::RET506) { checker.checks.push(Check::new( - CheckKind::SuperfluousElseRaise(branch), + violations::SuperfluousElseRaise(branch), Range::from_located(stmt), )); } @@ -250,7 +250,7 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) -> if matches!(child.node, StmtKind::Continue) { if checker.settings.enabled.contains(&CheckCode::RET507) { checker.checks.push(Check::new( - CheckKind::SuperfluousElseContinue(branch), + violations::SuperfluousElseContinue(branch), Range::from_located(stmt), )); } diff --git a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET501_RET501.py.snap b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET501_RET501.py.snap index afacc15fc62de..755f34581db51 100644 --- a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET501_RET501.py.snap +++ b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET501_RET501.py.snap @@ -2,7 +2,8 @@ source: src/flake8_return/mod.rs expression: checks --- -- kind: UnnecessaryReturnNone +- kind: + UnnecessaryReturnNone: ~ location: row: 4 column: 4 diff --git a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET502_RET502.py.snap b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET502_RET502.py.snap index 7cde8d1a036a0..6d5f75c4e3d42 100644 --- a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET502_RET502.py.snap +++ b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET502_RET502.py.snap @@ -2,7 +2,8 @@ source: src/flake8_return/mod.rs expression: checks --- -- kind: ImplicitReturnValue +- kind: + ImplicitReturnValue: ~ location: row: 3 column: 8 diff --git a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET503_RET503.py.snap b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET503_RET503.py.snap index 784a60286a81b..d4e2a63042908 100644 --- a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET503_RET503.py.snap +++ b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET503_RET503.py.snap @@ -2,7 +2,8 @@ source: src/flake8_return/mod.rs expression: checks --- -- kind: ImplicitReturn +- kind: + ImplicitReturn: ~ location: row: 7 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 16 fix: ~ parent: ~ -- kind: ImplicitReturn +- kind: + ImplicitReturn: ~ location: row: 14 column: 8 @@ -27,7 +29,8 @@ expression: checks row: 15 column: 0 parent: ~ -- kind: ImplicitReturn +- kind: + ImplicitReturn: ~ location: row: 23 column: 4 @@ -43,7 +46,8 @@ expression: checks row: 24 column: 0 parent: ~ -- kind: ImplicitReturn +- kind: + ImplicitReturn: ~ location: row: 29 column: 8 @@ -52,7 +56,8 @@ expression: checks column: 20 fix: ~ parent: ~ -- kind: ImplicitReturn +- kind: + ImplicitReturn: ~ location: row: 39 column: 8 diff --git a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET504_RET504.py.snap b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET504_RET504.py.snap index 2e2a40e1353b8..c6ffa729ae440 100644 --- a/src/flake8_return/snapshots/ruff__flake8_return__tests__RET504_RET504.py.snap +++ b/src/flake8_return/snapshots/ruff__flake8_return__tests__RET504_RET504.py.snap @@ -2,7 +2,8 @@ source: src/flake8_return/mod.rs expression: checks --- -- kind: UnnecessaryAssign +- kind: + UnnecessaryAssign: ~ location: row: 6 column: 11 @@ -11,7 +12,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: UnnecessaryAssign +- kind: + UnnecessaryAssign: ~ location: row: 13 column: 11 @@ -20,7 +22,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: UnnecessaryAssign +- kind: + UnnecessaryAssign: ~ location: row: 19 column: 15 @@ -29,7 +32,8 @@ expression: checks column: 16 fix: ~ parent: ~ -- kind: UnnecessaryAssign +- kind: + UnnecessaryAssign: ~ location: row: 31 column: 11 @@ -38,7 +42,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: UnnecessaryAssign +- kind: + UnnecessaryAssign: ~ location: row: 39 column: 11 diff --git a/src/flake8_simplify/plugins/ast_bool_op.rs b/src/flake8_simplify/plugins/ast_bool_op.rs index c584c02bf22a7..d98b6d8e96659 100644 --- a/src/flake8_simplify/plugins/ast_bool_op.rs +++ b/src/flake8_simplify/plugins/ast_bool_op.rs @@ -9,7 +9,8 @@ use crate::ast::helpers::{create_expr, unparse_expr}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// Return `true` if two `Expr` instances are equivalent names. fn is_same_expr<'a>(a: &'a Expr, b: &'a Expr) -> Option<&'a str> { @@ -62,7 +63,7 @@ pub fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) { for (arg_name, indices) in duplicates { if indices.len() > 1 { let mut check = Check::new( - CheckKind::DuplicateIsinstanceCall(arg_name.to_string()), + violations::DuplicateIsinstanceCall(arg_name.to_string()), Range::from_located(expr), ); if checker.patch(&CheckCode::SIM101) { @@ -171,7 +172,7 @@ pub fn compare_with_tuple(checker: &mut Checker, expr: &Expr) { .map(|value| unparse_expr(value, checker.style)) .collect(); let mut check = Check::new( - CheckKind::CompareWithTuple( + violations::CompareWithTuple( value.to_string(), str_values, unparse_expr(expr, checker.style), @@ -233,7 +234,7 @@ pub fn a_and_not_a(checker: &mut Checker, expr: &Expr) { for non_negate_expr in &non_negated_expr { if let Some(id) = is_same_expr(negate_expr, non_negate_expr) { let mut check = Check::new( - CheckKind::AAndNotA(id.to_string()), + violations::AAndNotA(id.to_string()), Range::from_located(expr), ); if checker.patch(&CheckCode::SIM220) { @@ -281,7 +282,7 @@ pub fn a_or_not_a(checker: &mut Checker, expr: &Expr) { for non_negate_expr in &non_negated_expr { if let Some(id) = is_same_expr(negate_expr, non_negate_expr) { let mut check = Check::new( - CheckKind::AOrNotA(id.to_string()), + violations::AOrNotA(id.to_string()), Range::from_located(expr), ); if checker.patch(&CheckCode::SIM220) { @@ -308,7 +309,7 @@ pub fn or_true(checker: &mut Checker, expr: &Expr) { .. } = &value.node { - let mut check = Check::new(CheckKind::OrTrue, Range::from_located(value)); + let mut check = Check::new(violations::OrTrue, Range::from_located(value)); if checker.patch(&CheckCode::SIM223) { check.amend(Fix::replacement( "True".to_string(), @@ -332,7 +333,7 @@ pub fn and_false(checker: &mut Checker, expr: &Expr) { .. } = &value.node { - let mut check = Check::new(CheckKind::AndFalse, Range::from_located(value)); + let mut check = Check::new(violations::AndFalse, Range::from_located(value)); if checker.patch(&CheckCode::SIM223) { check.amend(Fix::replacement( "False".to_string(), diff --git a/src/flake8_simplify/plugins/ast_for.rs b/src/flake8_simplify/plugins/ast_for.rs index 3b0b1865d230d..8de02716edeba 100644 --- a/src/flake8_simplify/plugins/ast_for.rs +++ b/src/flake8_simplify/plugins/ast_for.rs @@ -6,9 +6,10 @@ use crate::ast::helpers::{create_expr, create_stmt}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_style::SourceCodeStyleDetector; +use crate::violations; struct Loop<'a> { return_value: bool, @@ -118,7 +119,7 @@ pub fn convert_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling: &Stm checker.style, ); let mut check = Check::new( - CheckKind::ConvertLoopToAny(content.clone()), + violations::ConvertLoopToAny(content.clone()), Range::from_located(stmt), ); if checker.patch(&CheckCode::SIM110) { @@ -157,7 +158,7 @@ pub fn convert_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling: &Stm checker.style, ); let mut check = Check::new( - CheckKind::ConvertLoopToAll(content.clone()), + violations::ConvertLoopToAll(content.clone()), Range::from_located(stmt), ); if checker.patch(&CheckCode::SIM111) { diff --git a/src/flake8_simplify/plugins/ast_if.rs b/src/flake8_simplify/plugins/ast_if.rs index dfaf5944e4d2e..a39528228ee45 100644 --- a/src/flake8_simplify/plugins/ast_if.rs +++ b/src/flake8_simplify/plugins/ast_if.rs @@ -4,7 +4,8 @@ use crate::ast::helpers::{create_expr, create_stmt, unparse_expr, unparse_stmt}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; fn is_main_check(expr: &Expr) -> bool { if let ExprKind::Compare { @@ -60,7 +61,7 @@ pub fn nested_if_statements(checker: &mut Checker, stmt: &Stmt) { } checker.checks.push(Check::new( - CheckKind::NestedIfStatements, + violations::NestedIfStatements, Range::from_located(stmt), )); } @@ -88,7 +89,7 @@ pub fn return_bool_condition_directly(checker: &mut Checker, stmt: &Stmt) { } let condition = unparse_expr(test, checker.style); let mut check = Check::new( - CheckKind::ReturnBoolConditionDirectly(condition), + violations::ReturnBoolConditionDirectly(condition), Range::from_located(stmt), ); if checker.patch(&CheckCode::SIM103) { @@ -178,7 +179,7 @@ pub fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: Option<& let ternary = ternary(target_var, body_value, test, orelse_value); let content = unparse_stmt(&ternary, checker.style); let mut check = Check::new( - CheckKind::UseTernaryOperator(content.clone()), + violations::UseTernaryOperator(content.clone()), Range::from_located(stmt), ); if checker.patch(&CheckCode::SIM108) { diff --git a/src/flake8_simplify/plugins/ast_ifexp.rs b/src/flake8_simplify/plugins/ast_ifexp.rs index c2fe8ce5e8f02..b2b1e257305ba 100644 --- a/src/flake8_simplify/plugins/ast_ifexp.rs +++ b/src/flake8_simplify/plugins/ast_ifexp.rs @@ -4,7 +4,8 @@ use crate::ast::helpers::{create_expr, unparse_expr}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// SIM210 pub fn explicit_true_false_in_ifexpr( @@ -28,7 +29,7 @@ pub fn explicit_true_false_in_ifexpr( } let mut check = Check::new( - CheckKind::IfExprWithTrueFalse(unparse_expr(test, checker.style)), + violations::IfExprWithTrueFalse(unparse_expr(test, checker.style)), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -73,7 +74,7 @@ pub fn explicit_false_true_in_ifexpr( } let mut check = Check::new( - CheckKind::IfExprWithFalseTrue(unparse_expr(test, checker.style)), + violations::IfExprWithFalseTrue(unparse_expr(test, checker.style)), Range::from_located(expr), ); if checker.patch(check.kind.code()) { @@ -118,7 +119,7 @@ pub fn twisted_arms_in_ifexpr( } let mut check = Check::new( - CheckKind::NegateEqualOp( + violations::NegateEqualOp( unparse_expr(body, checker.style), unparse_expr(orelse, checker.style), ), diff --git a/src/flake8_simplify/plugins/ast_unary_op.rs b/src/flake8_simplify/plugins/ast_unary_op.rs index cdfb6a679a323..6509d1fa21841 100644 --- a/src/flake8_simplify/plugins/ast_unary_op.rs +++ b/src/flake8_simplify/plugins/ast_unary_op.rs @@ -4,7 +4,8 @@ use crate::ast::helpers::{create_expr, unparse_expr}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn is_exception_check(stmt: &Stmt) -> bool { let StmtKind::If {test: _, body, orelse: _} = &stmt.node else { @@ -35,7 +36,7 @@ pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop, } let mut check = Check::new( - CheckKind::NegateEqualOp( + violations::NegateEqualOp( unparse_expr(left, checker.style), unparse_expr(&comparators[0], checker.style), ), @@ -79,7 +80,7 @@ pub fn negation_with_not_equal_op( } let mut check = Check::new( - CheckKind::NegateNotEqualOp( + violations::NegateNotEqualOp( unparse_expr(left, checker.style), unparse_expr(&comparators[0], checker.style), ), @@ -115,7 +116,7 @@ pub fn double_negation(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand } let mut check = Check::new( - CheckKind::DoubleNegation(operand.to_string()), + violations::DoubleNegation(operand.to_string()), Range::from_located(operand), ); if checker.patch(check.kind.code()) { diff --git a/src/flake8_simplify/plugins/ast_with.rs b/src/flake8_simplify/plugins/ast_with.rs index 294200a53a9dc..987056c501bce 100644 --- a/src/flake8_simplify/plugins/ast_with.rs +++ b/src/flake8_simplify/plugins/ast_with.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Stmt, StmtKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// SIM117 pub fn multiple_with_statements(checker: &mut Checker, stmt: &Stmt) { @@ -14,7 +15,7 @@ pub fn multiple_with_statements(checker: &mut Checker, stmt: &Stmt) { } if matches!(body[0].node, StmtKind::With { .. }) { checker.checks.push(Check::new( - CheckKind::MultipleWithStatements, + violations::MultipleWithStatements, Range::from_located(stmt), )); } diff --git a/src/flake8_simplify/plugins/key_in_dict.rs b/src/flake8_simplify/plugins/key_in_dict.rs index 98c999720369c..b5e71cce51367 100644 --- a/src/flake8_simplify/plugins/key_in_dict.rs +++ b/src/flake8_simplify/plugins/key_in_dict.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Cmpop, Expr, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// SIM118 fn key_in_dict(checker: &mut Checker, left: &Expr, right: &Expr, range: Range) { @@ -34,7 +35,7 @@ fn key_in_dict(checker: &mut Checker, left: &Expr, right: &Expr, range: Range) { .slice_source_code_range(&Range::from_located(value)); let mut check = Check::new( - CheckKind::KeyInDict(left_content.to_string(), value_content.to_string()), + violations::KeyInDict(left_content.to_string(), value_content.to_string()), range, ); if checker.patch(check.kind.code()) { diff --git a/src/flake8_simplify/plugins/return_in_try_except_finally.rs b/src/flake8_simplify/plugins/return_in_try_except_finally.rs index e86bae57767c0..50e96a09b5c4b 100644 --- a/src/flake8_simplify/plugins/return_in_try_except_finally.rs +++ b/src/flake8_simplify/plugins/return_in_try_except_finally.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Excepthandler, ExcepthandlerKind, Stmt, StmtKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn find_return(stmts: &[Stmt]) -> Option<&Stmt> { stmts @@ -26,7 +27,7 @@ pub fn return_in_try_except_finally( if let Some(finally_return) = find_return(finalbody) { if try_has_return || except_has_return { checker.checks.push(Check::new( - CheckKind::ReturnInTryExceptFinally, + violations::ReturnInTryExceptFinally, Range::from_located(finally_return), )); } diff --git a/src/flake8_simplify/plugins/use_contextlib_suppress.rs b/src/flake8_simplify/plugins/use_contextlib_suppress.rs index 4fcb417e51f08..1f7180c38f87a 100644 --- a/src/flake8_simplify/plugins/use_contextlib_suppress.rs +++ b/src/flake8_simplify/plugins/use_contextlib_suppress.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Excepthandler, ExcepthandlerKind, Stmt, StmtKind}; use crate::ast::helpers; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// SIM105 pub fn use_contextlib_suppress( @@ -30,7 +31,7 @@ pub fn use_contextlib_suppress( handler_names.join(", ") }; let check = Check::new( - CheckKind::UseContextlibSuppress(exception), + violations::UseContextlibSuppress(exception), Range::from_located(stmt), ); checker.checks.push(check); diff --git a/src/flake8_simplify/plugins/yoda_conditions.rs b/src/flake8_simplify/plugins/yoda_conditions.rs index 4b4d81b6d29de..c142997ed085e 100644 --- a/src/flake8_simplify/plugins/yoda_conditions.rs +++ b/src/flake8_simplify/plugins/yoda_conditions.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Cmpop, Expr, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// SIM300 pub fn yoda_conditions( @@ -41,7 +42,7 @@ pub fn yoda_conditions( .slice_source_code_range(&Range::from_located(right)); let mut check = Check::new( - CheckKind::YodaConditions(left_content.to_string(), right_content.to_string()), + violations::YodaConditions(left_content.to_string(), right_content.to_string()), Range::from_located(expr), ); diff --git a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM102_SIM102.py.snap b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM102_SIM102.py.snap index 2d16d5ae1e9c0..52b5c408c7520 100644 --- a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM102_SIM102.py.snap +++ b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM102_SIM102.py.snap @@ -2,7 +2,8 @@ source: src/flake8_simplify/mod.rs expression: checks --- -- kind: NestedIfStatements +- kind: + NestedIfStatements: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: NestedIfStatements +- kind: + NestedIfStatements: ~ location: row: 8 column: 0 diff --git a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM107_SIM107.py.snap b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM107_SIM107.py.snap index dde8a34eca049..583ec3cd7e8ec 100644 --- a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM107_SIM107.py.snap +++ b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM107_SIM107.py.snap @@ -2,7 +2,8 @@ source: src/flake8_simplify/mod.rs expression: checks --- -- kind: ReturnInTryExceptFinally +- kind: + ReturnInTryExceptFinally: ~ location: row: 9 column: 8 diff --git a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM117_SIM117.py.snap b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM117_SIM117.py.snap index 1a92e301ac627..dd889fbdcc7c8 100644 --- a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM117_SIM117.py.snap +++ b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM117_SIM117.py.snap @@ -2,7 +2,8 @@ source: src/flake8_simplify/mod.rs expression: checks --- -- kind: MultipleWithStatements +- kind: + MultipleWithStatements: ~ location: row: 1 column: 0 diff --git a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM222_SIM222.py.snap b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM222_SIM222.py.snap index 88918b3031f0d..334fa55b2cee2 100644 --- a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM222_SIM222.py.snap +++ b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM222_SIM222.py.snap @@ -2,7 +2,8 @@ source: src/flake8_simplify/mod.rs expression: checks --- -- kind: OrTrue +- kind: + OrTrue: ~ location: row: 1 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: OrTrue +- kind: + OrTrue: ~ location: row: 4 column: 15 @@ -20,7 +22,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: OrTrue +- kind: + OrTrue: ~ location: row: 7 column: 14 diff --git a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM223_SIM223.py.snap b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM223_SIM223.py.snap index 086e125c1a973..61dd69b62dc4e 100644 --- a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM223_SIM223.py.snap +++ b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM223_SIM223.py.snap @@ -2,7 +2,8 @@ source: src/flake8_simplify/mod.rs expression: checks --- -- kind: AndFalse +- kind: + AndFalse: ~ location: row: 1 column: 9 @@ -18,7 +19,8 @@ expression: checks row: 1 column: 14 parent: ~ -- kind: AndFalse +- kind: + AndFalse: ~ location: row: 4 column: 16 @@ -34,7 +36,8 @@ expression: checks row: 4 column: 21 parent: ~ -- kind: AndFalse +- kind: + AndFalse: ~ location: row: 7 column: 15 diff --git a/src/flake8_tidy_imports/checks.rs b/src/flake8_tidy_imports/checks.rs index 255ff0daba88a..7ad61d229a42a 100644 --- a/src/flake8_tidy_imports/checks.rs +++ b/src/flake8_tidy_imports/checks.rs @@ -6,7 +6,8 @@ use crate::ast::helpers::match_call_path; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::flake8_tidy_imports::settings::Strictness; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// TID252 pub fn banned_relative_import( @@ -20,7 +21,7 @@ pub fn banned_relative_import( }; if level? > &strictness_level { Some(Check::new( - CheckKind::BannedRelativeImport(strictness.clone()), + violations::BannedRelativeImport(strictness.clone()), Range::from_located(stmt), )) } else { @@ -37,7 +38,7 @@ pub fn name_is_banned( let full_name = format!("{module}.{}", &name.node.name); if let Some(ban) = banned_apis.get(&full_name) { return Some(Check::new( - CheckKind::BannedApi { + violations::BannedApi { name: full_name, message: ban.msg.to_string(), }, @@ -57,7 +58,7 @@ pub fn name_or_parent_is_banned( loop { if let Some(ban) = banned_apis.get(name) { return Some(Check::new( - CheckKind::BannedApi { + violations::BannedApi { name: name.to_string(), message: ban.msg.to_string(), }, @@ -84,7 +85,7 @@ pub fn banned_attribute_access( if let Some((module, member)) = banned_path.rsplit_once('.') { if match_call_path(call_path, module, member, &checker.from_imports) { checker.checks.push(Check::new( - CheckKind::BannedApi { + violations::BannedApi { name: banned_path.to_string(), message: ban.msg.to_string(), }, diff --git a/src/flake8_unused_arguments/types.rs b/src/flake8_unused_arguments/types.rs index 34dcc7d01247a..0f1bb32f831a6 100644 --- a/src/flake8_unused_arguments/types.rs +++ b/src/flake8_unused_arguments/types.rs @@ -1,4 +1,5 @@ use crate::registry::{CheckCode, CheckKind}; +use crate::violations; /// An AST node that can contain arguments. pub enum Argumentable { @@ -12,11 +13,11 @@ pub enum Argumentable { impl Argumentable { pub fn check_for(&self, name: String) -> CheckKind { match self { - Argumentable::Function => CheckKind::UnusedFunctionArgument(name), - Argumentable::Method => CheckKind::UnusedMethodArgument(name), - Argumentable::ClassMethod => CheckKind::UnusedClassMethodArgument(name), - Argumentable::StaticMethod => CheckKind::UnusedStaticMethodArgument(name), - Argumentable::Lambda => CheckKind::UnusedLambdaArgument(name), + Argumentable::Function => violations::UnusedFunctionArgument(name).into(), + Argumentable::Method => violations::UnusedMethodArgument(name).into(), + Argumentable::ClassMethod => violations::UnusedClassMethodArgument(name).into(), + Argumentable::StaticMethod => violations::UnusedStaticMethodArgument(name).into(), + Argumentable::Lambda => violations::UnusedLambdaArgument(name).into(), } } diff --git a/src/isort/plugins.rs b/src/isort/plugins.rs index fbf67a3d69746..af3bf0a9c67ba 100644 --- a/src/isort/plugins.rs +++ b/src/isort/plugins.rs @@ -11,10 +11,9 @@ use crate::ast::whitespace::leading_space; use crate::autofix::Fix; use crate::isort::track::Block; use crate::isort::{comments, format_imports}; -use crate::registry::CheckKind; use crate::settings::flags; use crate::source_code_style::SourceCodeStyleDetector; -use crate::{Check, Settings, SourceCodeLocator}; +use crate::{violations, Check, Settings, SourceCodeLocator}; fn extract_range(body: &[&Stmt]) -> Range { let location = body.first().unwrap().location; @@ -46,7 +45,7 @@ pub fn check_imports( if preceded_by_multi_statement_line(block.imports.first().unwrap(), locator) || followed_by_multi_statement_line(block.imports.last().unwrap(), locator) { - return Some(Check::new(CheckKind::UnsortedImports, range)); + return Some(Check::new(violations::UnsortedImports, range)); } // Extract comments. Take care to grab any inline comments from the last line. @@ -93,7 +92,7 @@ pub fn check_imports( if actual == dedent(&expected) { None } else { - let mut check = Check::new(CheckKind::UnsortedImports, range); + let mut check = Check::new(violations::UnsortedImports, range); if matches!(autofix, flags::Autofix::Enabled) && settings.fixable.contains(check.kind.code()) { diff --git a/src/isort/snapshots/ruff__isort__tests__add_newline_before_comments.py.snap b/src/isort/snapshots/ruff__isort__tests__add_newline_before_comments.py.snap index 8a311203417e9..41ccb8b7ed436 100644 --- a/src/isort/snapshots/ruff__isort__tests__add_newline_before_comments.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__add_newline_before_comments.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__combine_as_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__combine_as_imports.py.snap index f2d2fb1fc9566..748662fdb3b1e 100644 --- a/src/isort/snapshots/ruff__isort__tests__combine_as_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__combine_as_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__combine_as_imports_combine_as_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__combine_as_imports_combine_as_imports.py.snap index 52551203422be..5e4b94db3a707 100644 --- a/src/isort/snapshots/ruff__isort__tests__combine_as_imports_combine_as_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__combine_as_imports_combine_as_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__combine_import_from.py.snap b/src/isort/snapshots/ruff__isort__tests__combine_import_from.py.snap index 3a9fbbbd51a3d..39eaa39e201e6 100644 --- a/src/isort/snapshots/ruff__isort__tests__combine_import_from.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__combine_import_from.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__comments.py.snap b/src/isort/snapshots/ruff__isort__tests__comments.py.snap index 5042899d74cdb..f70458fe38a49 100644 --- a/src/isort/snapshots/ruff__isort__tests__comments.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__comments.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 3 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__deduplicate_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__deduplicate_imports.py.snap index ecb456c6267b9..edf560ab77e78 100644 --- a/src/isort/snapshots/ruff__isort__tests__deduplicate_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__deduplicate_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__fit_line_length.py.snap b/src/isort/snapshots/ruff__isort__tests__fit_line_length.py.snap index e810990e4c527..e2d21ee2a94f1 100644 --- a/src/isort/snapshots/ruff__isort__tests__fit_line_length.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__fit_line_length.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 7 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__fit_line_length_comment.py.snap b/src/isort/snapshots/ruff__isort__tests__fit_line_length_comment.py.snap index f821aad600e24..e3028f8de57ef 100644 --- a/src/isort/snapshots/ruff__isort__tests__fit_line_length_comment.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__fit_line_length_comment.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__force_single_line_force_single_line.py.snap b/src/isort/snapshots/ruff__isort__tests__force_single_line_force_single_line.py.snap index c67686e31c572..01524ddf87502 100644 --- a/src/isort/snapshots/ruff__isort__tests__force_single_line_force_single_line.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__force_single_line_force_single_line.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases.py.snap b/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases.py.snap index 476e535a7d454..6e4376eeaa0dd 100644 --- a/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap b/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap index dfdc7dbc75ca8..ba82f91266b4d 100644 --- a/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__force_wrap_aliases_force_wrap_aliases.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__import_from_after_import.py.snap b/src/isort/snapshots/ruff__isort__tests__import_from_after_import.py.snap index 4358184f12463..c0f32be7aa239 100644 --- a/src/isort/snapshots/ruff__isort__tests__import_from_after_import.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__import_from_after_import.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__inline_comments.py.snap b/src/isort/snapshots/ruff__isort__tests__inline_comments.py.snap index b18bfc67545c7..260975fb58233 100644 --- a/src/isort/snapshots/ruff__isort__tests__inline_comments.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__inline_comments.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.py.snap b/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.py.snap index e2c19b65c41f7..19d3c5e6f48e5 100644 --- a/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 3 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 4 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 6 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 14 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 16 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 52 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.pyi.snap b/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.pyi.snap index da37ba9b2a745..7aa77fb847ecc 100644 --- a/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.pyi.snap +++ b/src/isort/snapshots/ruff__isort__tests__insert_empty_lines.pyi.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 3 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 4 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 6 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 14 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__leading_prefix.py.snap b/src/isort/snapshots/ruff__isort__tests__leading_prefix.py.snap index c150f6caadfea..2d527944cda66 100644 --- a/src/isort/snapshots/ruff__isort__tests__leading_prefix.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__leading_prefix.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 7 @@ -11,7 +12,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 5 column: 11 @@ -20,7 +22,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 10 column: 8 @@ -29,7 +32,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 13 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__line_ending_cr.py.snap b/src/isort/snapshots/ruff__isort__tests__line_ending_cr.py.snap index 63f0be521de23..c84f5e4cc0a47 100644 --- a/src/isort/snapshots/ruff__isort__tests__line_ending_cr.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__line_ending_cr.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__line_ending_crlf.py.snap b/src/isort/snapshots/ruff__isort__tests__line_ending_crlf.py.snap index 336c92580fab1..7fc4f5fd2a0e5 100644 --- a/src/isort/snapshots/ruff__isort__tests__line_ending_crlf.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__line_ending_crlf.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__line_ending_lf.py.snap b/src/isort/snapshots/ruff__isort__tests__line_ending_lf.py.snap index 20ec906cb7d25..81b2b8023cc47 100644 --- a/src/isort/snapshots/ruff__isort__tests__line_ending_lf.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__line_ending_lf.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__magic_trailing_comma.py.snap b/src/isort/snapshots/ruff__isort__tests__magic_trailing_comma.py.snap index 14564d99ad7c1..7a70faab4ef9d 100644 --- a/src/isort/snapshots/ruff__isort__tests__magic_trailing_comma.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__magic_trailing_comma.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 2 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__natural_order.py.snap b/src/isort/snapshots/ruff__isort__tests__natural_order.py.snap index ac7e4088d21f4..8559d5c1d5448 100644 --- a/src/isort/snapshots/ruff__isort__tests__natural_order.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__natural_order.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__no_wrap_star.py.snap b/src/isort/snapshots/ruff__isort__tests__no_wrap_star.py.snap index f60fa6e6f1287..6ec370b284322 100644 --- a/src/isort/snapshots/ruff__isort__tests__no_wrap_star.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__no_wrap_star.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__order_by_type.py.snap b/src/isort/snapshots/ruff__isort__tests__order_by_type.py.snap index 805e992423c6d..2dc4eb536ad6a 100644 --- a/src/isort/snapshots/ruff__isort__tests__order_by_type.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__order_by_type.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__order_by_type_false_order_by_type.py.snap b/src/isort/snapshots/ruff__isort__tests__order_by_type_false_order_by_type.py.snap index bee4aa4091458..fc3e69d12a775 100644 --- a/src/isort/snapshots/ruff__isort__tests__order_by_type_false_order_by_type.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__order_by_type_false_order_by_type.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__order_relative_imports_by_level.py.snap b/src/isort/snapshots/ruff__isort__tests__order_relative_imports_by_level.py.snap index 9c55050192d3f..38ed82f2d657a 100644 --- a/src/isort/snapshots/ruff__isort__tests__order_relative_imports_by_level.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__order_relative_imports_by_level.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__preserve_comment_order.py.snap b/src/isort/snapshots/ruff__isort__tests__preserve_comment_order.py.snap index e47aec929b944..bc6bbb81070f1 100644 --- a/src/isort/snapshots/ruff__isort__tests__preserve_comment_order.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__preserve_comment_order.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__preserve_import_star.py.snap b/src/isort/snapshots/ruff__isort__tests__preserve_import_star.py.snap index 048c5fd93b552..bb95f02045181 100644 --- a/src/isort/snapshots/ruff__isort__tests__preserve_import_star.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__preserve_import_star.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__preserve_indentation.py.snap b/src/isort/snapshots/ruff__isort__tests__preserve_indentation.py.snap index be175dfda8c0f..56d559bf50f2a 100644 --- a/src/isort/snapshots/ruff__isort__tests__preserve_indentation.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__preserve_indentation.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 2 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 4 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 5 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__reorder_within_section.py.snap b/src/isort/snapshots/ruff__isort__tests__reorder_within_section.py.snap index 49faf0b827ebd..702f622b886a0 100644 --- a/src/isort/snapshots/ruff__isort__tests__reorder_within_section.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__reorder_within_section.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__separate_first_party_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__separate_first_party_imports.py.snap index a239c3e812748..d67e4fe358ec6 100644 --- a/src/isort/snapshots/ruff__isort__tests__separate_first_party_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__separate_first_party_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__separate_future_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__separate_future_imports.py.snap index b81d05b15781e..3bf29c21df9ea 100644 --- a/src/isort/snapshots/ruff__isort__tests__separate_future_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__separate_future_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__separate_local_folder_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__separate_local_folder_imports.py.snap index 2a005d021785b..91e2d80782358 100644 --- a/src/isort/snapshots/ruff__isort__tests__separate_local_folder_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__separate_local_folder_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__separate_third_party_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__separate_third_party_imports.py.snap index 36b20d815b1e6..2c614ff6a0af0 100644 --- a/src/isort/snapshots/ruff__isort__tests__separate_third_party_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__separate_third_party_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__skip.py.snap b/src/isort/snapshots/ruff__isort__tests__skip.py.snap index 3085ab77216ca..0be98db662ed1 100644 --- a/src/isort/snapshots/ruff__isort__tests__skip.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__skip.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 7 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 8 column: 0 parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 9 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__sort_similar_imports.py.snap b/src/isort/snapshots/ruff__isort__tests__sort_similar_imports.py.snap index 761a30c0064dc..2e7474cc16c02 100644 --- a/src/isort/snapshots/ruff__isort__tests__sort_similar_imports.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__sort_similar_imports.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap b/src/isort/snapshots/ruff__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap index addf15e543304..ae62773b62d29 100644 --- a/src/isort/snapshots/ruff__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__split_on_trailing_comma_magic_trailing_comma.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 2 column: 0 diff --git a/src/isort/snapshots/ruff__isort__tests__trailing_suffix.py.snap b/src/isort/snapshots/ruff__isort__tests__trailing_suffix.py.snap index 6c6afbf1aa908..19a07930b19c3 100644 --- a/src/isort/snapshots/ruff__isort__tests__trailing_suffix.py.snap +++ b/src/isort/snapshots/ruff__isort__tests__trailing_suffix.py.snap @@ -2,7 +2,8 @@ source: src/isort/mod.rs expression: checks --- -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: UnsortedImports +- kind: + UnsortedImports: ~ location: row: 5 column: 4 diff --git a/src/lib.rs b/src/lib.rs index 62ff1f15e6c37..ddbfc816dc2de 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,6 +75,8 @@ pub mod source_code_generator; pub mod source_code_locator; pub mod source_code_style; mod vendor; +mod violation; +mod violations; pub mod visibility; cfg_if! { diff --git a/src/linter.rs b/src/linter.rs index 8c349e0121267..ba13899dc9f55 100644 --- a/src/linter.rs +++ b/src/linter.rs @@ -21,11 +21,11 @@ use crate::checkers::tokens::check_tokens; use crate::directives::Directives; use crate::message::{Message, Source}; use crate::noqa::add_noqa; -use crate::registry::{Check, CheckCode, CheckKind, LintSource}; +use crate::registry::{Check, CheckCode, LintSource}; use crate::settings::{flags, Settings}; use crate::source_code_locator::SourceCodeLocator; use crate::source_code_style::SourceCodeStyleDetector; -use crate::{cache, directives, fs, rustpython_helpers}; +use crate::{cache, directives, fs, rustpython_helpers, violations}; const CARGO_PKG_NAME: &str = env!("CARGO_PKG_NAME"); const CARGO_PKG_REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); @@ -119,7 +119,7 @@ pub(crate) fn check_path( Err(parse_error) => { if settings.enabled.contains(&CheckCode::E999) { checks.push(Check::new( - CheckKind::SyntaxError(parse_error.error.to_string()), + violations::SyntaxError(parse_error.error.to_string()), Range::new(parse_error.location, parse_error.location), )); } diff --git a/src/mccabe/checks.rs b/src/mccabe/checks.rs index 9431fdca61aa6..723fef5b37a1c 100644 --- a/src/mccabe/checks.rs +++ b/src/mccabe/checks.rs @@ -1,8 +1,9 @@ use rustpython_ast::{ExcepthandlerKind, ExprKind, Stmt, StmtKind}; use crate::ast::helpers::identifier_range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; fn get_complexity_number(stmts: &[Stmt]) -> usize { let mut complexity = 0; @@ -65,7 +66,7 @@ pub fn function_is_too_complex( let complexity = get_complexity_number(body) + 1; if complexity > max_complexity { Some(Check::new( - CheckKind::FunctionIsTooComplex(name.to_string(), complexity), + violations::FunctionIsTooComplex(name.to_string(), complexity), identifier_range(stmt, locator), )) } else { diff --git a/src/noqa.rs b/src/noqa.rs index eddc95195cde4..7ea2700cd8df5 100644 --- a/src/noqa.rs +++ b/src/noqa.rs @@ -213,8 +213,9 @@ mod tests { use crate::ast::types::Range; use crate::noqa::{add_noqa_inner, NOQA_LINE_REGEX}; - use crate::registry::{Check, CheckKind}; + use crate::registry::Check; use crate::source_code_style::LineEnding; + use crate::violations; #[test] fn regex() { @@ -247,7 +248,7 @@ mod tests { assert_eq!(output, format!("{contents}\n")); let checks = vec![Check::new( - CheckKind::UnusedVariable("x".to_string()), + violations::UnusedVariable("x".to_string()), Range::new(Location::new(1, 0), Location::new(1, 0)), )]; let contents = "x = 1"; @@ -265,11 +266,11 @@ mod tests { let checks = vec![ Check::new( - CheckKind::AmbiguousVariableName("x".to_string()), + violations::AmbiguousVariableName("x".to_string()), Range::new(Location::new(1, 0), Location::new(1, 0)), ), Check::new( - CheckKind::UnusedVariable("x".to_string()), + violations::UnusedVariable("x".to_string()), Range::new(Location::new(1, 0), Location::new(1, 0)), ), ]; @@ -288,11 +289,11 @@ mod tests { let checks = vec![ Check::new( - CheckKind::AmbiguousVariableName("x".to_string()), + violations::AmbiguousVariableName("x".to_string()), Range::new(Location::new(1, 0), Location::new(1, 0)), ), Check::new( - CheckKind::UnusedVariable("x".to_string()), + violations::UnusedVariable("x".to_string()), Range::new(Location::new(1, 0), Location::new(1, 0)), ), ]; diff --git a/src/pandas_vet/checks.rs b/src/pandas_vet/checks.rs index a9cc96118c388..2a22b552fa603 100644 --- a/src/pandas_vet/checks.rs +++ b/src/pandas_vet/checks.rs @@ -1,7 +1,8 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// PD002 pub fn inplace_argument(keywords: &[Keyword]) -> Option { @@ -18,7 +19,7 @@ pub fn inplace_argument(keywords: &[Keyword]) -> Option { }; if is_true_literal { return Some(Check::new( - CheckKind::UseOfInplaceArgument, + violations::UseOfInplaceArgument, Range::from_located(keyword), )); } @@ -33,7 +34,7 @@ pub fn use_of_pd_merge(func: &Expr) -> Option { if let ExprKind::Name { id, .. } = &value.node { if id == "pd" && attr == "merge" { return Some(Check::new( - CheckKind::UseOfPdMerge, + violations::UseOfPdMerge, Range::from_located(func), )); } @@ -55,7 +56,7 @@ pub fn assignment_to_df(targets: &[Expr]) -> Option { return None; } Some(Check::new( - CheckKind::DfIsABadVariableName, + violations::DfIsABadVariableName, Range::from_located(target), )) } diff --git a/src/pep8_naming/checks.rs b/src/pep8_naming/checks.rs index 36c52b287a1c0..15035f987d2c1 100644 --- a/src/pep8_naming/checks.rs +++ b/src/pep8_naming/checks.rs @@ -7,8 +7,9 @@ use crate::ast::types::{Range, Scope, ScopeKind}; use crate::pep8_naming::helpers; use crate::pep8_naming::settings::Settings; use crate::python::string::{self}; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; /// N801 pub fn invalid_class_name( @@ -19,7 +20,7 @@ pub fn invalid_class_name( let stripped = name.strip_prefix('_').unwrap_or(name); if !stripped.chars().next().map_or(false, char::is_uppercase) || stripped.contains('_') { return Some(Check::new( - CheckKind::InvalidClassName(name.to_string()), + violations::InvalidClassName(name.to_string()), identifier_range(class_def, locator), )); } @@ -35,7 +36,7 @@ pub fn invalid_function_name( ) -> Option { if name.to_lowercase() != name && !ignore_names.iter().any(|ignore_name| ignore_name == name) { return Some(Check::new( - CheckKind::InvalidFunctionName(name.to_string()), + violations::InvalidFunctionName(name.to_string()), identifier_range(func_def, locator), )); } @@ -46,7 +47,7 @@ pub fn invalid_function_name( pub fn invalid_argument_name(name: &str, arg: &Arg) -> Option { if name.to_lowercase() != name { return Some(Check::new( - CheckKind::InvalidArgumentName(name.to_string()), + violations::InvalidArgumentName(name.to_string()), Range::from_located(arg), )); } @@ -80,14 +81,14 @@ pub fn invalid_first_argument_name_for_class_method( if let Some(arg) = args.posonlyargs.first() { if arg.node.arg != "cls" { return Some(Check::new( - CheckKind::InvalidFirstArgumentNameForClassMethod, + violations::InvalidFirstArgumentNameForClassMethod, Range::from_located(arg), )); } } else if let Some(arg) = args.args.first() { if arg.node.arg != "cls" { return Some(Check::new( - CheckKind::InvalidFirstArgumentNameForClassMethod, + violations::InvalidFirstArgumentNameForClassMethod, Range::from_located(arg), )); } @@ -124,7 +125,7 @@ pub fn invalid_first_argument_name_for_method( return None; } Some(Check::new( - CheckKind::InvalidFirstArgumentNameForMethod, + violations::InvalidFirstArgumentNameForMethod, Range::from_located(arg), )) } @@ -148,7 +149,7 @@ pub fn dunder_function_name( } Some(Check::new( - CheckKind::DunderFunctionName, + violations::DunderFunctionName, identifier_range(stmt, locator), )) } @@ -162,7 +163,7 @@ pub fn constant_imported_as_non_constant( ) -> Option { if string::is_upper(name) && !string::is_upper(asname) { return Some(Check::new( - CheckKind::ConstantImportedAsNonConstant(name.to_string(), asname.to_string()), + violations::ConstantImportedAsNonConstant(name.to_string(), asname.to_string()), identifier_range(import_from, locator), )); } @@ -178,7 +179,7 @@ pub fn lowercase_imported_as_non_lowercase( ) -> Option { if !string::is_upper(name) && string::is_lower(name) && asname.to_lowercase() != asname { return Some(Check::new( - CheckKind::LowercaseImportedAsNonLowercase(name.to_string(), asname.to_string()), + violations::LowercaseImportedAsNonLowercase(name.to_string(), asname.to_string()), identifier_range(import_from, locator), )); } @@ -194,7 +195,7 @@ pub fn camelcase_imported_as_lowercase( ) -> Option { if helpers::is_camelcase(name) && string::is_lower(asname) { return Some(Check::new( - CheckKind::CamelcaseImportedAsLowercase(name.to_string(), asname.to_string()), + violations::CamelcaseImportedAsLowercase(name.to_string(), asname.to_string()), identifier_range(import_from, locator), )); } @@ -214,7 +215,7 @@ pub fn camelcase_imported_as_constant( && !helpers::is_acronym(name, asname) { return Some(Check::new( - CheckKind::CamelcaseImportedAsConstant(name.to_string(), asname.to_string()), + violations::CamelcaseImportedAsConstant(name.to_string(), asname.to_string()), identifier_range(import_from, locator), )); } @@ -234,7 +235,7 @@ pub fn camelcase_imported_as_acronym( && helpers::is_acronym(name, asname) { return Some(Check::new( - CheckKind::CamelcaseImportedAsAcronym(name.to_string(), asname.to_string()), + violations::CamelcaseImportedAsAcronym(name.to_string(), asname.to_string()), identifier_range(import_from, locator), )); } @@ -262,7 +263,7 @@ pub fn error_suffix_on_exception_name( return None; } Some(Check::new( - CheckKind::ErrorSuffixOnExceptionName(name.to_string()), + violations::ErrorSuffixOnExceptionName(name.to_string()), identifier_range(class_def, locator), )) } diff --git a/src/pep8_naming/plugins.rs b/src/pep8_naming/plugins.rs index 91f77cd7908e3..9735378d6f5f4 100644 --- a/src/pep8_naming/plugins.rs +++ b/src/pep8_naming/plugins.rs @@ -3,8 +3,7 @@ use rustpython_ast::{Expr, Stmt}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::pep8_naming::helpers; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// N806 pub fn non_lowercase_variable_in_function( @@ -17,7 +16,7 @@ pub fn non_lowercase_variable_in_function( && !helpers::is_namedtuple_assignment(stmt, &checker.from_imports) { checker.checks.push(Check::new( - CheckKind::NonLowercaseVariableInFunction(name.to_string()), + violations::NonLowercaseVariableInFunction(name.to_string()), Range::from_located(expr), )); } @@ -34,7 +33,7 @@ pub fn mixed_case_variable_in_class_scope( && !helpers::is_namedtuple_assignment(stmt, &checker.from_imports) { checker.checks.push(Check::new( - CheckKind::MixedCaseVariableInClassScope(name.to_string()), + violations::MixedCaseVariableInClassScope(name.to_string()), Range::from_located(expr), )); } @@ -51,7 +50,7 @@ pub fn mixed_case_variable_in_global_scope( && !helpers::is_namedtuple_assignment(stmt, &checker.from_imports) { checker.checks.push(Check::new( - CheckKind::MixedCaseVariableInGlobalScope(name.to_string()), + violations::MixedCaseVariableInGlobalScope(name.to_string()), Range::from_located(expr), )); } diff --git a/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N804_N804.py.snap b/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N804_N804.py.snap index dd00bf69dde66..8473c20b70cc2 100644 --- a/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N804_N804.py.snap +++ b/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N804_N804.py.snap @@ -2,7 +2,8 @@ source: src/pep8_naming/mod.rs expression: checks --- -- kind: InvalidFirstArgumentNameForClassMethod +- kind: + InvalidFirstArgumentNameForClassMethod: ~ location: row: 30 column: 26 @@ -11,7 +12,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: InvalidFirstArgumentNameForClassMethod +- kind: + InvalidFirstArgumentNameForClassMethod: ~ location: row: 38 column: 55 @@ -20,7 +22,8 @@ expression: checks column: 59 fix: ~ parent: ~ -- kind: InvalidFirstArgumentNameForClassMethod +- kind: + InvalidFirstArgumentNameForClassMethod: ~ location: row: 43 column: 19 diff --git a/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N805_N805.py.snap b/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N805_N805.py.snap index 3977ea2746f9b..563897fbc229a 100644 --- a/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N805_N805.py.snap +++ b/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N805_N805.py.snap @@ -2,7 +2,8 @@ source: src/pep8_naming/mod.rs expression: checks --- -- kind: InvalidFirstArgumentNameForMethod +- kind: + InvalidFirstArgumentNameForMethod: ~ location: row: 7 column: 19 @@ -11,7 +12,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: InvalidFirstArgumentNameForMethod +- kind: + InvalidFirstArgumentNameForMethod: ~ location: row: 12 column: 29 @@ -20,7 +22,8 @@ expression: checks column: 33 fix: ~ parent: ~ -- kind: InvalidFirstArgumentNameForMethod +- kind: + InvalidFirstArgumentNameForMethod: ~ location: row: 27 column: 14 @@ -29,7 +32,8 @@ expression: checks column: 17 fix: ~ parent: ~ -- kind: InvalidFirstArgumentNameForMethod +- kind: + InvalidFirstArgumentNameForMethod: ~ location: row: 31 column: 14 diff --git a/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N807_N807.py.snap b/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N807_N807.py.snap index c3c7a25a898f9..bf58ff7ecf033 100644 --- a/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N807_N807.py.snap +++ b/src/pep8_naming/snapshots/ruff__pep8_naming__tests__N807_N807.py.snap @@ -2,7 +2,8 @@ source: src/pep8_naming/mod.rs expression: checks --- -- kind: DunderFunctionName +- kind: + DunderFunctionName: ~ location: row: 1 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: DunderFunctionName +- kind: + DunderFunctionName: ~ location: row: 14 column: 8 diff --git a/src/pycodestyle/checks.rs b/src/pycodestyle/checks.rs index d62dc13879b28..59caea4356e96 100644 --- a/src/pycodestyle/checks.rs +++ b/src/pycodestyle/checks.rs @@ -7,9 +7,10 @@ use rustpython_parser::ast::{Cmpop, Expr, ExprKind}; use crate::ast::helpers::except_range; use crate::ast::types::Range; use crate::autofix::Fix; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::settings::Settings; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; static URL_REGEX: Lazy = Lazy::new(|| Regex::new(r"^https?://\S+$").unwrap()); @@ -43,7 +44,7 @@ pub fn line_too_long(lineno: usize, line: &str, settings: &Settings) -> Option kind: None } ) { - checks.push(Check::new(CheckKind::TypeComparison, location)); + checks.push(Check::new(violations::TypeComparison, location)); } } } @@ -84,7 +85,7 @@ pub fn type_comparison(ops: &[Cmpop], comparators: &[Expr], location: Range) -> if let ExprKind::Name { id, .. } = &value.node { // Ex) types.IntType if id == "types" { - checks.push(Check::new(CheckKind::TypeComparison, location)); + checks.push(Check::new(violations::TypeComparison, location)); } } } @@ -108,7 +109,7 @@ pub fn do_not_use_bare_except( .any(|stmt| matches!(stmt.node, StmtKind::Raise { exc: None, .. })) { Some(Check::new( - CheckKind::DoNotUseBareExcept, + violations::DoNotUseBareExcept, except_range(handler, locator), )) } else { @@ -124,7 +125,7 @@ fn is_ambiguous_name(name: &str) -> bool { pub fn ambiguous_variable_name(name: &str, range: Range) -> Option { if is_ambiguous_name(name) { Some(Check::new( - CheckKind::AmbiguousVariableName(name.to_string()), + violations::AmbiguousVariableName(name.to_string()), range, )) } else { @@ -139,7 +140,7 @@ where { if is_ambiguous_name(name) { Some(Check::new( - CheckKind::AmbiguousClassName(name.to_string()), + violations::AmbiguousClassName(name.to_string()), locate(), )) } else { @@ -154,7 +155,7 @@ where { if is_ambiguous_name(name) { Some(Check::new( - CheckKind::AmbiguousFunctionName(name.to_string()), + violations::AmbiguousFunctionName(name.to_string()), locate(), )) } else { @@ -171,7 +172,7 @@ pub fn no_newline_at_end_of_file(contents: &str, autofix: bool) -> Option // Both locations are at the end of the file (and thus the same). let location = Location::new(contents.lines().count(), line.len()); let mut check = Check::new( - CheckKind::NoNewLineAtEndOfFile, + violations::NoNewLineAtEndOfFile, Range::new(location, location), ); if autofix { @@ -252,7 +253,7 @@ pub fn invalid_escape_sequence( let location = Location::new(start.row() + row_offset, col); let end_location = Location::new(location.row(), location.column() + 2); let mut check = Check::new( - CheckKind::InvalidEscapeSequence(next_char), + violations::InvalidEscapeSequence(next_char), Range::new(location, end_location), ); if autofix { diff --git a/src/pycodestyle/plugins.rs b/src/pycodestyle/plugins.rs index 27dcaf60db63d..e00bad737b624 100644 --- a/src/pycodestyle/plugins.rs +++ b/src/pycodestyle/plugins.rs @@ -11,9 +11,10 @@ use crate::ast::types::Range; use crate::ast::whitespace::leading_space; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_style::SourceCodeStyleDetector; +use crate::violations; pub fn compare( left: &Expr, @@ -64,7 +65,7 @@ pub fn literal_comparisons( { if matches!(op, Cmpop::Eq) { let check = Check::new( - CheckKind::NoneComparison(op.into()), + violations::NoneComparison(op.into()), Range::from_located(comparator), ); if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { @@ -74,7 +75,7 @@ pub fn literal_comparisons( } if matches!(op, Cmpop::NotEq) { let check = Check::new( - CheckKind::NoneComparison(op.into()), + violations::NoneComparison(op.into()), Range::from_located(comparator), ); if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { @@ -92,7 +93,7 @@ pub fn literal_comparisons( { if matches!(op, Cmpop::Eq) { let check = Check::new( - CheckKind::TrueFalseComparison(value, op.into()), + violations::TrueFalseComparison(value, op.into()), Range::from_located(comparator), ); if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { @@ -102,7 +103,7 @@ pub fn literal_comparisons( } if matches!(op, Cmpop::NotEq) { let check = Check::new( - CheckKind::TrueFalseComparison(value, op.into()), + violations::TrueFalseComparison(value, op.into()), Range::from_located(comparator), ); if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { @@ -126,7 +127,7 @@ pub fn literal_comparisons( { if matches!(op, Cmpop::Eq) { let check = Check::new( - CheckKind::NoneComparison(op.into()), + violations::NoneComparison(op.into()), Range::from_located(next), ); if checker.patch(check.kind.code()) @@ -138,7 +139,7 @@ pub fn literal_comparisons( } if matches!(op, Cmpop::NotEq) { let check = Check::new( - CheckKind::NoneComparison(op.into()), + violations::NoneComparison(op.into()), Range::from_located(next), ); if checker.patch(check.kind.code()) @@ -158,7 +159,7 @@ pub fn literal_comparisons( { if matches!(op, Cmpop::Eq) { let check = Check::new( - CheckKind::TrueFalseComparison(value, op.into()), + violations::TrueFalseComparison(value, op.into()), Range::from_located(next), ); if checker.patch(check.kind.code()) @@ -170,7 +171,7 @@ pub fn literal_comparisons( } if matches!(op, Cmpop::NotEq) { let check = Check::new( - CheckKind::TrueFalseComparison(value, op.into()), + violations::TrueFalseComparison(value, op.into()), Range::from_located(next), ); if checker.patch(check.kind.code()) @@ -232,7 +233,7 @@ pub fn not_tests( Cmpop::In => { if check_not_in { let mut check = - Check::new(CheckKind::NotInTest, Range::from_located(operand)); + Check::new(violations::NotInTest, Range::from_located(operand)); if checker.patch(check.kind.code()) && should_fix { check.amend(Fix::replacement( compare(left, &[Cmpop::NotIn], comparators, checker.style), @@ -246,7 +247,7 @@ pub fn not_tests( Cmpop::Is => { if check_not_is { let mut check = - Check::new(CheckKind::NotIsTest, Range::from_located(operand)); + Check::new(violations::NotIsTest, Range::from_located(operand)); if checker.patch(check.kind.code()) && should_fix { check.amend(Fix::replacement( compare(left, &[Cmpop::IsNot], comparators, checker.style), @@ -299,7 +300,7 @@ pub fn do_not_assign_lambda(checker: &mut Checker, target: &Expr, value: &Expr, if let ExprKind::Name { id, .. } = &target.node { if let ExprKind::Lambda { args, body } = &value.node { let mut check = Check::new( - CheckKind::DoNotAssignLambda(id.to_string()), + violations::DoNotAssignLambda(id.to_string()), Range::from_located(stmt), ); if checker.patch(check.kind.code()) { diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E401_E40.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E401_E40.py.snap index 1811d225396e0..175afe49ba480 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E401_E40.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E401_E40.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: MultipleImportsOnOneLine +- kind: + MultipleImportsOnOneLine: ~ location: row: 2 column: 0 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E40.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E40.py.snap index 880da501ff0e6..e344b1698ef70 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E40.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E40.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: ModuleImportNotAtTopOfFile +- kind: + ModuleImportNotAtTopOfFile: ~ location: row: 55 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: ModuleImportNotAtTopOfFile +- kind: + ModuleImportNotAtTopOfFile: ~ location: row: 57 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 10 fix: ~ parent: ~ -- kind: ModuleImportNotAtTopOfFile +- kind: + ModuleImportNotAtTopOfFile: ~ location: row: 61 column: 0 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E402.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E402.py.snap index 0ed6d2c5d192b..41f812f9a639d 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E402.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E402_E402.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: ModuleImportNotAtTopOfFile +- kind: + ModuleImportNotAtTopOfFile: ~ location: row: 24 column: 0 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E713_E713.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E713_E713.py.snap index 81e616569af43..8671fe8ba51f3 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E713_E713.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E713_E713.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: NotInTest +- kind: + NotInTest: ~ location: row: 2 column: 7 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 13 parent: ~ -- kind: NotInTest +- kind: + NotInTest: ~ location: row: 5 column: 7 @@ -34,7 +36,8 @@ expression: checks row: 5 column: 15 parent: ~ -- kind: NotInTest +- kind: + NotInTest: ~ location: row: 8 column: 7 @@ -50,7 +53,8 @@ expression: checks row: 8 column: 13 parent: ~ -- kind: NotInTest +- kind: + NotInTest: ~ location: row: 11 column: 22 @@ -66,7 +70,8 @@ expression: checks row: 11 column: 28 parent: ~ -- kind: NotInTest +- kind: + NotInTest: ~ location: row: 14 column: 8 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E714_E714.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E714_E714.py.snap index 98b65e6c895de..4b818f5ff6421 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E714_E714.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E714_E714.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: NotIsTest +- kind: + NotIsTest: ~ location: row: 2 column: 7 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 13 parent: ~ -- kind: NotIsTest +- kind: + NotIsTest: ~ location: row: 5 column: 7 @@ -34,7 +36,8 @@ expression: checks row: 5 column: 15 parent: ~ -- kind: NotIsTest +- kind: + NotIsTest: ~ location: row: 8 column: 7 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E721_E721.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E721_E721.py.snap index f05b376269566..9b46ec8c4a306 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E721_E721.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E721_E721.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 2 column: 3 @@ -11,7 +12,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 5 column: 3 @@ -20,7 +22,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 10 column: 3 @@ -29,7 +32,8 @@ expression: checks column: 23 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 15 column: 3 @@ -38,7 +42,8 @@ expression: checks column: 34 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 18 column: 7 @@ -47,7 +52,8 @@ expression: checks column: 31 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 20 column: 7 @@ -56,7 +62,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 22 column: 7 @@ -65,7 +72,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 24 column: 7 @@ -74,7 +82,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 26 column: 7 @@ -83,7 +92,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 28 column: 7 @@ -92,7 +102,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 30 column: 7 @@ -101,7 +112,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 32 column: 7 @@ -110,7 +122,8 @@ expression: checks column: 34 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 34 column: 7 @@ -119,7 +132,8 @@ expression: checks column: 1 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 40 column: 7 @@ -128,7 +142,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: TypeComparison +- kind: + TypeComparison: ~ location: row: 42 column: 7 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E722_E722.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E722_E722.py.snap index ba398c6f6af86..f36ec0e9356da 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E722_E722.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__E722_E722.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: DoNotUseBareExcept +- kind: + DoNotUseBareExcept: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: DoNotUseBareExcept +- kind: + DoNotUseBareExcept: ~ location: row: 11 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: DoNotUseBareExcept +- kind: + DoNotUseBareExcept: ~ location: row: 16 column: 0 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_0.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_0.py.snap index 23f36b1cfbb66..d83aa01884090 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_0.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_0.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: NoNewLineAtEndOfFile +- kind: + NoNewLineAtEndOfFile: ~ location: row: 2 column: 8 diff --git a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_4.py.snap b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_4.py.snap index 8b67fd936ad60..0e0b7153e9b71 100644 --- a/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_4.py.snap +++ b/src/pycodestyle/snapshots/ruff__pycodestyle__tests__W292_W292_4.py.snap @@ -2,7 +2,8 @@ source: src/pycodestyle/mod.rs expression: checks --- -- kind: NoNewLineAtEndOfFile +- kind: + NoNewLineAtEndOfFile: ~ location: row: 1 column: 1 diff --git a/src/pydocstyle/plugins.rs b/src/pydocstyle/plugins.rs index 275b2d319249f..12f164f823930 100644 --- a/src/pydocstyle/plugins.rs +++ b/src/pydocstyle/plugins.rs @@ -16,7 +16,8 @@ use crate::docstrings::sections::{section_contexts, SectionContext}; use crate::docstrings::styles::SectionStyle; use crate::pydocstyle::helpers::{leading_quote, logical_line}; use crate::pydocstyle::settings::Convention; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; use crate::visibility::{is_init, is_magic, is_overload, is_override, is_staticmethod, Visibility}; /// D100, D101, D102, D103, D104, D105, D106, D107 @@ -33,7 +34,7 @@ pub fn not_missing( DefinitionKind::Module => { if checker.settings.enabled.contains(&CheckCode::D100) { checker.checks.push(Check::new( - CheckKind::PublicModule, + violations::PublicModule, Range::new(Location::new(1, 0), Location::new(1, 0)), )); } @@ -42,7 +43,7 @@ pub fn not_missing( DefinitionKind::Package => { if checker.settings.enabled.contains(&CheckCode::D104) { checker.checks.push(Check::new( - CheckKind::PublicPackage, + violations::PublicPackage, Range::new(Location::new(1, 0), Location::new(1, 0)), )); } @@ -51,7 +52,7 @@ pub fn not_missing( DefinitionKind::Class(stmt) => { if checker.settings.enabled.contains(&CheckCode::D101) { checker.checks.push(Check::new( - CheckKind::PublicClass, + violations::PublicClass, identifier_range(stmt, checker.locator), )); } @@ -60,7 +61,7 @@ pub fn not_missing( DefinitionKind::NestedClass(stmt) => { if checker.settings.enabled.contains(&CheckCode::D106) { checker.checks.push(Check::new( - CheckKind::PublicNestedClass, + violations::PublicNestedClass, identifier_range(stmt, checker.locator), )); } @@ -72,7 +73,7 @@ pub fn not_missing( } else { if checker.settings.enabled.contains(&CheckCode::D103) { checker.checks.push(Check::new( - CheckKind::PublicFunction, + violations::PublicFunction, identifier_range(stmt, checker.locator), )); } @@ -87,7 +88,7 @@ pub fn not_missing( } else if is_magic(stmt) { if checker.settings.enabled.contains(&CheckCode::D105) { checker.checks.push(Check::new( - CheckKind::MagicMethod, + violations::MagicMethod, identifier_range(stmt, checker.locator), )); } @@ -95,7 +96,7 @@ pub fn not_missing( } else if is_init(stmt) { if checker.settings.enabled.contains(&CheckCode::D107) { checker.checks.push(Check::new( - CheckKind::PublicInit, + violations::PublicInit, identifier_range(stmt, checker.locator), )); } @@ -103,7 +104,7 @@ pub fn not_missing( } else { if checker.settings.enabled.contains(&CheckCode::D102) { checker.checks.push(Check::new( - CheckKind::PublicMethod, + violations::PublicMethod, identifier_range(stmt, checker.locator), )); } @@ -131,7 +132,7 @@ pub fn one_liner(checker: &mut Checker, docstring: &Docstring) { if non_empty_line_count == 1 && line_count > 1 { checker.checks.push(Check::new( - CheckKind::FitsOnOneLine, + violations::FitsOnOneLine, Range::from_located(docstring.expr), )); } @@ -166,7 +167,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring) .count(); if blank_lines_before != 0 { let mut check = Check::new( - CheckKind::NoBlankLineBeforeFunction(blank_lines_before), + violations::NoBlankLineBeforeFunction(blank_lines_before), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -207,7 +208,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring) if blank_lines_after != 0 { let mut check = Check::new( - CheckKind::NoBlankLineAfterFunction(blank_lines_after), + violations::NoBlankLineAfterFunction(blank_lines_after), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -248,7 +249,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) { if checker.settings.enabled.contains(&CheckCode::D211) { if blank_lines_before != 0 { let mut check = Check::new( - CheckKind::NoBlankLineBeforeClass(blank_lines_before), + violations::NoBlankLineBeforeClass(blank_lines_before), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -264,7 +265,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) { if checker.settings.enabled.contains(&CheckCode::D203) { if blank_lines_before != 1 { let mut check = Check::new( - CheckKind::OneBlankLineBeforeClass(blank_lines_before), + violations::OneBlankLineBeforeClass(blank_lines_before), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -301,7 +302,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) { .count(); if blank_lines_after != 1 { let mut check = Check::new( - CheckKind::OneBlankLineAfterClass(blank_lines_after), + violations::OneBlankLineAfterClass(blank_lines_after), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -336,7 +337,7 @@ pub fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) { } if lines_count > 1 && blanks_count != 1 { let mut check = Check::new( - CheckKind::BlankLineAfterSummary(blanks_count), + violations::BlankLineAfterSummary(blanks_count), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -405,7 +406,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) { && line_indent.len() < docstring.indentation.len() { let mut check = Check::new( - CheckKind::NoUnderIndentation, + violations::NoUnderIndentation, Range::new( Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0), @@ -440,7 +441,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) { if checker.settings.enabled.contains(&CheckCode::D206) { if has_seen_tab { checker.checks.push(Check::new( - CheckKind::IndentWithSpaces, + violations::IndentWithSpaces, Range::from_located(docstring.expr), )); } @@ -455,7 +456,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) { // We report over-indentation on every line. This isn't great, but // enables autofix. let mut check = Check::new( - CheckKind::NoOverIndentation, + violations::NoOverIndentation, Range::new( Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0), @@ -479,7 +480,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) { let line_indent = whitespace::leading_space(lines[i]); if line_indent.len() > docstring.indentation.len() { let mut check = Check::new( - CheckKind::NoOverIndentation, + violations::NoOverIndentation, Range::new( Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0), @@ -512,7 +513,7 @@ pub fn newline_after_last_paragraph(checker: &mut Checker, docstring: &Docstring if let Some(last_line) = contents.lines().last().map(str::trim) { if last_line != "\"\"\"" && last_line != "'''" { let mut check = Check::new( - CheckKind::NewLineAfterLastParagraph, + violations::NewLineAfterLastParagraph, Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -551,7 +552,7 @@ pub fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) { return; } let mut check = Check::new( - CheckKind::NoSurroundingWhitespace, + violations::NoSurroundingWhitespace, Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -596,14 +597,14 @@ pub fn multi_line_summary_start(checker: &mut Checker, docstring: &Docstring) { if constants::TRIPLE_QUOTE_PREFIXES.contains(&first_line) { if checker.settings.enabled.contains(&CheckCode::D212) { checker.checks.push(Check::new( - CheckKind::MultiLineSummaryFirstLine, + violations::MultiLineSummaryFirstLine, Range::from_located(docstring.expr), )); } } else { if checker.settings.enabled.contains(&CheckCode::D213) { checker.checks.push(Check::new( - CheckKind::MultiLineSummarySecondLine, + violations::MultiLineSummarySecondLine, Range::from_located(docstring.expr), )); } @@ -635,7 +636,7 @@ pub fn triple_quotes(checker: &mut Checker, docstring: &Docstring) { }; if !starts_with_triple { checker.checks.push(Check::new( - CheckKind::UsesTripleQuotes, + violations::UsesTripleQuotes, Range::from_located(docstring.expr), )); } @@ -654,7 +655,7 @@ pub fn backslashes(checker: &mut Checker, docstring: &Docstring) { if BACKSLASH_REGEX.is_match(contents) { checker.checks.push(Check::new( - CheckKind::UsesRPrefixForBackslashedContent, + violations::UsesRPrefixForBackslashedContent, Range::from_located(docstring.expr), )); } @@ -695,8 +696,10 @@ pub fn ends_with_period(checker: &mut Checker, docstring: &Docstring) { let trimmed = line.trim_end(); if !trimmed.ends_with('.') { - let mut check = - Check::new(CheckKind::EndsInPeriod, Range::from_located(docstring.expr)); + let mut check = Check::new( + violations::EndsInPeriod, + Range::from_located(docstring.expr), + ); // Best-effort autofix: avoid adding a period after other punctuation marks. if checker.patch(&CheckCode::D400) && !trimmed.ends_with(':') && !trimmed.ends_with(';') { @@ -745,7 +748,7 @@ pub fn no_signature(checker: &mut Checker, docstring: &Docstring) { return; }; checker.checks.push(Check::new( - CheckKind::NoSignature, + violations::NoSignature, Range::from_located(docstring.expr), )); } @@ -776,7 +779,7 @@ pub fn capitalized(checker: &mut Checker, docstring: &Docstring) { return; }; checker.checks.push(Check::new( - CheckKind::FirstLineCapitalized, + violations::FirstLineCapitalized, Range::from_located(docstring.expr), )); } @@ -801,7 +804,7 @@ pub fn starts_with_this(checker: &mut Checker, docstring: &Docstring) { return; } checker.checks.push(Check::new( - CheckKind::NoThisPrefix, + violations::NoThisPrefix, Range::from_located(docstring.expr), )); } @@ -841,7 +844,7 @@ pub fn ends_with_punctuation(checker: &mut Checker, docstring: &Docstring) { let trimmed = line.trim_end(); if !(trimmed.ends_with('.') || trimmed.ends_with('!') || trimmed.ends_with('?')) { let mut check = Check::new( - CheckKind::EndsInPunctuation, + violations::EndsInPunctuation, Range::from_located(docstring.expr), ); // Best-effort autofix: avoid adding a period after other punctuation marks. @@ -883,7 +886,7 @@ pub fn if_needed(checker: &mut Checker, docstring: &Docstring) { return; } checker.checks.push(Check::new( - CheckKind::SkipDocstring, + violations::SkipDocstring, identifier_range(stmt, checker.locator), )); } @@ -896,7 +899,7 @@ pub fn not_empty(checker: &mut Checker, docstring: &Docstring) -> bool { if checker.settings.enabled.contains(&CheckCode::D419) { checker.checks.push(Check::new( - CheckKind::NonEmpty, + violations::NonEmpty, Range::from_located(docstring.expr), )); } @@ -959,7 +962,7 @@ fn blanks_and_section_underline( if blank_lines_after_header == context.following_lines.len() { if checker.settings.enabled.contains(&CheckCode::D407) { let mut check = Check::new( - CheckKind::DashedUnderlineAfterSection(context.section_name.to_string()), + violations::DashedUnderlineAfterSection(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -981,7 +984,7 @@ fn blanks_and_section_underline( } if checker.settings.enabled.contains(&CheckCode::D414) { checker.checks.push(Check::new( - CheckKind::NonEmptySection(context.section_name.to_string()), + violations::NonEmptySection(context.section_name.to_string()), Range::from_located(docstring.expr), )); } @@ -997,7 +1000,7 @@ fn blanks_and_section_underline( if blank_lines_after_header > 0 { if checker.settings.enabled.contains(&CheckCode::D408) { let mut check = Check::new( - CheckKind::SectionUnderlineAfterName(context.section_name.to_string()), + violations::SectionUnderlineAfterName(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1029,7 +1032,7 @@ fn blanks_and_section_underline( { if checker.settings.enabled.contains(&CheckCode::D409) { let mut check = Check::new( - CheckKind::SectionUnderlineMatchesSectionLength( + violations::SectionUnderlineMatchesSectionLength( context.section_name.to_string(), ), Range::from_located(docstring.expr), @@ -1068,7 +1071,7 @@ fn blanks_and_section_underline( let leading_space = whitespace::leading_space(non_empty_line); if leading_space.len() > docstring.indentation.len() { let mut check = Check::new( - CheckKind::SectionUnderlineNotOverIndented(context.section_name.to_string()), + violations::SectionUnderlineNotOverIndented(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1108,14 +1111,14 @@ fn blanks_and_section_underline( if blank_lines_after_dashes == rest_of_lines.len() { if checker.settings.enabled.contains(&CheckCode::D414) { checker.checks.push(Check::new( - CheckKind::NonEmptySection(context.section_name.to_string()), + violations::NonEmptySection(context.section_name.to_string()), Range::from_located(docstring.expr), )); } } else { if checker.settings.enabled.contains(&CheckCode::D412) { let mut check = Check::new( - CheckKind::NoBlankLinesBetweenHeaderAndContent( + violations::NoBlankLinesBetweenHeaderAndContent( context.section_name.to_string(), ), Range::from_located(docstring.expr), @@ -1147,7 +1150,7 @@ fn blanks_and_section_underline( } else { if checker.settings.enabled.contains(&CheckCode::D414) { checker.checks.push(Check::new( - CheckKind::NonEmptySection(context.section_name.to_string()), + violations::NonEmptySection(context.section_name.to_string()), Range::from_located(docstring.expr), )); } @@ -1155,7 +1158,7 @@ fn blanks_and_section_underline( } else { if checker.settings.enabled.contains(&CheckCode::D407) { let mut check = Check::new( - CheckKind::DashedUnderlineAfterSection(context.section_name.to_string()), + violations::DashedUnderlineAfterSection(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1178,7 +1181,7 @@ fn blanks_and_section_underline( if blank_lines_after_header > 0 { if checker.settings.enabled.contains(&CheckCode::D412) { let mut check = Check::new( - CheckKind::NoBlankLinesBetweenHeaderAndContent( + violations::NoBlankLinesBetweenHeaderAndContent( context.section_name.to_string(), ), Range::from_located(docstring.expr), @@ -1219,7 +1222,7 @@ fn common_section( .contains(capitalized_section_name.as_str()) { let mut check = Check::new( - CheckKind::CapitalizeSectionName(context.section_name.to_string()), + violations::CapitalizeSectionName(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1251,7 +1254,7 @@ fn common_section( let leading_space = whitespace::leading_space(context.line); if leading_space.len() > docstring.indentation.len() { let mut check = Check::new( - CheckKind::SectionNotOverIndented(context.section_name.to_string()), + violations::SectionNotOverIndented(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1277,7 +1280,7 @@ fn common_section( if context.is_last_section { if checker.settings.enabled.contains(&CheckCode::D413) { let mut check = Check::new( - CheckKind::BlankLineAfterLastSection(context.section_name.to_string()), + violations::BlankLineAfterLastSection(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1298,7 +1301,7 @@ fn common_section( } else { if checker.settings.enabled.contains(&CheckCode::D410) { let mut check = Check::new( - CheckKind::BlankLineAfterSection(context.section_name.to_string()), + violations::BlankLineAfterSection(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1322,7 +1325,7 @@ fn common_section( if checker.settings.enabled.contains(&CheckCode::D411) { if !context.previous_line.is_empty() { let mut check = Check::new( - CheckKind::BlankLineBeforeSection(context.section_name.to_string()), + violations::BlankLineBeforeSection(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1405,7 +1408,7 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: & if !missing_arg_names.is_empty() { let names = missing_arg_names.into_iter().sorted().collect(); checker.checks.push(Check::new( - CheckKind::DocumentAllArguments(names), + violations::DocumentAllArguments(names), Range::from_located(parent), )); } @@ -1511,7 +1514,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section .unwrap(); if !suffix.is_empty() { let mut check = Check::new( - CheckKind::NewLineAfterSectionName(context.section_name.to_string()), + violations::NewLineAfterSectionName(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { @@ -1557,7 +1560,7 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio .unwrap(); if suffix != ":" { let mut check = Check::new( - CheckKind::SectionNameEndsInColon(context.section_name.to_string()), + violations::SectionNameEndsInColon(context.section_name.to_string()), Range::from_located(docstring.expr), ); if checker.patch(check.kind.code()) { diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D100_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D100_D.py.snap index 4f6d0bc2c6413..304fdc4d3a5ca 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D100_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D100_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: PublicModule +- kind: + PublicModule: ~ location: row: 1 column: 0 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D101_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D101_D.py.snap index e4cf777ae8625..54deefab942bb 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D101_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D101_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: PublicClass +- kind: + PublicClass: ~ location: row: 15 column: 6 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D102_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D102_D.py.snap index c2d5e70d7e1f1..5f1aa6e9b8810 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D102_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D102_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: PublicMethod +- kind: + PublicMethod: ~ location: row: 23 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: PublicMethod +- kind: + PublicMethod: ~ location: row: 56 column: 8 @@ -20,7 +22,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: PublicMethod +- kind: + PublicMethod: ~ location: row: 68 column: 8 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D103_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D103_D.py.snap index f8b89e98b2cc8..0da3e9ee6b2ab 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D103_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D103_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: PublicFunction +- kind: + PublicFunction: ~ location: row: 400 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D104_D104____init__.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D104_D104____init__.py.snap index 6fba26c6ef2db..c7ebba2c7bd5c 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D104_D104____init__.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D104_D104____init__.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: PublicPackage +- kind: + PublicPackage: ~ location: row: 1 column: 0 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D105_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D105_D.py.snap index 62f23dbe8e670..4c653b4b2dfa4 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D105_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D105_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: MagicMethod +- kind: + MagicMethod: ~ location: row: 64 column: 8 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D107_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D107_D.py.snap index b901e1f5dc5c8..06a5abc3b8b8c 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D107_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D107_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: PublicInit +- kind: + PublicInit: ~ location: row: 60 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 16 fix: ~ parent: ~ -- kind: PublicInit +- kind: + PublicInit: ~ location: row: 534 column: 8 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D207_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D207_D.py.snap index 1e5e3f48c06a1..37f6e9e3cc411 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D207_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D207_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: NoUnderIndentation +- kind: + NoUnderIndentation: ~ location: row: 232 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 232 column: 0 parent: ~ -- kind: NoUnderIndentation +- kind: + NoUnderIndentation: ~ location: row: 244 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 244 column: 0 parent: ~ -- kind: NoUnderIndentation +- kind: + NoUnderIndentation: ~ location: row: 440 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 440 column: 4 parent: ~ -- kind: NoUnderIndentation +- kind: + NoUnderIndentation: ~ location: row: 441 column: 0 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D208_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D208_D.py.snap index ebacdb3b0736d..acc19a5626a29 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D208_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D208_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: NoOverIndentation +- kind: + NoOverIndentation: ~ location: row: 252 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 252 column: 7 parent: ~ -- kind: NoOverIndentation +- kind: + NoOverIndentation: ~ location: row: 264 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 264 column: 8 parent: ~ -- kind: NoOverIndentation +- kind: + NoOverIndentation: ~ location: row: 272 column: 0 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D209_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D209_D.py.snap index 35148d2c05a17..699c5f2382a23 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D209_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D209_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: NewLineAfterLastParagraph +- kind: + NewLineAfterLastParagraph: ~ location: row: 281 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D210_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D210_D.py.snap index 77e38395e58c6..056f16b9d8068 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D210_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D210_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: NoSurroundingWhitespace +- kind: + NoSurroundingWhitespace: ~ location: row: 288 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 288 column: 30 parent: ~ -- kind: NoSurroundingWhitespace +- kind: + NoSurroundingWhitespace: ~ location: row: 293 column: 4 @@ -34,7 +36,8 @@ expression: checks row: 293 column: 34 parent: ~ -- kind: NoSurroundingWhitespace +- kind: + NoSurroundingWhitespace: ~ location: row: 299 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 299 column: 36 parent: ~ -- kind: NoSurroundingWhitespace +- kind: + NoSurroundingWhitespace: ~ location: row: 581 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D212_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D212_D.py.snap index de425d9c87ed3..4bfe09762a362 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D212_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D212_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: MultiLineSummaryFirstLine +- kind: + MultiLineSummaryFirstLine: ~ location: row: 129 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D213_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D213_D.py.snap index 9f055ed09b386..498f7f47a6156 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D213_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D213_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 200 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 210 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 220 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 230 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 240 column: 4 @@ -47,7 +52,8 @@ expression: checks column: 3 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 250 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 260 column: 4 @@ -65,7 +72,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 270 column: 4 @@ -74,7 +82,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 281 column: 4 @@ -83,7 +92,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 299 column: 4 @@ -92,7 +102,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 343 column: 4 @@ -101,7 +112,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 383 column: 4 @@ -110,7 +122,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 392 column: 4 @@ -119,7 +132,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 438 column: 36 @@ -128,7 +142,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 450 column: 4 @@ -137,7 +152,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 526 column: 4 @@ -146,7 +162,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 546 column: 4 @@ -155,7 +172,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 555 column: 4 @@ -164,7 +182,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiLineSummarySecondLine +- kind: + MultiLineSummarySecondLine: ~ location: row: 568 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D300_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D300_D.py.snap index 7b32906f85465..3afc97c842e58 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D300_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D300_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: UsesTripleQuotes +- kind: + UsesTripleQuotes: ~ location: row: 307 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: UsesTripleQuotes +- kind: + UsesTripleQuotes: ~ location: row: 312 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: UsesTripleQuotes +- kind: + UsesTripleQuotes: ~ location: row: 317 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: UsesTripleQuotes +- kind: + UsesTripleQuotes: ~ location: row: 322 column: 4 @@ -38,7 +42,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: UsesTripleQuotes +- kind: + UsesTripleQuotes: ~ location: row: 328 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D301_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D301_D.py.snap index 0047642b71d24..5993d8d87dfe6 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D301_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D301_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: UsesRPrefixForBackslashedContent +- kind: + UsesRPrefixForBackslashedContent: ~ location: row: 328 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 16 fix: ~ parent: ~ -- kind: UsesRPrefixForBackslashedContent +- kind: + UsesRPrefixForBackslashedContent: ~ location: row: 333 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 20 fix: ~ parent: ~ -- kind: UsesRPrefixForBackslashedContent +- kind: + UsesRPrefixForBackslashedContent: ~ location: row: 338 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D.py.snap index b4da2a7a0f30c..ac7ef819f62fe 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 355 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 355 column: 14 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 406 column: 24 @@ -34,7 +36,8 @@ expression: checks row: 406 column: 36 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 410 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 410 column: 21 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 416 column: 4 @@ -66,7 +70,8 @@ expression: checks row: 416 column: 21 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 422 column: 34 @@ -82,7 +87,8 @@ expression: checks row: 422 column: 46 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 429 column: 48 @@ -98,7 +104,8 @@ expression: checks row: 429 column: 60 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 470 column: 4 @@ -114,7 +121,8 @@ expression: checks row: 470 column: 21 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 475 column: 4 @@ -130,7 +138,8 @@ expression: checks row: 475 column: 21 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 480 column: 4 @@ -146,7 +155,8 @@ expression: checks row: 480 column: 21 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 487 column: 4 @@ -162,7 +172,8 @@ expression: checks row: 487 column: 21 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 509 column: 4 @@ -178,7 +189,8 @@ expression: checks row: 509 column: 31 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 514 column: 4 @@ -194,7 +206,8 @@ expression: checks row: 514 column: 30 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 520 column: 4 @@ -210,7 +223,8 @@ expression: checks row: 520 column: 29 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 581 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D400.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D400.py.snap index 36549d3996bce..e90aaf51ab34d 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D400.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D400_D400.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 2 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 35 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 7 column: 4 @@ -34,7 +36,8 @@ expression: checks row: 7 column: 37 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 12 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 14 column: 28 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 20 column: 4 @@ -66,7 +70,8 @@ expression: checks row: 20 column: 37 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 25 column: 4 @@ -82,7 +87,8 @@ expression: checks row: 27 column: 28 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 32 column: 4 @@ -98,7 +104,8 @@ expression: checks row: 34 column: 48 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 39 column: 4 @@ -114,7 +121,8 @@ expression: checks row: 39 column: 36 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 44 column: 4 @@ -130,7 +138,8 @@ expression: checks row: 44 column: 38 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 49 column: 4 @@ -146,7 +155,8 @@ expression: checks row: 51 column: 28 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 57 column: 4 @@ -162,7 +172,8 @@ expression: checks row: 57 column: 38 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 62 column: 4 @@ -178,7 +189,8 @@ expression: checks row: 64 column: 28 parent: ~ -- kind: EndsInPeriod +- kind: + EndsInPeriod: ~ location: row: 69 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D402_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D402_D.py.snap index 0eac488d4fa5a..6b51f8ac292d4 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D402_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D402_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: NoSignature +- kind: + NoSignature: ~ location: row: 378 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D415_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D415_D.py.snap index b3e9f9bd66489..417a39f1b9629 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D415_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D415_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 355 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 355 column: 14 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 406 column: 24 @@ -34,7 +36,8 @@ expression: checks row: 406 column: 36 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 410 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 410 column: 21 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 416 column: 4 @@ -66,7 +70,8 @@ expression: checks row: 416 column: 21 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 422 column: 34 @@ -82,7 +87,8 @@ expression: checks row: 422 column: 46 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 429 column: 48 @@ -98,7 +104,8 @@ expression: checks row: 429 column: 60 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 470 column: 4 @@ -114,7 +121,8 @@ expression: checks row: 470 column: 21 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 475 column: 4 @@ -130,7 +138,8 @@ expression: checks row: 475 column: 21 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 480 column: 4 @@ -146,7 +155,8 @@ expression: checks row: 480 column: 21 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 487 column: 4 @@ -162,7 +172,8 @@ expression: checks row: 487 column: 21 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 509 column: 4 @@ -178,7 +189,8 @@ expression: checks row: 509 column: 31 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 520 column: 4 @@ -194,7 +206,8 @@ expression: checks row: 520 column: 29 parent: ~ -- kind: EndsInPunctuation +- kind: + EndsInPunctuation: ~ location: row: 581 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D418_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D418_D.py.snap index 0bb9f64ce97c7..93cfd4b4be9ed 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D418_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D418_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: SkipDocstring +- kind: + SkipDocstring: ~ location: row: 34 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 25 fix: ~ parent: ~ -- kind: SkipDocstring +- kind: + SkipDocstring: ~ location: row: 90 column: 8 @@ -20,7 +22,8 @@ expression: checks column: 30 fix: ~ parent: ~ -- kind: SkipDocstring +- kind: + SkipDocstring: ~ location: row: 110 column: 4 diff --git a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D419_D.py.snap b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D419_D.py.snap index ac9f1501a6386..0691b1135a7ee 100644 --- a/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D419_D.py.snap +++ b/src/pydocstyle/snapshots/ruff__pydocstyle__tests__D419_D.py.snap @@ -2,7 +2,8 @@ source: src/pydocstyle/mod.rs expression: checks --- -- kind: NonEmpty +- kind: + NonEmpty: ~ location: row: 20 column: 8 @@ -11,7 +12,8 @@ expression: checks column: 14 fix: ~ parent: ~ -- kind: NonEmpty +- kind: + NonEmpty: ~ location: row: 74 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 11 fix: ~ parent: ~ -- kind: NonEmpty +- kind: + NonEmpty: ~ location: row: 80 column: 8 diff --git a/src/pyflakes/checks.rs b/src/pyflakes/checks.rs index 876aa7e6808fe..53788e29c1167 100644 --- a/src/pyflakes/checks.rs +++ b/src/pyflakes/checks.rs @@ -6,14 +6,15 @@ use rustpython_parser::ast::{ use crate::ast::helpers::except_range; use crate::ast::types::{Binding, Range, Scope, ScopeKind}; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; /// F631 pub fn assert_tuple(test: &Expr, location: Range) -> Option { if let ExprKind::Tuple { elts, .. } = &test.node { if !elts.is_empty() { - return Some(Check::new(CheckKind::AssertTuple, location)); + return Some(Check::new(violations::AssertTuple, location)); } } None @@ -23,7 +24,7 @@ pub fn assert_tuple(test: &Expr, location: Range) -> Option { pub fn if_tuple(test: &Expr, location: Range) -> Option { if let ExprKind::Tuple { elts, .. } = &test.node { if !elts.is_empty() { - return Some(Check::new(CheckKind::IfTuple, location)); + return Some(Check::new(violations::IfTuple, location)); } } None @@ -39,7 +40,7 @@ pub fn undefined_local(name: &str, scopes: &[&Scope], bindings: &[Binding]) -> O if let Some((scope_id, location)) = binding.used { if scope_id == current.id { return Some(Check::new( - CheckKind::UndefinedLocal(name.to_string()), + violations::UndefinedLocal(name.to_string()), location, )); } @@ -60,7 +61,7 @@ pub fn default_except_not_last( let ExcepthandlerKind::ExceptHandler { type_, .. } = &handler.node; if type_.is_none() && idx < handlers.len() - 1 { return Some(Check::new( - CheckKind::DefaultExceptNotLast, + violations::DefaultExceptNotLast, except_range(handler, locator), )); } @@ -101,7 +102,7 @@ pub fn repeated_keys( (Some(DictionaryKey::Constant(v1)), Some(DictionaryKey::Constant(v2))) => { if check_repeated_literals && v1 == v2 { checks.push(Check::new( - CheckKind::MultiValueRepeatedKeyLiteral, + violations::MultiValueRepeatedKeyLiteral, Range::from_located(k2), )); } @@ -109,7 +110,7 @@ pub fn repeated_keys( (Some(DictionaryKey::Variable(v1)), Some(DictionaryKey::Variable(v2))) => { if check_repeated_variables && v1 == v2 { checks.push(Check::new( - CheckKind::MultiValueRepeatedKeyVariable((*v2).to_string()), + violations::MultiValueRepeatedKeyVariable((*v2).to_string()), Range::from_located(k2), )); } @@ -134,7 +135,7 @@ pub fn starred_expressions( for (index, elt) in elts.iter().enumerate() { if matches!(elt.node, ExprKind::Starred { .. }) { if has_starred && check_two_starred_expressions { - return Some(Check::new(CheckKind::TwoStarredExpressions, location)); + return Some(Check::new(violations::TwoStarredExpressions, location)); } has_starred = true; starred_index = Some(index); @@ -144,7 +145,10 @@ pub fn starred_expressions( if check_too_many_expressions { if let Some(starred_index) = starred_index { if starred_index >= 1 << 8 || elts.len() - starred_index > 1 << 24 { - return Some(Check::new(CheckKind::ExpressionsInStarAssignment, location)); + return Some(Check::new( + violations::ExpressionsInStarAssignment, + location, + )); } } } @@ -183,7 +187,7 @@ pub fn break_outside_loop<'a>( None } else { Some(Check::new( - CheckKind::BreakOutsideLoop, + violations::BreakOutsideLoop, Range::from_located(stmt), )) } @@ -220,7 +224,7 @@ pub fn continue_outside_loop<'a>( None } else { Some(Check::new( - CheckKind::ContinueOutsideLoop, + violations::ContinueOutsideLoop, Range::from_located(stmt), )) } diff --git a/src/pyflakes/plugins/f_string_missing_placeholders.rs b/src/pyflakes/plugins/f_string_missing_placeholders.rs index 548c5f3c790ac..47dbdeff8c178 100644 --- a/src/pyflakes/plugins/f_string_missing_placeholders.rs +++ b/src/pyflakes/plugins/f_string_missing_placeholders.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::helpers::find_useless_f_strings; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// F541 pub fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checker: &mut Checker) { @@ -12,7 +13,7 @@ pub fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checker: &mut .any(|value| matches!(value.node, ExprKind::FormattedValue { .. })) { for (prefix_range, tok_range) in find_useless_f_strings(expr, checker.locator) { - let mut check = Check::new(CheckKind::FStringMissingPlaceholders, tok_range); + let mut check = Check::new(violations::FStringMissingPlaceholders, tok_range); if checker.patch(&CheckCode::F541) { check.amend(Fix::deletion( prefix_range.location, diff --git a/src/pyflakes/plugins/invalid_literal_comparisons.rs b/src/pyflakes/plugins/invalid_literal_comparisons.rs index 43d8b40b8f4c9..2386fb8cdb5ac 100644 --- a/src/pyflakes/plugins/invalid_literal_comparisons.rs +++ b/src/pyflakes/plugins/invalid_literal_comparisons.rs @@ -7,7 +7,8 @@ use crate::ast::operations::locate_cmpops; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// F632 pub fn invalid_literal_comparison( @@ -24,7 +25,7 @@ pub fn invalid_literal_comparison( && (helpers::is_constant_non_singleton(left) || helpers::is_constant_non_singleton(right)) { - let mut check = Check::new(CheckKind::IsLiteral(op.into()), location); + let mut check = Check::new(violations::IsLiteral(op.into()), location); if checker.patch(check.kind.code()) { if let Some(located_op) = &located.get(index) { assert_eq!(&located_op.node, op); diff --git a/src/pyflakes/plugins/invalid_print_syntax.rs b/src/pyflakes/plugins/invalid_print_syntax.rs index bbc9fdf66f139..2f5b000181c8a 100644 --- a/src/pyflakes/plugins/invalid_print_syntax.rs +++ b/src/pyflakes/plugins/invalid_print_syntax.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// F633 pub fn invalid_print_syntax(checker: &mut Checker, left: &Expr) { @@ -16,7 +17,7 @@ pub fn invalid_print_syntax(checker: &mut Checker, left: &Expr) { return; }; checker.checks.push(Check::new( - CheckKind::InvalidPrintSyntax, + violations::InvalidPrintSyntax, Range::from_located(left), )); } diff --git a/src/pyflakes/plugins/raise_not_implemented.rs b/src/pyflakes/plugins/raise_not_implemented.rs index 41dde74a0c070..67b0938a8bfdf 100644 --- a/src/pyflakes/plugins/raise_not_implemented.rs +++ b/src/pyflakes/plugins/raise_not_implemented.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn match_not_implemented(expr: &Expr) -> Option<&Expr> { match &expr.node { @@ -29,7 +30,7 @@ pub fn raise_not_implemented(checker: &mut Checker, expr: &Expr) { let Some(expr) = match_not_implemented(expr) else { return; }; - let mut check = Check::new(CheckKind::RaiseNotImplemented, Range::from_located(expr)); + let mut check = Check::new(violations::RaiseNotImplemented, Range::from_located(expr)); if checker.patch(check.kind.code()) { check.amend(Fix::replacement( "NotImplementedError".to_string(), diff --git a/src/pyflakes/plugins/strings.rs b/src/pyflakes/plugins/strings.rs index 28c5b6dc24046..bd975c66a65e7 100644 --- a/src/pyflakes/plugins/strings.rs +++ b/src/pyflakes/plugins/strings.rs @@ -12,7 +12,8 @@ use crate::pyflakes::fixes::{ remove_unused_format_arguments_from_dict, remove_unused_keyword_arguments_from_format_call, }; use crate::pyflakes::format::FormatSummary; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn has_star_star_kwargs(keywords: &[Keyword]) -> bool { keywords.iter().any(|k| { @@ -42,7 +43,7 @@ pub(crate) fn percent_format_expected_mapping( | ExprKind::ListComp { .. } | ExprKind::SetComp { .. } | ExprKind::GeneratorExp { .. } => checker.checks.push(Check::new( - CheckKind::PercentFormatExpectedMapping, + violations::PercentFormatExpectedMapping, location, )), _ => {} @@ -64,7 +65,7 @@ pub(crate) fn percent_format_expected_sequence( ) { checker.checks.push(Check::new( - CheckKind::PercentFormatExpectedSequence, + violations::PercentFormatExpectedSequence, location, )); } @@ -110,7 +111,7 @@ pub(crate) fn percent_format_extra_named_arguments( } let mut check = Check::new( - CheckKind::PercentFormatExtraNamedArguments( + violations::PercentFormatExtraNamedArguments( missing.iter().map(|&arg| arg.to_string()).collect(), ), location, @@ -165,7 +166,7 @@ pub(crate) fn percent_format_missing_arguments( if !missing.is_empty() { checker.checks.push(Check::new( - CheckKind::PercentFormatMissingArgument( + violations::PercentFormatMissingArgument( missing.iter().map(|&s| s.clone()).collect(), ), location, @@ -182,7 +183,7 @@ pub(crate) fn percent_format_mixed_positional_and_named( ) { if !(summary.num_positional == 0 || summary.keywords.is_empty()) { checker.checks.push(Check::new( - CheckKind::PercentFormatMixedPositionalAndNamed, + violations::PercentFormatMixedPositionalAndNamed, location, )); } @@ -211,7 +212,7 @@ pub(crate) fn percent_format_positional_count_mismatch( if found != summary.num_positional { checker.checks.push(Check::new( - CheckKind::PercentFormatPositionalCountMismatch(summary.num_positional, found), + violations::PercentFormatPositionalCountMismatch(summary.num_positional, found), location, )); } @@ -230,7 +231,7 @@ pub(crate) fn percent_format_star_requires_sequence( if summary.starred { match &right.node { ExprKind::Dict { .. } | ExprKind::DictComp { .. } => checker.checks.push(Check::new( - CheckKind::PercentFormatStarRequiresSequence, + violations::PercentFormatStarRequiresSequence, location, )), _ => {} @@ -269,7 +270,7 @@ pub(crate) fn string_dot_format_extra_named_arguments( } let mut check = Check::new( - CheckKind::StringDotFormatExtraNamedArguments( + violations::StringDotFormatExtraNamedArguments( missing.iter().map(|&arg| arg.to_string()).collect(), ), location, @@ -306,7 +307,7 @@ pub(crate) fn string_dot_format_extra_positional_arguments( } checker.checks.push(Check::new( - CheckKind::StringDotFormatExtraPositionalArguments( + violations::StringDotFormatExtraPositionalArguments( missing .iter() .map(std::string::ToString::to_string) @@ -353,7 +354,7 @@ pub(crate) fn string_dot_format_missing_argument( if !missing.is_empty() { checker.checks.push(Check::new( - CheckKind::StringDotFormatMissingArguments(missing), + violations::StringDotFormatMissingArguments(missing), location, )); } @@ -367,7 +368,7 @@ pub(crate) fn string_dot_format_mixing_automatic( ) { if !(summary.autos.is_empty() || summary.indexes.is_empty()) { checker.checks.push(Check::new( - CheckKind::StringDotFormatMixingAutomatic, + violations::StringDotFormatMixingAutomatic, location, )); } diff --git a/src/pyflakes/plugins/unused_annotation.rs b/src/pyflakes/plugins/unused_annotation.rs index 9c5dc263f0475..53deb278a558f 100644 --- a/src/pyflakes/plugins/unused_annotation.rs +++ b/src/pyflakes/plugins/unused_annotation.rs @@ -1,6 +1,7 @@ use crate::ast::types::BindingKind; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// F842 pub fn unused_annotation(checker: &mut Checker, scope: usize) { @@ -15,7 +16,7 @@ pub fn unused_annotation(checker: &mut Checker, scope: usize) { && !checker.settings.dummy_variable_rgx.is_match(name) { checker.checks.push(Check::new( - CheckKind::UnusedAnnotation((*name).to_string()), + violations::UnusedAnnotation((*name).to_string()), binding.range, )); } diff --git a/src/pyflakes/plugins/unused_variable.rs b/src/pyflakes/plugins/unused_variable.rs index 8671b71d53b8d..4d952517b41d4 100644 --- a/src/pyflakes/plugins/unused_variable.rs +++ b/src/pyflakes/plugins/unused_variable.rs @@ -5,7 +5,8 @@ use crate::ast::types::{BindingKind, Range, RefEquality, ScopeKind}; use crate::autofix::helpers::delete_stmt; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; fn is_literal_or_name(expr: &Expr, checker: &Checker) -> bool { // Accept any obvious literals or names. @@ -169,7 +170,7 @@ pub fn unused_variable(checker: &mut Checker, scope: usize) { && name != &"__traceback_supplement__" { let mut check = Check::new( - CheckKind::UnusedVariable((*name).to_string()), + violations::UnusedVariable((*name).to_string()), binding.range, ); if checker.patch(&CheckCode::F841) { diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F404_F404.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F404_F404.py.snap index 539e431679112..5fd1374d36e7a 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F404_F404.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F404_F404.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: LateFutureImport +- kind: + LateFutureImport: ~ location: row: 6 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F502.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F502.py.snap index 5a66b35121566..79d7ad307a948 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F502.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F502.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 6 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 7 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 20 fix: ~ parent: ~ -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 8 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 9 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 22 fix: ~ parent: ~ -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 11 column: 0 @@ -47,7 +52,8 @@ expression: checks column: 37 fix: ~ parent: ~ -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 12 column: 0 @@ -56,7 +62,8 @@ expression: checks column: 37 fix: ~ parent: ~ -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 13 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F50x.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F50x.py.snap index fe0bd5d2bd88e..c1f251d39d0c5 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F50x.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F502_F50x.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: PercentFormatExpectedMapping +- kind: + PercentFormatExpectedMapping: ~ location: row: 9 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F503.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F503.py.snap index cce7b5cad7639..2f3a472fb1d9c 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F503.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F503.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: PercentFormatExpectedSequence +- kind: + PercentFormatExpectedSequence: ~ location: row: 17 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: PercentFormatExpectedSequence +- kind: + PercentFormatExpectedSequence: ~ location: row: 18 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 28 fix: ~ parent: ~ -- kind: PercentFormatExpectedSequence +- kind: + PercentFormatExpectedSequence: ~ location: row: 23 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F50x.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F50x.py.snap index e35d23bebbc66..54a1d1169e005 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F50x.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F503_F50x.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: PercentFormatExpectedSequence +- kind: + PercentFormatExpectedSequence: ~ location: row: 10 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F506_F50x.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F506_F50x.py.snap index fd60044ab9c7a..9d55765154278 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F506_F50x.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F506_F50x.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: PercentFormatMixedPositionalAndNamed +- kind: + PercentFormatMixedPositionalAndNamed: ~ location: row: 2 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: PercentFormatMixedPositionalAndNamed +- kind: + PercentFormatMixedPositionalAndNamed: ~ location: row: 3 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: PercentFormatMixedPositionalAndNamed +- kind: + PercentFormatMixedPositionalAndNamed: ~ location: row: 11 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F508_F50x.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F508_F50x.py.snap index 93a750122aef0..4257265b03fdb 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F508_F50x.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F508_F50x.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: PercentFormatStarRequiresSequence +- kind: + PercentFormatStarRequiresSequence: ~ location: row: 11 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F525_F525.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F525_F525.py.snap index fc2294fa96228..bfc2809566caa 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F525_F525.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F525_F525.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: StringDotFormatMixingAutomatic +- kind: + StringDotFormatMixingAutomatic: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 21 fix: ~ parent: ~ -- kind: StringDotFormatMixingAutomatic +- kind: + StringDotFormatMixingAutomatic: ~ location: row: 2 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F541_F541.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F541_F541.py.snap index cf2fbd5f5e8f7..3c839edc6bbd9 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F541_F541.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F541_F541.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 6 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 6 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 7 column: 4 @@ -34,7 +36,8 @@ expression: checks row: 7 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 9 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 9 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 13 column: 4 @@ -66,7 +70,8 @@ expression: checks row: 13 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 14 column: 4 @@ -82,7 +87,8 @@ expression: checks row: 14 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 16 column: 4 @@ -98,7 +104,8 @@ expression: checks row: 16 column: 6 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 17 column: 4 @@ -114,7 +121,8 @@ expression: checks row: 17 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 19 column: 4 @@ -130,7 +138,8 @@ expression: checks row: 19 column: 5 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 25 column: 12 @@ -146,7 +155,8 @@ expression: checks row: 25 column: 13 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 34 column: 6 @@ -162,7 +172,8 @@ expression: checks row: 34 column: 7 parent: ~ -- kind: FStringMissingPlaceholders +- kind: + FStringMissingPlaceholders: ~ location: row: 35 column: 3 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F601_F601.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F601_F601.py.snap index 600d1681cebcc..9e28311637d65 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F601_F601.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F601_F601.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: MultiValueRepeatedKeyLiteral +- kind: + MultiValueRepeatedKeyLiteral: ~ location: row: 3 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 7 fix: ~ parent: ~ -- kind: MultiValueRepeatedKeyLiteral +- kind: + MultiValueRepeatedKeyLiteral: ~ location: row: 9 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 5 fix: ~ parent: ~ -- kind: MultiValueRepeatedKeyLiteral +- kind: + MultiValueRepeatedKeyLiteral: ~ location: row: 11 column: 4 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F622_F622.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F622_F622.py.snap index 49d72c5e7b4f2..b93cae4ae4101 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F622_F622.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F622_F622.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: TwoStarredExpressions +- kind: + TwoStarredExpressions: ~ location: row: 1 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F631_F631.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F631_F631.py.snap index c17a95e000678..741ed93a375b2 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F631_F631.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F631_F631.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: AssertTuple +- kind: + AssertTuple: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 19 fix: ~ parent: ~ -- kind: AssertTuple +- kind: + AssertTuple: ~ location: row: 2 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F633_F633.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F633_F633.py.snap index 0cb8112d1f38e..8e726bbbfda14 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F633_F633.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F633_F633.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: InvalidPrintSyntax +- kind: + InvalidPrintSyntax: ~ location: row: 4 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F634_F634.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F634_F634.py.snap index f5d377f46d3bb..8f197141a7fa9 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F634_F634.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F634_F634.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: IfTuple +- kind: + IfTuple: ~ location: row: 1 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: IfTuple +- kind: + IfTuple: ~ location: row: 7 column: 4 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F701_F701.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F701_F701.py.snap index cce771e83df99..7a42c8669f381 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F701_F701.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F701_F701.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: BreakOutsideLoop +- kind: + BreakOutsideLoop: ~ location: row: 4 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: BreakOutsideLoop +- kind: + BreakOutsideLoop: ~ location: row: 16 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: BreakOutsideLoop +- kind: + BreakOutsideLoop: ~ location: row: 20 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 9 fix: ~ parent: ~ -- kind: BreakOutsideLoop +- kind: + BreakOutsideLoop: ~ location: row: 23 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F702_F702.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F702_F702.py.snap index b9bed825c9bba..e8645e7978b29 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F702_F702.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F702_F702.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: ContinueOutsideLoop +- kind: + ContinueOutsideLoop: ~ location: row: 4 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: ContinueOutsideLoop +- kind: + ContinueOutsideLoop: ~ location: row: 16 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: ContinueOutsideLoop +- kind: + ContinueOutsideLoop: ~ location: row: 20 column: 4 @@ -29,7 +32,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: ContinueOutsideLoop +- kind: + ContinueOutsideLoop: ~ location: row: 23 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F706_F706.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F706_F706.py.snap index 373c12669b90f..4822f0869a48d 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F706_F706.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F706_F706.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: ReturnOutsideFunction +- kind: + ReturnOutsideFunction: ~ location: row: 6 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: ReturnOutsideFunction +- kind: + ReturnOutsideFunction: ~ location: row: 9 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F707_F707.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F707_F707.py.snap index d7cc7ae330c1f..c8a87067d2803 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F707_F707.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F707_F707.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: DefaultExceptNotLast +- kind: + DefaultExceptNotLast: ~ location: row: 3 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: DefaultExceptNotLast +- kind: + DefaultExceptNotLast: ~ location: row: 10 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: DefaultExceptNotLast +- kind: + DefaultExceptNotLast: ~ location: row: 19 column: 0 diff --git a/src/pyflakes/snapshots/ruff__pyflakes__tests__F901_F901.py.snap b/src/pyflakes/snapshots/ruff__pyflakes__tests__F901_F901.py.snap index 2b7214641d759..e11dddac6ef56 100644 --- a/src/pyflakes/snapshots/ruff__pyflakes__tests__F901_F901.py.snap +++ b/src/pyflakes/snapshots/ruff__pyflakes__tests__F901_F901.py.snap @@ -2,7 +2,8 @@ source: src/pyflakes/mod.rs expression: checks --- -- kind: RaiseNotImplemented +- kind: + RaiseNotImplemented: ~ location: row: 2 column: 10 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 24 parent: ~ -- kind: RaiseNotImplemented +- kind: + RaiseNotImplemented: ~ location: row: 6 column: 10 diff --git a/src/pygrep_hooks/plugins/blanket_noqa.rs b/src/pygrep_hooks/plugins/blanket_noqa.rs index d1f46fa2e85e9..b627da5743e7e 100644 --- a/src/pygrep_hooks/plugins/blanket_noqa.rs +++ b/src/pygrep_hooks/plugins/blanket_noqa.rs @@ -3,7 +3,8 @@ use regex::Regex; use rustpython_ast::Location; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; static BLANKET_NOQA_REGEX: Lazy = Lazy::new(|| Regex::new(r"(?i)# noqa($|\s|:[^ ])").unwrap()); @@ -12,7 +13,7 @@ static BLANKET_NOQA_REGEX: Lazy = pub fn blanket_noqa(lineno: usize, line: &str) -> Option { BLANKET_NOQA_REGEX.find(line).map(|m| { Check::new( - CheckKind::BlanketNOQA, + violations::BlanketNOQA, Range::new( Location::new(lineno + 1, m.start()), Location::new(lineno + 1, m.end()), diff --git a/src/pygrep_hooks/plugins/blanket_type_ignore.rs b/src/pygrep_hooks/plugins/blanket_type_ignore.rs index da47ca19051f8..d671595639ef8 100644 --- a/src/pygrep_hooks/plugins/blanket_type_ignore.rs +++ b/src/pygrep_hooks/plugins/blanket_type_ignore.rs @@ -3,7 +3,8 @@ use regex::Regex; use rustpython_ast::Location; use crate::ast::types::Range; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; static BLANKET_TYPE_IGNORE_REGEX: Lazy = Lazy::new(|| Regex::new(r"# type:? *ignore($|\s)").unwrap()); @@ -12,7 +13,7 @@ static BLANKET_TYPE_IGNORE_REGEX: Lazy = pub fn blanket_type_ignore(lineno: usize, line: &str) -> Option { BLANKET_TYPE_IGNORE_REGEX.find(line).map(|m| { Check::new( - CheckKind::BlanketTypeIgnore, + violations::BlanketTypeIgnore, Range::new( Location::new(lineno + 1, m.start()), Location::new(lineno + 1, m.end()), diff --git a/src/pygrep_hooks/plugins/deprecated_log_warn.rs b/src/pygrep_hooks/plugins/deprecated_log_warn.rs index 97641dc975186..b59fc640c28a1 100644 --- a/src/pygrep_hooks/plugins/deprecated_log_warn.rs +++ b/src/pygrep_hooks/plugins/deprecated_log_warn.rs @@ -3,7 +3,8 @@ use rustpython_ast::Expr; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// PGH002 - deprecated use of logging.warn pub fn deprecated_log_warn(checker: &mut Checker, func: &Expr) { @@ -12,7 +13,7 @@ pub fn deprecated_log_warn(checker: &mut Checker, func: &Expr) { || match_call_path(&call_path, "logging", "warn", &checker.from_imports) { checker.checks.push(Check::new( - CheckKind::DeprecatedLogWarn, + violations::DeprecatedLogWarn, Range::from_located(func), )); } diff --git a/src/pygrep_hooks/plugins/no_eval.rs b/src/pygrep_hooks/plugins/no_eval.rs index d734d23047ac6..3174319bd2213 100644 --- a/src/pygrep_hooks/plugins/no_eval.rs +++ b/src/pygrep_hooks/plugins/no_eval.rs @@ -2,7 +2,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// PGH001 - no eval pub fn no_eval(checker: &mut Checker, func: &Expr) { @@ -17,5 +18,5 @@ pub fn no_eval(checker: &mut Checker, func: &Expr) { } checker .checks - .push(Check::new(CheckKind::NoEval, Range::from_located(func))); + .push(Check::new(violations::NoEval, Range::from_located(func))); } diff --git a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH001_PGH001_0.py.snap b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH001_PGH001_0.py.snap index f66fcf442ff26..817fc8ecbca4a 100644 --- a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH001_PGH001_0.py.snap +++ b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH001_PGH001_0.py.snap @@ -2,7 +2,8 @@ source: src/pygrep_hooks/mod.rs expression: checks --- -- kind: NoEval +- kind: + NoEval: ~ location: row: 3 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 4 fix: ~ parent: ~ -- kind: NoEval +- kind: + NoEval: ~ location: row: 9 column: 4 diff --git a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH002_PGH002_1.py.snap b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH002_PGH002_1.py.snap index 920b200e422f7..61c4f1c52850a 100644 --- a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH002_PGH002_1.py.snap +++ b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH002_PGH002_1.py.snap @@ -2,7 +2,8 @@ source: src/pygrep_hooks/mod.rs expression: checks --- -- kind: DeprecatedLogWarn +- kind: + DeprecatedLogWarn: ~ location: row: 4 column: 0 @@ -11,7 +12,8 @@ expression: checks column: 12 fix: ~ parent: ~ -- kind: DeprecatedLogWarn +- kind: + DeprecatedLogWarn: ~ location: row: 5 column: 0 @@ -20,7 +22,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: DeprecatedLogWarn +- kind: + DeprecatedLogWarn: ~ location: row: 6 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 4 fix: ~ parent: ~ -- kind: DeprecatedLogWarn +- kind: + DeprecatedLogWarn: ~ location: row: 15 column: 4 diff --git a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH003_PGH003_0.py.snap b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH003_PGH003_0.py.snap index 7932e21206573..648f6c79ba5ce 100644 --- a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH003_PGH003_0.py.snap +++ b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH003_PGH003_0.py.snap @@ -2,7 +2,8 @@ source: src/pygrep_hooks/mod.rs expression: checks --- -- kind: BlanketTypeIgnore +- kind: + BlanketTypeIgnore: ~ location: row: 1 column: 7 @@ -11,7 +12,8 @@ expression: checks column: 21 fix: ~ parent: ~ -- kind: BlanketTypeIgnore +- kind: + BlanketTypeIgnore: ~ location: row: 2 column: 7 @@ -20,7 +22,8 @@ expression: checks column: 20 fix: ~ parent: ~ -- kind: BlanketTypeIgnore +- kind: + BlanketTypeIgnore: ~ location: row: 3 column: 7 diff --git a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH004_PGH004_0.py.snap b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH004_PGH004_0.py.snap index c57d88c6b1121..8aab8e6f2a947 100644 --- a/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH004_PGH004_0.py.snap +++ b/src/pygrep_hooks/snapshots/ruff__pygrep_hooks__tests__PGH004_PGH004_0.py.snap @@ -2,7 +2,8 @@ source: src/pygrep_hooks/mod.rs expression: checks --- -- kind: BlanketNOQA +- kind: + BlanketNOQA: ~ location: row: 1 column: 7 @@ -11,7 +12,8 @@ expression: checks column: 13 fix: ~ parent: ~ -- kind: BlanketNOQA +- kind: + BlanketNOQA: ~ location: row: 2 column: 7 @@ -20,7 +22,8 @@ expression: checks column: 15 fix: ~ parent: ~ -- kind: BlanketNOQA +- kind: + BlanketNOQA: ~ location: row: 3 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: BlanketNOQA +- kind: + BlanketNOQA: ~ location: row: 4 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 6 fix: ~ parent: ~ -- kind: BlanketNOQA +- kind: + BlanketNOQA: ~ location: row: 5 column: 0 @@ -47,7 +52,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: BlanketNOQA +- kind: + BlanketNOQA: ~ location: row: 6 column: 0 diff --git a/src/pylint/plugins/await_outside_async.rs b/src/pylint/plugins/await_outside_async.rs index 580e8c8b6e457..9908fe4beb91b 100644 --- a/src/pylint/plugins/await_outside_async.rs +++ b/src/pylint/plugins/await_outside_async.rs @@ -2,8 +2,7 @@ use rustpython_ast::Expr; use crate::ast::types::{FunctionDef, Range, ScopeKind}; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLE1142 pub fn await_outside_async(checker: &mut Checker, expr: &Expr) { @@ -19,7 +18,7 @@ pub fn await_outside_async(checker: &mut Checker, expr: &Expr) { .unwrap_or(true) { checker.checks.push(Check::new( - CheckKind::AwaitOutsideAsync, + violations::AwaitOutsideAsync, Range::from_located(expr), )); } diff --git a/src/pylint/plugins/merge_isinstance.rs b/src/pylint/plugins/merge_isinstance.rs index eda2887a28568..432d8e0a15063 100644 --- a/src/pylint/plugins/merge_isinstance.rs +++ b/src/pylint/plugins/merge_isinstance.rs @@ -4,8 +4,7 @@ use rustpython_ast::{Boolop, Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLR1701 pub fn merge_isinstance(checker: &mut Checker, expr: &Expr, op: &Boolop, values: &[Expr]) { @@ -42,7 +41,7 @@ pub fn merge_isinstance(checker: &mut Checker, expr: &Expr, op: &Boolop, values: for (obj, (num_calls, types)) in obj_to_types { if num_calls > 1 && types.len() > 1 { checker.checks.push(Check::new( - CheckKind::ConsiderMergingIsinstance(obj, types.into_iter().sorted().collect()), + violations::ConsiderMergingIsinstance(obj, types.into_iter().sorted().collect()), Range::from_located(expr), )); } diff --git a/src/pylint/plugins/misplaced_comparison_constant.rs b/src/pylint/plugins/misplaced_comparison_constant.rs index 56d3dafd30c71..37cde53382e7c 100644 --- a/src/pylint/plugins/misplaced_comparison_constant.rs +++ b/src/pylint/plugins/misplaced_comparison_constant.rs @@ -3,8 +3,7 @@ use rustpython_ast::{Cmpop, Expr, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLC2201 pub fn misplaced_comparison_constant( @@ -42,7 +41,7 @@ pub fn misplaced_comparison_constant( }; let suggestion = format!("{right} {reversed_op} {left}"); let mut check = Check::new( - CheckKind::MisplacedComparisonConstant(suggestion.clone()), + violations::MisplacedComparisonConstant(suggestion.clone()), Range::from_located(expr), ); if checker.patch(check.kind.code()) { diff --git a/src/pylint/plugins/property_with_parameters.rs b/src/pylint/plugins/property_with_parameters.rs index 9b121af878d54..7b0f771973447 100644 --- a/src/pylint/plugins/property_with_parameters.rs +++ b/src/pylint/plugins/property_with_parameters.rs @@ -2,8 +2,7 @@ use rustpython_ast::{Arguments, Expr, ExprKind, Stmt}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLR0206 pub fn property_with_parameters( @@ -28,7 +27,7 @@ pub fn property_with_parameters( > 1 { checker.checks.push(Check::new( - CheckKind::PropertyWithParameters, + violations::PropertyWithParameters, Range::from_located(stmt), )); } diff --git a/src/pylint/plugins/unnecessary_direct_lambda_call.rs b/src/pylint/plugins/unnecessary_direct_lambda_call.rs index 1d56dcabe6b0a..37fef0e2ef78a 100644 --- a/src/pylint/plugins/unnecessary_direct_lambda_call.rs +++ b/src/pylint/plugins/unnecessary_direct_lambda_call.rs @@ -2,14 +2,13 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLC3002 pub fn unnecessary_direct_lambda_call(checker: &mut Checker, expr: &Expr, func: &Expr) { if let ExprKind::Lambda { .. } = &func.node { checker.checks.push(Check::new( - CheckKind::UnnecessaryDirectLambdaCall, + violations::UnnecessaryDirectLambdaCall, Range::from_located(expr), )); } diff --git a/src/pylint/plugins/use_from_import.rs b/src/pylint/plugins/use_from_import.rs index 31f96f010a5ee..b85798de832fe 100644 --- a/src/pylint/plugins/use_from_import.rs +++ b/src/pylint/plugins/use_from_import.rs @@ -2,8 +2,7 @@ use rustpython_ast::Alias; use crate::ast::types::Range; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLR0402 pub fn use_from_import(checker: &mut Checker, alias: &Alias) { @@ -17,7 +16,7 @@ pub fn use_from_import(checker: &mut Checker, alias: &Alias) { return; } checker.checks.push(Check::new( - CheckKind::ConsiderUsingFromImport(module.to_string(), name.to_string()), + violations::ConsiderUsingFromImport(module.to_string(), name.to_string()), Range::from_located(alias), )); } diff --git a/src/pylint/plugins/use_sys_exit.rs b/src/pylint/plugins/use_sys_exit.rs index 56d96b3ca1732..a5f2b3f3866af 100644 --- a/src/pylint/plugins/use_sys_exit.rs +++ b/src/pylint/plugins/use_sys_exit.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::{BindingKind, Range}; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// Return `true` if the `module` was imported using a star import (e.g., `from /// sys import *`). @@ -75,7 +76,7 @@ pub fn use_sys_exit(checker: &mut Checker, func: &Expr) { continue; } let mut check = Check::new( - CheckKind::UseSysExit(name.to_string()), + violations::UseSysExit(name.to_string()), Range::from_located(func), ); if checker.patch(check.kind.code()) { diff --git a/src/pylint/plugins/used_prior_global_declaration.rs b/src/pylint/plugins/used_prior_global_declaration.rs index 958f46f089efd..56701b50fbf8a 100644 --- a/src/pylint/plugins/used_prior_global_declaration.rs +++ b/src/pylint/plugins/used_prior_global_declaration.rs @@ -2,8 +2,7 @@ use rustpython_ast::Expr; use crate::ast::types::{Range, ScopeKind}; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLE0118 pub fn used_prior_global_declaration(checker: &mut Checker, name: &str, expr: &Expr) { @@ -15,7 +14,7 @@ pub fn used_prior_global_declaration(checker: &mut Checker, name: &str, expr: &E if let Some(stmt) = globals.get(name) { if expr.location < stmt.location { checker.checks.push(Check::new( - CheckKind::UsedPriorGlobalDeclaration(name.to_string(), stmt.location.row()), + violations::UsedPriorGlobalDeclaration(name.to_string(), stmt.location.row()), Range::from_located(expr), )); } diff --git a/src/pylint/plugins/useless_else_on_loop.rs b/src/pylint/plugins/useless_else_on_loop.rs index bdf509424957e..dfc9b29b99400 100644 --- a/src/pylint/plugins/useless_else_on_loop.rs +++ b/src/pylint/plugins/useless_else_on_loop.rs @@ -2,8 +2,7 @@ use rustpython_ast::{ExcepthandlerKind, Stmt, StmtKind}; use crate::ast::helpers; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; fn loop_exits_early(body: &[Stmt]) -> bool { body.iter().any(|stmt| match &stmt.node { @@ -34,7 +33,7 @@ fn loop_exits_early(body: &[Stmt]) -> bool { pub fn useless_else_on_loop(checker: &mut Checker, stmt: &Stmt, body: &[Stmt], orelse: &[Stmt]) { if !orelse.is_empty() && !loop_exits_early(body) { checker.checks.push(Check::new( - CheckKind::UselessElseOnLoop, + violations::UselessElseOnLoop, helpers::else_range(stmt, checker.locator).unwrap(), )); } diff --git a/src/pylint/plugins/useless_import_alias.rs b/src/pylint/plugins/useless_import_alias.rs index 0b4b7111e1521..0f98182727356 100644 --- a/src/pylint/plugins/useless_import_alias.rs +++ b/src/pylint/plugins/useless_import_alias.rs @@ -3,8 +3,7 @@ use rustpython_ast::Alias; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::CheckKind; -use crate::Check; +use crate::{violations, Check}; /// PLC0414 pub fn useless_import_alias(checker: &mut Checker, alias: &Alias) { @@ -18,7 +17,7 @@ pub fn useless_import_alias(checker: &mut Checker, alias: &Alias) { return; } - let mut check = Check::new(CheckKind::UselessImportAlias, Range::from_located(alias)); + let mut check = Check::new(violations::UselessImportAlias, Range::from_located(alias)); if checker.patch(check.kind.code()) { check.amend(Fix::replacement( asname.to_string(), diff --git a/src/pylint/snapshots/ruff__pylint__tests__PLC0414_import_aliasing.py.snap b/src/pylint/snapshots/ruff__pylint__tests__PLC0414_import_aliasing.py.snap index 69da7020c9677..25929dad51575 100644 --- a/src/pylint/snapshots/ruff__pylint__tests__PLC0414_import_aliasing.py.snap +++ b/src/pylint/snapshots/ruff__pylint__tests__PLC0414_import_aliasing.py.snap @@ -2,7 +2,8 @@ source: src/pylint/mod.rs expression: checks --- -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 6 column: 7 @@ -18,7 +19,8 @@ expression: checks row: 6 column: 33 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 7 column: 24 @@ -34,7 +36,8 @@ expression: checks row: 7 column: 50 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 15 column: 14 @@ -50,7 +53,8 @@ expression: checks row: 15 column: 24 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 18 column: 18 @@ -66,7 +70,8 @@ expression: checks row: 18 column: 28 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 19 column: 22 @@ -82,7 +87,8 @@ expression: checks row: 19 column: 38 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 21 column: 14 @@ -98,7 +104,8 @@ expression: checks row: 21 column: 24 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 22 column: 26 @@ -114,7 +121,8 @@ expression: checks row: 22 column: 38 parent: ~ -- kind: UselessImportAlias +- kind: + UselessImportAlias: ~ location: row: 24 column: 20 diff --git a/src/pylint/snapshots/ruff__pylint__tests__PLC3002_unnecessary_direct_lambda_call.py.snap b/src/pylint/snapshots/ruff__pylint__tests__PLC3002_unnecessary_direct_lambda_call.py.snap index 4f8cad22b5d98..ce6201842617f 100644 --- a/src/pylint/snapshots/ruff__pylint__tests__PLC3002_unnecessary_direct_lambda_call.py.snap +++ b/src/pylint/snapshots/ruff__pylint__tests__PLC3002_unnecessary_direct_lambda_call.py.snap @@ -2,7 +2,8 @@ source: src/pylint/mod.rs expression: checks --- -- kind: UnnecessaryDirectLambdaCall +- kind: + UnnecessaryDirectLambdaCall: ~ location: row: 4 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 33 fix: ~ parent: ~ -- kind: UnnecessaryDirectLambdaCall +- kind: + UnnecessaryDirectLambdaCall: ~ location: row: 5 column: 8 @@ -20,7 +22,8 @@ expression: checks column: 27 fix: ~ parent: ~ -- kind: UnnecessaryDirectLambdaCall +- kind: + UnnecessaryDirectLambdaCall: ~ location: row: 5 column: 29 diff --git a/src/pylint/snapshots/ruff__pylint__tests__PLE1142_await_outside_async.py.snap b/src/pylint/snapshots/ruff__pylint__tests__PLE1142_await_outside_async.py.snap index 7bda0c5ea29fc..d15813d9d5d39 100644 --- a/src/pylint/snapshots/ruff__pylint__tests__PLE1142_await_outside_async.py.snap +++ b/src/pylint/snapshots/ruff__pylint__tests__PLE1142_await_outside_async.py.snap @@ -2,7 +2,8 @@ source: src/pylint/mod.rs expression: checks --- -- kind: AwaitOutsideAsync +- kind: + AwaitOutsideAsync: ~ location: row: 12 column: 10 @@ -11,7 +12,8 @@ expression: checks column: 24 fix: ~ parent: ~ -- kind: AwaitOutsideAsync +- kind: + AwaitOutsideAsync: ~ location: row: 25 column: 8 diff --git a/src/pylint/snapshots/ruff__pylint__tests__PLR0206_property_with_parameters.py.snap b/src/pylint/snapshots/ruff__pylint__tests__PLR0206_property_with_parameters.py.snap index bdeec81ccf6ce..22ad28afbd445 100644 --- a/src/pylint/snapshots/ruff__pylint__tests__PLR0206_property_with_parameters.py.snap +++ b/src/pylint/snapshots/ruff__pylint__tests__PLR0206_property_with_parameters.py.snap @@ -2,7 +2,8 @@ source: src/pylint/mod.rs expression: checks --- -- kind: PropertyWithParameters +- kind: + PropertyWithParameters: ~ location: row: 7 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: PropertyWithParameters +- kind: + PropertyWithParameters: ~ location: row: 11 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 29 fix: ~ parent: ~ -- kind: PropertyWithParameters +- kind: + PropertyWithParameters: ~ location: row: 15 column: 4 diff --git a/src/pylint/snapshots/ruff__pylint__tests__PLW0120_useless_else_on_loop.py.snap b/src/pylint/snapshots/ruff__pylint__tests__PLW0120_useless_else_on_loop.py.snap index 717e25221655c..cdbe2b4d93e16 100644 --- a/src/pylint/snapshots/ruff__pylint__tests__PLW0120_useless_else_on_loop.py.snap +++ b/src/pylint/snapshots/ruff__pylint__tests__PLW0120_useless_else_on_loop.py.snap @@ -2,7 +2,8 @@ source: src/pylint/mod.rs expression: checks --- -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 9 column: 4 @@ -11,7 +12,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 18 column: 4 @@ -20,7 +22,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 30 column: 0 @@ -29,7 +32,8 @@ expression: checks column: 4 fix: ~ parent: ~ -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 37 column: 0 @@ -38,7 +42,8 @@ expression: checks column: 4 fix: ~ parent: ~ -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 42 column: 0 @@ -47,7 +52,8 @@ expression: checks column: 4 fix: ~ parent: ~ -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 88 column: 4 @@ -56,7 +62,8 @@ expression: checks column: 8 fix: ~ parent: ~ -- kind: UselessElseOnLoop +- kind: + UselessElseOnLoop: ~ location: row: 98 column: 8 diff --git a/src/pyupgrade/checks.rs b/src/pyupgrade/checks.rs index 9f71d430a274d..b80da6d462337 100644 --- a/src/pyupgrade/checks.rs +++ b/src/pyupgrade/checks.rs @@ -8,8 +8,9 @@ use crate::ast::helpers::{self}; use crate::ast::types::{Binding, BindingKind, Range, Scope, ScopeKind}; use crate::autofix::Fix; use crate::pyupgrade::types::Primitive; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::settings::types::PythonVersion; +use crate::violations; /// UP001 pub fn useless_metaclass_type(targets: &[Expr], value: &Expr, location: Range) -> Option { @@ -28,7 +29,7 @@ pub fn useless_metaclass_type(targets: &[Expr], value: &Expr, location: Range) - if id != "type" { return None; } - Some(Check::new(CheckKind::UselessMetaclassType, location)) + Some(Check::new(violations::UselessMetaclassType, location)) } /// UP003 @@ -50,7 +51,7 @@ pub fn type_of_primitive(func: &Expr, args: &[Expr], location: Range) -> Option< }; let primitive = Primitive::from_constant(value)?; - Some(Check::new(CheckKind::TypeOfPrimitive(primitive), location)) + Some(Check::new(violations::TypeOfPrimitive(primitive), location)) } /// UP004 @@ -80,7 +81,7 @@ pub fn useless_object_inheritance( continue; } return Some(Check::new( - CheckKind::UselessObjectInheritance(name.to_string()), + violations::UselessObjectInheritance(name.to_string()), Range::from_located(expr), )); } @@ -152,7 +153,7 @@ pub fn super_args( if first_arg_id == parent_name && second_arg_id == parent_arg { return Some(Check::new( - CheckKind::SuperCallWithParameters, + violations::SuperCallWithParameters, Range::from_located(expr), )); } @@ -169,7 +170,7 @@ pub fn unnecessary_coding_comment(lineno: usize, line: &str, autofix: bool) -> O // PEP3120 makes utf-8 the default encoding. if CODING_COMMENT_REGEX.is_match(line) { let mut check = Check::new( - CheckKind::PEP3120UnnecessaryCodingComment, + violations::PEP3120UnnecessaryCodingComment, Range::new(Location::new(lineno + 1, 0), Location::new(lineno + 2, 0)), ); if autofix { @@ -216,7 +217,7 @@ pub fn unnecessary_lru_cache_params( let range = Range::new(func.end_location.unwrap(), expr.end_location.unwrap()); // Ex) `functools.lru_cache()` if keywords.is_empty() { - return Some(Check::new(CheckKind::UnnecessaryLRUCacheParams, range)); + return Some(Check::new(violations::UnnecessaryLRUCacheParams, range)); } // Ex) `functools.lru_cache(maxsize=None)` if !(target_version >= PythonVersion::Py39 && keywords.len() == 1) { @@ -235,7 +236,7 @@ pub fn unnecessary_lru_cache_params( { continue; } - return Some(Check::new(CheckKind::UnnecessaryLRUCacheParams, range)); + return Some(Check::new(violations::UnnecessaryLRUCacheParams, range)); } None } diff --git a/src/pyupgrade/plugins/convert_named_tuple_functional_to_class.rs b/src/pyupgrade/plugins/convert_named_tuple_functional_to_class.rs index 9b37ff856a787..1ad215a28149c 100644 --- a/src/pyupgrade/plugins/convert_named_tuple_functional_to_class.rs +++ b/src/pyupgrade/plugins/convert_named_tuple_functional_to_class.rs @@ -8,9 +8,10 @@ use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::python::identifiers::IDENTIFIER_REGEX; use crate::python::keyword::KWLIST; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_style::SourceCodeStyleDetector; +use crate::violations; /// Return the typename, args, keywords and mother class fn match_named_tuple_assign<'a>( @@ -191,7 +192,7 @@ pub fn convert_named_tuple_functional_to_class( Ok(defaults) => match create_properties_from_args(args, defaults) { Ok(properties) => { let mut check = Check::new( - CheckKind::ConvertNamedTupleFunctionalToClass(typename.to_string()), + violations::ConvertNamedTupleFunctionalToClass(typename.to_string()), Range::from_located(stmt), ); if checker.patch(check.kind.code()) { diff --git a/src/pyupgrade/plugins/convert_typed_dict_functional_to_class.rs b/src/pyupgrade/plugins/convert_typed_dict_functional_to_class.rs index ffc37e4ccfcfe..7c0345e79408d 100644 --- a/src/pyupgrade/plugins/convert_typed_dict_functional_to_class.rs +++ b/src/pyupgrade/plugins/convert_typed_dict_functional_to_class.rs @@ -10,9 +10,10 @@ use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::python::identifiers::IDENTIFIER_REGEX; use crate::python::keyword::KWLIST; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_style::SourceCodeStyleDetector; +use crate::violations; /// Return the class name, arguments, keywords and base class for a `TypedDict` /// assignment. @@ -233,7 +234,7 @@ pub fn convert_typed_dict_functional_to_class( Ok(args) => args, }; let mut check = Check::new( - CheckKind::ConvertTypedDictFunctionalToClass(class_name.to_string()), + violations::ConvertTypedDictFunctionalToClass(class_name.to_string()), Range::from_located(stmt), ); if checker.patch(check.kind.code()) { diff --git a/src/pyupgrade/plugins/datetime_utc_alias.rs b/src/pyupgrade/plugins/datetime_utc_alias.rs index 17fb87de27f94..67d32e5b77a07 100644 --- a/src/pyupgrade/plugins/datetime_utc_alias.rs +++ b/src/pyupgrade/plugins/datetime_utc_alias.rs @@ -4,13 +4,14 @@ use crate::ast::helpers::{collect_call_paths, compose_call_path, dealias_call_pa use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// UP017 pub fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) { let dealiased_call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases); if dealiased_call_path == ["datetime", "timezone", "utc"] { - let mut check = Check::new(CheckKind::DatetimeTimezoneUTC, Range::from_located(expr)); + let mut check = Check::new(violations::DatetimeTimezoneUTC, Range::from_located(expr)); if checker.patch(&CheckCode::UP017) { check.amend(Fix::replacement( compose_call_path(expr) diff --git a/src/pyupgrade/plugins/deprecated_unittest_alias.rs b/src/pyupgrade/plugins/deprecated_unittest_alias.rs index a1dbfff244489..8dd1468432f8e 100644 --- a/src/pyupgrade/plugins/deprecated_unittest_alias.rs +++ b/src/pyupgrade/plugins/deprecated_unittest_alias.rs @@ -5,7 +5,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; static DEPRECATED_ALIASES: Lazy> = Lazy::new(|| { FxHashMap::from_iter([ @@ -42,7 +43,7 @@ pub fn deprecated_unittest_alias(checker: &mut Checker, expr: &Expr) { return; } let mut check = Check::new( - CheckKind::DeprecatedUnittestAlias(attr.to_string(), target.to_string()), + violations::DeprecatedUnittestAlias(attr.to_string(), target.to_string()), Range::from_located(expr), ); if checker.patch(check.kind.code()) { diff --git a/src/pyupgrade/plugins/native_literals.rs b/src/pyupgrade/plugins/native_literals.rs index bde80e8d86341..c42b41f9f5f76 100644 --- a/src/pyupgrade/plugins/native_literals.rs +++ b/src/pyupgrade/plugins/native_literals.rs @@ -5,7 +5,8 @@ use rustpython_parser::lexer::Tok; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind, LiteralType}; +use crate::registry::{Check, CheckCode, LiteralType}; +use crate::violations; /// UP018 pub fn native_literals( @@ -23,7 +24,7 @@ pub fn native_literals( if (id == "str" || id == "bytes") && checker.is_builtin(id) { let Some(arg) = args.get(0) else { - let mut check = Check::new(CheckKind::NativeLiterals(if id == "str" { + let mut check = Check::new(violations::NativeLiterals(if id == "str" { LiteralType::Str } else { LiteralType::Bytes @@ -92,7 +93,7 @@ pub fn native_literals( } let mut check = Check::new( - CheckKind::NativeLiterals(if id == "str" { + violations::NativeLiterals(if id == "str" { LiteralType::Str } else { LiteralType::Bytes diff --git a/src/pyupgrade/plugins/open_alias.rs b/src/pyupgrade/plugins/open_alias.rs index da33289717122..f1a581edfd98e 100644 --- a/src/pyupgrade/plugins/open_alias.rs +++ b/src/pyupgrade/plugins/open_alias.rs @@ -4,14 +4,15 @@ use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// UP020 pub fn open_alias(checker: &mut Checker, expr: &Expr, func: &Expr) { let call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases); if match_call_path(&call_path, "io", "open", &checker.from_imports) { - let mut check = Check::new(CheckKind::OpenAlias, Range::from_located(expr)); + let mut check = Check::new(violations::OpenAlias, Range::from_located(expr)); if checker.patch(&CheckCode::UP020) { check.amend(Fix::replacement( "open".to_string(), diff --git a/src/pyupgrade/plugins/os_error_alias.rs b/src/pyupgrade/plugins/os_error_alias.rs index 2745931711a69..e9d68ad407630 100644 --- a/src/pyupgrade/plugins/os_error_alias.rs +++ b/src/pyupgrade/plugins/os_error_alias.rs @@ -7,7 +7,8 @@ use crate::ast::helpers::{compose_call_path, match_module_member}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; const ERROR_NAMES: &[&str] = &["EnvironmentError", "IOError", "WindowsError"]; const ERROR_MODULES: &[&str] = &["mmap", "select", "socket"]; @@ -157,7 +158,7 @@ fn handle_making_changes( final_str.insert(0, '('); final_str.push(')'); } - let mut check = Check::new(CheckKind::OSErrorAlias(compose_call_path(target)), range); + let mut check = Check::new(violations::OSErrorAlias(compose_call_path(target)), range); if checker.patch(check.kind.code()) { check.amend(Fix::replacement( final_str, diff --git a/src/pyupgrade/plugins/redundant_open_modes.rs b/src/pyupgrade/plugins/redundant_open_modes.rs index 391b8beb51e88..863892578944a 100644 --- a/src/pyupgrade/plugins/redundant_open_modes.rs +++ b/src/pyupgrade/plugins/redundant_open_modes.rs @@ -10,8 +10,9 @@ use crate::ast::helpers::find_keyword; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; const OPEN_FUNC_NAME: &str = "open"; const MODE_KEYWORD_ARGUMENT: &str = "mode"; @@ -80,7 +81,7 @@ fn create_check( patch: bool, ) -> Check { let mut check = Check::new( - CheckKind::RedundantOpenModes(replacement_value.clone()), + violations::RedundantOpenModes(replacement_value.clone()), Range::from_located(expr), ); if patch { diff --git a/src/pyupgrade/plugins/remove_six_compat.rs b/src/pyupgrade/plugins/remove_six_compat.rs index 36fa572a09c95..f7ed63726d45b 100644 --- a/src/pyupgrade/plugins/remove_six_compat.rs +++ b/src/pyupgrade/plugins/remove_six_compat.rs @@ -4,10 +4,10 @@ use crate::ast::helpers::{collect_call_paths, create_expr, create_stmt, dealias_ use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_style::SourceCodeStyleDetector; -use crate::SourceCodeLocator; +use crate::{violations, SourceCodeLocator}; /// Return `true` if the `Expr` is a reference to `${module}.${any}`. fn is_module_member(call_path: &[&str], module: &str) -> bool { @@ -35,7 +35,7 @@ fn map_name(name: &str, expr: &Expr, patch: bool) -> Option { _ => None, }; if let Some(replacement) = replacement { - let mut check = Check::new(CheckKind::RemoveSixCompat, Range::from_located(expr)); + let mut check = Check::new(violations::RemoveSixCompat, Range::from_located(expr)); if patch { check.amend(Fix::replacement( replacement.to_string(), @@ -58,7 +58,7 @@ fn replace_by_str_literal( ) -> Option { match &arg.node { ExprKind::Constant { .. } => { - let mut check = Check::new(CheckKind::RemoveSixCompat, Range::from_located(expr)); + let mut check = Check::new(violations::RemoveSixCompat, Range::from_located(expr)); if patch { let content = format!( "{}{}", @@ -132,7 +132,7 @@ fn replace_by_expr_kind( patch: bool, stylist: &SourceCodeStyleDetector, ) -> Check { - let mut check = Check::new(CheckKind::RemoveSixCompat, Range::from_located(expr)); + let mut check = Check::new(violations::RemoveSixCompat, Range::from_located(expr)); if patch { let mut generator: SourceCodeGenerator = stylist.into(); generator.unparse_expr(&create_expr(node), 0); @@ -151,7 +151,7 @@ fn replace_by_stmt_kind( patch: bool, stylist: &SourceCodeStyleDetector, ) -> Check { - let mut check = Check::new(CheckKind::RemoveSixCompat, Range::from_located(expr)); + let mut check = Check::new(violations::RemoveSixCompat, Range::from_located(expr)); if patch { let mut generator: SourceCodeGenerator = stylist.into(); generator.unparse_stmt(&create_stmt(node)); diff --git a/src/pyupgrade/plugins/replace_stdout_stderr.rs b/src/pyupgrade/plugins/replace_stdout_stderr.rs index 16a1eed12f56b..2c22ac44be926 100644 --- a/src/pyupgrade/plugins/replace_stdout_stderr.rs +++ b/src/pyupgrade/plugins/replace_stdout_stderr.rs @@ -5,7 +5,8 @@ use crate::ast::types::Range; use crate::ast::whitespace::indentation; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; #[derive(Debug)] struct MiddleContent<'a> { @@ -74,7 +75,7 @@ pub fn replace_stdout_stderr(checker: &mut Checker, expr: &Expr, kwargs: &[Keywo return; } - let mut check = Check::new(CheckKind::ReplaceStdoutStderr, Range::from_located(expr)); + let mut check = Check::new(violations::ReplaceStdoutStderr, Range::from_located(expr)); if checker.patch(check.kind.code()) { let first = if stdout.location < stderr.location { stdout diff --git a/src/pyupgrade/plugins/replace_universal_newlines.rs b/src/pyupgrade/plugins/replace_universal_newlines.rs index 697246b780a8f..682536808c9a7 100644 --- a/src/pyupgrade/plugins/replace_universal_newlines.rs +++ b/src/pyupgrade/plugins/replace_universal_newlines.rs @@ -4,7 +4,8 @@ use crate::ast::helpers::{find_keyword, match_module_member}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// UP021 pub fn replace_universal_newlines(checker: &mut Checker, expr: &Expr, kwargs: &[Keyword]) { @@ -23,7 +24,7 @@ pub fn replace_universal_newlines(checker: &mut Checker, expr: &Expr, kwargs: &[ kwarg.location.column() + "universal_newlines".len(), ), ); - let mut check = Check::new(CheckKind::ReplaceUniversalNewlines, range); + let mut check = Check::new(violations::ReplaceUniversalNewlines, range); if checker.patch(check.kind.code()) { check.amend(Fix::replacement( "text".to_string(), diff --git a/src/pyupgrade/plugins/rewrite_c_element_tree.rs b/src/pyupgrade/plugins/rewrite_c_element_tree.rs index ba38194ed32dd..c2bb290e39157 100644 --- a/src/pyupgrade/plugins/rewrite_c_element_tree.rs +++ b/src/pyupgrade/plugins/rewrite_c_element_tree.rs @@ -3,10 +3,11 @@ use rustpython_ast::{Located, Stmt, StmtKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; fn add_check_for_node(checker: &mut Checker, node: &Located) { - let mut check = Check::new(CheckKind::RewriteCElementTree, Range::from_located(node)); + let mut check = Check::new(violations::RewriteCElementTree, Range::from_located(node)); if checker.patch(check.kind.code()) { let contents = checker .locator diff --git a/src/pyupgrade/plugins/rewrite_mock_import.rs b/src/pyupgrade/plugins/rewrite_mock_import.rs index 38f3fa8da9f73..a719af4bc42a4 100644 --- a/src/pyupgrade/plugins/rewrite_mock_import.rs +++ b/src/pyupgrade/plugins/rewrite_mock_import.rs @@ -12,9 +12,10 @@ use crate::ast::whitespace::indentation; use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::cst::matchers::{match_import, match_import_from, match_module}; -use crate::registry::{Check, CheckCode, CheckKind, MockReference}; +use crate::registry::{Check, CheckCode, MockReference}; use crate::source_code_locator::SourceCodeLocator; use crate::source_code_style::SourceCodeStyleDetector; +use crate::violations; /// Return a vector of all non-`mock` imports. fn clean_import_aliases(aliases: Vec) -> (Vec, Vec>) { @@ -204,7 +205,7 @@ pub fn rewrite_mock_attribute(checker: &mut Checker, expr: &Expr) { if let ExprKind::Attribute { value, .. } = &expr.node { if collect_call_paths(value) == ["mock", "mock"] { let mut check = Check::new( - CheckKind::RewriteMockImport(MockReference::Attribute), + violations::RewriteMockImport(MockReference::Attribute), Range::from_located(value), ); if checker.patch(&CheckCode::UP026) { @@ -246,7 +247,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) { for name in names { if name.node.name == "mock" || name.node.name == "mock.mock" { let mut check = Check::new( - CheckKind::RewriteMockImport(MockReference::Import), + violations::RewriteMockImport(MockReference::Import), Range::from_located(name), ); if let Some(content) = content.as_ref() { @@ -272,7 +273,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) { if module == "mock" { let mut check = Check::new( - CheckKind::RewriteMockImport(MockReference::Import), + violations::RewriteMockImport(MockReference::Import), Range::from_located(stmt), ); if checker.patch(&CheckCode::UP026) { diff --git a/src/pyupgrade/plugins/rewrite_unicode_literal.rs b/src/pyupgrade/plugins/rewrite_unicode_literal.rs index 27e587354595a..7bddc53c41a69 100644 --- a/src/pyupgrade/plugins/rewrite_unicode_literal.rs +++ b/src/pyupgrade/plugins/rewrite_unicode_literal.rs @@ -3,13 +3,15 @@ use rustpython_ast::{Expr, Location}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// UP025 pub fn rewrite_unicode_literal(checker: &mut Checker, expr: &Expr, kind: Option<&str>) { if let Some(const_kind) = kind { if const_kind.to_lowercase() == "u" { - let mut check = Check::new(CheckKind::RewriteUnicodeLiteral, Range::from_located(expr)); + let mut check = + Check::new(violations::RewriteUnicodeLiteral, Range::from_located(expr)); if checker.patch(check.kind.code()) { check.amend(Fix::deletion( expr.location, diff --git a/src/pyupgrade/plugins/rewrite_yield_from.rs b/src/pyupgrade/plugins/rewrite_yield_from.rs index 5e161f1a64976..8978fd0dcb39d 100644 --- a/src/pyupgrade/plugins/rewrite_yield_from.rs +++ b/src/pyupgrade/plugins/rewrite_yield_from.rs @@ -6,7 +6,8 @@ use crate::ast::visitor; use crate::ast::visitor::Visitor; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// Return `true` if the two expressions are equivalent, and consistent solely /// of tuples and names. @@ -156,7 +157,8 @@ pub fn rewrite_yield_from(checker: &mut Checker, stmt: &Stmt) { continue; } - let mut check = Check::new(CheckKind::RewriteYieldFrom, Range::from_located(item.stmt)); + let mut check = + Check::new(violations::RewriteYieldFrom, Range::from_located(item.stmt)); if checker.patch(check.kind.code()) { let contents = checker .locator diff --git a/src/pyupgrade/plugins/type_of_primitive.rs b/src/pyupgrade/plugins/type_of_primitive.rs index 63f24bb345218..ba9b4b81eb8dc 100644 --- a/src/pyupgrade/plugins/type_of_primitive.rs +++ b/src/pyupgrade/plugins/type_of_primitive.rs @@ -5,6 +5,7 @@ use crate::autofix::Fix; use crate::checkers::ast::Checker; use crate::pyupgrade::checks; use crate::registry::CheckKind; +use crate::violations; /// UP003 pub fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { @@ -12,7 +13,7 @@ pub fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args: return; }; if checker.patch(check.kind.code()) { - if let CheckKind::TypeOfPrimitive(primitive) = &check.kind { + if let CheckKind::TypeOfPrimitive(violations::TypeOfPrimitive(primitive)) = &check.kind { check.amend(Fix::replacement( primitive.builtin(), expr.location, diff --git a/src/pyupgrade/plugins/typing_text_str_alias.rs b/src/pyupgrade/plugins/typing_text_str_alias.rs index 945d6fbca4605..9a5a6e9ba0c97 100644 --- a/src/pyupgrade/plugins/typing_text_str_alias.rs +++ b/src/pyupgrade/plugins/typing_text_str_alias.rs @@ -4,7 +4,8 @@ use crate::ast::helpers::match_module_member; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// UP019 pub fn typing_text_str_alias(checker: &mut Checker, expr: &Expr) { @@ -15,7 +16,7 @@ pub fn typing_text_str_alias(checker: &mut Checker, expr: &Expr) { &checker.from_imports, &checker.import_aliases, ) { - let mut check = Check::new(CheckKind::TypingTextStrAlias, Range::from_located(expr)); + let mut check = Check::new(violations::TypingTextStrAlias, Range::from_located(expr)); if checker.patch(check.kind.code()) { check.amend(Fix::replacement( "str".to_string(), diff --git a/src/pyupgrade/plugins/unnecessary_builtin_import.rs b/src/pyupgrade/plugins/unnecessary_builtin_import.rs index 62bcad9ec01b2..7e66889bef1b7 100644 --- a/src/pyupgrade/plugins/unnecessary_builtin_import.rs +++ b/src/pyupgrade/plugins/unnecessary_builtin_import.rs @@ -4,9 +4,9 @@ use rustpython_ast::{Alias, AliasData, Located}; use rustpython_parser::ast::Stmt; use crate::ast::types::Range; -use crate::autofix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::{autofix, violations}; const BUILTINS: &[&str] = &[ "*", @@ -69,7 +69,7 @@ pub fn unnecessary_builtin_import( return; } let mut check = Check::new( - CheckKind::UnnecessaryBuiltinImport( + violations::UnnecessaryBuiltinImport( unused_imports .iter() .map(|alias| alias.node.name.to_string()) diff --git a/src/pyupgrade/plugins/unnecessary_encode_utf8.rs b/src/pyupgrade/plugins/unnecessary_encode_utf8.rs index 008091ac021ea..3c3eac3d65d77 100644 --- a/src/pyupgrade/plugins/unnecessary_encode_utf8.rs +++ b/src/pyupgrade/plugins/unnecessary_encode_utf8.rs @@ -3,8 +3,9 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; use crate::source_code_locator::SourceCodeLocator; +use crate::violations; const UTF8_LITERALS: &[&str] = &["utf-8", "utf8", "utf_8", "u8", "utf", "cp65001"]; @@ -59,13 +60,13 @@ fn delete_default_encode_arg_or_kwarg( patch: bool, ) -> Option { if let Some(arg) = args.get(0) { - let mut check = Check::new(CheckKind::UnnecessaryEncodeUTF8, Range::from_located(expr)); + let mut check = Check::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr)); if patch { check.amend(Fix::deletion(arg.location, arg.end_location.unwrap())); } Some(check) } else if let Some(kwarg) = kwargs.get(0) { - let mut check = Check::new(CheckKind::UnnecessaryEncodeUTF8, Range::from_located(expr)); + let mut check = Check::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr)); if patch { check.amend(Fix::deletion(kwarg.location, kwarg.end_location.unwrap())); } @@ -82,7 +83,7 @@ fn replace_with_bytes_literal( locator: &SourceCodeLocator, patch: bool, ) -> Check { - let mut check = Check::new(CheckKind::UnnecessaryEncodeUTF8, Range::from_located(expr)); + let mut check = Check::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr)); if patch { let content = locator.slice_source_code_range(&Range::new( constant.location, diff --git a/src/pyupgrade/plugins/unnecessary_future_import.rs b/src/pyupgrade/plugins/unnecessary_future_import.rs index 472af437a0aa9..a89fe4694f8d2 100644 --- a/src/pyupgrade/plugins/unnecessary_future_import.rs +++ b/src/pyupgrade/plugins/unnecessary_future_import.rs @@ -4,10 +4,10 @@ use rustpython_ast::{Alias, AliasData, Located}; use rustpython_parser::ast::Stmt; use crate::ast::types::Range; -use crate::autofix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::settings::types::PythonVersion; +use crate::{autofix, violations}; const PY33_PLUS_REMOVE_FUTURES: &[&str] = &[ "nested_scopes", @@ -54,7 +54,7 @@ pub fn unnecessary_future_import(checker: &mut Checker, stmt: &Stmt, names: &[Lo return; } let mut check = Check::new( - CheckKind::UnnecessaryFutureImport( + violations::UnnecessaryFutureImport( unused_imports .iter() .map(|alias| alias.node.name.to_string()) diff --git a/src/pyupgrade/plugins/unpack_list_comprehension.rs b/src/pyupgrade/plugins/unpack_list_comprehension.rs index ce8a1c93bde4c..7609845771655 100644 --- a/src/pyupgrade/plugins/unpack_list_comprehension.rs +++ b/src/pyupgrade/plugins/unpack_list_comprehension.rs @@ -3,7 +3,8 @@ use rustpython_ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckCode, CheckKind}; +use crate::registry::{Check, CheckCode}; +use crate::violations; /// Returns `true` if `expr` contains an `ExprKind::Await`. fn contains_await(expr: &Expr) -> bool { @@ -75,7 +76,7 @@ pub fn unpack_list_comprehension(checker: &mut Checker, targets: &[Expr], value: } let mut check = Check::new( - CheckKind::RewriteListComprehension, + violations::RewriteListComprehension, Range::from_located(value), ); if checker.patch(&CheckCode::UP027) { diff --git a/src/pyupgrade/plugins/use_pep585_annotation.rs b/src/pyupgrade/plugins/use_pep585_annotation.rs index 74ec9b0058e0d..38857eeb32339 100644 --- a/src/pyupgrade/plugins/use_pep585_annotation.rs +++ b/src/pyupgrade/plugins/use_pep585_annotation.rs @@ -3,13 +3,14 @@ use rustpython_ast::Expr; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; +use crate::violations; /// UP006 pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr, id: &str) { let replacement = *checker.import_aliases.get(id).unwrap_or(&id); let mut check = Check::new( - CheckKind::UsePEP585Annotation(replacement.to_string()), + violations::UsePEP585Annotation(replacement.to_string()), Range::from_located(expr), ); if checker.patch(check.kind.code()) { diff --git a/src/pyupgrade/plugins/use_pep604_annotation.rs b/src/pyupgrade/plugins/use_pep604_annotation.rs index acbe4c0160ff4..0d03535383117 100644 --- a/src/pyupgrade/plugins/use_pep604_annotation.rs +++ b/src/pyupgrade/plugins/use_pep604_annotation.rs @@ -4,8 +4,9 @@ use crate::ast::helpers::{collect_call_paths, dealias_call_path}; use crate::ast::types::Range; use crate::autofix::Fix; use crate::checkers::ast::Checker; -use crate::registry::{Check, CheckKind}; +use crate::registry::Check; use crate::source_code_generator::SourceCodeGenerator; +use crate::violations; fn optional(expr: &Expr) -> Expr { Expr::new( @@ -63,7 +64,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s let call_path = dealias_call_path(collect_call_paths(value), &checker.import_aliases); if checker.match_typing_call_path(&call_path, "Optional") { - let mut check = Check::new(CheckKind::UsePEP604Annotation, Range::from_located(expr)); + let mut check = Check::new(violations::UsePEP604Annotation, Range::from_located(expr)); if checker.patch(check.kind.code()) { let mut generator: SourceCodeGenerator = checker.style.into(); generator.unparse_expr(&optional(slice), 0); @@ -75,7 +76,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s } checker.checks.push(check); } else if checker.match_typing_call_path(&call_path, "Union") { - let mut check = Check::new(CheckKind::UsePEP604Annotation, Range::from_located(expr)); + let mut check = Check::new(violations::UsePEP604Annotation, Range::from_located(expr)); if checker.patch(check.kind.code()) { match &slice.node { ExprKind::Slice { .. } => { diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP001_UP001.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP001_UP001.py.snap index d54efd2b4a9a5..8c14c38cdc778 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP001_UP001.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP001_UP001.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: UselessMetaclassType +- kind: + UselessMetaclassType: ~ location: row: 2 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 24 parent: ~ -- kind: UselessMetaclassType +- kind: + UselessMetaclassType: ~ location: row: 6 column: 4 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP007_UP007.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP007_UP007.py.snap index 718e96d2f579c..bc403677409b5 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP007_UP007.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP007_UP007.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 6 column: 9 @@ -18,7 +19,8 @@ expression: checks row: 6 column: 22 parent: ~ -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 10 column: 9 @@ -34,7 +36,8 @@ expression: checks row: 10 column: 29 parent: ~ -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 14 column: 9 @@ -50,7 +53,8 @@ expression: checks row: 14 column: 45 parent: ~ -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 14 column: 25 @@ -66,7 +70,8 @@ expression: checks row: 14 column: 44 parent: ~ -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 18 column: 9 @@ -82,7 +87,8 @@ expression: checks row: 18 column: 31 parent: ~ -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 22 column: 9 @@ -98,7 +104,8 @@ expression: checks row: 22 column: 33 parent: ~ -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 26 column: 9 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP008_UP008.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP008_UP008.py.snap index 28f74176bc77d..162cbbff354bd 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP008_UP008.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP008_UP008.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: SuperCallWithParameters +- kind: + SuperCallWithParameters: ~ location: row: 17 column: 17 @@ -18,7 +19,8 @@ expression: checks row: 17 column: 35 parent: ~ -- kind: SuperCallWithParameters +- kind: + SuperCallWithParameters: ~ location: row: 18 column: 8 @@ -34,7 +36,8 @@ expression: checks row: 18 column: 26 parent: ~ -- kind: SuperCallWithParameters +- kind: + SuperCallWithParameters: ~ location: row: 19 column: 8 @@ -50,7 +53,8 @@ expression: checks row: 22 column: 9 parent: ~ -- kind: SuperCallWithParameters +- kind: + SuperCallWithParameters: ~ location: row: 36 column: 8 @@ -66,7 +70,8 @@ expression: checks row: 36 column: 28 parent: ~ -- kind: SuperCallWithParameters +- kind: + SuperCallWithParameters: ~ location: row: 50 column: 12 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_0.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_0.py.snap index 6504264ee98d5..33d15234b5202 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_0.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_0.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: PEP3120UnnecessaryCodingComment +- kind: + PEP3120UnnecessaryCodingComment: ~ location: row: 1 column: 0 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_1.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_1.py.snap index 2e9efd1a8a438..e9dc184b38843 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_1.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP009_UP009_1.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: PEP3120UnnecessaryCodingComment +- kind: + PEP3120UnnecessaryCodingComment: ~ location: row: 2 column: 0 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP011_UP011_0.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP011_UP011_0.py.snap index 5fb2b1b410a6c..e11e1d5c05da4 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP011_UP011_0.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP011_UP011_0.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 5 column: 10 @@ -18,7 +19,8 @@ expression: checks row: 5 column: 12 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 11 column: 20 @@ -34,7 +36,8 @@ expression: checks row: 11 column: 22 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 16 column: 10 @@ -50,7 +53,8 @@ expression: checks row: 16 column: 24 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 21 column: 20 @@ -66,7 +70,8 @@ expression: checks row: 21 column: 34 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 27 column: 10 @@ -82,7 +87,8 @@ expression: checks row: 28 column: 1 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 33 column: 10 @@ -98,7 +104,8 @@ expression: checks row: 35 column: 1 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 40 column: 20 @@ -114,7 +121,8 @@ expression: checks row: 42 column: 19 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 47 column: 20 @@ -130,7 +138,8 @@ expression: checks row: 51 column: 1 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 56 column: 20 @@ -146,7 +155,8 @@ expression: checks row: 62 column: 1 parent: ~ -- kind: UnnecessaryLRUCacheParams +- kind: + UnnecessaryLRUCacheParams: ~ location: row: 67 column: 20 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP012_UP012.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP012_UP012.py.snap index 2f43e2f8184be..76a740ed0a879 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP012_UP012.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP012_UP012.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 2 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 21 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 3 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 3 column: 18 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 4 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 4 column: 14 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 5 column: 0 @@ -66,7 +70,8 @@ expression: checks row: 5 column: 20 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 6 column: 0 @@ -82,7 +87,8 @@ expression: checks row: 6 column: 22 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 7 column: 0 @@ -98,7 +104,8 @@ expression: checks row: 7 column: 30 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 8 column: 0 @@ -114,7 +121,8 @@ expression: checks row: 14 column: 1 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 26 column: 0 @@ -130,7 +138,8 @@ expression: checks row: 26 column: 26 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 44 column: 0 @@ -146,7 +155,8 @@ expression: checks row: 44 column: 30 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 46 column: 0 @@ -162,7 +172,8 @@ expression: checks row: 46 column: 38 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 48 column: 0 @@ -178,7 +189,8 @@ expression: checks row: 48 column: 24 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 49 column: 0 @@ -194,7 +206,8 @@ expression: checks row: 49 column: 22 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 50 column: 0 @@ -210,7 +223,8 @@ expression: checks row: 50 column: 24 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 51 column: 0 @@ -226,7 +240,8 @@ expression: checks row: 51 column: 22 parent: ~ -- kind: UnnecessaryEncodeUTF8 +- kind: + UnnecessaryEncodeUTF8: ~ location: row: 52 column: 6 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP016_UP016.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP016_UP016.py.snap index 0022beb43914a..83f799b0a7929 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP016_UP016.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP016_UP016.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 7 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 7 column: 13 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 8 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 8 column: 15 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 9 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 9 column: 15 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 10 column: 0 @@ -66,7 +70,8 @@ expression: checks row: 10 column: 16 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 11 column: 0 @@ -82,7 +87,8 @@ expression: checks row: 11 column: 17 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 12 column: 0 @@ -98,7 +104,8 @@ expression: checks row: 12 column: 10 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 13 column: 0 @@ -114,7 +121,8 @@ expression: checks row: 13 column: 13 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 14 column: 0 @@ -130,7 +138,8 @@ expression: checks row: 14 column: 10 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 15 column: 0 @@ -146,7 +155,8 @@ expression: checks row: 15 column: 9 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 16 column: 0 @@ -162,7 +172,8 @@ expression: checks row: 16 column: 20 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 17 column: 0 @@ -178,7 +189,8 @@ expression: checks row: 17 column: 8 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 18 column: 0 @@ -194,7 +206,8 @@ expression: checks row: 18 column: 12 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 19 column: 0 @@ -210,7 +223,8 @@ expression: checks row: 19 column: 15 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 20 column: 0 @@ -226,7 +240,8 @@ expression: checks row: 20 column: 16 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 21 column: 16 @@ -242,7 +257,8 @@ expression: checks row: 21 column: 31 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 22 column: 16 @@ -258,7 +274,8 @@ expression: checks row: 22 column: 33 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 23 column: 16 @@ -274,7 +291,8 @@ expression: checks row: 23 column: 32 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 26 column: 0 @@ -290,7 +308,8 @@ expression: checks row: 26 column: 18 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 27 column: 0 @@ -306,7 +325,8 @@ expression: checks row: 27 column: 17 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 28 column: 0 @@ -322,7 +342,8 @@ expression: checks row: 28 column: 19 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 29 column: 0 @@ -338,7 +359,8 @@ expression: checks row: 29 column: 18 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 30 column: 0 @@ -354,7 +376,8 @@ expression: checks row: 30 column: 17 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 31 column: 0 @@ -370,7 +393,8 @@ expression: checks row: 31 column: 19 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 32 column: 0 @@ -386,7 +410,8 @@ expression: checks row: 32 column: 34 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 33 column: 0 @@ -402,7 +427,8 @@ expression: checks row: 33 column: 37 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 34 column: 0 @@ -418,7 +444,8 @@ expression: checks row: 34 column: 27 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 37 column: 0 @@ -434,7 +461,8 @@ expression: checks row: 37 column: 29 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 38 column: 0 @@ -450,7 +478,8 @@ expression: checks row: 38 column: 25 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 39 column: 0 @@ -466,7 +495,8 @@ expression: checks row: 39 column: 28 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 40 column: 0 @@ -482,7 +512,8 @@ expression: checks row: 40 column: 25 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 41 column: 0 @@ -498,7 +529,8 @@ expression: checks row: 41 column: 29 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 42 column: 0 @@ -514,7 +546,8 @@ expression: checks row: 42 column: 28 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 45 column: 0 @@ -530,7 +563,8 @@ expression: checks row: 45 column: 12 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 46 column: 0 @@ -546,7 +580,8 @@ expression: checks row: 46 column: 12 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 47 column: 0 @@ -562,7 +597,8 @@ expression: checks row: 47 column: 24 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 48 column: 0 @@ -578,7 +614,8 @@ expression: checks row: 48 column: 21 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 49 column: 0 @@ -594,7 +631,8 @@ expression: checks row: 49 column: 22 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 53 column: 0 @@ -610,7 +648,8 @@ expression: checks row: 53 column: 30 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 54 column: 0 @@ -626,7 +665,8 @@ expression: checks row: 54 column: 34 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 57 column: 0 @@ -642,7 +682,8 @@ expression: checks row: 57 column: 29 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 58 column: 0 @@ -658,7 +699,8 @@ expression: checks row: 58 column: 24 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 59 column: 0 @@ -674,7 +716,8 @@ expression: checks row: 59 column: 28 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 62 column: 0 @@ -690,7 +733,8 @@ expression: checks row: 62 column: 16 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 63 column: 0 @@ -706,7 +750,8 @@ expression: checks row: 63 column: 21 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 64 column: 0 @@ -722,7 +767,8 @@ expression: checks row: 64 column: 15 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 67 column: 5 @@ -738,7 +784,8 @@ expression: checks row: 67 column: 23 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 67 column: 5 @@ -754,7 +801,8 @@ expression: checks row: 67 column: 23 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 68 column: 5 @@ -770,7 +818,8 @@ expression: checks row: 68 column: 22 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 68 column: 5 @@ -786,7 +835,8 @@ expression: checks row: 68 column: 22 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 69 column: 5 @@ -802,7 +852,8 @@ expression: checks row: 69 column: 24 parent: ~ -- kind: RemoveSixCompat +- kind: + RemoveSixCompat: ~ location: row: 69 column: 5 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP019_UP019.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP019_UP019.py.snap index e1ce41f4a5d0a..ea9157c0d289f 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP019_UP019.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP019_UP019.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: TypingTextStrAlias +- kind: + TypingTextStrAlias: ~ location: row: 7 column: 21 @@ -18,7 +19,8 @@ expression: checks row: 7 column: 25 parent: ~ -- kind: TypingTextStrAlias +- kind: + TypingTextStrAlias: ~ location: row: 11 column: 28 @@ -34,7 +36,8 @@ expression: checks row: 11 column: 39 parent: ~ -- kind: TypingTextStrAlias +- kind: + TypingTextStrAlias: ~ location: row: 15 column: 27 @@ -50,7 +53,8 @@ expression: checks row: 15 column: 37 parent: ~ -- kind: TypingTextStrAlias +- kind: + TypingTextStrAlias: ~ location: row: 19 column: 28 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP021_UP021.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP021_UP021.py.snap index 92eb29496f53e..d5fbb9877811b 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP021_UP021.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP021_UP021.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: ReplaceUniversalNewlines +- kind: + ReplaceUniversalNewlines: ~ location: row: 6 column: 24 @@ -18,7 +19,8 @@ expression: checks row: 6 column: 42 parent: ~ -- kind: ReplaceUniversalNewlines +- kind: + ReplaceUniversalNewlines: ~ location: row: 7 column: 22 @@ -34,7 +36,8 @@ expression: checks row: 7 column: 40 parent: ~ -- kind: ReplaceUniversalNewlines +- kind: + ReplaceUniversalNewlines: ~ location: row: 9 column: 13 @@ -50,7 +53,8 @@ expression: checks row: 9 column: 31 parent: ~ -- kind: ReplaceUniversalNewlines +- kind: + ReplaceUniversalNewlines: ~ location: row: 10 column: 21 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP022_UP022.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP022_UP022.py.snap index f8649a7d16ab2..35036e9812efb 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP022_UP022.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP022_UP022.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 4 column: 9 @@ -18,7 +19,8 @@ expression: checks row: 4 column: 68 parent: ~ -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 6 column: 9 @@ -34,7 +36,8 @@ expression: checks row: 6 column: 79 parent: ~ -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 8 column: 9 @@ -50,7 +53,8 @@ expression: checks row: 8 column: 85 parent: ~ -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 10 column: 9 @@ -66,7 +70,8 @@ expression: checks row: 11 column: 71 parent: ~ -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 14 column: 9 @@ -82,7 +87,8 @@ expression: checks row: 15 column: 71 parent: ~ -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 18 column: 9 @@ -98,7 +104,8 @@ expression: checks row: 22 column: 26 parent: ~ -- kind: ReplaceStdoutStderr +- kind: + ReplaceStdoutStderr: ~ location: row: 29 column: 13 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP023_UP023.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP023_UP023.py.snap index 076e83bb4941d..d54cc1ac917ee 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP023_UP023.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP023_UP023.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 2 column: 0 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 59 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 3 column: 7 @@ -34,7 +36,8 @@ expression: checks row: 3 column: 35 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 6 column: 0 @@ -50,7 +53,8 @@ expression: checks row: 6 column: 44 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 7 column: 10 @@ -66,7 +70,8 @@ expression: checks row: 7 column: 49 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 10 column: 0 @@ -82,7 +87,8 @@ expression: checks row: 14 column: 1 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 16 column: 11 @@ -98,7 +104,8 @@ expression: checks row: 16 column: 39 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 17 column: 26 @@ -114,7 +121,8 @@ expression: checks row: 17 column: 45 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 19 column: 22 @@ -130,7 +138,8 @@ expression: checks row: 19 column: 40 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 21 column: 19 @@ -146,7 +155,8 @@ expression: checks row: 21 column: 47 parent: ~ -- kind: RewriteCElementTree +- kind: + RewriteCElementTree: ~ location: row: 24 column: 31 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP025_UP025.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP025_UP025.py.snap index c8f8e7fba63f6..7bcba2bd67ba8 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP025_UP025.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP025_UP025.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 2 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 5 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 4 column: 0 @@ -34,7 +36,8 @@ expression: checks row: 4 column: 1 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 6 column: 6 @@ -50,7 +53,8 @@ expression: checks row: 6 column: 7 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 8 column: 6 @@ -66,7 +70,8 @@ expression: checks row: 8 column: 7 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 12 column: 4 @@ -82,7 +87,8 @@ expression: checks row: 12 column: 5 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 12 column: 14 @@ -98,7 +104,8 @@ expression: checks row: 12 column: 15 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 12 column: 26 @@ -114,7 +121,8 @@ expression: checks row: 12 column: 27 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 12 column: 38 @@ -130,7 +138,8 @@ expression: checks row: 12 column: 39 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 16 column: 4 @@ -146,7 +155,8 @@ expression: checks row: 16 column: 5 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 17 column: 4 @@ -162,7 +172,8 @@ expression: checks row: 17 column: 5 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 18 column: 4 @@ -178,7 +189,8 @@ expression: checks row: 18 column: 5 parent: ~ -- kind: RewriteUnicodeLiteral +- kind: + RewriteUnicodeLiteral: ~ location: row: 19 column: 4 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP027_UP027.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP027_UP027.py.snap index 0f9ff5e81f5bb..1b113e1efca6e 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP027_UP027.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP027_UP027.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: RewriteListComprehension +- kind: + RewriteListComprehension: ~ location: row: 2 column: 16 @@ -18,7 +19,8 @@ expression: checks row: 2 column: 38 parent: ~ -- kind: RewriteListComprehension +- kind: + RewriteListComprehension: ~ location: row: 4 column: 15 @@ -34,7 +36,8 @@ expression: checks row: 4 column: 37 parent: ~ -- kind: RewriteListComprehension +- kind: + RewriteListComprehension: ~ location: row: 6 column: 25 @@ -50,7 +53,8 @@ expression: checks row: 6 column: 47 parent: ~ -- kind: RewriteListComprehension +- kind: + RewriteListComprehension: ~ location: row: 8 column: 16 @@ -66,7 +70,8 @@ expression: checks row: 8 column: 51 parent: ~ -- kind: RewriteListComprehension +- kind: + RewriteListComprehension: ~ location: row: 10 column: 16 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP028_UP028_0.py.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP028_UP028_0.py.snap index 48da6bdc5f0a7..94ac2e3c5074c 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP028_UP028_0.py.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__UP028_UP028_0.py.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 2 column: 4 @@ -18,7 +19,8 @@ expression: checks row: 3 column: 15 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 7 column: 4 @@ -34,7 +36,8 @@ expression: checks row: 8 column: 20 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 12 column: 4 @@ -50,7 +53,8 @@ expression: checks row: 13 column: 15 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 17 column: 4 @@ -66,7 +70,8 @@ expression: checks row: 18 column: 15 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 22 column: 4 @@ -82,7 +87,8 @@ expression: checks row: 23 column: 15 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 27 column: 4 @@ -98,7 +104,8 @@ expression: checks row: 28 column: 18 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 33 column: 4 @@ -114,7 +121,8 @@ expression: checks row: 39 column: 18 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 44 column: 4 @@ -130,7 +138,8 @@ expression: checks row: 45 column: 18 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 49 column: 4 @@ -146,7 +155,8 @@ expression: checks row: 50 column: 18 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 55 column: 8 @@ -162,7 +172,8 @@ expression: checks row: 57 column: 22 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 67 column: 4 @@ -178,7 +189,8 @@ expression: checks row: 68 column: 15 parent: ~ -- kind: RewriteYieldFrom +- kind: + RewriteYieldFrom: ~ location: row: 72 column: 4 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__datetime_utc_alias_py311.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__datetime_utc_alias_py311.snap index ca6a1b67c40ff..286db221ee4c9 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__datetime_utc_alias_py311.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__datetime_utc_alias_py311.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: DatetimeTimezoneUTC +- kind: + DatetimeTimezoneUTC: ~ location: row: 10 column: 6 @@ -18,7 +19,8 @@ expression: checks row: 10 column: 27 parent: ~ -- kind: DatetimeTimezoneUTC +- kind: + DatetimeTimezoneUTC: ~ location: row: 11 column: 6 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_p37.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_p37.snap index 0f17cd8d33c0a..e1ed149655ed2 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_p37.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_p37.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 40 column: 3 diff --git a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_py310.snap b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_py310.snap index 0f17cd8d33c0a..e1ed149655ed2 100644 --- a/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_py310.snap +++ b/src/pyupgrade/snapshots/ruff__pyupgrade__tests__future_annotations_pep_604_py310.snap @@ -2,7 +2,8 @@ source: src/pyupgrade/mod.rs expression: checks --- -- kind: UsePEP604Annotation +- kind: + UsePEP604Annotation: ~ location: row: 40 column: 3 diff --git a/src/registry.rs b/src/registry.rs index 81da27454ac96..6c546c7c78c2e 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -2,7 +2,6 @@ use std::fmt; -use itertools::Itertools; use once_cell::sync::Lazy; use ruff_macros::CheckCodePrefix; use rustc_hash::FxHashMap; @@ -13,422 +12,496 @@ use strum_macros::{AsRefStr, Display, EnumIter, EnumString}; use crate::ast::types::Range; use crate::autofix::Fix; -use crate::flake8_debugger::types::DebuggerUsingType; -use crate::flake8_pytest_style::types::{ - ParametrizeNameType, ParametrizeValuesRowType, ParametrizeValuesType, -}; -use crate::flake8_quotes::settings::Quote; -use crate::flake8_tidy_imports::settings::Strictness; -use crate::pyupgrade::types::Primitive; +use crate::violation::Violation; +use crate::violations; -#[derive( - AsRefStr, - CheckCodePrefix, - EnumIter, - EnumString, - Debug, - Display, - PartialEq, - Eq, - Clone, - Serialize, - Deserialize, - Hash, - PartialOrd, - Ord, -)] -pub enum CheckCode { +macro_rules! define_rule_mapping { + ($($code:ident => $mod:ident::$name:ident,)+) => { + #[derive( + AsRefStr, + CheckCodePrefix, + EnumIter, + EnumString, + Debug, + Display, + PartialEq, + Eq, + Clone, + Serialize, + Deserialize, + Hash, + PartialOrd, + Ord, + )] + pub enum CheckCode { + $( + $code, + )+ + } + + + #[derive(AsRefStr, Debug, PartialEq, Eq, Serialize, Deserialize)] + pub enum CheckKind { + $( + $name($mod::$name), + )+ + } + + impl CheckCode { + /// A placeholder representation of the `CheckKind` for the check. + pub fn kind(&self) -> CheckKind { + match self { + $( + CheckCode::$code => CheckKind::$name(<$mod::$name as Violation>::placeholder()), + )+ + } + } + } + + impl CheckKind { + /// A four-letter shorthand code for the check. + pub fn code(&self) -> &'static CheckCode { + match self { + $( + CheckKind::$name(..) => &CheckCode::$code, + )+ + } + } + + + /// The body text for the check. + pub fn body(&self) -> String { + match self { + $( + CheckKind::$name(x) => Violation::message(x), + )+ + } + } + + + /// Whether the check kind is (potentially) fixable. + pub fn fixable(&self) -> bool { + match self { + $( + CheckKind::$name(x) => x.autofix_title_formatter().is_some(), + )+ + } + } + + + /// The message used to describe the fix action for a given `CheckKind`. + pub fn commit(&self) -> Option { + match self { + $( + CheckKind::$name(x) => x.autofix_title_formatter().map(|f| f(x)), + )+ + } + } + } + + $( + impl From<$mod::$name> for CheckKind { + fn from(x: $mod::$name) -> Self { + CheckKind::$name(x) + } + } + )+ + + }; +} + +define_rule_mapping!( // pycodestyle errors - E401, - E402, - E501, - E711, - E712, - E713, - E714, - E721, - E722, - E731, - E741, - E742, - E743, - E902, - E999, + E401 => violations::MultipleImportsOnOneLine, + E402 => violations::ModuleImportNotAtTopOfFile, + E501 => violations::LineTooLong, + E711 => violations::NoneComparison, + E712 => violations::TrueFalseComparison, + E713 => violations::NotInTest, + E714 => violations::NotIsTest, + E721 => violations::TypeComparison, + E722 => violations::DoNotUseBareExcept, + E731 => violations::DoNotAssignLambda, + E741 => violations::AmbiguousVariableName, + E742 => violations::AmbiguousClassName, + E743 => violations::AmbiguousFunctionName, + E902 => violations::IOError, + E999 => violations::SyntaxError, // pycodestyle warnings - W292, - W605, + W292 => violations::NoNewLineAtEndOfFile, + W605 => violations::InvalidEscapeSequence, // pyflakes - F401, - F402, - F403, - F404, - F405, - F406, - F407, - F501, - F502, - F503, - F504, - F505, - F506, - F507, - F508, - F509, - F521, - F522, - F523, - F524, - F525, - F541, - F601, - F602, - F621, - F622, - F631, - F632, - F633, - F634, - F701, - F702, - F704, - F706, - F707, - F722, - F811, - F821, - F822, - F823, - F841, - F842, - F901, + F401 => violations::UnusedImport, + F402 => violations::ImportShadowedByLoopVar, + F403 => violations::ImportStarUsed, + F404 => violations::LateFutureImport, + F405 => violations::ImportStarUsage, + F406 => violations::ImportStarNotPermitted, + F407 => violations::FutureFeatureNotDefined, + F501 => violations::PercentFormatInvalidFormat, + F502 => violations::PercentFormatExpectedMapping, + F503 => violations::PercentFormatExpectedSequence, + F504 => violations::PercentFormatExtraNamedArguments, + F505 => violations::PercentFormatMissingArgument, + F506 => violations::PercentFormatMixedPositionalAndNamed, + F507 => violations::PercentFormatPositionalCountMismatch, + F508 => violations::PercentFormatStarRequiresSequence, + F509 => violations::PercentFormatUnsupportedFormatCharacter, + F521 => violations::StringDotFormatInvalidFormat, + F522 => violations::StringDotFormatExtraNamedArguments, + F523 => violations::StringDotFormatExtraPositionalArguments, + F524 => violations::StringDotFormatMissingArguments, + F525 => violations::StringDotFormatMixingAutomatic, + F541 => violations::FStringMissingPlaceholders, + F601 => violations::MultiValueRepeatedKeyLiteral, + F602 => violations::MultiValueRepeatedKeyVariable, + F621 => violations::ExpressionsInStarAssignment, + F622 => violations::TwoStarredExpressions, + F631 => violations::AssertTuple, + F632 => violations::IsLiteral, + F633 => violations::InvalidPrintSyntax, + F634 => violations::IfTuple, + F701 => violations::BreakOutsideLoop, + F702 => violations::ContinueOutsideLoop, + F704 => violations::YieldOutsideFunction, + F706 => violations::ReturnOutsideFunction, + F707 => violations::DefaultExceptNotLast, + F722 => violations::ForwardAnnotationSyntaxError, + F811 => violations::RedefinedWhileUnused, + F821 => violations::UndefinedName, + F822 => violations::UndefinedExport, + F823 => violations::UndefinedLocal, + F841 => violations::UnusedVariable, + F842 => violations::UnusedAnnotation, + F901 => violations::RaiseNotImplemented, // pylint - PLC0414, - PLC2201, - PLC3002, - PLE0117, - PLE0118, - PLE1142, - PLR0206, - PLR0402, - PLR1701, - PLR1722, - PLW0120, - PLW0602, + PLC0414 => violations::UselessImportAlias, + PLC2201 => violations::MisplacedComparisonConstant, + PLC3002 => violations::UnnecessaryDirectLambdaCall, + PLE0117 => violations::NonlocalWithoutBinding, + PLE0118 => violations::UsedPriorGlobalDeclaration, + PLE1142 => violations::AwaitOutsideAsync, + PLR0206 => violations::PropertyWithParameters, + PLR0402 => violations::ConsiderUsingFromImport, + PLR1701 => violations::ConsiderMergingIsinstance, + PLR1722 => violations::UseSysExit, + PLW0120 => violations::UselessElseOnLoop, + PLW0602 => violations::GlobalVariableNotAssigned, // flake8-builtins - A001, - A002, - A003, + A001 => violations::BuiltinVariableShadowing, + A002 => violations::BuiltinArgumentShadowing, + A003 => violations::BuiltinAttributeShadowing, // flake8-bugbear - B002, - B003, - B004, - B005, - B006, - B007, - B008, - B009, - B010, - B011, - B012, - B013, - B014, - B015, - B016, - B017, - B018, - B019, - B020, - B021, - B022, - B023, - B024, - B025, - B026, - B027, - B904, - B905, + B002 => violations::UnaryPrefixIncrement, + B003 => violations::AssignmentToOsEnviron, + B004 => violations::UnreliableCallableCheck, + B005 => violations::StripWithMultiCharacters, + B006 => violations::MutableArgumentDefault, + B007 => violations::UnusedLoopControlVariable, + B008 => violations::FunctionCallArgumentDefault, + B009 => violations::GetAttrWithConstant, + B010 => violations::SetAttrWithConstant, + B011 => violations::DoNotAssertFalse, + B012 => violations::JumpStatementInFinally, + B013 => violations::RedundantTupleInExceptionHandler, + B014 => violations::DuplicateHandlerException, + B015 => violations::UselessComparison, + B016 => violations::CannotRaiseLiteral, + B017 => violations::NoAssertRaisesException, + B018 => violations::UselessExpression, + B019 => violations::CachedInstanceMethod, + B020 => violations::LoopVariableOverridesIterator, + B021 => violations::FStringDocstring, + B022 => violations::UselessContextlibSuppress, + B023 => violations::FunctionUsesLoopVariable, + B024 => violations::AbstractBaseClassWithoutAbstractMethod, + B025 => violations::DuplicateTryBlockException, + B026 => violations::StarArgUnpackingAfterKeywordArg, + B027 => violations::EmptyMethodWithoutAbstractDecorator, + B904 => violations::RaiseWithoutFromInsideExcept, + B905 => violations::ZipWithoutExplicitStrict, // flake8-blind-except - BLE001, + BLE001 => violations::BlindExcept, // flake8-comprehensions - C400, - C401, - C402, - C403, - C404, - C405, - C406, - C408, - C409, - C410, - C411, - C413, - C414, - C415, - C416, - C417, + C400 => violations::UnnecessaryGeneratorList, + C401 => violations::UnnecessaryGeneratorSet, + C402 => violations::UnnecessaryGeneratorDict, + C403 => violations::UnnecessaryListComprehensionSet, + C404 => violations::UnnecessaryListComprehensionDict, + C405 => violations::UnnecessaryLiteralSet, + C406 => violations::UnnecessaryLiteralDict, + C408 => violations::UnnecessaryCollectionCall, + C409 => violations::UnnecessaryLiteralWithinTupleCall, + C410 => violations::UnnecessaryLiteralWithinListCall, + C411 => violations::UnnecessaryListCall, + C413 => violations::UnnecessaryCallAroundSorted, + C414 => violations::UnnecessaryDoubleCastOrProcess, + C415 => violations::UnnecessarySubscriptReversal, + C416 => violations::UnnecessaryComprehension, + C417 => violations::UnnecessaryMap, // flake8-debugger - T100, + T100 => violations::Debugger, // mccabe - C901, + C901 => violations::FunctionIsTooComplex, // flake8-tidy-imports - TID251, - TID252, + TID251 => violations::BannedApi, + TID252 => violations::BannedRelativeImport, // flake8-return - RET501, - RET502, - RET503, - RET504, - RET505, - RET506, - RET507, - RET508, + RET501 => violations::UnnecessaryReturnNone, + RET502 => violations::ImplicitReturnValue, + RET503 => violations::ImplicitReturn, + RET504 => violations::UnnecessaryAssign, + RET505 => violations::SuperfluousElseReturn, + RET506 => violations::SuperfluousElseRaise, + RET507 => violations::SuperfluousElseContinue, + RET508 => violations::SuperfluousElseBreak, // flake8-implicit-str-concat - ISC001, - ISC002, - ISC003, + ISC001 => violations::SingleLineImplicitStringConcatenation, + ISC002 => violations::MultiLineImplicitStringConcatenation, + ISC003 => violations::ExplicitStringConcatenation, // flake8-print - T201, - T203, + T201 => violations::PrintFound, + T203 => violations::PPrintFound, // flake8-quotes - Q000, - Q001, - Q002, - Q003, + Q000 => violations::BadQuotesInlineString, + Q001 => violations::BadQuotesMultilineString, + Q002 => violations::BadQuotesDocstring, + Q003 => violations::AvoidQuoteEscape, // flake8-annotations - ANN001, - ANN002, - ANN003, - ANN101, - ANN102, - ANN201, - ANN202, - ANN204, - ANN205, - ANN206, - ANN401, + ANN001 => violations::MissingTypeFunctionArgument, + ANN002 => violations::MissingTypeArgs, + ANN003 => violations::MissingTypeKwargs, + ANN101 => violations::MissingTypeSelf, + ANN102 => violations::MissingTypeCls, + ANN201 => violations::MissingReturnTypePublicFunction, + ANN202 => violations::MissingReturnTypePrivateFunction, + ANN204 => violations::MissingReturnTypeSpecialMethod, + ANN205 => violations::MissingReturnTypeStaticMethod, + ANN206 => violations::MissingReturnTypeClassMethod, + ANN401 => violations::DynamicallyTypedExpression, // flake8-2020 - YTT101, - YTT102, - YTT103, - YTT201, - YTT202, - YTT203, - YTT204, - YTT301, - YTT302, - YTT303, + YTT101 => violations::SysVersionSlice3Referenced, + YTT102 => violations::SysVersion2Referenced, + YTT103 => violations::SysVersionCmpStr3, + YTT201 => violations::SysVersionInfo0Eq3Referenced, + YTT202 => violations::SixPY3Referenced, + YTT203 => violations::SysVersionInfo1CmpInt, + YTT204 => violations::SysVersionInfoMinorCmpInt, + YTT301 => violations::SysVersion0Referenced, + YTT302 => violations::SysVersionCmpStr10, + YTT303 => violations::SysVersionSlice1Referenced, // flake8-simplify - SIM101, - SIM102, - SIM103, - SIM105, - SIM107, - SIM108, - SIM109, - SIM110, - SIM111, - SIM117, - SIM118, - SIM201, - SIM202, - SIM208, - SIM210, - SIM211, - SIM212, - SIM220, - SIM221, - SIM222, - SIM223, - SIM300, + SIM101 => violations::DuplicateIsinstanceCall, + SIM102 => violations::NestedIfStatements, + SIM103 => violations::ReturnBoolConditionDirectly, + SIM105 => violations::UseContextlibSuppress, + SIM107 => violations::ReturnInTryExceptFinally, + SIM108 => violations::UseTernaryOperator, + SIM109 => violations::CompareWithTuple, + SIM110 => violations::ConvertLoopToAny, + SIM111 => violations::ConvertLoopToAll, + SIM117 => violations::MultipleWithStatements, + SIM118 => violations::KeyInDict, + SIM201 => violations::NegateEqualOp, + SIM202 => violations::NegateNotEqualOp, + SIM208 => violations::DoubleNegation, + SIM210 => violations::IfExprWithTrueFalse, + SIM211 => violations::IfExprWithFalseTrue, + SIM212 => violations::IfExprWithTwistedArms, + SIM220 => violations::AAndNotA, + SIM221 => violations::AOrNotA, + SIM222 => violations::OrTrue, + SIM223 => violations::AndFalse, + SIM300 => violations::YodaConditions, // pyupgrade - UP001, - UP003, - UP004, - UP005, - UP006, - UP007, - UP008, - UP009, - UP010, - UP011, - UP012, - UP013, - UP014, - UP015, - UP016, - UP017, - UP018, - UP019, - UP020, - UP021, - UP022, - UP023, - UP024, - UP025, - UP026, - UP027, - UP028, - UP029, + UP001 => violations::UselessMetaclassType, + UP003 => violations::TypeOfPrimitive, + UP004 => violations::UselessObjectInheritance, + UP005 => violations::DeprecatedUnittestAlias, + UP006 => violations::UsePEP585Annotation, + UP007 => violations::UsePEP604Annotation, + UP008 => violations::SuperCallWithParameters, + UP009 => violations::PEP3120UnnecessaryCodingComment, + UP010 => violations::UnnecessaryFutureImport, + UP011 => violations::UnnecessaryLRUCacheParams, + UP012 => violations::UnnecessaryEncodeUTF8, + UP013 => violations::ConvertTypedDictFunctionalToClass, + UP014 => violations::ConvertNamedTupleFunctionalToClass, + UP015 => violations::RedundantOpenModes, + UP016 => violations::RemoveSixCompat, + UP017 => violations::DatetimeTimezoneUTC, + UP018 => violations::NativeLiterals, + UP019 => violations::TypingTextStrAlias, + UP020 => violations::OpenAlias, + UP021 => violations::ReplaceUniversalNewlines, + UP022 => violations::ReplaceStdoutStderr, + UP023 => violations::RewriteCElementTree, + UP024 => violations::OSErrorAlias, + UP025 => violations::RewriteUnicodeLiteral, + UP026 => violations::RewriteMockImport, + UP027 => violations::RewriteListComprehension, + UP028 => violations::RewriteYieldFrom, + UP029 => violations::UnnecessaryBuiltinImport, // pydocstyle - D100, - D101, - D102, - D103, - D104, - D105, - D106, - D107, - D200, - D201, - D202, - D203, - D204, - D205, - D206, - D207, - D208, - D209, - D210, - D211, - D212, - D213, - D214, - D215, - D300, - D301, - D400, - D402, - D403, - D404, - D405, - D406, - D407, - D408, - D409, - D410, - D411, - D412, - D413, - D414, - D415, - D416, - D417, - D418, - D419, + D100 => violations::PublicModule, + D101 => violations::PublicClass, + D102 => violations::PublicMethod, + D103 => violations::PublicFunction, + D104 => violations::PublicPackage, + D105 => violations::MagicMethod, + D106 => violations::PublicNestedClass, + D107 => violations::PublicInit, + D200 => violations::FitsOnOneLine, + D201 => violations::NoBlankLineBeforeFunction, + D202 => violations::NoBlankLineAfterFunction, + D203 => violations::OneBlankLineBeforeClass, + D204 => violations::OneBlankLineAfterClass, + D205 => violations::BlankLineAfterSummary, + D206 => violations::IndentWithSpaces, + D207 => violations::NoUnderIndentation, + D208 => violations::NoOverIndentation, + D209 => violations::NewLineAfterLastParagraph, + D210 => violations::NoSurroundingWhitespace, + D211 => violations::NoBlankLineBeforeClass, + D212 => violations::MultiLineSummaryFirstLine, + D213 => violations::MultiLineSummarySecondLine, + D214 => violations::SectionNotOverIndented, + D215 => violations::SectionUnderlineNotOverIndented, + D300 => violations::UsesTripleQuotes, + D301 => violations::UsesRPrefixForBackslashedContent, + D400 => violations::EndsInPeriod, + D402 => violations::NoSignature, + D403 => violations::FirstLineCapitalized, + D404 => violations::NoThisPrefix, + D405 => violations::CapitalizeSectionName, + D406 => violations::NewLineAfterSectionName, + D407 => violations::DashedUnderlineAfterSection, + D408 => violations::SectionUnderlineAfterName, + D409 => violations::SectionUnderlineMatchesSectionLength, + D410 => violations::BlankLineAfterSection, + D411 => violations::BlankLineBeforeSection, + D412 => violations::NoBlankLinesBetweenHeaderAndContent, + D413 => violations::BlankLineAfterLastSection, + D414 => violations::NonEmptySection, + D415 => violations::EndsInPunctuation, + D416 => violations::SectionNameEndsInColon, + D417 => violations::DocumentAllArguments, + D418 => violations::SkipDocstring, + D419 => violations::NonEmpty, // pep8-naming - N801, - N802, - N803, - N804, - N805, - N806, - N807, - N811, - N812, - N813, - N814, - N815, - N816, - N817, - N818, + N801 => violations::InvalidClassName, + N802 => violations::InvalidFunctionName, + N803 => violations::InvalidArgumentName, + N804 => violations::InvalidFirstArgumentNameForClassMethod, + N805 => violations::InvalidFirstArgumentNameForMethod, + N806 => violations::NonLowercaseVariableInFunction, + N807 => violations::DunderFunctionName, + N811 => violations::ConstantImportedAsNonConstant, + N812 => violations::LowercaseImportedAsNonLowercase, + N813 => violations::CamelcaseImportedAsLowercase, + N814 => violations::CamelcaseImportedAsConstant, + N815 => violations::MixedCaseVariableInClassScope, + N816 => violations::MixedCaseVariableInGlobalScope, + N817 => violations::CamelcaseImportedAsAcronym, + N818 => violations::ErrorSuffixOnExceptionName, // isort - I001, + I001 => violations::UnsortedImports, // eradicate - ERA001, + ERA001 => violations::CommentedOutCode, // flake8-bandit - S101, - S102, - S103, - S104, - S105, - S106, - S107, - S108, - S113, - S324, - S501, - S506, + S101 => violations::AssertUsed, + S102 => violations::ExecUsed, + S103 => violations::BadFilePermissions, + S104 => violations::HardcodedBindAllInterfaces, + S105 => violations::HardcodedPasswordString, + S106 => violations::HardcodedPasswordFuncArg, + S107 => violations::HardcodedPasswordDefault, + S108 => violations::HardcodedTempFile, + S113 => violations::RequestWithoutTimeout, + S324 => violations::HashlibInsecureHashFunction, + S501 => violations::RequestWithNoCertValidation, + S506 => violations::UnsafeYAMLLoad, // flake8-boolean-trap - FBT001, - FBT002, - FBT003, + FBT001 => violations::BooleanPositionalArgInFunctionDefinition, + FBT002 => violations::BooleanDefaultValueInFunctionDefinition, + FBT003 => violations::BooleanPositionalValueInFunctionCall, // flake8-unused-arguments - ARG001, - ARG002, - ARG003, - ARG004, - ARG005, + ARG001 => violations::UnusedFunctionArgument, + ARG002 => violations::UnusedMethodArgument, + ARG003 => violations::UnusedClassMethodArgument, + ARG004 => violations::UnusedStaticMethodArgument, + ARG005 => violations::UnusedLambdaArgument, // flake8-import-conventions - ICN001, + ICN001 => violations::ImportAliasIsNotConventional, // flake8-datetimez - DTZ001, - DTZ002, - DTZ003, - DTZ004, - DTZ005, - DTZ006, - DTZ007, - DTZ011, - DTZ012, + DTZ001 => violations::CallDatetimeWithoutTzinfo, + DTZ002 => violations::CallDatetimeToday, + DTZ003 => violations::CallDatetimeUtcnow, + DTZ004 => violations::CallDatetimeUtcfromtimestamp, + DTZ005 => violations::CallDatetimeNowWithoutTzinfo, + DTZ006 => violations::CallDatetimeFromtimestamp, + DTZ007 => violations::CallDatetimeStrptimeWithoutZone, + DTZ011 => violations::CallDateToday, + DTZ012 => violations::CallDateFromtimestamp, // pygrep-hooks - PGH001, - PGH002, - PGH003, - PGH004, + PGH001 => violations::NoEval, + PGH002 => violations::DeprecatedLogWarn, + PGH003 => violations::BlanketTypeIgnore, + PGH004 => violations::BlanketNOQA, // pandas-vet - PD002, - PD003, - PD004, - PD007, - PD008, - PD009, - PD010, - PD011, - PD012, - PD013, - PD015, - PD901, + PD002 => violations::UseOfInplaceArgument, + PD003 => violations::UseOfDotIsNull, + PD004 => violations::UseOfDotNotNull, + PD007 => violations::UseOfDotIx, + PD008 => violations::UseOfDotAt, + PD009 => violations::UseOfDotIat, + PD010 => violations::UseOfDotPivotOrUnstack, + PD011 => violations::UseOfDotValues, + PD012 => violations::UseOfDotReadTable, + PD013 => violations::UseOfDotStack, + PD015 => violations::UseOfPdMerge, + PD901 => violations::DfIsABadVariableName, // flake8-errmsg - EM101, - EM102, - EM103, + EM101 => violations::RawStringInException, + EM102 => violations::FStringInException, + EM103 => violations::DotFormatInException, // flake8-pytest-style - PT001, - PT002, - PT003, - PT004, - PT005, - PT006, - PT007, - PT008, - PT009, - PT010, - PT011, - PT012, - PT013, - PT015, - PT016, - PT017, - PT018, - PT019, - PT020, - PT021, - PT022, - PT023, - PT024, - PT025, - PT026, + PT001 => violations::IncorrectFixtureParenthesesStyle, + PT002 => violations::FixturePositionalArgs, + PT003 => violations::ExtraneousScopeFunction, + PT004 => violations::MissingFixtureNameUnderscore, + PT005 => violations::IncorrectFixtureNameUnderscore, + PT006 => violations::ParametrizeNamesWrongType, + PT007 => violations::ParametrizeValuesWrongType, + PT008 => violations::PatchWithLambda, + PT009 => violations::UnittestAssertion, + PT010 => violations::RaisesWithoutException, + PT011 => violations::RaisesTooBroad, + PT012 => violations::RaisesWithMultipleStatements, + PT013 => violations::IncorrectPytestImport, + PT015 => violations::AssertAlwaysFalse, + PT016 => violations::FailWithoutMessage, + PT017 => violations::AssertInExcept, + PT018 => violations::CompositeAssertion, + PT019 => violations::FixtureParamWithoutValue, + PT020 => violations::DeprecatedYieldFixture, + PT021 => violations::FixtureFinalizerCallback, + PT022 => violations::UselessYieldFixture, + PT023 => violations::IncorrectMarkParenthesesStyle, + PT024 => violations::UnnecessaryAsyncioMarkOnFixture, + PT025 => violations::ErroneousUseFixturesOnFixture, + PT026 => violations::UseFixturesWithoutParameters, // flake8-pie - PIE790, - PIE794, - PIE807, + PIE790 => violations::NoUnnecessaryPass, + PIE794 => violations::DupeClassFieldDefinitions, + PIE807 => violations::PreferListBuiltin, // Ruff - RUF001, - RUF002, - RUF003, - RUF004, - RUF100, -} + RUF001 => violations::AmbiguousUnicodeCharacterString, + RUF002 => violations::AmbiguousUnicodeCharacterDocstring, + RUF003 => violations::AmbiguousUnicodeCharacterComment, + RUF004 => violations::KeywordArgumentBeforeStarArgument, + RUF100 => violations::UnusedNOQA, +); #[derive(EnumIter, Debug, PartialEq, Eq)] pub enum CheckCategory { @@ -791,400 +864,6 @@ pub enum MockReference { Attribute, } -#[derive(AsRefStr, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum CheckKind { - // pycodestyle errors - AmbiguousClassName(String), - AmbiguousFunctionName(String), - AmbiguousVariableName(String), - DoNotAssignLambda(String), - DoNotUseBareExcept, - IOError(String), - LineTooLong(usize, usize), - ModuleImportNotAtTopOfFile, - MultipleImportsOnOneLine, - NoneComparison(EqCmpop), - NotInTest, - NotIsTest, - SyntaxError(String), - TrueFalseComparison(bool, EqCmpop), - TypeComparison, - // pycodestyle warnings - NoNewLineAtEndOfFile, - InvalidEscapeSequence(char), - // pyflakes - AssertTuple, - BreakOutsideLoop, - ContinueOutsideLoop, - DefaultExceptNotLast, - ExpressionsInStarAssignment, - FStringMissingPlaceholders, - ForwardAnnotationSyntaxError(String), - FutureFeatureNotDefined(String), - IfTuple, - ImportShadowedByLoopVar(String, usize), - ImportStarNotPermitted(String), - ImportStarUsage(String, Vec), - ImportStarUsed(String), - InvalidPrintSyntax, - IsLiteral(IsCmpop), - LateFutureImport, - MultiValueRepeatedKeyLiteral, - MultiValueRepeatedKeyVariable(String), - PercentFormatExpectedMapping, - PercentFormatExpectedSequence, - PercentFormatExtraNamedArguments(Vec), - PercentFormatInvalidFormat(String), - PercentFormatMissingArgument(Vec), - PercentFormatMixedPositionalAndNamed, - PercentFormatPositionalCountMismatch(usize, usize), - PercentFormatStarRequiresSequence, - PercentFormatUnsupportedFormatCharacter(char), - RaiseNotImplemented, - RedefinedWhileUnused(String, usize), - ReturnOutsideFunction, - StringDotFormatExtraNamedArguments(Vec), - StringDotFormatExtraPositionalArguments(Vec), - StringDotFormatInvalidFormat(String), - StringDotFormatMissingArguments(Vec), - StringDotFormatMixingAutomatic, - TwoStarredExpressions, - UndefinedExport(String), - UndefinedLocal(String), - UnusedAnnotation(String), - UndefinedName(String), - UnusedImport(String, bool, bool), - UnusedVariable(String), - YieldOutsideFunction(DeferralKeyword), - // pylint - AwaitOutsideAsync, - ConsiderMergingIsinstance(String, Vec), - ConsiderUsingFromImport(String, String), - GlobalVariableNotAssigned(String), - MisplacedComparisonConstant(String), - NonlocalWithoutBinding(String), - PropertyWithParameters, - UnnecessaryDirectLambdaCall, - UseSysExit(String), - UsedPriorGlobalDeclaration(String, usize), - UselessElseOnLoop, - UselessImportAlias, - // flake8-builtins - BuiltinVariableShadowing(String), - BuiltinArgumentShadowing(String), - BuiltinAttributeShadowing(String), - // flake8-blind-except - BlindExcept(String), - // flake8-bugbear - AbstractBaseClassWithoutAbstractMethod(String), - AssignmentToOsEnviron, - CachedInstanceMethod, - CannotRaiseLiteral, - DoNotAssertFalse, - DuplicateHandlerException(Vec), - DuplicateTryBlockException(String), - EmptyMethodWithoutAbstractDecorator(String), - FStringDocstring, - FunctionCallArgumentDefault(Option), - FunctionUsesLoopVariable(String), - GetAttrWithConstant, - JumpStatementInFinally(String), - LoopVariableOverridesIterator(String), - MutableArgumentDefault, - NoAssertRaisesException, - RaiseWithoutFromInsideExcept, - RedundantTupleInExceptionHandler(String), - SetAttrWithConstant, - StarArgUnpackingAfterKeywordArg, - StripWithMultiCharacters, - UnaryPrefixIncrement, - UnreliableCallableCheck, - UnusedLoopControlVariable(String), - UselessComparison, - UselessContextlibSuppress, - UselessExpression, - ZipWithoutExplicitStrict, - // flake8-comprehensions - UnnecessaryGeneratorList, - UnnecessaryGeneratorSet, - UnnecessaryGeneratorDict, - UnnecessaryListComprehensionSet, - UnnecessaryListComprehensionDict, - UnnecessaryLiteralSet(String), - UnnecessaryLiteralDict(String), - UnnecessaryCollectionCall(String), - UnnecessaryLiteralWithinTupleCall(String), - UnnecessaryLiteralWithinListCall(String), - UnnecessaryListCall, - UnnecessaryCallAroundSorted(String), - UnnecessaryDoubleCastOrProcess(String, String), - UnnecessarySubscriptReversal(String), - UnnecessaryComprehension(String), - UnnecessaryMap(String), - // flake8-debugger - Debugger(DebuggerUsingType), - // flake8-tidy-imports - BannedApi { name: String, message: String }, - BannedRelativeImport(Strictness), - // flake8-return - UnnecessaryReturnNone, - ImplicitReturnValue, - ImplicitReturn, - UnnecessaryAssign, - SuperfluousElseReturn(Branch), - SuperfluousElseRaise(Branch), - SuperfluousElseContinue(Branch), - SuperfluousElseBreak(Branch), - // flake8-implicit-str-concat - SingleLineImplicitStringConcatenation, - MultiLineImplicitStringConcatenation, - ExplicitStringConcatenation, - // flake8-print - PrintFound, - PPrintFound, - // flake8-quotes - BadQuotesInlineString(Quote), - BadQuotesMultilineString(Quote), - BadQuotesDocstring(Quote), - AvoidQuoteEscape, - // flake8-annotations - MissingTypeFunctionArgument(String), - MissingTypeArgs(String), - MissingTypeKwargs(String), - MissingTypeSelf(String), - MissingTypeCls(String), - MissingReturnTypePublicFunction(String), - MissingReturnTypePrivateFunction(String), - MissingReturnTypeSpecialMethod(String), - MissingReturnTypeStaticMethod(String), - MissingReturnTypeClassMethod(String), - DynamicallyTypedExpression(String), - // flake8-2020 - SysVersionSlice3Referenced, - SysVersion2Referenced, - SysVersionCmpStr3, - SysVersionInfo0Eq3Referenced, - SixPY3Referenced, - SysVersionInfo1CmpInt, - SysVersionInfoMinorCmpInt, - SysVersion0Referenced, - SysVersionCmpStr10, - SysVersionSlice1Referenced, - // flake8-simplify - ReturnBoolConditionDirectly(String), - UseTernaryOperator(String), - CompareWithTuple(String, Vec, String), - DuplicateIsinstanceCall(String), - AAndNotA(String), - AOrNotA(String), - NegateEqualOp(String, String), - NegateNotEqualOp(String, String), - DoubleNegation(String), - IfExprWithTrueFalse(String), - IfExprWithFalseTrue(String), - IfExprWithTwistedArms(String, String), - AndFalse, - ConvertLoopToAll(String), - ConvertLoopToAny(String), - KeyInDict(String, String), - MultipleWithStatements, - NestedIfStatements, - OrTrue, - ReturnInTryExceptFinally, - UseContextlibSuppress(String), - YodaConditions(String, String), - // pyupgrade - ConvertNamedTupleFunctionalToClass(String), - ConvertTypedDictFunctionalToClass(String), - DatetimeTimezoneUTC, - DeprecatedUnittestAlias(String, String), - NativeLiterals(LiteralType), - OSErrorAlias(Option), - OpenAlias, - PEP3120UnnecessaryCodingComment, - RedundantOpenModes(Option), - RemoveSixCompat, - ReplaceStdoutStderr, - ReplaceUniversalNewlines, - RewriteCElementTree, - RewriteListComprehension, - RewriteMockImport(MockReference), - RewriteUnicodeLiteral, - RewriteYieldFrom, - SuperCallWithParameters, - TypeOfPrimitive(Primitive), - TypingTextStrAlias, - UnnecessaryBuiltinImport(Vec), - UnnecessaryEncodeUTF8, - UnnecessaryFutureImport(Vec), - UnnecessaryLRUCacheParams, - UsePEP585Annotation(String), - UsePEP604Annotation, - UselessMetaclassType, - UselessObjectInheritance(String), - // pydocstyle - BlankLineAfterLastSection(String), - BlankLineAfterSection(String), - BlankLineAfterSummary(usize), - BlankLineBeforeSection(String), - CapitalizeSectionName(String), - DashedUnderlineAfterSection(String), - DocumentAllArguments(Vec), - EndsInPeriod, - EndsInPunctuation, - FirstLineCapitalized, - FitsOnOneLine, - IndentWithSpaces, - MagicMethod, - MultiLineSummaryFirstLine, - MultiLineSummarySecondLine, - NewLineAfterLastParagraph, - NewLineAfterSectionName(String), - NoBlankLineAfterFunction(usize), - NoBlankLineBeforeClass(usize), - NoBlankLineBeforeFunction(usize), - NoBlankLinesBetweenHeaderAndContent(String), - NoOverIndentation, - NoSignature, - NoSurroundingWhitespace, - NoThisPrefix, - NoUnderIndentation, - NonEmpty, - NonEmptySection(String), - OneBlankLineAfterClass(usize), - OneBlankLineBeforeClass(usize), - PublicClass, - PublicFunction, - PublicInit, - PublicMethod, - PublicModule, - PublicNestedClass, - PublicPackage, - SectionNameEndsInColon(String), - SectionNotOverIndented(String), - SectionUnderlineAfterName(String), - SectionUnderlineMatchesSectionLength(String), - SectionUnderlineNotOverIndented(String), - SkipDocstring, - UsesRPrefixForBackslashedContent, - UsesTripleQuotes, - // pep8-naming - InvalidClassName(String), - InvalidFunctionName(String), - InvalidArgumentName(String), - InvalidFirstArgumentNameForClassMethod, - InvalidFirstArgumentNameForMethod, - NonLowercaseVariableInFunction(String), - DunderFunctionName, - ConstantImportedAsNonConstant(String, String), - LowercaseImportedAsNonLowercase(String, String), - CamelcaseImportedAsLowercase(String, String), - CamelcaseImportedAsConstant(String, String), - MixedCaseVariableInClassScope(String), - MixedCaseVariableInGlobalScope(String), - CamelcaseImportedAsAcronym(String, String), - ErrorSuffixOnExceptionName(String), - // isort - UnsortedImports, - // eradicate - CommentedOutCode, - // flake8-bandit - AssertUsed, - ExecUsed, - BadFilePermissions(u16), - HardcodedBindAllInterfaces, - HardcodedPasswordString(String), - HardcodedPasswordFuncArg(String), - HardcodedPasswordDefault(String), - HardcodedTempFile(String), - HashlibInsecureHashFunction(String), - RequestWithoutTimeout(Option), - RequestWithNoCertValidation(String), - UnsafeYAMLLoad(Option), - // mccabe - FunctionIsTooComplex(String, usize), - // flake8-boolean-trap - BooleanPositionalArgInFunctionDefinition, - BooleanDefaultValueInFunctionDefinition, - BooleanPositionalValueInFunctionCall, - // pygrep-hooks - NoEval, - DeprecatedLogWarn, - BlanketTypeIgnore, - BlanketNOQA, - // flake8-unused-arguments - UnusedFunctionArgument(String), - UnusedMethodArgument(String), - UnusedClassMethodArgument(String), - UnusedStaticMethodArgument(String), - UnusedLambdaArgument(String), - // flake8-import-conventions - ImportAliasIsNotConventional(String, String), - // pandas-vet - UseOfInplaceArgument, - UseOfDotIsNull, - UseOfDotNotNull, - UseOfDotIx, - UseOfDotAt, - UseOfDotIat, - UseOfDotPivotOrUnstack, - UseOfDotValues, - UseOfDotReadTable, - UseOfDotStack, - UseOfPdMerge, - DfIsABadVariableName, - // flake8-errmsg - RawStringInException, - FStringInException, - DotFormatInException, - // flake8-datetimez - CallDatetimeWithoutTzinfo, - CallDatetimeToday, - CallDatetimeUtcnow, - CallDatetimeUtcfromtimestamp, - CallDatetimeNowWithoutTzinfo, - CallDatetimeFromtimestamp, - CallDatetimeStrptimeWithoutZone, - CallDateToday, - CallDateFromtimestamp, - // flake8-pytest-style - IncorrectFixtureParenthesesStyle(String, String), - FixturePositionalArgs(String), - ExtraneousScopeFunction, - MissingFixtureNameUnderscore(String), - IncorrectFixtureNameUnderscore(String), - ParametrizeNamesWrongType(ParametrizeNameType), - ParametrizeValuesWrongType(ParametrizeValuesType, ParametrizeValuesRowType), - PatchWithLambda, - UnittestAssertion(String), - RaisesWithoutException, - RaisesTooBroad(String), - RaisesWithMultipleStatements, - IncorrectPytestImport, - AssertAlwaysFalse, - FailWithoutMessage, - AssertInExcept(String), - CompositeAssertion, - FixtureParamWithoutValue(String), - DeprecatedYieldFixture, - FixtureFinalizerCallback, - UselessYieldFixture(String), - IncorrectMarkParenthesesStyle(String, String, String), - UnnecessaryAsyncioMarkOnFixture, - ErroneousUseFixturesOnFixture, - UseFixturesWithoutParameters, - // flake8-pie - DupeClassFieldDefinitions(String), - NoUnnecessaryPass, - PreferListBuiltin, - // Ruff - AmbiguousUnicodeCharacterString(char, char), - AmbiguousUnicodeCharacterDocstring(char, char), - AmbiguousUnicodeCharacterComment(char, char), - KeywordArgumentBeforeStarArgument(String), - UnusedNOQA(Option), -} - impl CheckCode { /// The source for the check (either the AST, the filesystem, or the /// physical lines). @@ -1213,475 +892,6 @@ impl CheckCode { } } - /// A placeholder representation of the `CheckKind` for the check. - pub fn kind(&self) -> CheckKind { - match self { - // pycodestyle (errors) - CheckCode::E401 => CheckKind::MultipleImportsOnOneLine, - CheckCode::E402 => CheckKind::ModuleImportNotAtTopOfFile, - CheckCode::E501 => CheckKind::LineTooLong(89, 88), - CheckCode::E711 => CheckKind::NoneComparison(EqCmpop::Eq), - CheckCode::E712 => CheckKind::TrueFalseComparison(true, EqCmpop::Eq), - CheckCode::E713 => CheckKind::NotInTest, - CheckCode::E714 => CheckKind::NotIsTest, - CheckCode::E721 => CheckKind::TypeComparison, - CheckCode::E722 => CheckKind::DoNotUseBareExcept, - CheckCode::E731 => CheckKind::DoNotAssignLambda("...".to_string()), - CheckCode::E741 => CheckKind::AmbiguousVariableName("...".to_string()), - CheckCode::E742 => CheckKind::AmbiguousClassName("...".to_string()), - CheckCode::E743 => CheckKind::AmbiguousFunctionName("...".to_string()), - CheckCode::E902 => CheckKind::IOError("IOError: `...`".to_string()), - CheckCode::E999 => CheckKind::SyntaxError("`...`".to_string()), - // pycodestyle (warnings) - CheckCode::W292 => CheckKind::NoNewLineAtEndOfFile, - CheckCode::W605 => CheckKind::InvalidEscapeSequence('c'), - // pyflakes - CheckCode::F401 => CheckKind::UnusedImport("...".to_string(), false, false), - CheckCode::F402 => CheckKind::ImportShadowedByLoopVar("...".to_string(), 1), - CheckCode::F403 => CheckKind::ImportStarUsed("...".to_string()), - CheckCode::F404 => CheckKind::LateFutureImport, - CheckCode::F405 => { - CheckKind::ImportStarUsage("...".to_string(), vec!["...".to_string()]) - } - CheckCode::F406 => CheckKind::ImportStarNotPermitted("...".to_string()), - CheckCode::F407 => CheckKind::FutureFeatureNotDefined("...".to_string()), - CheckCode::F501 => CheckKind::PercentFormatInvalidFormat("...".to_string()), - CheckCode::F502 => CheckKind::PercentFormatExpectedMapping, - CheckCode::F503 => CheckKind::PercentFormatExpectedSequence, - CheckCode::F504 => CheckKind::PercentFormatExtraNamedArguments(vec!["...".to_string()]), - CheckCode::F505 => CheckKind::PercentFormatMissingArgument(vec!["...".to_string()]), - CheckCode::F506 => CheckKind::PercentFormatMixedPositionalAndNamed, - CheckCode::F507 => CheckKind::PercentFormatPositionalCountMismatch(4, 2), - CheckCode::F508 => CheckKind::PercentFormatStarRequiresSequence, - CheckCode::F509 => CheckKind::PercentFormatUnsupportedFormatCharacter('c'), - CheckCode::F521 => CheckKind::StringDotFormatInvalidFormat("...".to_string()), - CheckCode::F522 => { - CheckKind::StringDotFormatExtraNamedArguments(vec!["...".to_string()]) - } - CheckCode::F523 => { - CheckKind::StringDotFormatExtraPositionalArguments(vec!["...".to_string()]) - } - CheckCode::F524 => CheckKind::StringDotFormatMissingArguments(vec!["...".to_string()]), - CheckCode::F525 => CheckKind::StringDotFormatMixingAutomatic, - CheckCode::F541 => CheckKind::FStringMissingPlaceholders, - CheckCode::F601 => CheckKind::MultiValueRepeatedKeyLiteral, - CheckCode::F602 => CheckKind::MultiValueRepeatedKeyVariable("...".to_string()), - CheckCode::F621 => CheckKind::ExpressionsInStarAssignment, - CheckCode::F622 => CheckKind::TwoStarredExpressions, - CheckCode::F631 => CheckKind::AssertTuple, - CheckCode::F632 => CheckKind::IsLiteral(IsCmpop::Is), - CheckCode::F633 => CheckKind::InvalidPrintSyntax, - CheckCode::F634 => CheckKind::IfTuple, - CheckCode::F701 => CheckKind::BreakOutsideLoop, - CheckCode::F702 => CheckKind::ContinueOutsideLoop, - CheckCode::F704 => CheckKind::YieldOutsideFunction(DeferralKeyword::Yield), - CheckCode::F706 => CheckKind::ReturnOutsideFunction, - CheckCode::F707 => CheckKind::DefaultExceptNotLast, - CheckCode::F722 => CheckKind::ForwardAnnotationSyntaxError("...".to_string()), - CheckCode::F811 => CheckKind::RedefinedWhileUnused("...".to_string(), 1), - CheckCode::F821 => CheckKind::UndefinedName("...".to_string()), - CheckCode::F822 => CheckKind::UndefinedExport("...".to_string()), - CheckCode::F823 => CheckKind::UndefinedLocal("...".to_string()), - CheckCode::F841 => CheckKind::UnusedVariable("...".to_string()), - CheckCode::F842 => CheckKind::UnusedAnnotation("...".to_string()), - CheckCode::F901 => CheckKind::RaiseNotImplemented, - // pylint - CheckCode::PLC0414 => CheckKind::UselessImportAlias, - CheckCode::PLC2201 => CheckKind::MisplacedComparisonConstant("...".to_string()), - CheckCode::PLC3002 => CheckKind::UnnecessaryDirectLambdaCall, - CheckCode::PLE0117 => CheckKind::NonlocalWithoutBinding("...".to_string()), - CheckCode::PLE0118 => CheckKind::UsedPriorGlobalDeclaration("...".to_string(), 1), - CheckCode::PLE1142 => CheckKind::AwaitOutsideAsync, - CheckCode::PLR0402 => { - CheckKind::ConsiderUsingFromImport("...".to_string(), "...".to_string()) - } - CheckCode::PLR0206 => CheckKind::PropertyWithParameters, - CheckCode::PLR1701 => { - CheckKind::ConsiderMergingIsinstance("...".to_string(), vec!["...".to_string()]) - } - CheckCode::PLR1722 => CheckKind::UseSysExit("exit".to_string()), - CheckCode::PLW0120 => CheckKind::UselessElseOnLoop, - CheckCode::PLW0602 => CheckKind::GlobalVariableNotAssigned("...".to_string()), - // flake8-builtins - CheckCode::A001 => CheckKind::BuiltinVariableShadowing("...".to_string()), - CheckCode::A002 => CheckKind::BuiltinArgumentShadowing("...".to_string()), - CheckCode::A003 => CheckKind::BuiltinAttributeShadowing("...".to_string()), - // flake8-bugbear - CheckCode::B002 => CheckKind::UnaryPrefixIncrement, - CheckCode::B003 => CheckKind::AssignmentToOsEnviron, - CheckCode::B004 => CheckKind::UnreliableCallableCheck, - CheckCode::B005 => CheckKind::StripWithMultiCharacters, - CheckCode::B006 => CheckKind::MutableArgumentDefault, - CheckCode::B007 => CheckKind::UnusedLoopControlVariable("i".to_string()), - CheckCode::B008 => CheckKind::FunctionCallArgumentDefault(None), - CheckCode::B009 => CheckKind::GetAttrWithConstant, - CheckCode::B010 => CheckKind::SetAttrWithConstant, - CheckCode::B011 => CheckKind::DoNotAssertFalse, - CheckCode::B012 => { - CheckKind::JumpStatementInFinally("return/continue/break".to_string()) - } - CheckCode::B013 => { - CheckKind::RedundantTupleInExceptionHandler("ValueError".to_string()) - } - CheckCode::B014 => CheckKind::DuplicateHandlerException(vec!["ValueError".to_string()]), - CheckCode::B015 => CheckKind::UselessComparison, - CheckCode::B016 => CheckKind::CannotRaiseLiteral, - CheckCode::B017 => CheckKind::NoAssertRaisesException, - CheckCode::B018 => CheckKind::UselessExpression, - CheckCode::B019 => CheckKind::CachedInstanceMethod, - CheckCode::B020 => CheckKind::LoopVariableOverridesIterator("...".to_string()), - CheckCode::B021 => CheckKind::FStringDocstring, - CheckCode::B022 => CheckKind::UselessContextlibSuppress, - CheckCode::B023 => CheckKind::FunctionUsesLoopVariable("...".to_string()), - CheckCode::B024 => CheckKind::AbstractBaseClassWithoutAbstractMethod("...".to_string()), - CheckCode::B025 => CheckKind::DuplicateTryBlockException("Exception".to_string()), - CheckCode::B026 => CheckKind::StarArgUnpackingAfterKeywordArg, - CheckCode::B027 => CheckKind::EmptyMethodWithoutAbstractDecorator("...".to_string()), - CheckCode::B904 => CheckKind::RaiseWithoutFromInsideExcept, - CheckCode::B905 => CheckKind::ZipWithoutExplicitStrict, - // flake8-comprehensions - CheckCode::C400 => CheckKind::UnnecessaryGeneratorList, - CheckCode::C401 => CheckKind::UnnecessaryGeneratorSet, - CheckCode::C402 => CheckKind::UnnecessaryGeneratorDict, - CheckCode::C403 => CheckKind::UnnecessaryListComprehensionSet, - CheckCode::C404 => CheckKind::UnnecessaryListComprehensionDict, - CheckCode::C405 => CheckKind::UnnecessaryLiteralSet("(list|tuple)".to_string()), - CheckCode::C406 => CheckKind::UnnecessaryLiteralDict("(list|tuple)".to_string()), - CheckCode::C408 => { - CheckKind::UnnecessaryCollectionCall("(dict|list|tuple)".to_string()) - } - CheckCode::C409 => { - CheckKind::UnnecessaryLiteralWithinTupleCall("(list|tuple)".to_string()) - } - CheckCode::C410 => { - CheckKind::UnnecessaryLiteralWithinListCall("(list|tuple)".to_string()) - } - CheckCode::C411 => CheckKind::UnnecessaryListCall, - CheckCode::C413 => { - CheckKind::UnnecessaryCallAroundSorted("(list|reversed)".to_string()) - } - CheckCode::C414 => CheckKind::UnnecessaryDoubleCastOrProcess( - "(list|reversed|set|sorted|tuple)".to_string(), - "(list|set|sorted|tuple)".to_string(), - ), - CheckCode::C415 => { - CheckKind::UnnecessarySubscriptReversal("(reversed|set|sorted)".to_string()) - } - CheckCode::C416 => CheckKind::UnnecessaryComprehension("(list|set)".to_string()), - CheckCode::C417 => CheckKind::UnnecessaryMap("(list|set|dict)".to_string()), - // flake8-debugger - CheckCode::T100 => CheckKind::Debugger(DebuggerUsingType::Import("...".to_string())), - // flake8-tidy-imports - CheckCode::TID251 => CheckKind::BannedApi { - name: "...".to_string(), - message: "...".to_string(), - }, - CheckCode::TID252 => CheckKind::BannedRelativeImport(Strictness::All), - // flake8-return - CheckCode::RET501 => CheckKind::UnnecessaryReturnNone, - CheckCode::RET502 => CheckKind::ImplicitReturnValue, - CheckCode::RET503 => CheckKind::ImplicitReturn, - CheckCode::RET504 => CheckKind::UnnecessaryAssign, - CheckCode::RET505 => CheckKind::SuperfluousElseReturn(Branch::Else), - CheckCode::RET506 => CheckKind::SuperfluousElseRaise(Branch::Else), - CheckCode::RET507 => CheckKind::SuperfluousElseContinue(Branch::Else), - CheckCode::RET508 => CheckKind::SuperfluousElseBreak(Branch::Else), - // flake8-implicit-str-concat - CheckCode::ISC001 => CheckKind::SingleLineImplicitStringConcatenation, - CheckCode::ISC002 => CheckKind::MultiLineImplicitStringConcatenation, - CheckCode::ISC003 => CheckKind::ExplicitStringConcatenation, - // flake8-print - CheckCode::T201 => CheckKind::PrintFound, - CheckCode::T203 => CheckKind::PPrintFound, - // flake8-quotes - CheckCode::Q000 => CheckKind::BadQuotesInlineString(Quote::Double), - CheckCode::Q001 => CheckKind::BadQuotesMultilineString(Quote::Double), - CheckCode::Q002 => CheckKind::BadQuotesDocstring(Quote::Double), - CheckCode::Q003 => CheckKind::AvoidQuoteEscape, - // flake8-annotations - CheckCode::ANN001 => CheckKind::MissingTypeFunctionArgument("...".to_string()), - CheckCode::ANN002 => CheckKind::MissingTypeArgs("...".to_string()), - CheckCode::ANN003 => CheckKind::MissingTypeKwargs("...".to_string()), - CheckCode::ANN101 => CheckKind::MissingTypeSelf("...".to_string()), - CheckCode::ANN102 => CheckKind::MissingTypeCls("...".to_string()), - CheckCode::ANN201 => CheckKind::MissingReturnTypePublicFunction("...".to_string()), - CheckCode::ANN202 => CheckKind::MissingReturnTypePrivateFunction("...".to_string()), - CheckCode::ANN204 => CheckKind::MissingReturnTypeSpecialMethod("...".to_string()), - CheckCode::ANN205 => CheckKind::MissingReturnTypeStaticMethod("...".to_string()), - CheckCode::ANN206 => CheckKind::MissingReturnTypeClassMethod("...".to_string()), - CheckCode::ANN401 => CheckKind::DynamicallyTypedExpression("...".to_string()), - // flake8-2020 - CheckCode::YTT101 => CheckKind::SysVersionSlice3Referenced, - CheckCode::YTT102 => CheckKind::SysVersion2Referenced, - CheckCode::YTT103 => CheckKind::SysVersionCmpStr3, - CheckCode::YTT201 => CheckKind::SysVersionInfo0Eq3Referenced, - CheckCode::YTT202 => CheckKind::SixPY3Referenced, - CheckCode::YTT203 => CheckKind::SysVersionInfo1CmpInt, - CheckCode::YTT204 => CheckKind::SysVersionInfoMinorCmpInt, - CheckCode::YTT301 => CheckKind::SysVersion0Referenced, - CheckCode::YTT302 => CheckKind::SysVersionCmpStr10, - CheckCode::YTT303 => CheckKind::SysVersionSlice1Referenced, - // flake8-blind-except - CheckCode::BLE001 => CheckKind::BlindExcept("Exception".to_string()), - // flake8-simplify - CheckCode::SIM101 => CheckKind::DuplicateIsinstanceCall("...".to_string()), - CheckCode::SIM102 => CheckKind::NestedIfStatements, - CheckCode::SIM103 => CheckKind::ReturnBoolConditionDirectly("...".to_string()), - CheckCode::SIM105 => CheckKind::UseContextlibSuppress("...".to_string()), - CheckCode::SIM107 => CheckKind::ReturnInTryExceptFinally, - CheckCode::SIM108 => CheckKind::UseTernaryOperator("...".to_string()), - CheckCode::SIM109 => CheckKind::CompareWithTuple( - "value".to_string(), - vec!["...".to_string(), "...".to_string()], - "value == ... or value == ...".to_string(), - ), - CheckCode::SIM110 => { - CheckKind::ConvertLoopToAny("return any(x for x in y)".to_string()) - } - CheckCode::SIM111 => { - CheckKind::ConvertLoopToAll("return all(x for x in y)".to_string()) - } - CheckCode::SIM117 => CheckKind::MultipleWithStatements, - CheckCode::SIM118 => CheckKind::KeyInDict("key".to_string(), "dict".to_string()), - CheckCode::SIM201 => CheckKind::NegateEqualOp("left".to_string(), "right".to_string()), - CheckCode::SIM202 => { - CheckKind::NegateNotEqualOp("left".to_string(), "right".to_string()) - } - CheckCode::SIM208 => CheckKind::DoubleNegation("expr".to_string()), - CheckCode::SIM210 => CheckKind::IfExprWithTrueFalse("expr".to_string()), - CheckCode::SIM211 => CheckKind::IfExprWithFalseTrue("expr".to_string()), - CheckCode::SIM212 => { - CheckKind::IfExprWithTwistedArms("expr1".to_string(), "expr2".to_string()) - } - CheckCode::SIM220 => CheckKind::AAndNotA("...".to_string()), - CheckCode::SIM221 => CheckKind::AOrNotA("...".to_string()), - CheckCode::SIM222 => CheckKind::OrTrue, - CheckCode::SIM223 => CheckKind::AndFalse, - CheckCode::SIM300 => CheckKind::YodaConditions("left".to_string(), "right".to_string()), - // pyupgrade - CheckCode::UP001 => CheckKind::UselessMetaclassType, - CheckCode::UP003 => CheckKind::TypeOfPrimitive(Primitive::Str), - CheckCode::UP004 => CheckKind::UselessObjectInheritance("...".to_string()), - CheckCode::UP005 => CheckKind::DeprecatedUnittestAlias( - "assertEquals".to_string(), - "assertEqual".to_string(), - ), - CheckCode::UP006 => CheckKind::UsePEP585Annotation("List".to_string()), - CheckCode::UP007 => CheckKind::UsePEP604Annotation, - CheckCode::UP008 => CheckKind::SuperCallWithParameters, - CheckCode::UP009 => CheckKind::PEP3120UnnecessaryCodingComment, - CheckCode::UP010 => CheckKind::UnnecessaryFutureImport(vec!["...".to_string()]), - CheckCode::UP011 => CheckKind::UnnecessaryLRUCacheParams, - CheckCode::UP012 => CheckKind::UnnecessaryEncodeUTF8, - CheckCode::UP013 => CheckKind::ConvertTypedDictFunctionalToClass("...".to_string()), - CheckCode::UP014 => CheckKind::ConvertNamedTupleFunctionalToClass("...".to_string()), - CheckCode::UP015 => CheckKind::RedundantOpenModes(None), - CheckCode::UP016 => CheckKind::RemoveSixCompat, - CheckCode::UP017 => CheckKind::DatetimeTimezoneUTC, - CheckCode::UP018 => CheckKind::NativeLiterals(LiteralType::Str), - CheckCode::UP019 => CheckKind::TypingTextStrAlias, - CheckCode::UP020 => CheckKind::OpenAlias, - CheckCode::UP021 => CheckKind::ReplaceUniversalNewlines, - CheckCode::UP022 => CheckKind::ReplaceStdoutStderr, - CheckCode::UP023 => CheckKind::RewriteCElementTree, - CheckCode::UP024 => CheckKind::OSErrorAlias(None), - CheckCode::UP025 => CheckKind::RewriteUnicodeLiteral, - CheckCode::UP026 => CheckKind::RewriteMockImport(MockReference::Import), - CheckCode::UP027 => CheckKind::RewriteListComprehension, - CheckCode::UP028 => CheckKind::RewriteYieldFrom, - CheckCode::UP029 => CheckKind::UnnecessaryBuiltinImport(vec!["...".to_string()]), - // pydocstyle - CheckCode::D100 => CheckKind::PublicModule, - CheckCode::D101 => CheckKind::PublicClass, - CheckCode::D102 => CheckKind::PublicMethod, - CheckCode::D103 => CheckKind::PublicFunction, - CheckCode::D104 => CheckKind::PublicPackage, - CheckCode::D105 => CheckKind::MagicMethod, - CheckCode::D106 => CheckKind::PublicNestedClass, - CheckCode::D107 => CheckKind::PublicInit, - CheckCode::D200 => CheckKind::FitsOnOneLine, - CheckCode::D201 => CheckKind::NoBlankLineBeforeFunction(1), - CheckCode::D202 => CheckKind::NoBlankLineAfterFunction(1), - CheckCode::D203 => CheckKind::OneBlankLineBeforeClass(0), - CheckCode::D204 => CheckKind::OneBlankLineAfterClass(0), - CheckCode::D205 => CheckKind::BlankLineAfterSummary(2), - CheckCode::D206 => CheckKind::IndentWithSpaces, - CheckCode::D207 => CheckKind::NoUnderIndentation, - CheckCode::D208 => CheckKind::NoOverIndentation, - CheckCode::D209 => CheckKind::NewLineAfterLastParagraph, - CheckCode::D210 => CheckKind::NoSurroundingWhitespace, - CheckCode::D211 => CheckKind::NoBlankLineBeforeClass(1), - CheckCode::D212 => CheckKind::MultiLineSummaryFirstLine, - CheckCode::D213 => CheckKind::MultiLineSummarySecondLine, - CheckCode::D214 => CheckKind::SectionNotOverIndented("Returns".to_string()), - CheckCode::D215 => CheckKind::SectionUnderlineNotOverIndented("Returns".to_string()), - CheckCode::D300 => CheckKind::UsesTripleQuotes, - CheckCode::D301 => CheckKind::UsesRPrefixForBackslashedContent, - CheckCode::D400 => CheckKind::EndsInPeriod, - CheckCode::D402 => CheckKind::NoSignature, - CheckCode::D403 => CheckKind::FirstLineCapitalized, - CheckCode::D404 => CheckKind::NoThisPrefix, - CheckCode::D405 => CheckKind::CapitalizeSectionName("returns".to_string()), - CheckCode::D406 => CheckKind::NewLineAfterSectionName("Returns".to_string()), - CheckCode::D407 => CheckKind::DashedUnderlineAfterSection("Returns".to_string()), - CheckCode::D408 => CheckKind::SectionUnderlineAfterName("Returns".to_string()), - CheckCode::D409 => { - CheckKind::SectionUnderlineMatchesSectionLength("Returns".to_string()) - } - CheckCode::D410 => CheckKind::BlankLineAfterSection("Returns".to_string()), - CheckCode::D411 => CheckKind::BlankLineBeforeSection("Returns".to_string()), - CheckCode::D412 => { - CheckKind::NoBlankLinesBetweenHeaderAndContent("Returns".to_string()) - } - CheckCode::D413 => CheckKind::BlankLineAfterLastSection("Returns".to_string()), - CheckCode::D414 => CheckKind::NonEmptySection("Returns".to_string()), - CheckCode::D415 => CheckKind::EndsInPunctuation, - CheckCode::D416 => CheckKind::SectionNameEndsInColon("Returns".to_string()), - CheckCode::D417 => { - CheckKind::DocumentAllArguments(vec!["x".to_string(), "y".to_string()]) - } - CheckCode::D418 => CheckKind::SkipDocstring, - CheckCode::D419 => CheckKind::NonEmpty, - // pep8-naming - CheckCode::N801 => CheckKind::InvalidClassName("...".to_string()), - CheckCode::N802 => CheckKind::InvalidFunctionName("...".to_string()), - CheckCode::N803 => CheckKind::InvalidArgumentName("...".to_string()), - CheckCode::N804 => CheckKind::InvalidFirstArgumentNameForClassMethod, - CheckCode::N805 => CheckKind::InvalidFirstArgumentNameForMethod, - CheckCode::N806 => CheckKind::NonLowercaseVariableInFunction("...".to_string()), - CheckCode::N807 => CheckKind::DunderFunctionName, - CheckCode::N811 => { - CheckKind::ConstantImportedAsNonConstant("...".to_string(), "...".to_string()) - } - CheckCode::N812 => { - CheckKind::LowercaseImportedAsNonLowercase("...".to_string(), "...".to_string()) - } - CheckCode::N813 => { - CheckKind::CamelcaseImportedAsLowercase("...".to_string(), "...".to_string()) - } - CheckCode::N814 => { - CheckKind::CamelcaseImportedAsConstant("...".to_string(), "...".to_string()) - } - CheckCode::N815 => CheckKind::MixedCaseVariableInClassScope("mixedCase".to_string()), - CheckCode::N816 => CheckKind::MixedCaseVariableInGlobalScope("mixedCase".to_string()), - CheckCode::N817 => { - CheckKind::CamelcaseImportedAsAcronym("...".to_string(), "...".to_string()) - } - CheckCode::N818 => CheckKind::ErrorSuffixOnExceptionName("...".to_string()), - // isort - CheckCode::I001 => CheckKind::UnsortedImports, - // eradicate - CheckCode::ERA001 => CheckKind::CommentedOutCode, - // flake8-bandit - CheckCode::S101 => CheckKind::AssertUsed, - CheckCode::S102 => CheckKind::ExecUsed, - CheckCode::S103 => CheckKind::BadFilePermissions(0o777), - CheckCode::S104 => CheckKind::HardcodedBindAllInterfaces, - CheckCode::S105 => CheckKind::HardcodedPasswordString("...".to_string()), - CheckCode::S106 => CheckKind::HardcodedPasswordFuncArg("...".to_string()), - CheckCode::S107 => CheckKind::HardcodedPasswordDefault("...".to_string()), - CheckCode::S108 => CheckKind::HardcodedTempFile("...".to_string()), - CheckCode::S113 => CheckKind::RequestWithoutTimeout(None), - CheckCode::S324 => CheckKind::HashlibInsecureHashFunction("...".to_string()), - CheckCode::S501 => CheckKind::RequestWithNoCertValidation("...".to_string()), - CheckCode::S506 => CheckKind::UnsafeYAMLLoad(None), - // mccabe - CheckCode::C901 => CheckKind::FunctionIsTooComplex("...".to_string(), 10), - // flake8-boolean-trap - CheckCode::FBT001 => CheckKind::BooleanPositionalArgInFunctionDefinition, - CheckCode::FBT002 => CheckKind::BooleanDefaultValueInFunctionDefinition, - CheckCode::FBT003 => CheckKind::BooleanPositionalValueInFunctionCall, - // pygrep-hooks - CheckCode::PGH001 => CheckKind::NoEval, - CheckCode::PGH002 => CheckKind::DeprecatedLogWarn, - CheckCode::PGH003 => CheckKind::BlanketTypeIgnore, - CheckCode::PGH004 => CheckKind::BlanketNOQA, - // flake8-unused-arguments - CheckCode::ARG001 => CheckKind::UnusedFunctionArgument("...".to_string()), - CheckCode::ARG002 => CheckKind::UnusedMethodArgument("...".to_string()), - CheckCode::ARG003 => CheckKind::UnusedClassMethodArgument("...".to_string()), - CheckCode::ARG004 => CheckKind::UnusedStaticMethodArgument("...".to_string()), - CheckCode::ARG005 => CheckKind::UnusedLambdaArgument("...".to_string()), - // flake8-import-conventions - CheckCode::ICN001 => { - CheckKind::ImportAliasIsNotConventional("...".to_string(), "...".to_string()) - } - // pandas-vet - CheckCode::PD002 => CheckKind::UseOfInplaceArgument, - CheckCode::PD003 => CheckKind::UseOfDotIsNull, - CheckCode::PD004 => CheckKind::UseOfDotNotNull, - CheckCode::PD007 => CheckKind::UseOfDotIx, - CheckCode::PD008 => CheckKind::UseOfDotAt, - CheckCode::PD009 => CheckKind::UseOfDotIat, - CheckCode::PD010 => CheckKind::UseOfDotPivotOrUnstack, - CheckCode::PD011 => CheckKind::UseOfDotValues, - CheckCode::PD012 => CheckKind::UseOfDotReadTable, - CheckCode::PD013 => CheckKind::UseOfDotStack, - CheckCode::PD015 => CheckKind::UseOfPdMerge, - CheckCode::PD901 => CheckKind::DfIsABadVariableName, - // flake8-errmsg - CheckCode::EM101 => CheckKind::RawStringInException, - CheckCode::EM102 => CheckKind::FStringInException, - CheckCode::EM103 => CheckKind::DotFormatInException, - // flake8-datetimez - CheckCode::DTZ001 => CheckKind::CallDatetimeWithoutTzinfo, - CheckCode::DTZ002 => CheckKind::CallDatetimeToday, - CheckCode::DTZ003 => CheckKind::CallDatetimeUtcnow, - CheckCode::DTZ004 => CheckKind::CallDatetimeUtcfromtimestamp, - CheckCode::DTZ005 => CheckKind::CallDatetimeNowWithoutTzinfo, - CheckCode::DTZ006 => CheckKind::CallDatetimeFromtimestamp, - CheckCode::DTZ007 => CheckKind::CallDatetimeStrptimeWithoutZone, - CheckCode::DTZ011 => CheckKind::CallDateToday, - CheckCode::DTZ012 => CheckKind::CallDateFromtimestamp, - // flake8-pytest-style - CheckCode::PT001 => { - CheckKind::IncorrectFixtureParenthesesStyle("()".to_string(), String::new()) - } - CheckCode::PT002 => CheckKind::FixturePositionalArgs("...".to_string()), - CheckCode::PT003 => CheckKind::ExtraneousScopeFunction, - CheckCode::PT004 => CheckKind::MissingFixtureNameUnderscore("...".to_string()), - CheckCode::PT005 => CheckKind::IncorrectFixtureNameUnderscore("...".to_string()), - CheckCode::PT006 => CheckKind::ParametrizeNamesWrongType(ParametrizeNameType::Tuple), - CheckCode::PT007 => CheckKind::ParametrizeValuesWrongType( - ParametrizeValuesType::List, - ParametrizeValuesRowType::Tuple, - ), - CheckCode::PT008 => CheckKind::PatchWithLambda, - CheckCode::PT009 => CheckKind::UnittestAssertion("...".to_string()), - CheckCode::PT010 => CheckKind::RaisesWithoutException, - CheckCode::PT011 => CheckKind::RaisesTooBroad("...".to_string()), - CheckCode::PT012 => CheckKind::RaisesWithMultipleStatements, - CheckCode::PT013 => CheckKind::IncorrectPytestImport, - - CheckCode::PT015 => CheckKind::AssertAlwaysFalse, - CheckCode::PT016 => CheckKind::FailWithoutMessage, - CheckCode::PT017 => CheckKind::AssertInExcept("...".to_string()), - CheckCode::PT018 => CheckKind::CompositeAssertion, - CheckCode::PT019 => CheckKind::FixtureParamWithoutValue("...".to_string()), - CheckCode::PT020 => CheckKind::DeprecatedYieldFixture, - CheckCode::PT021 => CheckKind::FixtureFinalizerCallback, - CheckCode::PT022 => CheckKind::UselessYieldFixture("...".to_string()), - CheckCode::PT023 => CheckKind::IncorrectMarkParenthesesStyle( - "...".to_string(), - String::new(), - "()".to_string(), - ), - CheckCode::PT024 => CheckKind::UnnecessaryAsyncioMarkOnFixture, - CheckCode::PT025 => CheckKind::ErroneousUseFixturesOnFixture, - CheckCode::PT026 => CheckKind::UseFixturesWithoutParameters, - // flake8-pie - CheckCode::PIE790 => CheckKind::NoUnnecessaryPass, - CheckCode::PIE794 => CheckKind::DupeClassFieldDefinitions("...".to_string()), - CheckCode::PIE807 => CheckKind::PreferListBuiltin, - // Ruff - CheckCode::RUF001 => CheckKind::AmbiguousUnicodeCharacterString('𝐁', 'B'), - CheckCode::RUF002 => CheckKind::AmbiguousUnicodeCharacterDocstring('𝐁', 'B'), - CheckCode::RUF003 => CheckKind::AmbiguousUnicodeCharacterComment('𝐁', 'B'), - CheckCode::RUF004 => CheckKind::KeywordArgumentBeforeStarArgument("...".to_string()), - CheckCode::RUF100 => CheckKind::UnusedNOQA(None), - } - } - pub fn category(&self) -> CheckCategory { #[allow(clippy::match_same_arms)] match self { @@ -2080,2095 +1290,42 @@ impl CheckCode { } impl CheckKind { - /// A four-letter shorthand code for the check. - pub fn code(&self) -> &'static CheckCode { - match self { - // pycodestyle (errors) - CheckKind::AmbiguousClassName(..) => &CheckCode::E742, - CheckKind::AmbiguousFunctionName(..) => &CheckCode::E743, - CheckKind::AmbiguousVariableName(..) => &CheckCode::E741, - CheckKind::AssertTuple => &CheckCode::F631, - CheckKind::BreakOutsideLoop => &CheckCode::F701, - CheckKind::ContinueOutsideLoop => &CheckCode::F702, - CheckKind::DefaultExceptNotLast => &CheckCode::F707, - CheckKind::DoNotAssignLambda(..) => &CheckCode::E731, - CheckKind::DoNotUseBareExcept => &CheckCode::E722, - CheckKind::FStringMissingPlaceholders => &CheckCode::F541, - CheckKind::ForwardAnnotationSyntaxError(..) => &CheckCode::F722, - CheckKind::FutureFeatureNotDefined(..) => &CheckCode::F407, - CheckKind::IOError(..) => &CheckCode::E902, - CheckKind::IfTuple => &CheckCode::F634, - CheckKind::ImportShadowedByLoopVar(..) => &CheckCode::F402, - CheckKind::ImportStarNotPermitted(..) => &CheckCode::F406, - CheckKind::ImportStarUsage(..) => &CheckCode::F405, - CheckKind::ImportStarUsed(..) => &CheckCode::F403, - CheckKind::InvalidPrintSyntax => &CheckCode::F633, - CheckKind::IsLiteral(..) => &CheckCode::F632, - CheckKind::LateFutureImport => &CheckCode::F404, - CheckKind::LineTooLong(..) => &CheckCode::E501, - CheckKind::MultipleImportsOnOneLine => &CheckCode::E401, - CheckKind::ModuleImportNotAtTopOfFile => &CheckCode::E402, - CheckKind::MultiValueRepeatedKeyLiteral => &CheckCode::F601, - CheckKind::MultiValueRepeatedKeyVariable(..) => &CheckCode::F602, - CheckKind::NoneComparison(..) => &CheckCode::E711, - CheckKind::NotInTest => &CheckCode::E713, - CheckKind::NotIsTest => &CheckCode::E714, - CheckKind::PercentFormatExpectedMapping => &CheckCode::F502, - CheckKind::PercentFormatExpectedSequence => &CheckCode::F503, - CheckKind::PercentFormatExtraNamedArguments(..) => &CheckCode::F504, - CheckKind::PercentFormatInvalidFormat(..) => &CheckCode::F501, - CheckKind::PercentFormatMissingArgument(..) => &CheckCode::F505, - CheckKind::PercentFormatMixedPositionalAndNamed => &CheckCode::F506, - CheckKind::PercentFormatPositionalCountMismatch(..) => &CheckCode::F507, - CheckKind::PercentFormatStarRequiresSequence => &CheckCode::F508, - CheckKind::PercentFormatUnsupportedFormatCharacter(..) => &CheckCode::F509, - CheckKind::RaiseNotImplemented => &CheckCode::F901, - CheckKind::ReturnOutsideFunction => &CheckCode::F706, - CheckKind::StringDotFormatExtraNamedArguments(..) => &CheckCode::F522, - CheckKind::StringDotFormatExtraPositionalArguments(..) => &CheckCode::F523, - CheckKind::StringDotFormatInvalidFormat(..) => &CheckCode::F521, - CheckKind::StringDotFormatMissingArguments(..) => &CheckCode::F524, - CheckKind::StringDotFormatMixingAutomatic => &CheckCode::F525, - CheckKind::SyntaxError(..) => &CheckCode::E999, - CheckKind::ExpressionsInStarAssignment => &CheckCode::F621, - CheckKind::TrueFalseComparison(..) => &CheckCode::E712, - CheckKind::TwoStarredExpressions => &CheckCode::F622, - CheckKind::TypeComparison => &CheckCode::E721, - CheckKind::UndefinedExport(..) => &CheckCode::F822, - CheckKind::UndefinedLocal(..) => &CheckCode::F823, - CheckKind::RedefinedWhileUnused(..) => &CheckCode::F811, - CheckKind::UndefinedName(..) => &CheckCode::F821, - CheckKind::UnusedImport(..) => &CheckCode::F401, - CheckKind::UnusedVariable(..) => &CheckCode::F841, - CheckKind::UnusedAnnotation(..) => &CheckCode::F842, - CheckKind::YieldOutsideFunction(..) => &CheckCode::F704, - // pycodestyle (warnings) - CheckKind::NoNewLineAtEndOfFile => &CheckCode::W292, - CheckKind::InvalidEscapeSequence(..) => &CheckCode::W605, - // pylint - CheckKind::AwaitOutsideAsync => &CheckCode::PLE1142, - CheckKind::ConsiderMergingIsinstance(..) => &CheckCode::PLR1701, - CheckKind::ConsiderUsingFromImport(..) => &CheckCode::PLR0402, - CheckKind::GlobalVariableNotAssigned(..) => &CheckCode::PLW0602, - CheckKind::MisplacedComparisonConstant(..) => &CheckCode::PLC2201, - CheckKind::PropertyWithParameters => &CheckCode::PLR0206, - CheckKind::UnnecessaryDirectLambdaCall => &CheckCode::PLC3002, - CheckKind::UseSysExit(..) => &CheckCode::PLR1722, - CheckKind::NonlocalWithoutBinding(..) => &CheckCode::PLE0117, - CheckKind::UsedPriorGlobalDeclaration(..) => &CheckCode::PLE0118, - CheckKind::UselessElseOnLoop => &CheckCode::PLW0120, - CheckKind::UselessImportAlias => &CheckCode::PLC0414, - // flake8-builtins - CheckKind::BuiltinVariableShadowing(..) => &CheckCode::A001, - CheckKind::BuiltinArgumentShadowing(..) => &CheckCode::A002, - CheckKind::BuiltinAttributeShadowing(..) => &CheckCode::A003, - // flake8-bugbear - CheckKind::AbstractBaseClassWithoutAbstractMethod(..) => &CheckCode::B024, - CheckKind::AssignmentToOsEnviron => &CheckCode::B003, - CheckKind::CachedInstanceMethod => &CheckCode::B019, - CheckKind::CannotRaiseLiteral => &CheckCode::B016, - CheckKind::DoNotAssertFalse => &CheckCode::B011, - CheckKind::DuplicateHandlerException(..) => &CheckCode::B014, - CheckKind::DuplicateTryBlockException(..) => &CheckCode::B025, - CheckKind::EmptyMethodWithoutAbstractDecorator(..) => &CheckCode::B027, - CheckKind::FStringDocstring => &CheckCode::B021, - CheckKind::FunctionCallArgumentDefault(..) => &CheckCode::B008, - CheckKind::FunctionUsesLoopVariable(..) => &CheckCode::B023, - CheckKind::GetAttrWithConstant => &CheckCode::B009, - CheckKind::JumpStatementInFinally(..) => &CheckCode::B012, - CheckKind::LoopVariableOverridesIterator(..) => &CheckCode::B020, - CheckKind::MutableArgumentDefault => &CheckCode::B006, - CheckKind::NoAssertRaisesException => &CheckCode::B017, - CheckKind::RaiseWithoutFromInsideExcept => &CheckCode::B904, - CheckKind::ZipWithoutExplicitStrict => &CheckCode::B905, - CheckKind::RedundantTupleInExceptionHandler(..) => &CheckCode::B013, - CheckKind::SetAttrWithConstant => &CheckCode::B010, - CheckKind::StarArgUnpackingAfterKeywordArg => &CheckCode::B026, - CheckKind::StripWithMultiCharacters => &CheckCode::B005, - CheckKind::UnaryPrefixIncrement => &CheckCode::B002, - CheckKind::UnreliableCallableCheck => &CheckCode::B004, - CheckKind::UnusedLoopControlVariable(..) => &CheckCode::B007, - CheckKind::UselessComparison => &CheckCode::B015, - CheckKind::UselessContextlibSuppress => &CheckCode::B022, - CheckKind::UselessExpression => &CheckCode::B018, - // flake8-blind-except - CheckKind::BlindExcept(..) => &CheckCode::BLE001, - // flake8-comprehensions - CheckKind::UnnecessaryGeneratorList => &CheckCode::C400, - CheckKind::UnnecessaryGeneratorSet => &CheckCode::C401, - CheckKind::UnnecessaryGeneratorDict => &CheckCode::C402, - CheckKind::UnnecessaryListComprehensionSet => &CheckCode::C403, - CheckKind::UnnecessaryListComprehensionDict => &CheckCode::C404, - CheckKind::UnnecessaryLiteralSet(..) => &CheckCode::C405, - CheckKind::UnnecessaryLiteralDict(..) => &CheckCode::C406, - CheckKind::UnnecessaryCollectionCall(..) => &CheckCode::C408, - CheckKind::UnnecessaryLiteralWithinTupleCall(..) => &CheckCode::C409, - CheckKind::UnnecessaryLiteralWithinListCall(..) => &CheckCode::C410, - CheckKind::UnnecessaryListCall => &CheckCode::C411, - CheckKind::UnnecessaryCallAroundSorted(..) => &CheckCode::C413, - CheckKind::UnnecessaryDoubleCastOrProcess(..) => &CheckCode::C414, - CheckKind::UnnecessarySubscriptReversal(..) => &CheckCode::C415, - CheckKind::UnnecessaryComprehension(..) => &CheckCode::C416, - CheckKind::UnnecessaryMap(..) => &CheckCode::C417, - // flake8-debugger - CheckKind::Debugger(..) => &CheckCode::T100, - // flake8-tidy-imports - CheckKind::BannedApi { .. } => &CheckCode::TID251, - CheckKind::BannedRelativeImport(..) => &CheckCode::TID252, - // flake8-return - CheckKind::UnnecessaryReturnNone => &CheckCode::RET501, - CheckKind::ImplicitReturnValue => &CheckCode::RET502, - CheckKind::ImplicitReturn => &CheckCode::RET503, - CheckKind::UnnecessaryAssign => &CheckCode::RET504, - CheckKind::SuperfluousElseReturn(..) => &CheckCode::RET505, - CheckKind::SuperfluousElseRaise(..) => &CheckCode::RET506, - CheckKind::SuperfluousElseContinue(..) => &CheckCode::RET507, - CheckKind::SuperfluousElseBreak(..) => &CheckCode::RET508, - // flake8-implicit-str-concat - CheckKind::SingleLineImplicitStringConcatenation => &CheckCode::ISC001, - CheckKind::MultiLineImplicitStringConcatenation => &CheckCode::ISC002, - CheckKind::ExplicitStringConcatenation => &CheckCode::ISC003, - // flake8-print - CheckKind::PrintFound => &CheckCode::T201, - CheckKind::PPrintFound => &CheckCode::T203, - // flake8-quotes - CheckKind::BadQuotesInlineString(..) => &CheckCode::Q000, - CheckKind::BadQuotesMultilineString(..) => &CheckCode::Q001, - CheckKind::BadQuotesDocstring(..) => &CheckCode::Q002, - CheckKind::AvoidQuoteEscape => &CheckCode::Q003, - // flake8-annotations - CheckKind::MissingTypeFunctionArgument(..) => &CheckCode::ANN001, - CheckKind::MissingTypeArgs(..) => &CheckCode::ANN002, - CheckKind::MissingTypeKwargs(..) => &CheckCode::ANN003, - CheckKind::MissingTypeSelf(..) => &CheckCode::ANN101, - CheckKind::MissingTypeCls(..) => &CheckCode::ANN102, - CheckKind::MissingReturnTypePublicFunction(..) => &CheckCode::ANN201, - CheckKind::MissingReturnTypePrivateFunction(..) => &CheckCode::ANN202, - CheckKind::MissingReturnTypeSpecialMethod(..) => &CheckCode::ANN204, - CheckKind::MissingReturnTypeStaticMethod(..) => &CheckCode::ANN205, - CheckKind::MissingReturnTypeClassMethod(..) => &CheckCode::ANN206, - CheckKind::DynamicallyTypedExpression(..) => &CheckCode::ANN401, - // flake8-2020 - CheckKind::SysVersionSlice3Referenced => &CheckCode::YTT101, - CheckKind::SysVersion2Referenced => &CheckCode::YTT102, - CheckKind::SysVersionCmpStr3 => &CheckCode::YTT103, - CheckKind::SysVersionInfo0Eq3Referenced => &CheckCode::YTT201, - CheckKind::SixPY3Referenced => &CheckCode::YTT202, - CheckKind::SysVersionInfo1CmpInt => &CheckCode::YTT203, - CheckKind::SysVersionInfoMinorCmpInt => &CheckCode::YTT204, - CheckKind::SysVersion0Referenced => &CheckCode::YTT301, - CheckKind::SysVersionCmpStr10 => &CheckCode::YTT302, - CheckKind::SysVersionSlice1Referenced => &CheckCode::YTT303, - // flake8-simplify - CheckKind::AAndNotA(..) => &CheckCode::SIM220, - CheckKind::AOrNotA(..) => &CheckCode::SIM221, - CheckKind::AndFalse => &CheckCode::SIM223, - CheckKind::CompareWithTuple(..) => &CheckCode::SIM109, - CheckKind::ConvertLoopToAll(..) => &CheckCode::SIM111, - CheckKind::ConvertLoopToAny(..) => &CheckCode::SIM110, - CheckKind::DoubleNegation(..) => &CheckCode::SIM208, - CheckKind::DuplicateIsinstanceCall(..) => &CheckCode::SIM101, - CheckKind::IfExprWithFalseTrue(..) => &CheckCode::SIM211, - CheckKind::IfExprWithTrueFalse(..) => &CheckCode::SIM210, - CheckKind::IfExprWithTwistedArms(..) => &CheckCode::SIM212, - CheckKind::KeyInDict(..) => &CheckCode::SIM118, - CheckKind::MultipleWithStatements => &CheckCode::SIM117, - CheckKind::NegateEqualOp(..) => &CheckCode::SIM201, - CheckKind::NegateNotEqualOp(..) => &CheckCode::SIM202, - CheckKind::NestedIfStatements => &CheckCode::SIM102, - CheckKind::OrTrue => &CheckCode::SIM222, - CheckKind::ReturnBoolConditionDirectly(..) => &CheckCode::SIM103, - CheckKind::ReturnInTryExceptFinally => &CheckCode::SIM107, - CheckKind::UseContextlibSuppress(..) => &CheckCode::SIM105, - CheckKind::UseTernaryOperator(..) => &CheckCode::SIM108, - CheckKind::YodaConditions(..) => &CheckCode::SIM300, - // pyupgrade - CheckKind::ConvertNamedTupleFunctionalToClass(..) => &CheckCode::UP014, - CheckKind::ConvertTypedDictFunctionalToClass(..) => &CheckCode::UP013, - CheckKind::DatetimeTimezoneUTC => &CheckCode::UP017, - CheckKind::DeprecatedUnittestAlias(..) => &CheckCode::UP005, - CheckKind::NativeLiterals(..) => &CheckCode::UP018, - CheckKind::OSErrorAlias(..) => &CheckCode::UP024, - CheckKind::OpenAlias => &CheckCode::UP020, - CheckKind::PEP3120UnnecessaryCodingComment => &CheckCode::UP009, - CheckKind::RedundantOpenModes(..) => &CheckCode::UP015, - CheckKind::RemoveSixCompat => &CheckCode::UP016, - CheckKind::ReplaceStdoutStderr => &CheckCode::UP022, - CheckKind::ReplaceUniversalNewlines => &CheckCode::UP021, - CheckKind::RewriteCElementTree => &CheckCode::UP023, - CheckKind::RewriteListComprehension => &CheckCode::UP027, - CheckKind::RewriteMockImport(..) => &CheckCode::UP026, - CheckKind::RewriteUnicodeLiteral => &CheckCode::UP025, - CheckKind::RewriteYieldFrom => &CheckCode::UP028, - CheckKind::SuperCallWithParameters => &CheckCode::UP008, - CheckKind::TypeOfPrimitive(..) => &CheckCode::UP003, - CheckKind::TypingTextStrAlias => &CheckCode::UP019, - CheckKind::UnnecessaryBuiltinImport(..) => &CheckCode::UP029, - CheckKind::UnnecessaryEncodeUTF8 => &CheckCode::UP012, - CheckKind::UnnecessaryFutureImport(..) => &CheckCode::UP010, - CheckKind::UnnecessaryLRUCacheParams => &CheckCode::UP011, - CheckKind::UsePEP585Annotation(..) => &CheckCode::UP006, - CheckKind::UsePEP604Annotation => &CheckCode::UP007, - CheckKind::UselessMetaclassType => &CheckCode::UP001, - CheckKind::UselessObjectInheritance(..) => &CheckCode::UP004, - // pydocstyle - CheckKind::BlankLineAfterLastSection(..) => &CheckCode::D413, - CheckKind::BlankLineAfterSection(..) => &CheckCode::D410, - CheckKind::BlankLineBeforeSection(..) => &CheckCode::D411, - CheckKind::CapitalizeSectionName(..) => &CheckCode::D405, - CheckKind::DashedUnderlineAfterSection(..) => &CheckCode::D407, - CheckKind::DocumentAllArguments(..) => &CheckCode::D417, - CheckKind::EndsInPeriod => &CheckCode::D400, - CheckKind::EndsInPunctuation => &CheckCode::D415, - CheckKind::FirstLineCapitalized => &CheckCode::D403, - CheckKind::FitsOnOneLine => &CheckCode::D200, - CheckKind::IndentWithSpaces => &CheckCode::D206, - CheckKind::MagicMethod => &CheckCode::D105, - CheckKind::MultiLineSummaryFirstLine => &CheckCode::D212, - CheckKind::MultiLineSummarySecondLine => &CheckCode::D213, - CheckKind::NewLineAfterLastParagraph => &CheckCode::D209, - CheckKind::NewLineAfterSectionName(..) => &CheckCode::D406, - CheckKind::NoBlankLineAfterFunction(..) => &CheckCode::D202, - CheckKind::BlankLineAfterSummary(..) => &CheckCode::D205, - CheckKind::NoBlankLineBeforeClass(..) => &CheckCode::D211, - CheckKind::NoBlankLineBeforeFunction(..) => &CheckCode::D201, - CheckKind::NoBlankLinesBetweenHeaderAndContent(..) => &CheckCode::D412, - CheckKind::NoOverIndentation => &CheckCode::D208, - CheckKind::NoSignature => &CheckCode::D402, - CheckKind::NoSurroundingWhitespace => &CheckCode::D210, - CheckKind::NoThisPrefix => &CheckCode::D404, - CheckKind::NoUnderIndentation => &CheckCode::D207, - CheckKind::NonEmpty => &CheckCode::D419, - CheckKind::NonEmptySection(..) => &CheckCode::D414, - CheckKind::OneBlankLineAfterClass(..) => &CheckCode::D204, - CheckKind::OneBlankLineBeforeClass(..) => &CheckCode::D203, - CheckKind::PublicClass => &CheckCode::D101, - CheckKind::PublicFunction => &CheckCode::D103, - CheckKind::PublicInit => &CheckCode::D107, - CheckKind::PublicMethod => &CheckCode::D102, - CheckKind::PublicModule => &CheckCode::D100, - CheckKind::PublicNestedClass => &CheckCode::D106, - CheckKind::PublicPackage => &CheckCode::D104, - CheckKind::SectionNameEndsInColon(..) => &CheckCode::D416, - CheckKind::SectionNotOverIndented(..) => &CheckCode::D214, - CheckKind::SectionUnderlineAfterName(..) => &CheckCode::D408, - CheckKind::SectionUnderlineMatchesSectionLength(..) => &CheckCode::D409, - CheckKind::SectionUnderlineNotOverIndented(..) => &CheckCode::D215, - CheckKind::SkipDocstring => &CheckCode::D418, - CheckKind::UsesRPrefixForBackslashedContent => &CheckCode::D301, - CheckKind::UsesTripleQuotes => &CheckCode::D300, - // pep8-naming - CheckKind::InvalidClassName(..) => &CheckCode::N801, - CheckKind::InvalidFunctionName(..) => &CheckCode::N802, - CheckKind::InvalidArgumentName(..) => &CheckCode::N803, - CheckKind::InvalidFirstArgumentNameForClassMethod => &CheckCode::N804, - CheckKind::InvalidFirstArgumentNameForMethod => &CheckCode::N805, - CheckKind::NonLowercaseVariableInFunction(..) => &CheckCode::N806, - CheckKind::DunderFunctionName => &CheckCode::N807, - CheckKind::ConstantImportedAsNonConstant(..) => &CheckCode::N811, - CheckKind::LowercaseImportedAsNonLowercase(..) => &CheckCode::N812, - CheckKind::CamelcaseImportedAsLowercase(..) => &CheckCode::N813, - CheckKind::CamelcaseImportedAsConstant(..) => &CheckCode::N814, - CheckKind::MixedCaseVariableInClassScope(..) => &CheckCode::N815, - CheckKind::MixedCaseVariableInGlobalScope(..) => &CheckCode::N816, - CheckKind::CamelcaseImportedAsAcronym(..) => &CheckCode::N817, - CheckKind::ErrorSuffixOnExceptionName(..) => &CheckCode::N818, - // isort - CheckKind::UnsortedImports => &CheckCode::I001, - // eradicate - CheckKind::CommentedOutCode => &CheckCode::ERA001, - // flake8-bandit - CheckKind::AssertUsed => &CheckCode::S101, - CheckKind::ExecUsed => &CheckCode::S102, - CheckKind::BadFilePermissions(..) => &CheckCode::S103, - CheckKind::HardcodedBindAllInterfaces => &CheckCode::S104, - CheckKind::HardcodedPasswordString(..) => &CheckCode::S105, - CheckKind::HardcodedPasswordFuncArg(..) => &CheckCode::S106, - CheckKind::HardcodedPasswordDefault(..) => &CheckCode::S107, - CheckKind::HardcodedTempFile(..) => &CheckCode::S108, - CheckKind::RequestWithoutTimeout(..) => &CheckCode::S113, - CheckKind::HashlibInsecureHashFunction(..) => &CheckCode::S324, - CheckKind::RequestWithNoCertValidation(..) => &CheckCode::S501, - CheckKind::UnsafeYAMLLoad(..) => &CheckCode::S506, - // mccabe - CheckKind::FunctionIsTooComplex(..) => &CheckCode::C901, - // flake8-boolean-trap - CheckKind::BooleanPositionalArgInFunctionDefinition => &CheckCode::FBT001, - CheckKind::BooleanDefaultValueInFunctionDefinition => &CheckCode::FBT002, - CheckKind::BooleanPositionalValueInFunctionCall => &CheckCode::FBT003, - // pygrep-hooks - CheckKind::NoEval => &CheckCode::PGH001, - CheckKind::DeprecatedLogWarn => &CheckCode::PGH002, - CheckKind::BlanketTypeIgnore => &CheckCode::PGH003, - CheckKind::BlanketNOQA => &CheckCode::PGH004, - // flake8-unused-arguments - CheckKind::UnusedFunctionArgument(..) => &CheckCode::ARG001, - CheckKind::UnusedMethodArgument(..) => &CheckCode::ARG002, - CheckKind::UnusedClassMethodArgument(..) => &CheckCode::ARG003, - CheckKind::UnusedStaticMethodArgument(..) => &CheckCode::ARG004, - CheckKind::UnusedLambdaArgument(..) => &CheckCode::ARG005, - // flake8-import-conventions - CheckKind::ImportAliasIsNotConventional(..) => &CheckCode::ICN001, - // pandas-vet - CheckKind::UseOfInplaceArgument => &CheckCode::PD002, - CheckKind::UseOfDotIsNull => &CheckCode::PD003, - CheckKind::UseOfDotNotNull => &CheckCode::PD004, - CheckKind::UseOfDotIx => &CheckCode::PD007, - CheckKind::UseOfDotAt => &CheckCode::PD008, - CheckKind::UseOfDotIat => &CheckCode::PD009, - CheckKind::UseOfDotPivotOrUnstack => &CheckCode::PD010, - CheckKind::UseOfDotValues => &CheckCode::PD011, - CheckKind::UseOfDotReadTable => &CheckCode::PD012, - CheckKind::UseOfDotStack => &CheckCode::PD013, - CheckKind::UseOfPdMerge => &CheckCode::PD015, - CheckKind::DfIsABadVariableName => &CheckCode::PD901, - // flake8-errmsg - CheckKind::RawStringInException => &CheckCode::EM101, - CheckKind::FStringInException => &CheckCode::EM102, - CheckKind::DotFormatInException => &CheckCode::EM103, - // flake8-datetimez - CheckKind::CallDatetimeWithoutTzinfo => &CheckCode::DTZ001, - CheckKind::CallDatetimeToday => &CheckCode::DTZ002, - CheckKind::CallDatetimeUtcnow => &CheckCode::DTZ003, - CheckKind::CallDatetimeUtcfromtimestamp => &CheckCode::DTZ004, - CheckKind::CallDatetimeNowWithoutTzinfo => &CheckCode::DTZ005, - CheckKind::CallDatetimeFromtimestamp => &CheckCode::DTZ006, - CheckKind::CallDatetimeStrptimeWithoutZone => &CheckCode::DTZ007, - CheckKind::CallDateToday => &CheckCode::DTZ011, - CheckKind::CallDateFromtimestamp => &CheckCode::DTZ012, - // flake8-pytest-style - CheckKind::IncorrectFixtureParenthesesStyle(..) => &CheckCode::PT001, - CheckKind::FixturePositionalArgs(..) => &CheckCode::PT002, - CheckKind::ExtraneousScopeFunction => &CheckCode::PT003, - CheckKind::MissingFixtureNameUnderscore(..) => &CheckCode::PT004, - CheckKind::IncorrectFixtureNameUnderscore(..) => &CheckCode::PT005, - CheckKind::ParametrizeNamesWrongType(..) => &CheckCode::PT006, - CheckKind::ParametrizeValuesWrongType(..) => &CheckCode::PT007, - CheckKind::PatchWithLambda => &CheckCode::PT008, - CheckKind::UnittestAssertion(..) => &CheckCode::PT009, - CheckKind::RaisesWithoutException => &CheckCode::PT010, - CheckKind::RaisesTooBroad(..) => &CheckCode::PT011, - CheckKind::RaisesWithMultipleStatements => &CheckCode::PT012, - CheckKind::IncorrectPytestImport => &CheckCode::PT013, - CheckKind::AssertAlwaysFalse => &CheckCode::PT015, - CheckKind::FailWithoutMessage => &CheckCode::PT016, - CheckKind::AssertInExcept(..) => &CheckCode::PT017, - CheckKind::CompositeAssertion => &CheckCode::PT018, - CheckKind::FixtureParamWithoutValue(..) => &CheckCode::PT019, - CheckKind::DeprecatedYieldFixture => &CheckCode::PT020, - CheckKind::FixtureFinalizerCallback => &CheckCode::PT021, - CheckKind::UselessYieldFixture(..) => &CheckCode::PT022, - CheckKind::IncorrectMarkParenthesesStyle(..) => &CheckCode::PT023, - CheckKind::UnnecessaryAsyncioMarkOnFixture => &CheckCode::PT024, - CheckKind::ErroneousUseFixturesOnFixture => &CheckCode::PT025, - CheckKind::UseFixturesWithoutParameters => &CheckCode::PT026, - // flake8-pie - CheckKind::NoUnnecessaryPass => &CheckCode::PIE790, - CheckKind::DupeClassFieldDefinitions(..) => &CheckCode::PIE794, - CheckKind::PreferListBuiltin => &CheckCode::PIE807, - // Ruff - CheckKind::AmbiguousUnicodeCharacterString(..) => &CheckCode::RUF001, - CheckKind::AmbiguousUnicodeCharacterDocstring(..) => &CheckCode::RUF002, - CheckKind::AmbiguousUnicodeCharacterComment(..) => &CheckCode::RUF003, - CheckKind::KeywordArgumentBeforeStarArgument(..) => &CheckCode::RUF004, - CheckKind::UnusedNOQA(..) => &CheckCode::RUF100, - } - } - - /// The body text for the check. - pub fn body(&self) -> String { + /// The summary text for the check. Typically a truncated form of the body + /// text. + pub fn summary(&self) -> String { match self { - // pycodestyle (errors) - CheckKind::AmbiguousClassName(name) => { - format!("Ambiguous class name: `{name}`") - } - CheckKind::AmbiguousFunctionName(name) => { - format!("Ambiguous function name: `{name}`") - } - CheckKind::AmbiguousVariableName(name) => { - format!("Ambiguous variable name: `{name}`") - } - CheckKind::AssertTuple => { - "Assert test is a non-empty tuple, which is always `True`".to_string() - } - CheckKind::BreakOutsideLoop => "`break` outside loop".to_string(), - CheckKind::ContinueOutsideLoop => "`continue` not properly in loop".to_string(), - CheckKind::DefaultExceptNotLast => { - "An `except` block as not the last exception handler".to_string() - } - CheckKind::DoNotAssignLambda(..) => { - "Do not assign a `lambda` expression, use a `def`".to_string() - } - CheckKind::DoNotUseBareExcept => "Do not use bare `except`".to_string(), - CheckKind::ForwardAnnotationSyntaxError(body) => { - format!("Syntax error in forward annotation: `{body}`") - } - CheckKind::FStringMissingPlaceholders => { - "f-string without any placeholders".to_string() - } - CheckKind::FutureFeatureNotDefined(name) => { - format!("Future feature `{name}` is not defined") - } - CheckKind::IOError(message) => message.clone(), - CheckKind::IfTuple => "If test is a tuple, which is always `True`".to_string(), - CheckKind::InvalidPrintSyntax => { - "Use of `>>` is invalid with `print` function".to_string() - } - CheckKind::ImportShadowedByLoopVar(name, line) => { - format!("Import `{name}` from line {line} shadowed by loop variable") - } - CheckKind::ImportStarNotPermitted(name) => { - format!("`from {name} import *` only allowed at module level") - } - CheckKind::ImportStarUsed(name) => { - format!("`from {name} import *` used; unable to detect undefined names") - } - CheckKind::ImportStarUsage(name, sources) => { - let sources = sources - .iter() - .map(|source| format!("`{source}`")) - .join(", "); - format!("`{name}` may be undefined, or defined from star imports: {sources}") - } - CheckKind::IsLiteral(cmpop) => match cmpop { - IsCmpop::Is => "Use `==` to compare constant literals".to_string(), - IsCmpop::IsNot => "Use `!=` to compare constant literals".to_string(), - }, - CheckKind::LateFutureImport => { - "`from __future__` imports must occur at the beginning of the file".to_string() - } - CheckKind::LineTooLong(length, limit) => { - format!("Line too long ({length} > {limit} characters)") - } - CheckKind::ModuleImportNotAtTopOfFile => { - "Module level import not at top of file".to_string() - } - CheckKind::MultipleImportsOnOneLine => "Multiple imports on one line".to_string(), - CheckKind::MultiValueRepeatedKeyLiteral => { - "Dictionary key literal repeated".to_string() - } - CheckKind::MultiValueRepeatedKeyVariable(name) => { - format!("Dictionary key `{name}` repeated") - } - CheckKind::NoneComparison(op) => match op { - EqCmpop::Eq => "Comparison to `None` should be `cond is None`".to_string(), - EqCmpop::NotEq => "Comparison to `None` should be `cond is not None`".to_string(), - }, - CheckKind::NotInTest => "Test for membership should be `not in`".to_string(), - CheckKind::NotIsTest => "Test for object identity should be `is not`".to_string(), - CheckKind::PercentFormatInvalidFormat(message) => { - format!("'...' % ... has invalid format string: {message}") - } - CheckKind::PercentFormatUnsupportedFormatCharacter(char) => { - format!("'...' % ... has unsupported format character '{char}'") - } - CheckKind::PercentFormatExpectedMapping => { - "'...' % ... expected mapping but got sequence".to_string() - } - CheckKind::PercentFormatExpectedSequence => { - "'...' % ... expected sequence but got mapping".to_string() - } - CheckKind::PercentFormatExtraNamedArguments(missing) => { - let message = missing.join(", "); - format!("'...' % ... has unused named argument(s): {message}") - } - CheckKind::PercentFormatMissingArgument(missing) => { - let message = missing.join(", "); - format!("'...' % ... is missing argument(s) for placeholder(s): {message}") - } - CheckKind::PercentFormatMixedPositionalAndNamed => { - "'...' % ... has mixed positional and named placeholders".to_string() - } - CheckKind::PercentFormatPositionalCountMismatch(wanted, got) => { - format!("'...' % ... has {wanted} placeholder(s) but {got} substitution(s)") - } - CheckKind::PercentFormatStarRequiresSequence => { - "'...' % ... `*` specifier requires sequence".to_string() - } - CheckKind::RaiseNotImplemented => { - "`raise NotImplemented` should be `raise NotImplementedError`".to_string() - } - CheckKind::RedefinedWhileUnused(name, line) => { - format!("Redefinition of unused `{name}` from line {line}") - } - CheckKind::ReturnOutsideFunction => { - "`return` statement outside of a function/method".to_string() - } - CheckKind::StringDotFormatExtraNamedArguments(missing) => { - let message = missing.join(", "); - format!("'...'.format(...) has unused named argument(s): {message}") - } - CheckKind::StringDotFormatExtraPositionalArguments(missing) => { - let message = missing.join(", "); - format!("'...'.format(...) has unused arguments at position(s): {message}") - } - CheckKind::StringDotFormatInvalidFormat(message) => { - format!("'...'.format(...) has invalid format string: {message}") - } - CheckKind::StringDotFormatMissingArguments(missing) => { - let message = missing.join(", "); - format!("'...'.format(...) is missing argument(s) for placeholder(s): {message}") - } - CheckKind::StringDotFormatMixingAutomatic => { - "'...'.format(...) mixes automatic and manual numbering".to_string() - } - CheckKind::SyntaxError(message) => format!("SyntaxError: {message}"), - CheckKind::ExpressionsInStarAssignment => { - "Too many expressions in star-unpacking assignment".to_string() - } - CheckKind::TrueFalseComparison(true, EqCmpop::Eq) => { - "Comparison to `True` should be `cond is True`".to_string() - } - CheckKind::TrueFalseComparison(true, EqCmpop::NotEq) => { - "Comparison to `True` should be `cond is not True`".to_string() - } - CheckKind::TrueFalseComparison(false, EqCmpop::Eq) => { - "Comparison to `False` should be `cond is False`".to_string() - } - CheckKind::TrueFalseComparison(false, EqCmpop::NotEq) => { - "Comparison to `False` should be `cond is not False`".to_string() - } - CheckKind::TwoStarredExpressions => "Two starred expressions in assignment".to_string(), - CheckKind::TypeComparison => "Do not compare types, use `isinstance()`".to_string(), - CheckKind::UndefinedExport(name) => { - format!("Undefined name `{name}` in `__all__`") - } - CheckKind::UndefinedLocal(name) => { - format!("Local variable `{name}` referenced before assignment") - } - CheckKind::UndefinedName(name) => { - format!("Undefined name `{name}`") - } - CheckKind::UnusedAnnotation(name) => { - format!("Local variable `{name}` is annotated but never used") - } - CheckKind::UnusedImport(name, ignore_init, ..) => { - if *ignore_init { - format!( - "`{name}` imported but unused; consider adding to `__all__` or using a \ - redundant alias" - ) - } else { - format!("`{name}` imported but unused") - } - } - CheckKind::UnusedVariable(name) => { - format!("Local variable `{name}` is assigned to but never used") - } - CheckKind::YieldOutsideFunction(keyword) => { - format!("`{keyword}` statement outside of a function") - } - // pycodestyle (warnings) - CheckKind::NoNewLineAtEndOfFile => "No newline at end of file".to_string(), - CheckKind::InvalidEscapeSequence(char) => { - format!("Invalid escape sequence: '\\{char}'") - } - // pylint - CheckKind::UselessImportAlias => { - "Import alias does not rename original package".to_string() - } - CheckKind::ConsiderMergingIsinstance(obj, types) => { - let types = types.join(", "); - format!("Merge these isinstance calls: `isinstance({obj}, ({types}))`") - } - CheckKind::MisplacedComparisonConstant(comparison) => { - format!("Comparison should be {comparison}") - } - CheckKind::NonlocalWithoutBinding(name) => { - format!("Nonlocal name `{name}` found without binding") - } - CheckKind::UnnecessaryDirectLambdaCall => "Lambda expression called directly. Execute \ - the expression inline instead." - .to_string(), - CheckKind::PropertyWithParameters => { - "Cannot have defined parameters for properties".to_string() - } - CheckKind::ConsiderUsingFromImport(module, name) => { - format!("Use `from {module} import {name}` in lieu of alias") - } - CheckKind::UsedPriorGlobalDeclaration(name, line) => { - format!("Name `{name}` is used prior to global declaration on line {line}") - } - CheckKind::GlobalVariableNotAssigned(name) => { - format!("Using global for `{name}` but no assignment is done") - } - CheckKind::AwaitOutsideAsync => { - "`await` should be used within an async function".to_string() - } - CheckKind::UselessElseOnLoop => "Else clause on loop without a break statement, \ - remove the else and de-indent all the code inside it" - .to_string(), - CheckKind::UseSysExit(name) => format!("Use `sys.exit()` instead of `{name}`"), - // flake8-builtins - CheckKind::BuiltinVariableShadowing(name) => { - format!("Variable `{name}` is shadowing a python builtin") - } - CheckKind::BuiltinArgumentShadowing(name) => { - format!("Argument `{name}` is shadowing a python builtin") - } - CheckKind::BuiltinAttributeShadowing(name) => { - format!("Class attribute `{name}` is shadowing a python builtin") - } - // flake8-bugbear - CheckKind::UnaryPrefixIncrement => "Python does not support the unary prefix \ - increment. Writing `++n` is equivalent to \ - `+(+(n))`, which equals `n`. You meant `n += 1`." - .to_string(), - CheckKind::AssignmentToOsEnviron => { - "Assigning to `os.environ` doesn't clear the environment".to_string() - } - CheckKind::UnreliableCallableCheck => " Using `hasattr(x, '__call__')` to test if x \ - is callable is unreliable. Use `callable(x)` \ - for consistent results." - .to_string(), - CheckKind::StripWithMultiCharacters => { - "Using `.strip()` with multi-character strings is misleading the reader".to_string() - } - CheckKind::MutableArgumentDefault => { - "Do not use mutable data structures for argument defaults".to_string() - } - CheckKind::UnusedLoopControlVariable(name) => format!( - "Loop control variable `{name}` not used within the loop body. If this is \ - intended, start the name with an underscore." - ), - CheckKind::FunctionCallArgumentDefault(name) => { - if let Some(name) = name { - format!("Do not perform function call `{name}` in argument defaults") - } else { - "Do not perform function call in argument defaults".to_string() - } + CheckKind::UnaryPrefixIncrement(..) => { + "Python does not support the unary prefix increment".to_string() } - CheckKind::FunctionUsesLoopVariable(name) => { - format!("Function definition does not bind loop variable `{name}`") + CheckKind::UnusedLoopControlVariable(violations::UnusedLoopControlVariable(name)) => { + format!("Loop control variable `{name}` not used within the loop body") } - CheckKind::GetAttrWithConstant => "Do not call `getattr` with a constant attribute \ - value. It is not any safer than normal property \ - access." - .to_string(), - CheckKind::SetAttrWithConstant => "Do not call `setattr` with a constant attribute \ - value. It is not any safer than normal property \ - access." - .to_string(), - CheckKind::DoNotAssertFalse => "Do not `assert False` (`python -O` removes these \ - calls), raise `AssertionError()`" - .to_string(), - CheckKind::JumpStatementInFinally(name) => { - format!("`{name}` inside finally blocks cause exceptions to be silenced") + CheckKind::NoAssertRaisesException(..) => { + "`assertRaises(Exception)` should be considered evil".to_string() } - CheckKind::RedundantTupleInExceptionHandler(name) => { - format!( - "A length-one tuple literal is redundant. Write `except {name}` instead of \ - `except ({name},)`." - ) + CheckKind::StarArgUnpackingAfterKeywordArg(..) => { + "Star-arg unpacking after a keyword argument is strongly discouraged".to_string() } - CheckKind::UselessComparison => "Pointless comparison. This comparison does nothing \ - but waste CPU instructions. Either prepend `assert` \ - or remove it." - .to_string(), - CheckKind::CannotRaiseLiteral => "Cannot raise a literal. Did you intend to return it \ - or raise an Exception?" - .to_string(), - CheckKind::DuplicateHandlerException(names) => { - if names.len() == 1 { - let name = &names[0]; - format!("Exception handler with duplicate exception: `{name}`") - } else { - let names = names.iter().map(|name| format!("`{name}`")).join(", "); - format!("Exception handler with duplicate exceptions: {names}") - } + + // flake8-datetimez + CheckKind::CallDatetimeToday(..) => { + "The use of `datetime.datetime.today()` is not allowed".to_string() } - CheckKind::NoAssertRaisesException => { - "`assertRaises(Exception)` should be considered evil. It can lead to your test \ - passing even if the code being tested is never executed due to a typo. Either \ - assert for a more specific exception (builtin or custom), use \ - `assertRaisesRegex`, or use the context manager form of `assertRaises`." - .to_string() + CheckKind::CallDatetimeUtcnow(..) => { + "The use of `datetime.datetime.utcnow()` is not allowed".to_string() } - CheckKind::UselessExpression => { - "Found useless expression. Either assign it to a variable or remove it.".to_string() + CheckKind::CallDatetimeUtcfromtimestamp(..) => { + "The use of `datetime.datetime.utcfromtimestamp()` is not allowed".to_string() } - CheckKind::CachedInstanceMethod => "Use of `functools.lru_cache` or `functools.cache` \ - on methods can lead to memory leaks" - .to_string(), - CheckKind::LoopVariableOverridesIterator(name) => { - format!("Loop control variable `{name}` overrides iterable it iterates") + CheckKind::CallDateToday(..) => { + "The use of `datetime.date.today()` is not allowed.".to_string() } - CheckKind::FStringDocstring => "f-string used as docstring. This will be interpreted \ - by python as a joined string rather than a docstring." - .to_string(), - CheckKind::UselessContextlibSuppress => { - "No arguments passed to `contextlib.suppress`. No exceptions will be suppressed \ - and therefore this context manager is redundant" - .to_string() - } - CheckKind::AbstractBaseClassWithoutAbstractMethod(name) => { - format!("`{name}` is an abstract base class, but it has no abstract methods") - } - CheckKind::DuplicateTryBlockException(name) => { - format!("try-except block with duplicate exception `{name}`") - } - CheckKind::StarArgUnpackingAfterKeywordArg => { - "Star-arg unpacking after a keyword argument is strongly discouraged. It only \ - works when the keyword parameter is declared after all parameters supplied by the \ - unpacked sequence, and this change of ordering can surprise and mislead readers." - .to_string() - } - CheckKind::EmptyMethodWithoutAbstractDecorator(name) => { - format!( - "`{name}` is an empty method in an abstract base class, but has no abstract \ - decorator" - ) - } - CheckKind::RaiseWithoutFromInsideExcept => { - "Within an except clause, raise exceptions with raise ... from err or raise ... \ - from None to distinguish them from errors in exception handling" - .to_string() - } - CheckKind::ZipWithoutExplicitStrict => { - "`zip()` without an explicit `strict=` parameter".to_string() - } - // flake8-comprehensions - CheckKind::UnnecessaryGeneratorList => { - "Unnecessary generator (rewrite as a `list` comprehension)".to_string() - } - CheckKind::UnnecessaryGeneratorSet => { - "Unnecessary generator (rewrite as a `set` comprehension)".to_string() - } - CheckKind::UnnecessaryGeneratorDict => { - "Unnecessary generator (rewrite as a `dict` comprehension)".to_string() - } - CheckKind::UnnecessaryListComprehensionSet => { - "Unnecessary `list` comprehension (rewrite as a `set` comprehension)".to_string() - } - CheckKind::UnnecessaryListComprehensionDict => { - "Unnecessary `list` comprehension (rewrite as a `dict` comprehension)".to_string() - } - CheckKind::UnnecessaryLiteralSet(obj_type) => { - format!("Unnecessary `{obj_type}` literal (rewrite as a `set` literal)") - } - CheckKind::UnnecessaryLiteralDict(obj_type) => { - format!("Unnecessary `{obj_type}` literal (rewrite as a `dict` literal)") - } - CheckKind::UnnecessaryCollectionCall(obj_type) => { - format!("Unnecessary `{obj_type}` call (rewrite as a literal)") - } - CheckKind::UnnecessaryLiteralWithinTupleCall(literal) => { - if literal == "list" { - format!( - "Unnecessary `{literal}` literal passed to `tuple()` (rewrite as a \ - `tuple` literal)" - ) - } else { - format!( - "Unnecessary `{literal}` literal passed to `tuple()` (remove the outer \ - call to `tuple()`)" - ) - } - } - CheckKind::UnnecessaryLiteralWithinListCall(literal) => { - if literal == "list" { - format!( - "Unnecessary `{literal}` literal passed to `list()` (remove the outer \ - call to `list()`)" - ) - } else { - format!( - "Unnecessary `{literal}` literal passed to `list()` (rewrite as a `list` \ - literal)" - ) - } - } - CheckKind::UnnecessaryListCall => { - "Unnecessary `list` call (remove the outer call to `list()`)".to_string() - } - CheckKind::UnnecessaryCallAroundSorted(func) => { - format!("Unnecessary `{func}` call around `sorted()`") - } - CheckKind::UnnecessaryDoubleCastOrProcess(inner, outer) => { - format!("Unnecessary `{inner}` call within `{outer}()`") - } - CheckKind::UnnecessarySubscriptReversal(func) => { - format!("Unnecessary subscript reversal of iterable within `{func}()`") - } - CheckKind::UnnecessaryComprehension(obj_type) => { - format!("Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)") - } - CheckKind::UnnecessaryMap(obj_type) => { - if obj_type == "generator" { - "Unnecessary `map` usage (rewrite using a generator expression)".to_string() - } else { - format!("Unnecessary `map` usage (rewrite using a `{obj_type}` comprehension)") - } - } - // flake8-debugger - CheckKind::Debugger(using_type) => match using_type { - DebuggerUsingType::Call(name) => format!("Trace found: `{name}` used"), - DebuggerUsingType::Import(name) => format!("Import for `{name}` found"), - }, - // flake8-tidy-imports - CheckKind::BannedApi { name, message } => format!("`{name}` is banned: {message}"), - CheckKind::BannedRelativeImport(strictness) => match strictness { - Strictness::Parents => { - "Relative imports from parent modules are banned".to_string() - } - Strictness::All => "Relative imports are banned".to_string(), - }, - // flake8-return - CheckKind::UnnecessaryReturnNone => "Do not explicitly `return None` in function if \ - it is the only possible return value" - .to_string(), - CheckKind::ImplicitReturnValue => "Do not implicitly `return None` in function able \ - to return non-`None` value" - .to_string(), - CheckKind::ImplicitReturn => "Missing explicit `return` at the end of function able \ - to return non-`None` value" - .to_string(), - CheckKind::UnnecessaryAssign => { - "Unnecessary variable assignment before `return` statement".to_string() - } - CheckKind::SuperfluousElseReturn(branch) => { - format!("Unnecessary `{branch}` after `return` statement") - } - CheckKind::SuperfluousElseRaise(branch) => { - format!("Unnecessary `{branch}` after `raise` statement") - } - CheckKind::SuperfluousElseContinue(branch) => { - format!("Unnecessary `{branch}` after `continue` statement") - } - CheckKind::SuperfluousElseBreak(branch) => { - format!("Unnecessary `{branch}` after `break` statement") - } - // flake8-implicit-str-concat - CheckKind::SingleLineImplicitStringConcatenation => { - "Implicitly concatenated string literals on one line".to_string() - } - CheckKind::MultiLineImplicitStringConcatenation => { - "Implicitly concatenated string literals over continuation line".to_string() - } - CheckKind::ExplicitStringConcatenation => { - "Explicitly concatenated string should be implicitly concatenated".to_string() - } - // flake8-print - CheckKind::PrintFound => "`print` found".to_string(), - CheckKind::PPrintFound => "`pprint` found".to_string(), - // flake8-quotes - CheckKind::BadQuotesInlineString(quote) => match quote { - Quote::Single => "Double quotes found but single quotes preferred".to_string(), - Quote::Double => "Single quotes found but double quotes preferred".to_string(), - }, - CheckKind::BadQuotesMultilineString(quote) => match quote { - Quote::Single => { - "Double quote multiline found but single quotes preferred".to_string() - } - Quote::Double => { - "Single quote multiline found but double quotes preferred".to_string() - } - }, - CheckKind::BadQuotesDocstring(quote) => match quote { - Quote::Single => { - "Double quote docstring found but single quotes preferred".to_string() - } - Quote::Double => { - "Single quote docstring found but double quotes preferred".to_string() - } - }, - CheckKind::AvoidQuoteEscape => { - "Change outer quotes to avoid escaping inner quotes".to_string() - } - // flake8-annotations - CheckKind::MissingTypeFunctionArgument(name) => { - format!("Missing type annotation for function argument `{name}`") - } - CheckKind::MissingTypeArgs(name) => format!("Missing type annotation for `*{name}`"), - CheckKind::MissingTypeKwargs(name) => { - format!("Missing type annotation for `**{name}`") - } - CheckKind::MissingTypeSelf(name) => { - format!("Missing type annotation for `{name}` in method") - } - CheckKind::MissingTypeCls(name) => { - format!("Missing type annotation for `{name}` in classmethod") - } - CheckKind::MissingReturnTypePublicFunction(name) => { - format!("Missing return type annotation for public function `{name}`") - } - CheckKind::MissingReturnTypePrivateFunction(name) => { - format!("Missing return type annotation for private function `{name}`") - } - CheckKind::MissingReturnTypeSpecialMethod(name) => { - format!("Missing return type annotation for special method `{name}`") - } - CheckKind::MissingReturnTypeStaticMethod(name) => { - format!("Missing return type annotation for staticmethod `{name}`") - } - CheckKind::MissingReturnTypeClassMethod(name) => { - format!("Missing return type annotation for classmethod `{name}`") - } - CheckKind::DynamicallyTypedExpression(name) => { - format!("Dynamically typed expressions (typing.Any) are disallowed in `{name}`") - } - // flake8-2020 - CheckKind::SysVersionSlice3Referenced => { - "`sys.version[:3]` referenced (python3.10), use `sys.version_info`".to_string() - } - CheckKind::SysVersion2Referenced => { - "`sys.version[2]` referenced (python3.10), use `sys.version_info`".to_string() - } - CheckKind::SysVersionCmpStr3 => { - "`sys.version` compared to string (python3.10), use `sys.version_info`".to_string() - } - CheckKind::SysVersionInfo0Eq3Referenced => { - "`sys.version_info[0] == 3` referenced (python4), use `>=`".to_string() - } - CheckKind::SixPY3Referenced => { - "`six.PY3` referenced (python4), use `not six.PY2`".to_string() - } - CheckKind::SysVersionInfo1CmpInt => "`sys.version_info[1]` compared to integer \ - (python4), compare `sys.version_info` to tuple" - .to_string(), - CheckKind::SysVersionInfoMinorCmpInt => "`sys.version_info.minor` compared to integer \ - (python4), compare `sys.version_info` to \ - tuple" - .to_string(), - CheckKind::SysVersion0Referenced => { - "`sys.version[0]` referenced (python10), use `sys.version_info`".to_string() - } - CheckKind::SysVersionCmpStr10 => { - "`sys.version` compared to string (python10), use `sys.version_info`".to_string() - } - CheckKind::SysVersionSlice1Referenced => { - "`sys.version[:1]` referenced (python10), use `sys.version_info`".to_string() - } - // flake8-simplify - CheckKind::ReturnBoolConditionDirectly(cond) => { - format!("Return the condition `{cond}` directly") - } - CheckKind::CompareWithTuple(value, values, or_op) => { - let values = values.join(", "); - format!("Use `{value} in ({values})` instead of `{or_op}`") - } - CheckKind::DuplicateIsinstanceCall(name) => { - format!("Multiple `isinstance` calls for `{name}`, merge into a single call") - } - CheckKind::UseContextlibSuppress(exception) => { - format!("Use `contextlib.suppress({exception})` instead of try-except-pass") - } - CheckKind::UseTernaryOperator(new_code) => { - format!("Use ternary operator `{new_code}` instead of if-else-block") - } - CheckKind::ReturnInTryExceptFinally => { - "Don't use `return` in `try`/`except` and `finally`".to_string() - } - CheckKind::AAndNotA(name) => format!("Use `False` instead of `{name} and not {name}`"), - CheckKind::AOrNotA(name) => format!("Use `True` instead of `{name} or not {name}`"), - CheckKind::AndFalse => "Use `False` instead of `... and False`".to_string(), - CheckKind::ConvertLoopToAll(all) => { - format!("Use `{all}` instead of `for` loop") - } - CheckKind::ConvertLoopToAny(any) => { - format!("Use `{any}` instead of `for` loop") - } - CheckKind::NegateEqualOp(left, right) => { - format!("Use `{left} != {right}` instead of `not {left} == {right}`") - } - CheckKind::NegateNotEqualOp(left, right) => { - format!("Use `{left} == {right}` instead of `not {left} != {right}`") - } - CheckKind::DoubleNegation(expr) => { - format!("Use `{expr}` instead of `not (not {expr})`") - } - CheckKind::IfExprWithTrueFalse(expr) => { - format!("Use `bool({expr})` instead of `True if {expr} else False`") - } - CheckKind::IfExprWithFalseTrue(expr) => { - format!("Use `not {expr}` instead of `False if {expr} else True`") - } - CheckKind::IfExprWithTwistedArms(expr_body, expr_else) => { - format!( - "Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if \ - not {expr_else} else {expr_else}`" - ) - } - CheckKind::KeyInDict(key, dict) => { - format!("Use `{key} in {dict}` instead of `{key} in {dict}.keys()`") - } - CheckKind::MultipleWithStatements => "Use a single `with` statement with multiple \ - contexts instead of nested `with` statements" - .to_string(), - CheckKind::NestedIfStatements => { - "Use a single `if` statement instead of nested `if` statements".to_string() - } - CheckKind::OrTrue => "Use `True` instead of `... or True`".to_string(), - CheckKind::YodaConditions(left, right) => { - format!("Yoda conditions are discouraged, use `{left} == {right}` instead") - } - // pyupgrade - CheckKind::TypeOfPrimitive(primitive) => { - format!("Use `{}` instead of `type(...)`", primitive.builtin()) - } - CheckKind::UselessMetaclassType => "`__metaclass__ = type` is implied".to_string(), - CheckKind::TypingTextStrAlias => "`typing.Text` is deprecated, use `str`".to_string(), - CheckKind::DeprecatedUnittestAlias(alias, target) => { - format!("`{alias}` is deprecated, use `{target}`") - } - CheckKind::UselessObjectInheritance(name) => { - format!("Class `{name}` inherits from `object`") - } - CheckKind::UsePEP585Annotation(name) => { - format!( - "Use `{}` instead of `{}` for type annotations", - name.to_lowercase(), - name, - ) - } - CheckKind::UsePEP604Annotation => "Use `X | Y` for type annotations".to_string(), - CheckKind::SuperCallWithParameters => { - "Use `super()` instead of `super(__class__, self)`".to_string() - } - CheckKind::UnnecessaryFutureImport(names) => { - if names.len() == 1 { - let import = &names[0]; - format!("Unnecessary `__future__` import `{import}` for target Python version") - } else { - let imports = names.iter().map(|name| format!("`{name}`")).join(", "); - format!("Unnecessary `__future__` imports {imports} for target Python version") - } - } - CheckKind::UnnecessaryBuiltinImport(names) => { - if names.len() == 1 { - let import = &names[0]; - format!("Unnecessary builtin import: `{import}`") - } else { - let imports = names.iter().map(|name| format!("`{name}`")).join(", "); - format!("Unnecessary builtin imports: {imports}") - } - } - CheckKind::UnnecessaryLRUCacheParams => { - "Unnecessary parameters to `functools.lru_cache`".to_string() - } - CheckKind::UnnecessaryEncodeUTF8 => "Unnecessary call to `encode` as UTF-8".to_string(), - CheckKind::RedundantOpenModes(replacement) => match replacement { - None => "Unnecessary open mode parameters".to_string(), - Some(replacement) => { - format!("Unnecessary open mode parameters, use \"{replacement}\"") - } - }, - CheckKind::RemoveSixCompat => "Unnecessary `six` compatibility usage".to_string(), - CheckKind::DatetimeTimezoneUTC => "Use `datetime.UTC` alias".to_string(), - CheckKind::NativeLiterals(literal_type) => { - format!("Unnecessary call to `{literal_type}`") - } - CheckKind::OpenAlias => "Use builtin `open`".to_string(), - CheckKind::ConvertTypedDictFunctionalToClass(name) => { - format!("Convert `{name}` from `TypedDict` functional to class syntax") - } - CheckKind::ConvertNamedTupleFunctionalToClass(name) => { - format!("Convert `{name}` from `NamedTuple` functional to class syntax") - } - CheckKind::ReplaceUniversalNewlines => { - "`universal_newlines` is deprecated, use `text`".to_string() - } - CheckKind::ReplaceStdoutStderr => { - "Sending stdout and stderr to pipe is deprecated, use `capture_output`".to_string() - } - CheckKind::RewriteCElementTree => { - "`cElementTree` is deprecated, use `ElementTree`".to_string() - } - CheckKind::OSErrorAlias(..) => "Replace aliased errors with `OSError`".to_string(), - CheckKind::RewriteUnicodeLiteral => "Remove unicode literals from strings".to_string(), - CheckKind::RewriteMockImport(..) => { - "`mock` is deprecated, use `unittest.mock`".to_string() - } - CheckKind::RewriteListComprehension => { - "Replace unpacked list comprehension with a generator expression".to_string() - } - CheckKind::RewriteYieldFrom => { - "Replace `yield` over `for` loop with `yield from`".to_string() - } - // pydocstyle - CheckKind::FitsOnOneLine => "One-line docstring should fit on one line".to_string(), - CheckKind::BlankLineAfterSummary(num_lines) => { - if *num_lines == 0 { - "1 blank line required between summary line and description".to_string() - } else { - format!( - "1 blank line required between summary line and description (found \ - {num_lines})" - ) - } - } - CheckKind::NewLineAfterLastParagraph => { - "Multi-line docstring closing quotes should be on a separate line".to_string() - } - CheckKind::NoSurroundingWhitespace => { - "No whitespaces allowed surrounding docstring text".to_string() - } - CheckKind::EndsInPeriod => "First line should end with a period".to_string(), - CheckKind::NonEmpty => "Docstring is empty".to_string(), - CheckKind::EndsInPunctuation => "First line should end with a period, question mark, \ - or exclamation point" - .to_string(), - CheckKind::FirstLineCapitalized => { - "First word of the first line should be properly capitalized".to_string() - } - CheckKind::UsesRPrefixForBackslashedContent => { - r#"Use r""" if any backslashes in a docstring"#.to_string() - } - CheckKind::UsesTripleQuotes => r#"Use """triple double quotes""""#.to_string(), - CheckKind::MultiLineSummaryFirstLine => { - "Multi-line docstring summary should start at the first line".to_string() - } - CheckKind::MultiLineSummarySecondLine => { - "Multi-line docstring summary should start at the second line".to_string() - } - CheckKind::NoSignature => { - "First line should not be the function's signature".to_string() - } - CheckKind::NoBlankLineBeforeFunction(num_lines) => { - format!("No blank lines allowed before function docstring (found {num_lines})") - } - CheckKind::NoBlankLineAfterFunction(num_lines) => { - format!("No blank lines allowed after function docstring (found {num_lines})") - } - CheckKind::NoBlankLineBeforeClass(..) => { - "No blank lines allowed before class docstring".to_string() - } - CheckKind::OneBlankLineBeforeClass(..) => { - "1 blank line required before class docstring".to_string() - } - CheckKind::OneBlankLineAfterClass(..) => { - "1 blank line required after class docstring".to_string() - } - CheckKind::PublicModule => "Missing docstring in public module".to_string(), - CheckKind::PublicClass => "Missing docstring in public class".to_string(), - CheckKind::PublicMethod => "Missing docstring in public method".to_string(), - CheckKind::PublicFunction => "Missing docstring in public function".to_string(), - CheckKind::PublicPackage => "Missing docstring in public package".to_string(), - CheckKind::MagicMethod => "Missing docstring in magic method".to_string(), - CheckKind::PublicNestedClass => "Missing docstring in public nested class".to_string(), - CheckKind::PublicInit => "Missing docstring in `__init__`".to_string(), - CheckKind::NoThisPrefix => { - "First word of the docstring should not be \"This\"".to_string() - } - CheckKind::SkipDocstring => { - "Function decorated with `@overload` shouldn't contain a docstring".to_string() - } - CheckKind::CapitalizeSectionName(name) => { - format!("Section name should be properly capitalized (\"{name}\")") - } - CheckKind::BlankLineAfterLastSection(name) => { - format!("Missing blank line after last section (\"{name}\")") - } - CheckKind::BlankLineAfterSection(name) => { - format!("Missing blank line after section (\"{name}\")") - } - CheckKind::BlankLineBeforeSection(name) => { - format!("Missing blank line before section (\"{name}\")") - } - CheckKind::NewLineAfterSectionName(name) => { - format!("Section name should end with a newline (\"{name}\")") - } - CheckKind::DashedUnderlineAfterSection(name) => { - format!("Missing dashed underline after section (\"{name}\")") - } - CheckKind::SectionUnderlineAfterName(name) => { - format!( - "Section underline should be in the line following the section's name \ - (\"{name}\")" - ) - } - CheckKind::SectionUnderlineMatchesSectionLength(name) => { - format!("Section underline should match the length of its name (\"{name}\")") - } - CheckKind::NoBlankLinesBetweenHeaderAndContent(name) => { - format!( - "No blank lines allowed between a section header and its content (\"{name}\")" - ) - } - CheckKind::NonEmptySection(name) => format!("Section has no content (\"{name}\")"), - CheckKind::SectionNotOverIndented(name) => { - format!("Section is over-indented (\"{name}\")") - } - CheckKind::SectionUnderlineNotOverIndented(name) => { - format!("Section underline is over-indented (\"{name}\")") - } - CheckKind::SectionNameEndsInColon(name) => { - format!("Section name should end with a colon (\"{name}\")") - } - CheckKind::DocumentAllArguments(names) => { - if names.len() == 1 { - let name = &names[0]; - format!("Missing argument description in the docstring: `{name}`") - } else { - let names = names.iter().map(|name| format!("`{name}`")).join(", "); - format!("Missing argument descriptions in the docstring: {names}") - } - } - CheckKind::IndentWithSpaces => { - "Docstring should be indented with spaces, not tabs".to_string() - } - CheckKind::NoUnderIndentation => "Docstring is under-indented".to_string(), - CheckKind::NoOverIndentation => "Docstring is over-indented".to_string(), - // pep8-naming - CheckKind::InvalidClassName(name) => { - format!("Class name `{name}` should use CapWords convention ") - } - CheckKind::InvalidFunctionName(name) => { - format!("Function name `{name}` should be lowercase") - } - CheckKind::InvalidArgumentName(name) => { - format!("Argument name `{name}` should be lowercase") - } - CheckKind::InvalidFirstArgumentNameForClassMethod => { - "First argument of a class method should be named `cls`".to_string() - } - CheckKind::InvalidFirstArgumentNameForMethod => { - "First argument of a method should be named `self`".to_string() - } - CheckKind::NonLowercaseVariableInFunction(name) => { - format!("Variable `{name}` in function should be lowercase") - } - CheckKind::DunderFunctionName => { - "Function name should not start and end with `__`".to_string() - } - CheckKind::ConstantImportedAsNonConstant(name, asname) => { - format!("Constant `{name}` imported as non-constant `{asname}`") - } - CheckKind::LowercaseImportedAsNonLowercase(name, asname) => { - format!("Lowercase `{name}` imported as non-lowercase `{asname}`") - } - CheckKind::CamelcaseImportedAsLowercase(name, asname) => { - format!("Camelcase `{name}` imported as lowercase `{asname}`") - } - CheckKind::CamelcaseImportedAsConstant(name, asname) => { - format!("Camelcase `{name}` imported as constant `{asname}`") - } - CheckKind::MixedCaseVariableInClassScope(name) => { - format!("Variable `{name}` in class scope should not be mixedCase") - } - CheckKind::MixedCaseVariableInGlobalScope(name) => { - format!("Variable `{name}` in global scope should not be mixedCase") - } - CheckKind::CamelcaseImportedAsAcronym(name, asname) => { - format!("Camelcase `{name}` imported as acronym `{asname}`") - } - CheckKind::ErrorSuffixOnExceptionName(name) => { - format!("Exception name `{name}` should be named with an Error suffix") - } - CheckKind::PEP3120UnnecessaryCodingComment => { - "UTF-8 encoding declaration is unnecessary".to_string() - } - // isort - CheckKind::UnsortedImports => "Import block is un-sorted or un-formatted".to_string(), - // eradicate - CheckKind::CommentedOutCode => "Found commented-out code".to_string(), - // flake8-bandit - CheckKind::AssertUsed => "Use of `assert` detected".to_string(), - CheckKind::ExecUsed => "Use of `exec` detected".to_string(), - CheckKind::BadFilePermissions(mask) => { - format!("`os.chmod` setting a permissive mask `{mask:#o}` on file or directory",) - } - CheckKind::HardcodedBindAllInterfaces => { - "Possible binding to all interfaces".to_string() - } - CheckKind::HardcodedPasswordString(string) - | CheckKind::HardcodedPasswordFuncArg(string) - | CheckKind::HardcodedPasswordDefault(string) => { - format!("Possible hardcoded password: \"{}\"", string.escape_debug()) - } - CheckKind::HardcodedTempFile(string) => { - format!( - "Probable insecure usage of temporary file or directory: \"{}\"", - string.escape_debug() - ) - } - CheckKind::HashlibInsecureHashFunction(string) => { - format!( - "Probable use of insecure hash functions in `hashlib`: \"{}\"", - string.escape_debug() - ) - } - CheckKind::RequestWithNoCertValidation(string) => { - format!( - "Probable use of `{string}` call with `verify=False` disabling SSL \ - certificate checks" - ) - } - CheckKind::UnsafeYAMLLoad(loader) => match loader { - Some(name) => { - format!( - "Probable use of unsafe loader `{name}` with `yaml.load`. Allows \ - instantiation of arbitrary objects. Consider `yaml.safe_load`." - ) - } - None => "Probable use of unsafe `yaml.load`. Allows instantiation of arbitrary \ - objects. Consider `yaml.safe_load`." - .to_string(), - }, - CheckKind::RequestWithoutTimeout(timeout) => match timeout { - Some(value) => { - format!("Probable use of requests call with timeout set to `{value}`") - } - None => "Probable use of requests call without timeout".to_string(), - }, - // flake8-blind-except - CheckKind::BlindExcept(name) => format!("Do not catch blind exception: `{name}`"), - // mccabe - CheckKind::FunctionIsTooComplex(name, complexity) => { - format!("`{name}` is too complex ({complexity})") - } - // flake8-boolean-trap - CheckKind::BooleanPositionalArgInFunctionDefinition => { - "Boolean positional arg in function definition".to_string() - } - CheckKind::BooleanDefaultValueInFunctionDefinition => { - "Boolean default value in function definition".to_string() - } - CheckKind::BooleanPositionalValueInFunctionCall => { - "Boolean positional value in function call".to_string() - } - // pygrep-hooks - CheckKind::BlanketNOQA => "Use specific error codes when using `noqa`".to_string(), - CheckKind::BlanketTypeIgnore => { - "Use specific error codes when ignoring type issues".to_string() - } - CheckKind::DeprecatedLogWarn => { - "`warn` is deprecated in favor of `warning`".to_string() - } - CheckKind::NoEval => "No builtin `eval()` allowed".to_string(), - // flake8-unused-arguments - CheckKind::UnusedFunctionArgument(name) => { - format!("Unused function argument: `{name}`") - } - CheckKind::UnusedMethodArgument(name) => format!("Unused method argument: `{name}`"), - CheckKind::UnusedClassMethodArgument(name) => { - format!("Unused class method argument: `{name}`") - } - CheckKind::UnusedStaticMethodArgument(name) => { - format!("Unused static method argument: `{name}`") - } - CheckKind::UnusedLambdaArgument(name) => format!("Unused lambda argument: `{name}`"), - // flake8-import-conventions - CheckKind::ImportAliasIsNotConventional(name, asname) => { - format!("`{name}` should be imported as `{asname}`") - } - // pandas-vet - CheckKind::UseOfInplaceArgument => { - "`inplace=True` should be avoided; it has inconsistent behavior".to_string() - } - CheckKind::UseOfDotIsNull => { - "`.isna` is preferred to `.isnull`; functionality is equivalent".to_string() - } - CheckKind::UseOfDotNotNull => { - "`.notna` is preferred to `.notnull`; functionality is equivalent".to_string() - } - CheckKind::UseOfDotIx => { - "`.ix` is deprecated; use more explicit `.loc` or `.iloc`".to_string() - } - CheckKind::UseOfDotAt => { - "Use `.loc` instead of `.at`. If speed is important, use numpy.".to_string() - } - CheckKind::UseOfDotIat => { - "Use `.iloc` instead of `.iat`. If speed is important, use numpy.".to_string() - } - CheckKind::UseOfDotPivotOrUnstack => "`.pivot_table` is preferred to `.pivot` or \ - `.unstack`; provides same functionality" - .to_string(), - CheckKind::UseOfDotValues => "Use `.to_numpy()` instead of `.values`".to_string(), - CheckKind::UseOfDotReadTable => { - "`.read_csv` is preferred to `.read_table`; provides same functionality".to_string() - } - CheckKind::UseOfDotStack => { - "`.melt` is preferred to `.stack`; provides same functionality".to_string() - } - CheckKind::DfIsABadVariableName => { - "`df` is a bad variable name. Be kinder to your future self.".to_string() - } - CheckKind::UseOfPdMerge => "Use `.merge` method instead of `pd.merge` function. They \ - have equivalent functionality." - .to_string(), - // flake8-errmsg - CheckKind::RawStringInException => { - "Exception must not use a string literal, assign to variable first".to_string() - } - CheckKind::FStringInException => { - "Exception must not use an f-string literal, assign to variable first".to_string() - } - CheckKind::DotFormatInException => "Exception must not use a `.format()` string \ - directly, assign to variable first" - .to_string(), - // flake8-datetimez - CheckKind::CallDatetimeWithoutTzinfo => "The use of `datetime.datetime()` without \ - `tzinfo` argument is not allowed" - .to_string(), - CheckKind::CallDatetimeToday => "The use of `datetime.datetime.today()` is not \ - allowed. Use `datetime.datetime.now(tz=)` instead." - .to_string(), - CheckKind::CallDatetimeUtcnow => "The use of `datetime.datetime.utcnow()` is not \ - allowed. Use `datetime.datetime.now(tz=)` instead." - .to_string(), - CheckKind::CallDatetimeUtcfromtimestamp => { - "The use of `datetime.datetime.utcfromtimestamp()` is not allowed. Use \ - `datetime.datetime.fromtimestamp(, tz=)` instead." - .to_string() - } - CheckKind::CallDatetimeNowWithoutTzinfo => "The use of `datetime.datetime.now()` \ - without `tz` argument is not allowed" - .to_string(), - CheckKind::CallDatetimeFromtimestamp => "The use of \ - `datetime.datetime.fromtimestamp()` without \ - `tz` argument is not allowed" - .to_string(), - CheckKind::CallDatetimeStrptimeWithoutZone => { - "The use of `datetime.datetime.strptime()` without %z must be followed by \ - `.replace(tzinfo=)`" - .to_string() - } - CheckKind::CallDateToday => "The use of `datetime.date.today()` is not allowed. Use \ - `datetime.datetime.now(tz=).date()` instead." - .to_string(), - CheckKind::CallDateFromtimestamp => { - "The use of `datetime.date.fromtimestamp()` is not allowed. Use \ - `datetime.datetime.fromtimestamp(, tz=).date()` instead." - .to_string() - } - // flake8-pytest-style - CheckKind::IncorrectFixtureParenthesesStyle(expected_parens, actual_parens) => { - format!( - "Use `@pytest.fixture{expected_parens}` over `@pytest.fixture{actual_parens}`" - ) - } - CheckKind::FixturePositionalArgs(function) => { - format!( - "Configuration for fixture `{function}` specified via positional args, use \ - kwargs" - ) - } - CheckKind::ExtraneousScopeFunction => { - "`scope='function'` is implied in `@pytest.fixture()`".to_string() - } - CheckKind::MissingFixtureNameUnderscore(function) => { - format!("Fixture `{function}` does not return anything, add leading underscore") - } - CheckKind::IncorrectFixtureNameUnderscore(function) => { - format!("Fixture `{function}` returns a value, remove leading underscore") - } - CheckKind::ParametrizeNamesWrongType(expected) => { - format!("Wrong name(s) type in `@pytest.mark.parametrize`, expected `{expected}`") - } - CheckKind::ParametrizeValuesWrongType(values, row) => { - format!( - "Wrong values type in `@pytest.mark.parametrize` expected `{values}` of \ - `{row}`" - ) - } - CheckKind::PatchWithLambda => { - "Use `return_value=` instead of patching with `lambda`".to_string() - } - CheckKind::UnittestAssertion(assertion) => { - format!("Use a regular `assert` instead of unittest-style `{assertion}`") - } - CheckKind::RaisesWithoutException => { - "set the expected exception in `pytest.raises()`".to_string() - } - CheckKind::RaisesTooBroad(exception) => { - format!( - "`pytest.raises({exception})` is too broad, set the `match` parameter or use \ - a more specific exception" - ) - } - CheckKind::RaisesWithMultipleStatements => { - "`pytest.raises()` block should contain a single simple statement".to_string() - } - CheckKind::IncorrectPytestImport => { - "Found incorrect import of pytest, use simple `import pytest` instead".to_string() - } - CheckKind::AssertAlwaysFalse => { - "Assertion always fails, replace with `pytest.fail()`".to_string() - } - CheckKind::FailWithoutMessage => "No message passed to `pytest.fail()`".to_string(), - CheckKind::AssertInExcept(name) => { - format!( - "Found assertion on exception `{name}` in except block, use `pytest.raises()` \ - instead" - ) - } - CheckKind::CompositeAssertion => { - "Assertion should be broken down into multiple parts".to_string() - } - CheckKind::FixtureParamWithoutValue(name) => { - format!( - "Fixture `{name}` without value is injected as parameter, use \ - `@pytest.mark.usefixtures` instead" - ) - } - CheckKind::DeprecatedYieldFixture => { - "`@pytest.yield_fixture` is deprecated, use `@pytest.fixture`".to_string() - } - CheckKind::FixtureFinalizerCallback => { - "Use `yield` instead of `request.addfinalizer`".to_string() - } - CheckKind::UselessYieldFixture(name) => { - format!("No teardown in fixture `{name}`, use `return` instead of `yield`") - } - CheckKind::IncorrectMarkParenthesesStyle(mark_name, expected_parens, actual_parens) => { - format!( - "Use `@pytest.mark.{mark_name}{expected_parens}` over \ - `@pytest.mark.{mark_name}{actual_parens}`" - ) - } - CheckKind::UnnecessaryAsyncioMarkOnFixture => { - "`pytest.mark.asyncio` is unnecessary for fixtures".to_string() - } - CheckKind::ErroneousUseFixturesOnFixture => { - "`pytest.mark.usefixtures` has no effect on fixtures".to_string() - } - CheckKind::UseFixturesWithoutParameters => { - "Useless `pytest.mark.usefixtures` without parameters".to_string() - } - // flake8-pie - CheckKind::DupeClassFieldDefinitions(name) => { - format!("Class field `{name}` is defined multiple times") - } - CheckKind::NoUnnecessaryPass => "Unnecessary `pass` statement".to_string(), - CheckKind::PreferListBuiltin => "Prefer `list()` over useless lambda".to_string(), - // Ruff - CheckKind::AmbiguousUnicodeCharacterString(confusable, representant) => { - format!( - "String contains ambiguous unicode character '{confusable}' (did you mean \ - '{representant}'?)" - ) - } - CheckKind::AmbiguousUnicodeCharacterDocstring(confusable, representant) => { - format!( - "Docstring contains ambiguous unicode character '{confusable}' (did you mean \ - '{representant}'?)" - ) - } - CheckKind::AmbiguousUnicodeCharacterComment(confusable, representant) => { - format!( - "Comment contains ambiguous unicode character '{confusable}' (did you mean \ - '{representant}'?)" - ) - } - CheckKind::KeywordArgumentBeforeStarArgument(name) => { - format!("Keyword argument `{name}` must come after starred arguments") - } - CheckKind::UnusedNOQA(codes) => match codes { - None => "Unused blanket `noqa` directive".to_string(), - Some(codes) => { - let mut codes_by_reason = vec![]; - if !codes.unmatched.is_empty() { - codes_by_reason.push(format!( - "unused: {}", - codes - .unmatched - .iter() - .map(|code| format!("`{code}`")) - .join(", ") - )); - } - if !codes.disabled.is_empty() { - codes_by_reason.push(format!( - "non-enabled: {}", - codes - .disabled - .iter() - .map(|code| format!("`{code}`")) - .join(", ") - )); - } - if !codes.unknown.is_empty() { - codes_by_reason.push(format!( - "unknown: {}", - codes - .unknown - .iter() - .map(|code| format!("`{code}`")) - .join(", ") - )); - } - if codes_by_reason.is_empty() { - "Unused `noqa` directive".to_string() - } else { - format!("Unused `noqa` directive ({})", codes_by_reason.join("; ")) - } - } - }, - } - } - - /// The summary text for the check. Typically a truncated form of the body - /// text. - pub fn summary(&self) -> String { - match self { - CheckKind::UnaryPrefixIncrement => { - "Python does not support the unary prefix increment".to_string() - } - CheckKind::UnusedLoopControlVariable(name) => { - format!("Loop control variable `{name}` not used within the loop body") - } - CheckKind::NoAssertRaisesException => { - "`assertRaises(Exception)` should be considered evil".to_string() - } - CheckKind::StarArgUnpackingAfterKeywordArg => { - "Star-arg unpacking after a keyword argument is strongly discouraged".to_string() - } - - // flake8-datetimez - CheckKind::CallDatetimeToday => { - "The use of `datetime.datetime.today()` is not allowed".to_string() - } - CheckKind::CallDatetimeUtcnow => { - "The use of `datetime.datetime.utcnow()` is not allowed".to_string() - } - CheckKind::CallDatetimeUtcfromtimestamp => { - "The use of `datetime.datetime.utcfromtimestamp()` is not allowed".to_string() - } - CheckKind::CallDateToday => { - "The use of `datetime.date.today()` is not allowed.".to_string() - } - CheckKind::CallDateFromtimestamp => { - "The use of `datetime.date.fromtimestamp()` is not allowed".to_string() + CheckKind::CallDateFromtimestamp(..) => { + "The use of `datetime.date.fromtimestamp()` is not allowed".to_string() } _ => self.body(), } } - - /// Whether the check kind is (potentially) fixable. - pub fn fixable(&self) -> bool { - match self { - // Always-fixable checks. - CheckKind::AAndNotA(..) - | CheckKind::AOrNotA(..) - | CheckKind::AmbiguousUnicodeCharacterComment(..) - | CheckKind::AmbiguousUnicodeCharacterDocstring(..) - | CheckKind::AmbiguousUnicodeCharacterString(..) - | CheckKind::AndFalse - | CheckKind::BlankLineAfterLastSection(..) - | CheckKind::BlankLineAfterSection(..) - | CheckKind::BlankLineBeforeSection(..) - | CheckKind::CapitalizeSectionName(..) - | CheckKind::CommentedOutCode - | CheckKind::CompareWithTuple(..) - | CheckKind::ConvertLoopToAll(..) - | CheckKind::ConvertLoopToAny(..) - | CheckKind::ConvertNamedTupleFunctionalToClass(..) - | CheckKind::ConvertTypedDictFunctionalToClass(..) - | CheckKind::DashedUnderlineAfterSection(..) - | CheckKind::DatetimeTimezoneUTC - | CheckKind::DeprecatedUnittestAlias(..) - | CheckKind::DoNotAssertFalse - | CheckKind::DoNotAssignLambda(..) - | CheckKind::DoubleNegation(..) - | CheckKind::DupeClassFieldDefinitions(..) - | CheckKind::DuplicateHandlerException(..) - | CheckKind::DuplicateIsinstanceCall(..) - | CheckKind::EndsInPeriod - | CheckKind::EndsInPunctuation - | CheckKind::FStringMissingPlaceholders - | CheckKind::GetAttrWithConstant - | CheckKind::IfExprWithFalseTrue(..) - | CheckKind::IfExprWithTrueFalse(..) - | CheckKind::IfExprWithTwistedArms(..) - | CheckKind::ImplicitReturn - | CheckKind::ImplicitReturnValue - | CheckKind::IncorrectFixtureParenthesesStyle(..) - | CheckKind::IncorrectMarkParenthesesStyle(..) - | CheckKind::InvalidEscapeSequence(..) - | CheckKind::IsLiteral(..) - | CheckKind::KeyInDict(..) - | CheckKind::MisplacedComparisonConstant(..) - | CheckKind::MissingReturnTypeSpecialMethod(..) - | CheckKind::NativeLiterals(..) - | CheckKind::NegateEqualOp(..) - | CheckKind::NegateNotEqualOp(..) - | CheckKind::NewLineAfterLastParagraph - | CheckKind::NewLineAfterSectionName(..) - | CheckKind::NoBlankLineAfterFunction(..) - | CheckKind::NoBlankLineBeforeClass(..) - | CheckKind::NoBlankLineBeforeFunction(..) - | CheckKind::NoBlankLinesBetweenHeaderAndContent(..) - | CheckKind::NoNewLineAtEndOfFile - | CheckKind::NoOverIndentation - | CheckKind::NoSurroundingWhitespace - | CheckKind::NoUnderIndentation - | CheckKind::NoUnnecessaryPass - | CheckKind::NoneComparison(..) - | CheckKind::NotInTest - | CheckKind::NotIsTest - | CheckKind::OSErrorAlias(..) - | CheckKind::OneBlankLineAfterClass(..) - | CheckKind::OneBlankLineBeforeClass(..) - | CheckKind::OpenAlias - | CheckKind::OrTrue - | CheckKind::PEP3120UnnecessaryCodingComment - | CheckKind::PPrintFound - | CheckKind::ParametrizeNamesWrongType(..) - | CheckKind::PercentFormatExtraNamedArguments(..) - | CheckKind::PreferListBuiltin - | CheckKind::PrintFound - | CheckKind::RaiseNotImplemented - | CheckKind::RedundantOpenModes(..) - | CheckKind::RedundantTupleInExceptionHandler(..) - | CheckKind::RemoveSixCompat - | CheckKind::ReplaceStdoutStderr - | CheckKind::ReplaceUniversalNewlines - | CheckKind::ReturnBoolConditionDirectly(..) - | CheckKind::RewriteCElementTree - | CheckKind::RewriteListComprehension - | CheckKind::RewriteMockImport(..) - | CheckKind::RewriteUnicodeLiteral - | CheckKind::RewriteYieldFrom - | CheckKind::SectionNameEndsInColon(..) - | CheckKind::SectionNotOverIndented(..) - | CheckKind::SectionUnderlineAfterName(..) - | CheckKind::SectionUnderlineMatchesSectionLength(..) - | CheckKind::SectionUnderlineNotOverIndented(..) - | CheckKind::SetAttrWithConstant - | CheckKind::StringDotFormatExtraNamedArguments(..) - | CheckKind::SuperCallWithParameters - | CheckKind::TrueFalseComparison(..) - | CheckKind::TypeOfPrimitive(..) - | CheckKind::TypingTextStrAlias - | CheckKind::UnnecessaryBuiltinImport(..) - | CheckKind::UnnecessaryCallAroundSorted(..) - | CheckKind::UnnecessaryCollectionCall(..) - | CheckKind::UnnecessaryComprehension(..) - | CheckKind::UnnecessaryEncodeUTF8 - | CheckKind::UnnecessaryFutureImport(..) - | CheckKind::UnnecessaryGeneratorDict - | CheckKind::UnnecessaryGeneratorList - | CheckKind::UnnecessaryGeneratorSet - | CheckKind::UnnecessaryLRUCacheParams - | CheckKind::UnnecessaryListCall - | CheckKind::UnnecessaryListComprehensionDict - | CheckKind::UnnecessaryListComprehensionSet - | CheckKind::UnnecessaryLiteralDict(..) - | CheckKind::UnnecessaryLiteralSet(..) - | CheckKind::UnnecessaryLiteralWithinListCall(..) - | CheckKind::UnnecessaryLiteralWithinTupleCall(..) - | CheckKind::UnnecessaryReturnNone - | CheckKind::UnsortedImports - | CheckKind::UnusedLoopControlVariable(..) - | CheckKind::UnusedNOQA(..) - | CheckKind::UnusedVariable(..) - | CheckKind::UseFixturesWithoutParameters - | CheckKind::UsePEP585Annotation(..) - | CheckKind::UsePEP604Annotation - | CheckKind::UseSysExit(..) - | CheckKind::UseTernaryOperator(..) - | CheckKind::UselessImportAlias - | CheckKind::UselessMetaclassType - | CheckKind::UselessObjectInheritance(..) - | CheckKind::UselessYieldFixture(..) - | CheckKind::YodaConditions(..) => true, - // Conditionally-fixable checks. - CheckKind::UnusedImport(_, false, _) => true, - CheckKind::BlankLineAfterSummary(num_lines) if *num_lines > 0 => true, - // Non-fixable checks. - _ => false, - } - } - - /// The message used to describe the fix action for a given `CheckKind`. - pub fn commit(&self) -> Option { - match self { - CheckKind::AAndNotA(..) => Some("Replace with `False`".to_string()), - CheckKind::AOrNotA(..) => Some("Replace with `True`".to_string()), - CheckKind::AmbiguousUnicodeCharacterString(confusable, representant) - | CheckKind::AmbiguousUnicodeCharacterDocstring(confusable, representant) - | CheckKind::AmbiguousUnicodeCharacterComment(confusable, representant) => { - Some(format!("Replace '{confusable}' with '{representant}'")) - } - CheckKind::AndFalse => Some("Replace with `False`".to_string()), - CheckKind::BlankLineAfterLastSection(name) => { - Some(format!("Add blank line after \"{name}\"")) - } - CheckKind::BlankLineAfterSection(name) => { - Some(format!("Add blank line after \"{name}\"")) - } - CheckKind::BlankLineAfterSummary(..) => Some("Insert single blank line".to_string()), - CheckKind::BlankLineBeforeSection(name) => { - Some(format!("Add blank line before \"{name}\"")) - } - CheckKind::CapitalizeSectionName(name) => Some(format!("Capitalize \"{name}\"")), - CheckKind::CommentedOutCode => Some("Remove commented-out code".to_string()), - CheckKind::CompareWithTuple(value, values, or_op) => { - let values = values.join(", "); - Some(format!("Replace `{or_op}` with `{value} in {values}`")) - } - CheckKind::ConvertLoopToAll(all) => Some(format!("Replace with `{all}`")), - CheckKind::ConvertLoopToAny(any) => Some(format!("Replace with `{any}`")), - CheckKind::ConvertTypedDictFunctionalToClass(name) - | CheckKind::ConvertNamedTupleFunctionalToClass(name) => { - Some(format!("Convert `{name}` to class syntax")) - } - CheckKind::DashedUnderlineAfterSection(name) => { - Some(format!("Add dashed line under \"{name}\"")) - } - CheckKind::DatetimeTimezoneUTC => Some("Convert to `datetime.UTC` alias".to_string()), - CheckKind::DeprecatedUnittestAlias(alias, target) => { - Some(format!("Replace `{target}` with `{alias}`")) - } - CheckKind::DoNotAssertFalse => Some("Replace `assert False`".to_string()), - CheckKind::DoNotAssignLambda(name) => Some(format!("Rewrite `{name}` as a `def`")), - CheckKind::DoubleNegation(expr) => Some(format!("Replace with `{expr}`")), - CheckKind::DupeClassFieldDefinitions(name) => { - Some(format!("Remove duplicate field definition for `{name}`")) - } - CheckKind::DuplicateHandlerException(..) => Some("De-duplicate exceptions".to_string()), - CheckKind::DuplicateIsinstanceCall(name) => { - Some(format!("Merge `isinstance` calls for `{name}`")) - } - CheckKind::EndsInPeriod => Some("Add period".to_string()), - CheckKind::EndsInPunctuation => Some("Add closing punctuation".to_string()), - CheckKind::ExtraneousScopeFunction => Some("Remove `scope=` argument".to_string()), - CheckKind::FStringMissingPlaceholders => { - Some("Remove extraneous `f` prefix".to_string()) - } - CheckKind::GetAttrWithConstant => { - Some("Replace `getattr` with attribute access".to_string()) - } - CheckKind::IfExprWithFalseTrue(expr) => Some(format!("Replace with `not {expr}`")), - CheckKind::IfExprWithTrueFalse(expr) => Some(format!("Replace with `bool({expr})`")), - CheckKind::IfExprWithTwistedArms(expr1, expr2) => { - Some(format!("Replace with `{expr1} if {expr1} else {expr2}`")) - } - CheckKind::ImplicitReturnValue => Some("Add explicit `None` return value".to_string()), - CheckKind::ImplicitReturn => Some("Add explicit `return` statement".to_string()), - CheckKind::IncorrectMarkParenthesesStyle(..) => { - Some("Add/remove parentheses".to_string()) - } - CheckKind::IncorrectFixtureParenthesesStyle(..) => { - Some("Add/remove parentheses".to_string()) - } - CheckKind::InvalidEscapeSequence(..) => { - Some("Add backslash to escape sequence".to_string()) - } - CheckKind::IsLiteral(cmpop) => Some(match cmpop { - IsCmpop::Is => "Replace `is` with `==`".to_string(), - IsCmpop::IsNot => "Replace `is not` with `!=`".to_string(), - }), - CheckKind::KeyInDict(key, dict) => Some(format!("Convert to `{key} in {dict}`")), - CheckKind::MisplacedComparisonConstant(comparison) => { - Some(format!("Replace with {comparison}")) - } - CheckKind::MissingReturnTypeSpecialMethod(..) => { - Some("Add `None` return type".to_string()) - } - CheckKind::NativeLiterals(literal_type) => { - Some(format!("Replace with `{literal_type}`")) - } - CheckKind::NegateEqualOp(..) => Some("Replace with `!=` operator".to_string()), - CheckKind::NegateNotEqualOp(..) => Some("Replace with `==` operator".to_string()), - CheckKind::NewLineAfterLastParagraph => { - Some("Move closing quotes to new line".to_string()) - } - CheckKind::OpenAlias => Some("Replace with builtin `open`".to_string()), - CheckKind::OrTrue => Some("Replace with `True`".to_string()), - CheckKind::ReplaceUniversalNewlines => { - Some("Replace with `text` keyword argument".to_string()) - } - CheckKind::ReplaceStdoutStderr => { - Some("Replace with `capture_output` keyword argument".to_string()) - } - CheckKind::RewriteCElementTree => Some("Replace with `ElementTree`".to_string()), - CheckKind::RewriteUnicodeLiteral => Some("Remove unicode prefix".to_string()), - CheckKind::RewriteMockImport(reference_type) => Some(match reference_type { - MockReference::Import => "Import from `unittest.mock` instead".to_string(), - MockReference::Attribute => "Replace `mock.mock` with `mock`".to_string(), - }), - CheckKind::RewriteListComprehension => { - Some("Replace with generator expression".to_string()) - } - CheckKind::RewriteYieldFrom => Some("Replace with `yield from`".to_string()), - CheckKind::NewLineAfterSectionName(name) => { - Some(format!("Add newline after \"{name}\"")) - } - CheckKind::NoBlankLineBeforeFunction(..) => { - Some("Remove blank line(s) before function docstring".to_string()) - } - CheckKind::NoBlankLineAfterFunction(..) => { - Some("Remove blank line(s) after function docstring".to_string()) - } - CheckKind::NoBlankLineBeforeClass(..) => { - Some("Remove blank line(s) before class docstring".to_string()) - } - CheckKind::NoUnnecessaryPass => Some("Remove unnecessary `pass`".to_string()), - CheckKind::OneBlankLineBeforeClass(..) => { - Some("Insert 1 blank line before class docstring".to_string()) - } - CheckKind::OneBlankLineAfterClass(..) => { - Some("Insert 1 blank line after class docstring".to_string()) - } - CheckKind::OSErrorAlias(name) => Some(match name { - None => "Replace with builtin `OSError`".to_string(), - Some(name) => format!("Replace `{name}` with builtin `OSError`"), - }), - CheckKind::NoBlankLinesBetweenHeaderAndContent(..) => { - Some("Remove blank line(s)".to_string()) - } - CheckKind::NoNewLineAtEndOfFile => Some("Add trailing newline".to_string()), - CheckKind::NoOverIndentation => Some("Remove over-indentation".to_string()), - CheckKind::NoSurroundingWhitespace => Some("Trim surrounding whitespace".to_string()), - CheckKind::NoUnderIndentation => Some("Increase indentation".to_string()), - CheckKind::NoneComparison(op) => Some(match op { - EqCmpop::Eq => "Replace with `cond is None`".to_string(), - EqCmpop::NotEq => "Replace with `cond is not None`".to_string(), - }), - CheckKind::NotInTest => Some("Convert to `not in`".to_string()), - CheckKind::NotIsTest => Some("Convert to `is not`".to_string()), - CheckKind::ParametrizeNamesWrongType(expected) => { - Some(format!("Use a `{expected}` for parameter names")) - } - CheckKind::PEP3120UnnecessaryCodingComment => { - Some("Remove unnecessary coding comment".to_string()) - } - CheckKind::PreferListBuiltin => Some("Replace with `list`".to_string()), - CheckKind::PPrintFound => Some("Remove `pprint`".to_string()), - CheckKind::PercentFormatExtraNamedArguments(missing) - | CheckKind::StringDotFormatExtraNamedArguments(missing) => { - let message = missing.join(", "); - Some(format!("Remove extra named arguments: {message}")) - } - CheckKind::PrintFound => Some("Remove `print`".to_string()), - CheckKind::RaiseNotImplemented => Some("Use `raise NotImplementedError`".to_string()), - CheckKind::RedundantOpenModes(replacement) => Some(match replacement { - None => "Remove open mode parameters".to_string(), - Some(replacement) => { - format!("Replace with \"{replacement}\"") - } - }), - CheckKind::RedundantTupleInExceptionHandler(name) => { - Some(format!("Replace with `except {name}`")) - } - CheckKind::RemoveSixCompat => Some("Remove `six` usage".to_string()), - CheckKind::ReturnBoolConditionDirectly(cond) => { - Some(format!("Replace with `return {cond}`")) - } - CheckKind::SectionNameEndsInColon(name) => Some(format!("Add colon to \"{name}\"")), - CheckKind::SectionNotOverIndented(name) => { - Some(format!("Remove over-indentation from \"{name}\"")) - } - CheckKind::SectionUnderlineAfterName(name) => { - Some(format!("Add underline to \"{name}\"")) - } - CheckKind::SectionUnderlineMatchesSectionLength(name) => { - Some(format!("Adjust underline length to match \"{name}\"")) - } - CheckKind::SectionUnderlineNotOverIndented(name) => { - Some(format!("Remove over-indentation from \"{name}\" underline")) - } - CheckKind::SetAttrWithConstant => Some("Replace `setattr` with assignment".to_string()), - CheckKind::SuperCallWithParameters => Some("Remove `__super__` parameters".to_string()), - CheckKind::TrueFalseComparison(true, EqCmpop::Eq) => { - Some("Replace with `cond is True`".to_string()) - } - CheckKind::TrueFalseComparison(true, EqCmpop::NotEq) => { - Some("Replace with `cond is not True`".to_string()) - } - CheckKind::TrueFalseComparison(false, EqCmpop::Eq) => { - Some("Replace with `cond is False`".to_string()) - } - CheckKind::TrueFalseComparison(false, EqCmpop::NotEq) => { - Some("Replace with `cond is not False`".to_string()) - } - CheckKind::TypeOfPrimitive(primitive) => Some(format!( - "Replace `type(...)` with `{}`", - primitive.builtin() - )), - CheckKind::TypingTextStrAlias => Some("Replace with `str`".to_string()), - CheckKind::UnnecessaryBuiltinImport(..) => { - Some("Remove unnecessary builtin import".to_string()) - } - CheckKind::UnnecessaryCallAroundSorted(func) => { - Some(format!("Remove unnecessary `{func}` call")) - } - CheckKind::UnnecessaryCollectionCall(..) => Some("Rewrite as a literal".to_string()), - CheckKind::UnnecessaryComprehension(obj_type) => { - Some(format!("Rewrite using `{obj_type}()`")) - } - CheckKind::UnnecessaryEncodeUTF8 => Some("Remove unnecessary `encode`".to_string()), - CheckKind::UnnecessaryFutureImport(..) => { - Some("Remove unnecessary `__future__` import".to_string()) - } - CheckKind::UnnecessaryGeneratorDict => { - Some("Rewrite as a `dict` comprehension".to_string()) - } - CheckKind::UnnecessaryGeneratorList => { - Some("Rewrite as a `list` comprehension".to_string()) - } - CheckKind::UnnecessaryGeneratorSet => { - Some("Rewrite as a `set` comprehension".to_string()) - } - CheckKind::UnnecessaryLRUCacheParams => { - Some("Remove unnecessary parameters".to_string()) - } - CheckKind::UnnecessaryListCall => Some("Remove outer `list` call".to_string()), - CheckKind::UnnecessaryListComprehensionDict => { - Some("Rewrite as a `dict` comprehension".to_string()) - } - CheckKind::UnnecessaryListComprehensionSet => { - Some("Rewrite as a `set` comprehension".to_string()) - } - CheckKind::UnnecessaryLiteralDict(..) => { - Some("Rewrite as a `dict` literal".to_string()) - } - CheckKind::UnnecessaryLiteralSet(..) => Some("Rewrite as a `set` literal".to_string()), - CheckKind::UnnecessaryLiteralWithinTupleCall(literal) => Some({ - if literal == "list" { - "Rewrite as a `tuple` literal".to_string() - } else { - "Remove outer `tuple` call".to_string() - } - }), - CheckKind::UnnecessaryLiteralWithinListCall(literal) => Some({ - if literal == "list" { - "Remove outer `list` call".to_string() - } else { - "Rewrite as a `list` literal".to_string() - } - }), - CheckKind::UnnecessaryReturnNone => Some("Remove explicit `return None`".to_string()), - CheckKind::UnsortedImports => Some("Organize imports".to_string()), - CheckKind::UnusedImport(name, false, multiple) => { - if *multiple { - Some("Remove unused import".to_string()) - } else { - Some(format!("Remove unused import: `{name}`")) - } - } - CheckKind::UnusedLoopControlVariable(name) => { - Some(format!("Rename unused `{name}` to `_{name}`")) - } - CheckKind::UnusedNOQA(..) => Some("Remove unused `noqa` directive".to_string()), - CheckKind::UnusedVariable(name) => { - Some(format!("Remove assignment to unused variable `{name}`")) - } - CheckKind::UsePEP585Annotation(name) => { - Some(format!("Replace `{name}` with `{}`", name.to_lowercase(),)) - } - CheckKind::UsePEP604Annotation => Some("Convert to `X | Y`".to_string()), - CheckKind::UseFixturesWithoutParameters => { - Some("Remove `usefixtures` decorator or pass parameters".to_string()) - } - CheckKind::UseTernaryOperator(new_code) => { - Some(format!("Replace if-else-block with `{new_code}`")) - } - CheckKind::UseSysExit(name) => Some(format!("Replace `{name}` with `sys.exit()`")), - CheckKind::UselessImportAlias => Some("Remove import alias".to_string()), - CheckKind::UselessMetaclassType => Some("Remove `__metaclass__ = type`".to_string()), - CheckKind::UselessObjectInheritance(..) => { - Some("Remove `object` inheritance".to_string()) - } - CheckKind::UselessYieldFixture(..) => Some("Replace `yield` with `return`".to_string()), - CheckKind::YodaConditions(left, right) => { - Some(format!("Replace Yoda condition with `{left} == {right}`")) - } - _ => None, - } - } } #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -4181,9 +1338,9 @@ pub struct Check { } impl Check { - pub fn new(kind: CheckKind, range: Range) -> Self { + pub fn new>(kind: K, range: Range) -> Self { Self { - kind, + kind: kind.into(), location: range.location, end_location: range.end_location, fix: None, diff --git a/src/ruff/checks.rs b/src/ruff/checks.rs index 4df462a26b910..e8a013dfcfe5f 100644 --- a/src/ruff/checks.rs +++ b/src/ruff/checks.rs @@ -7,7 +7,7 @@ use crate::autofix::Fix; use crate::registry::CheckKind; use crate::settings::flags; use crate::source_code_locator::SourceCodeLocator; -use crate::{Check, Settings}; +use crate::{violations, Check, Settings}; /// See: static CONFUSABLES: Lazy> = Lazy::new(|| { @@ -1630,20 +1630,23 @@ pub fn ambiguous_unicode_character( }; let location = Location::new(start.row() + row_offset, col); let end_location = Location::new(location.row(), location.column() + 1); - let mut check = Check::new( + let mut check = Check::new::( match context { - Context::String => CheckKind::AmbiguousUnicodeCharacterString( + Context::String => violations::AmbiguousUnicodeCharacterString( current_char, representant, - ), - Context::Docstring => CheckKind::AmbiguousUnicodeCharacterDocstring( + ) + .into(), + Context::Docstring => violations::AmbiguousUnicodeCharacterDocstring( current_char, representant, - ), - Context::Comment => CheckKind::AmbiguousUnicodeCharacterComment( + ) + .into(), + Context::Comment => violations::AmbiguousUnicodeCharacterComment( current_char, representant, - ), + ) + .into(), }, Range::new(location, end_location), ); @@ -1687,7 +1690,7 @@ pub fn keyword_argument_before_star_argument(args: &[Expr], keywords: &[Keyword] let KeywordData { arg, .. } = &keyword.node; if let Some(arg) = arg { checks.push(Check::new( - CheckKind::KeywordArgumentBeforeStarArgument(arg.to_string()), + violations::KeywordArgumentBeforeStarArgument(arg.to_string()), Range::from_located(keyword), )); } diff --git a/src/violation.rs b/src/violation.rs new file mode 100644 index 0000000000000..2f7d3204d4cc2 --- /dev/null +++ b/src/violation.rs @@ -0,0 +1,60 @@ +use std::fmt::Debug; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +pub trait Violation: Debug + PartialEq + Eq + Serialize + DeserializeOwned { + /// The message used to describe the violation. + fn message(&self) -> String; + + /// If autofix is (potentially) available for this violation returns another + /// function that in turn can be used to obtain a string describing the + /// autofix. + fn autofix_title_formatter(&self) -> Option String> { + None + } + + /// A placeholder instance of the violation. + fn placeholder() -> Self; +} + +/// This trait exists just to make implementing the [`Violation`] trait more +/// convenient for violations that can always be autofixed. +pub trait AlwaysAutofixableViolation: + Debug + PartialEq + Eq + Serialize + DeserializeOwned +{ + /// The message used to describe the violation. + fn message(&self) -> String; + + /// The title displayed for the available autofix. + fn autofix_title(&self) -> String; + + /// A placeholder instance of the violation. + fn placeholder() -> Self; +} + +/// A blanket implementation. +impl Violation for VA { + fn message(&self) -> String { + ::message(self) + } + + fn autofix_title_formatter(&self) -> Option String> { + Some(Self::autofix_title) + } + + fn placeholder() -> Self { + ::placeholder() + } +} + +/// This macro just exists so that you don't have to add the `#[derive]` +/// attribute every time you define a new violation. And so that new traits can +/// be easily derived everywhere by just changing a single line. +#[macro_export] +macro_rules! define_violation { + ($($struct:tt)*) => { + #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] + $($struct)* + }; +} diff --git a/src/violations.rs b/src/violations.rs new file mode 100644 index 0000000000000..0dab8fe1d1595 --- /dev/null +++ b/src/violations.rs @@ -0,0 +1,5773 @@ +use itertools::Itertools; + +use crate::define_violation; +use crate::flake8_debugger::types::DebuggerUsingType; +use crate::flake8_pytest_style::types::{ + ParametrizeNameType, ParametrizeValuesRowType, ParametrizeValuesType, +}; +use crate::flake8_quotes::settings::Quote; +use crate::flake8_tidy_imports::settings::Strictness; +use crate::pyupgrade::types::Primitive; +use crate::registry::{ + Branch, DeferralKeyword, EqCmpop, IsCmpop, LiteralType, MockReference, UnusedCodes, +}; +use crate::violation::{AlwaysAutofixableViolation, Violation}; + +// pycodestyle errors + +define_violation!( + pub struct MultipleImportsOnOneLine; +); +impl Violation for MultipleImportsOnOneLine { + fn message(&self) -> String { + "Multiple imports on one line".to_string() + } + + fn placeholder() -> Self { + MultipleImportsOnOneLine + } +} + +define_violation!( + pub struct ModuleImportNotAtTopOfFile; +); +impl Violation for ModuleImportNotAtTopOfFile { + fn message(&self) -> String { + "Module level import not at top of file".to_string() + } + + fn placeholder() -> Self { + ModuleImportNotAtTopOfFile + } +} + +define_violation!( + pub struct LineTooLong(pub usize, pub usize); +); +impl Violation for LineTooLong { + fn message(&self) -> String { + let LineTooLong(length, limit) = self; + format!("Line too long ({length} > {limit} characters)") + } + + fn placeholder() -> Self { + LineTooLong(89, 88) + } +} + +define_violation!( + pub struct NoneComparison(pub EqCmpop); +); +impl AlwaysAutofixableViolation for NoneComparison { + fn message(&self) -> String { + let NoneComparison(op) = self; + match op { + EqCmpop::Eq => "Comparison to `None` should be `cond is None`".to_string(), + EqCmpop::NotEq => "Comparison to `None` should be `cond is not None`".to_string(), + } + } + + fn autofix_title(&self) -> String { + let NoneComparison(op) = self; + match op { + EqCmpop::Eq => "Replace with `cond is None`".to_string(), + EqCmpop::NotEq => "Replace with `cond is not None`".to_string(), + } + } + + fn placeholder() -> Self { + NoneComparison(EqCmpop::Eq) + } +} + +define_violation!( + pub struct TrueFalseComparison(pub bool, pub EqCmpop); +); +impl AlwaysAutofixableViolation for TrueFalseComparison { + fn message(&self) -> String { + let TrueFalseComparison(value, op) = self; + match (value, op) { + (true, EqCmpop::Eq) => "Comparison to `True` should be `cond is True`".to_string(), + (true, EqCmpop::NotEq) => { + "Comparison to `True` should be `cond is not True`".to_string() + } + (false, EqCmpop::Eq) => "Comparison to `False` should be `cond is False`".to_string(), + (false, EqCmpop::NotEq) => { + "Comparison to `False` should be `cond is not False`".to_string() + } + } + } + + fn autofix_title(&self) -> String { + let TrueFalseComparison(value, op) = self; + match (value, op) { + (true, EqCmpop::Eq) => "Replace with `cond is True`".to_string(), + (true, EqCmpop::NotEq) => "Replace with `cond is not True`".to_string(), + (false, EqCmpop::Eq) => "Replace with `cond is False`".to_string(), + (false, EqCmpop::NotEq) => "Replace with `cond is not False`".to_string(), + } + } + + fn placeholder() -> Self { + TrueFalseComparison(true, EqCmpop::Eq) + } +} + +define_violation!( + pub struct NotInTest; +); +impl AlwaysAutofixableViolation for NotInTest { + fn message(&self) -> String { + "Test for membership should be `not in`".to_string() + } + + fn autofix_title(&self) -> String { + "Convert to `not in`".to_string() + } + + fn placeholder() -> Self { + NotInTest + } +} + +define_violation!( + pub struct NotIsTest; +); +impl AlwaysAutofixableViolation for NotIsTest { + fn message(&self) -> String { + "Test for object identity should be `is not`".to_string() + } + + fn autofix_title(&self) -> String { + "Convert to `is not`".to_string() + } + + fn placeholder() -> Self { + NotIsTest + } +} + +define_violation!( + pub struct TypeComparison; +); +impl Violation for TypeComparison { + fn message(&self) -> String { + "Do not compare types, use `isinstance()`".to_string() + } + + fn placeholder() -> Self { + TypeComparison + } +} + +define_violation!( + pub struct DoNotUseBareExcept; +); +impl Violation for DoNotUseBareExcept { + fn message(&self) -> String { + "Do not use bare `except`".to_string() + } + + fn placeholder() -> Self { + DoNotUseBareExcept + } +} + +define_violation!( + pub struct DoNotAssignLambda(pub String); +); +impl AlwaysAutofixableViolation for DoNotAssignLambda { + fn message(&self) -> String { + "Do not assign a `lambda` expression, use a `def`".to_string() + } + + fn autofix_title(&self) -> String { + let DoNotAssignLambda(name) = self; + format!("Rewrite `{name}` as a `def`") + } + + fn placeholder() -> Self { + DoNotAssignLambda("...".to_string()) + } +} + +define_violation!( + pub struct AmbiguousVariableName(pub String); +); +impl Violation for AmbiguousVariableName { + fn message(&self) -> String { + let AmbiguousVariableName(name) = self; + format!("Ambiguous variable name: `{name}`") + } + + fn placeholder() -> Self { + AmbiguousVariableName("...".to_string()) + } +} + +define_violation!( + pub struct AmbiguousClassName(pub String); +); +impl Violation for AmbiguousClassName { + fn message(&self) -> String { + let AmbiguousClassName(name) = self; + format!("Ambiguous class name: `{name}`") + } + + fn placeholder() -> Self { + AmbiguousClassName("...".to_string()) + } +} + +define_violation!( + pub struct AmbiguousFunctionName(pub String); +); +impl Violation for AmbiguousFunctionName { + fn message(&self) -> String { + let AmbiguousFunctionName(name) = self; + format!("Ambiguous function name: `{name}`") + } + + fn placeholder() -> Self { + AmbiguousFunctionName("...".to_string()) + } +} + +define_violation!( + pub struct IOError(pub String); +); +impl Violation for IOError { + fn message(&self) -> String { + let IOError(message) = self; + message.clone() + } + + fn placeholder() -> Self { + IOError("IOError: `...`".to_string()) + } +} + +define_violation!( + pub struct SyntaxError(pub String); +); +impl Violation for SyntaxError { + fn message(&self) -> String { + let SyntaxError(message) = self; + format!("SyntaxError: {message}") + } + + fn placeholder() -> Self { + SyntaxError("`...`".to_string()) + } +} + +// pycodestyle warnings + +define_violation!( + pub struct NoNewLineAtEndOfFile; +); +impl AlwaysAutofixableViolation for NoNewLineAtEndOfFile { + fn message(&self) -> String { + "No newline at end of file".to_string() + } + + fn autofix_title(&self) -> String { + "Add trailing newline".to_string() + } + + fn placeholder() -> Self { + NoNewLineAtEndOfFile + } +} + +define_violation!( + pub struct InvalidEscapeSequence(pub char); +); +impl AlwaysAutofixableViolation for InvalidEscapeSequence { + fn message(&self) -> String { + let InvalidEscapeSequence(char) = self; + format!("Invalid escape sequence: '\\{char}'") + } + + fn autofix_title(&self) -> String { + "Add backslash to escape sequence".to_string() + } + + fn placeholder() -> Self { + InvalidEscapeSequence('c') + } +} + +// pyflakes + +define_violation!( + pub struct UnusedImport(pub String, pub bool, pub bool); +); +fn fmt_unused_import_autofix_msg(unused_import: &UnusedImport) -> String { + let UnusedImport(name, _, multiple) = unused_import; + if *multiple { + "Remove unused import".to_string() + } else { + format!("Remove unused import: `{name}`") + } +} +impl Violation for UnusedImport { + fn message(&self) -> String { + let UnusedImport(name, ignore_init, ..) = self; + if *ignore_init { + format!( + "`{name}` imported but unused; consider adding to `__all__` or using a redundant \ + alias" + ) + } else { + format!("`{name}` imported but unused") + } + } + + fn autofix_title_formatter(&self) -> Option String> { + let UnusedImport(_, ignore_init, _) = self; + if *ignore_init { + None + } else { + Some(fmt_unused_import_autofix_msg) + } + } + + fn placeholder() -> Self { + UnusedImport("...".to_string(), false, false) + } +} + +define_violation!( + pub struct ImportShadowedByLoopVar(pub String, pub usize); +); +impl Violation for ImportShadowedByLoopVar { + fn message(&self) -> String { + let ImportShadowedByLoopVar(name, line) = self; + format!("Import `{name}` from line {line} shadowed by loop variable") + } + + fn placeholder() -> Self { + ImportShadowedByLoopVar("...".to_string(), 1) + } +} + +define_violation!( + pub struct ImportStarUsed(pub String); +); +impl Violation for ImportStarUsed { + fn message(&self) -> String { + let ImportStarUsed(name) = self; + format!("`from {name} import *` used; unable to detect undefined names") + } + + fn placeholder() -> Self { + ImportStarUsed("...".to_string()) + } +} + +define_violation!( + pub struct LateFutureImport; +); +impl Violation for LateFutureImport { + fn message(&self) -> String { + "`from __future__` imports must occur at the beginning of the file".to_string() + } + + fn placeholder() -> Self { + LateFutureImport + } +} + +define_violation!( + pub struct ImportStarUsage(pub String, pub Vec); +); +impl Violation for ImportStarUsage { + fn message(&self) -> String { + let ImportStarUsage(name, sources) = self; + let sources = sources + .iter() + .map(|source| format!("`{source}`")) + .join(", "); + format!("`{name}` may be undefined, or defined from star imports: {sources}") + } + + fn placeholder() -> Self { + ImportStarUsage("...".to_string(), vec!["...".to_string()]) + } +} + +define_violation!( + pub struct ImportStarNotPermitted(pub String); +); +impl Violation for ImportStarNotPermitted { + fn message(&self) -> String { + let ImportStarNotPermitted(name) = self; + format!("`from {name} import *` only allowed at module level") + } + + fn placeholder() -> Self { + ImportStarNotPermitted("...".to_string()) + } +} + +define_violation!( + pub struct FutureFeatureNotDefined(pub String); +); +impl Violation for FutureFeatureNotDefined { + fn message(&self) -> String { + let FutureFeatureNotDefined(name) = self; + format!("Future feature `{name}` is not defined") + } + + fn placeholder() -> Self { + FutureFeatureNotDefined("...".to_string()) + } +} + +define_violation!( + pub struct PercentFormatInvalidFormat(pub String); +); +impl Violation for PercentFormatInvalidFormat { + fn message(&self) -> String { + let PercentFormatInvalidFormat(message) = self; + format!("'...' % ... has invalid format string: {message}") + } + + fn placeholder() -> Self { + PercentFormatInvalidFormat("...".to_string()) + } +} + +define_violation!( + pub struct PercentFormatExpectedMapping; +); +impl Violation for PercentFormatExpectedMapping { + fn message(&self) -> String { + "'...' % ... expected mapping but got sequence".to_string() + } + + fn placeholder() -> Self { + PercentFormatExpectedMapping + } +} + +define_violation!( + pub struct PercentFormatExpectedSequence; +); +impl Violation for PercentFormatExpectedSequence { + fn message(&self) -> String { + "'...' % ... expected sequence but got mapping".to_string() + } + + fn placeholder() -> Self { + PercentFormatExpectedSequence + } +} + +define_violation!( + pub struct PercentFormatExtraNamedArguments(pub Vec); +); +impl AlwaysAutofixableViolation for PercentFormatExtraNamedArguments { + fn message(&self) -> String { + let PercentFormatExtraNamedArguments(missing) = self; + let message = missing.join(", "); + format!("'...' % ... has unused named argument(s): {message}") + } + + fn autofix_title(&self) -> String { + let PercentFormatExtraNamedArguments(missing) = self; + let message = missing.join(", "); + format!("Remove extra named arguments: {message}") + } + + fn placeholder() -> Self { + PercentFormatExtraNamedArguments(vec!["...".to_string()]) + } +} + +define_violation!( + pub struct PercentFormatMissingArgument(pub Vec); +); +impl Violation for PercentFormatMissingArgument { + fn message(&self) -> String { + let PercentFormatMissingArgument(missing) = self; + let message = missing.join(", "); + format!("'...' % ... is missing argument(s) for placeholder(s): {message}") + } + + fn placeholder() -> Self { + PercentFormatMissingArgument(vec!["...".to_string()]) + } +} + +define_violation!( + pub struct PercentFormatMixedPositionalAndNamed; +); +impl Violation for PercentFormatMixedPositionalAndNamed { + fn message(&self) -> String { + "'...' % ... has mixed positional and named placeholders".to_string() + } + + fn placeholder() -> Self { + PercentFormatMixedPositionalAndNamed + } +} + +define_violation!( + pub struct PercentFormatPositionalCountMismatch(pub usize, pub usize); +); +impl Violation for PercentFormatPositionalCountMismatch { + fn message(&self) -> String { + let PercentFormatPositionalCountMismatch(wanted, got) = self; + format!("'...' % ... has {wanted} placeholder(s) but {got} substitution(s)") + } + + fn placeholder() -> Self { + PercentFormatPositionalCountMismatch(4, 2) + } +} + +define_violation!( + pub struct PercentFormatStarRequiresSequence; +); +impl Violation for PercentFormatStarRequiresSequence { + fn message(&self) -> String { + "'...' % ... `*` specifier requires sequence".to_string() + } + + fn placeholder() -> Self { + PercentFormatStarRequiresSequence + } +} + +define_violation!( + pub struct PercentFormatUnsupportedFormatCharacter(pub char); +); +impl Violation for PercentFormatUnsupportedFormatCharacter { + fn message(&self) -> String { + let PercentFormatUnsupportedFormatCharacter(char) = self; + format!("'...' % ... has unsupported format character '{char}'") + } + + fn placeholder() -> Self { + PercentFormatUnsupportedFormatCharacter('c') + } +} + +define_violation!( + pub struct StringDotFormatInvalidFormat(pub String); +); +impl Violation for StringDotFormatInvalidFormat { + fn message(&self) -> String { + let StringDotFormatInvalidFormat(message) = self; + format!("'...'.format(...) has invalid format string: {message}") + } + + fn placeholder() -> Self { + StringDotFormatInvalidFormat("...".to_string()) + } +} + +define_violation!( + pub struct StringDotFormatExtraNamedArguments(pub Vec); +); +impl AlwaysAutofixableViolation for StringDotFormatExtraNamedArguments { + fn message(&self) -> String { + let StringDotFormatExtraNamedArguments(missing) = self; + let message = missing.join(", "); + format!("'...'.format(...) has unused named argument(s): {message}") + } + + fn autofix_title(&self) -> String { + let StringDotFormatExtraNamedArguments(missing) = self; + let message = missing.join(", "); + format!("Remove extra named arguments: {message}") + } + + fn placeholder() -> Self { + StringDotFormatExtraNamedArguments(vec!["...".to_string()]) + } +} + +define_violation!( + pub struct StringDotFormatExtraPositionalArguments(pub Vec); +); +impl Violation for StringDotFormatExtraPositionalArguments { + fn message(&self) -> String { + let StringDotFormatExtraPositionalArguments(missing) = self; + let message = missing.join(", "); + format!("'...'.format(...) has unused arguments at position(s): {message}") + } + + fn placeholder() -> Self { + StringDotFormatExtraPositionalArguments(vec!["...".to_string()]) + } +} + +define_violation!( + pub struct StringDotFormatMissingArguments(pub Vec); +); +impl Violation for StringDotFormatMissingArguments { + fn message(&self) -> String { + let StringDotFormatMissingArguments(missing) = self; + let message = missing.join(", "); + format!("'...'.format(...) is missing argument(s) for placeholder(s): {message}") + } + + fn placeholder() -> Self { + StringDotFormatMissingArguments(vec!["...".to_string()]) + } +} + +define_violation!( + pub struct StringDotFormatMixingAutomatic; +); +impl Violation for StringDotFormatMixingAutomatic { + fn message(&self) -> String { + "'...'.format(...) mixes automatic and manual numbering".to_string() + } + + fn placeholder() -> Self { + StringDotFormatMixingAutomatic + } +} + +define_violation!( + pub struct FStringMissingPlaceholders; +); +impl AlwaysAutofixableViolation for FStringMissingPlaceholders { + fn message(&self) -> String { + "f-string without any placeholders".to_string() + } + + fn autofix_title(&self) -> String { + "Remove extraneous `f` prefix".to_string() + } + + fn placeholder() -> Self { + FStringMissingPlaceholders + } +} + +define_violation!( + pub struct MultiValueRepeatedKeyLiteral; +); +impl Violation for MultiValueRepeatedKeyLiteral { + fn message(&self) -> String { + "Dictionary key literal repeated".to_string() + } + + fn placeholder() -> Self { + MultiValueRepeatedKeyLiteral + } +} + +define_violation!( + pub struct MultiValueRepeatedKeyVariable(pub String); +); +impl Violation for MultiValueRepeatedKeyVariable { + fn message(&self) -> String { + let MultiValueRepeatedKeyVariable(name) = self; + format!("Dictionary key `{name}` repeated") + } + + fn placeholder() -> Self { + MultiValueRepeatedKeyVariable("...".to_string()) + } +} + +define_violation!( + pub struct ExpressionsInStarAssignment; +); +impl Violation for ExpressionsInStarAssignment { + fn message(&self) -> String { + "Too many expressions in star-unpacking assignment".to_string() + } + + fn placeholder() -> Self { + ExpressionsInStarAssignment + } +} + +define_violation!( + pub struct TwoStarredExpressions; +); +impl Violation for TwoStarredExpressions { + fn message(&self) -> String { + "Two starred expressions in assignment".to_string() + } + + fn placeholder() -> Self { + TwoStarredExpressions + } +} + +define_violation!( + pub struct AssertTuple; +); +impl Violation for AssertTuple { + fn message(&self) -> String { + "Assert test is a non-empty tuple, which is always `True`".to_string() + } + + fn placeholder() -> Self { + AssertTuple + } +} + +define_violation!( + pub struct IsLiteral(pub IsCmpop); +); +impl AlwaysAutofixableViolation for IsLiteral { + fn message(&self) -> String { + let IsLiteral(cmpop) = self; + match cmpop { + IsCmpop::Is => "Use `==` to compare constant literals".to_string(), + IsCmpop::IsNot => "Use `!=` to compare constant literals".to_string(), + } + } + + fn autofix_title(&self) -> String { + let IsLiteral(cmpop) = self; + match cmpop { + IsCmpop::Is => "Replace `is` with `==`".to_string(), + IsCmpop::IsNot => "Replace `is not` with `!=`".to_string(), + } + } + + fn placeholder() -> Self { + IsLiteral(IsCmpop::Is) + } +} + +define_violation!( + pub struct InvalidPrintSyntax; +); +impl Violation for InvalidPrintSyntax { + fn message(&self) -> String { + "Use of `>>` is invalid with `print` function".to_string() + } + + fn placeholder() -> Self { + InvalidPrintSyntax + } +} + +define_violation!( + pub struct IfTuple; +); +impl Violation for IfTuple { + fn message(&self) -> String { + "If test is a tuple, which is always `True`".to_string() + } + + fn placeholder() -> Self { + IfTuple + } +} + +define_violation!( + pub struct BreakOutsideLoop; +); +impl Violation for BreakOutsideLoop { + fn message(&self) -> String { + "`break` outside loop".to_string() + } + + fn placeholder() -> Self { + BreakOutsideLoop + } +} + +define_violation!( + pub struct ContinueOutsideLoop; +); +impl Violation for ContinueOutsideLoop { + fn message(&self) -> String { + "`continue` not properly in loop".to_string() + } + + fn placeholder() -> Self { + ContinueOutsideLoop + } +} + +define_violation!( + pub struct YieldOutsideFunction(pub DeferralKeyword); +); +impl Violation for YieldOutsideFunction { + fn message(&self) -> String { + let YieldOutsideFunction(keyword) = self; + format!("`{keyword}` statement outside of a function") + } + + fn placeholder() -> Self { + YieldOutsideFunction(DeferralKeyword::Yield) + } +} + +define_violation!( + pub struct ReturnOutsideFunction; +); +impl Violation for ReturnOutsideFunction { + fn message(&self) -> String { + "`return` statement outside of a function/method".to_string() + } + + fn placeholder() -> Self { + ReturnOutsideFunction + } +} + +define_violation!( + pub struct DefaultExceptNotLast; +); +impl Violation for DefaultExceptNotLast { + fn message(&self) -> String { + "An `except` block as not the last exception handler".to_string() + } + + fn placeholder() -> Self { + DefaultExceptNotLast + } +} + +define_violation!( + pub struct ForwardAnnotationSyntaxError(pub String); +); +impl Violation for ForwardAnnotationSyntaxError { + fn message(&self) -> String { + let ForwardAnnotationSyntaxError(body) = self; + format!("Syntax error in forward annotation: `{body}`") + } + + fn placeholder() -> Self { + ForwardAnnotationSyntaxError("...".to_string()) + } +} + +define_violation!( + pub struct RedefinedWhileUnused(pub String, pub usize); +); +impl Violation for RedefinedWhileUnused { + fn message(&self) -> String { + let RedefinedWhileUnused(name, line) = self; + format!("Redefinition of unused `{name}` from line {line}") + } + + fn placeholder() -> Self { + RedefinedWhileUnused("...".to_string(), 1) + } +} + +define_violation!( + pub struct UndefinedName(pub String); +); +impl Violation for UndefinedName { + fn message(&self) -> String { + let UndefinedName(name) = self; + format!("Undefined name `{name}`") + } + + fn placeholder() -> Self { + UndefinedName("...".to_string()) + } +} + +define_violation!( + pub struct UndefinedExport(pub String); +); +impl Violation for UndefinedExport { + fn message(&self) -> String { + let UndefinedExport(name) = self; + format!("Undefined name `{name}` in `__all__`") + } + + fn placeholder() -> Self { + UndefinedExport("...".to_string()) + } +} + +define_violation!( + pub struct UndefinedLocal(pub String); +); +impl Violation for UndefinedLocal { + fn message(&self) -> String { + let UndefinedLocal(name) = self; + format!("Local variable `{name}` referenced before assignment") + } + + fn placeholder() -> Self { + UndefinedLocal("...".to_string()) + } +} + +define_violation!( + pub struct UnusedVariable(pub String); +); +impl AlwaysAutofixableViolation for UnusedVariable { + fn message(&self) -> String { + let UnusedVariable(name) = self; + format!("Local variable `{name}` is assigned to but never used") + } + + fn autofix_title(&self) -> String { + let UnusedVariable(name) = self; + format!("Remove assignment to unused variable `{name}`") + } + + fn placeholder() -> Self { + UnusedVariable("...".to_string()) + } +} + +define_violation!( + pub struct UnusedAnnotation(pub String); +); +impl Violation for UnusedAnnotation { + fn message(&self) -> String { + let UnusedAnnotation(name) = self; + format!("Local variable `{name}` is annotated but never used") + } + + fn placeholder() -> Self { + UnusedAnnotation("...".to_string()) + } +} + +define_violation!( + pub struct RaiseNotImplemented; +); +impl AlwaysAutofixableViolation for RaiseNotImplemented { + fn message(&self) -> String { + "`raise NotImplemented` should be `raise NotImplementedError`".to_string() + } + + fn autofix_title(&self) -> String { + "Use `raise NotImplementedError`".to_string() + } + + fn placeholder() -> Self { + RaiseNotImplemented + } +} + +// pylint + +define_violation!( + pub struct UselessImportAlias; +); +impl AlwaysAutofixableViolation for UselessImportAlias { + fn message(&self) -> String { + "Import alias does not rename original package".to_string() + } + + fn autofix_title(&self) -> String { + "Remove import alias".to_string() + } + + fn placeholder() -> Self { + UselessImportAlias + } +} + +define_violation!( + pub struct MisplacedComparisonConstant(pub String); +); +impl AlwaysAutofixableViolation for MisplacedComparisonConstant { + fn message(&self) -> String { + let MisplacedComparisonConstant(comparison) = self; + format!("Comparison should be {comparison}") + } + + fn autofix_title(&self) -> String { + let MisplacedComparisonConstant(comparison) = self; + format!("Replace with {comparison}") + } + + fn placeholder() -> Self { + MisplacedComparisonConstant("...".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryDirectLambdaCall; +); +impl Violation for UnnecessaryDirectLambdaCall { + fn message(&self) -> String { + "Lambda expression called directly. Execute the expression inline instead.".to_string() + } + + fn placeholder() -> Self { + UnnecessaryDirectLambdaCall + } +} + +define_violation!( + pub struct NonlocalWithoutBinding(pub String); +); +impl Violation for NonlocalWithoutBinding { + fn message(&self) -> String { + let NonlocalWithoutBinding(name) = self; + format!("Nonlocal name `{name}` found without binding") + } + + fn placeholder() -> Self { + NonlocalWithoutBinding("...".to_string()) + } +} + +define_violation!( + pub struct UsedPriorGlobalDeclaration(pub String, pub usize); +); +impl Violation for UsedPriorGlobalDeclaration { + fn message(&self) -> String { + let UsedPriorGlobalDeclaration(name, line) = self; + format!("Name `{name}` is used prior to global declaration on line {line}") + } + + fn placeholder() -> Self { + UsedPriorGlobalDeclaration("...".to_string(), 1) + } +} + +define_violation!( + pub struct AwaitOutsideAsync; +); +impl Violation for AwaitOutsideAsync { + fn message(&self) -> String { + "`await` should be used within an async function".to_string() + } + + fn placeholder() -> Self { + AwaitOutsideAsync + } +} + +define_violation!( + pub struct PropertyWithParameters; +); +impl Violation for PropertyWithParameters { + fn message(&self) -> String { + "Cannot have defined parameters for properties".to_string() + } + + fn placeholder() -> Self { + PropertyWithParameters + } +} + +define_violation!( + pub struct ConsiderUsingFromImport(pub String, pub String); +); +impl Violation for ConsiderUsingFromImport { + fn message(&self) -> String { + let ConsiderUsingFromImport(module, name) = self; + format!("Use `from {module} import {name}` in lieu of alias") + } + + fn placeholder() -> Self { + ConsiderUsingFromImport("...".to_string(), "...".to_string()) + } +} + +define_violation!( + pub struct ConsiderMergingIsinstance(pub String, pub Vec); +); +impl Violation for ConsiderMergingIsinstance { + fn message(&self) -> String { + let ConsiderMergingIsinstance(obj, types) = self; + let types = types.join(", "); + format!("Merge these isinstance calls: `isinstance({obj}, ({types}))`") + } + + fn placeholder() -> Self { + ConsiderMergingIsinstance("...".to_string(), vec!["...".to_string()]) + } +} + +define_violation!( + pub struct UseSysExit(pub String); +); +impl AlwaysAutofixableViolation for UseSysExit { + fn message(&self) -> String { + let UseSysExit(name) = self; + format!("Use `sys.exit()` instead of `{name}`") + } + + fn autofix_title(&self) -> String { + let UseSysExit(name) = self; + format!("Replace `{name}` with `sys.exit()`") + } + + fn placeholder() -> Self { + UseSysExit("exit".to_string()) + } +} + +define_violation!( + pub struct UselessElseOnLoop; +); +impl Violation for UselessElseOnLoop { + fn message(&self) -> String { + "Else clause on loop without a break statement, remove the else and de-indent all the code \ + inside it" + .to_string() + } + + fn placeholder() -> Self { + UselessElseOnLoop + } +} + +define_violation!( + pub struct GlobalVariableNotAssigned(pub String); +); +impl Violation for GlobalVariableNotAssigned { + fn message(&self) -> String { + let GlobalVariableNotAssigned(name) = self; + format!("Using global for `{name}` but no assignment is done") + } + + fn placeholder() -> Self { + GlobalVariableNotAssigned("...".to_string()) + } +} + +// flake8-builtins + +define_violation!( + pub struct BuiltinVariableShadowing(pub String); +); +impl Violation for BuiltinVariableShadowing { + fn message(&self) -> String { + let BuiltinVariableShadowing(name) = self; + format!("Variable `{name}` is shadowing a python builtin") + } + + fn placeholder() -> Self { + BuiltinVariableShadowing("...".to_string()) + } +} + +define_violation!( + pub struct BuiltinArgumentShadowing(pub String); +); +impl Violation for BuiltinArgumentShadowing { + fn message(&self) -> String { + let BuiltinArgumentShadowing(name) = self; + format!("Argument `{name}` is shadowing a python builtin") + } + + fn placeholder() -> Self { + BuiltinArgumentShadowing("...".to_string()) + } +} + +define_violation!( + pub struct BuiltinAttributeShadowing(pub String); +); +impl Violation for BuiltinAttributeShadowing { + fn message(&self) -> String { + let BuiltinAttributeShadowing(name) = self; + format!("Class attribute `{name}` is shadowing a python builtin") + } + + fn placeholder() -> Self { + BuiltinAttributeShadowing("...".to_string()) + } +} + +// flake8-bugbear + +define_violation!( + pub struct UnaryPrefixIncrement; +); +impl Violation for UnaryPrefixIncrement { + fn message(&self) -> String { + "Python does not support the unary prefix increment. Writing `++n` is equivalent to \ + `+(+(n))`, which equals `n`. You meant `n += 1`." + .to_string() + } + + fn placeholder() -> Self { + UnaryPrefixIncrement + } +} + +define_violation!( + pub struct AssignmentToOsEnviron; +); +impl Violation for AssignmentToOsEnviron { + fn message(&self) -> String { + "Assigning to `os.environ` doesn't clear the environment".to_string() + } + + fn placeholder() -> Self { + AssignmentToOsEnviron + } +} + +define_violation!( + pub struct UnreliableCallableCheck; +); +impl Violation for UnreliableCallableCheck { + fn message(&self) -> String { + " Using `hasattr(x, '__call__')` to test if x is callable is unreliable. Use `callable(x)` \ + for consistent results." + .to_string() + } + + fn placeholder() -> Self { + UnreliableCallableCheck + } +} + +define_violation!( + pub struct StripWithMultiCharacters; +); +impl Violation for StripWithMultiCharacters { + fn message(&self) -> String { + "Using `.strip()` with multi-character strings is misleading the reader".to_string() + } + + fn placeholder() -> Self { + StripWithMultiCharacters + } +} + +define_violation!( + pub struct MutableArgumentDefault; +); +impl Violation for MutableArgumentDefault { + fn message(&self) -> String { + "Do not use mutable data structures for argument defaults".to_string() + } + + fn placeholder() -> Self { + MutableArgumentDefault + } +} + +define_violation!( + pub struct UnusedLoopControlVariable(pub String); +); +impl AlwaysAutofixableViolation for UnusedLoopControlVariable { + fn message(&self) -> String { + let UnusedLoopControlVariable(name) = self; + format!( + "Loop control variable `{name}` not used within the loop body. If this is intended, \ + start the name with an underscore." + ) + } + + fn autofix_title(&self) -> String { + let UnusedLoopControlVariable(name) = self; + format!("Rename unused `{name}` to `_{name}`") + } + + fn placeholder() -> Self { + UnusedLoopControlVariable("i".to_string()) + } +} + +define_violation!( + pub struct FunctionCallArgumentDefault(pub Option); +); +impl Violation for FunctionCallArgumentDefault { + fn message(&self) -> String { + let FunctionCallArgumentDefault(name) = self; + if let Some(name) = name { + format!("Do not perform function call `{name}` in argument defaults") + } else { + "Do not perform function call in argument defaults".to_string() + } + } + + fn placeholder() -> Self { + FunctionCallArgumentDefault(None) + } +} + +define_violation!( + pub struct GetAttrWithConstant; +); +impl AlwaysAutofixableViolation for GetAttrWithConstant { + fn message(&self) -> String { + "Do not call `getattr` with a constant attribute value. It is not any safer than normal \ + property access." + .to_string() + } + + fn autofix_title(&self) -> String { + "Replace `getattr` with attribute access".to_string() + } + + fn placeholder() -> Self { + GetAttrWithConstant + } +} + +define_violation!( + pub struct SetAttrWithConstant; +); +impl AlwaysAutofixableViolation for SetAttrWithConstant { + fn message(&self) -> String { + "Do not call `setattr` with a constant attribute value. It is not any safer than normal \ + property access." + .to_string() + } + + fn autofix_title(&self) -> String { + "Replace `setattr` with assignment".to_string() + } + + fn placeholder() -> Self { + SetAttrWithConstant + } +} + +define_violation!( + pub struct DoNotAssertFalse; +); +impl AlwaysAutofixableViolation for DoNotAssertFalse { + fn message(&self) -> String { + "Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`" + .to_string() + } + + fn autofix_title(&self) -> String { + "Replace `assert False`".to_string() + } + + fn placeholder() -> Self { + DoNotAssertFalse + } +} + +define_violation!( + pub struct JumpStatementInFinally(pub String); +); +impl Violation for JumpStatementInFinally { + fn message(&self) -> String { + let JumpStatementInFinally(name) = self; + format!("`{name}` inside finally blocks cause exceptions to be silenced") + } + + fn placeholder() -> Self { + JumpStatementInFinally("return/continue/break".to_string()) + } +} + +define_violation!( + pub struct RedundantTupleInExceptionHandler(pub String); +); +impl AlwaysAutofixableViolation for RedundantTupleInExceptionHandler { + fn message(&self) -> String { + let RedundantTupleInExceptionHandler(name) = self; + format!( + "A length-one tuple literal is redundant. Write `except {name}` instead of `except \ + ({name},)`." + ) + } + + fn autofix_title(&self) -> String { + let RedundantTupleInExceptionHandler(name) = self; + format!("Replace with `except {name}`") + } + + fn placeholder() -> Self { + RedundantTupleInExceptionHandler("ValueError".to_string()) + } +} + +define_violation!( + pub struct DuplicateHandlerException(pub Vec); +); +impl AlwaysAutofixableViolation for DuplicateHandlerException { + fn message(&self) -> String { + let DuplicateHandlerException(names) = self; + if names.len() == 1 { + let name = &names[0]; + format!("Exception handler with duplicate exception: `{name}`") + } else { + let names = names.iter().map(|name| format!("`{name}`")).join(", "); + format!("Exception handler with duplicate exceptions: {names}") + } + } + + fn autofix_title(&self) -> String { + "De-duplicate exceptions".to_string() + } + + fn placeholder() -> Self { + DuplicateHandlerException(vec!["ValueError".to_string()]) + } +} + +define_violation!( + pub struct UselessComparison; +); +impl Violation for UselessComparison { + fn message(&self) -> String { + "Pointless comparison. This comparison does nothing but waste CPU instructions. Either \ + prepend `assert` or remove it." + .to_string() + } + + fn placeholder() -> Self { + UselessComparison + } +} + +define_violation!( + pub struct CannotRaiseLiteral; +); +impl Violation for CannotRaiseLiteral { + fn message(&self) -> String { + "Cannot raise a literal. Did you intend to return it or raise an Exception?".to_string() + } + + fn placeholder() -> Self { + CannotRaiseLiteral + } +} + +define_violation!( + pub struct NoAssertRaisesException; +); +impl Violation for NoAssertRaisesException { + fn message(&self) -> String { + "`assertRaises(Exception)` should be considered evil. It can lead to your test passing \ + even if the code being tested is never executed due to a typo. Either assert for a more \ + specific exception (builtin or custom), use `assertRaisesRegex`, or use the context \ + manager form of `assertRaises`." + .to_string() + } + + fn placeholder() -> Self { + NoAssertRaisesException + } +} + +define_violation!( + pub struct UselessExpression; +); +impl Violation for UselessExpression { + fn message(&self) -> String { + "Found useless expression. Either assign it to a variable or remove it.".to_string() + } + + fn placeholder() -> Self { + UselessExpression + } +} + +define_violation!( + pub struct CachedInstanceMethod; +); +impl Violation for CachedInstanceMethod { + fn message(&self) -> String { + "Use of `functools.lru_cache` or `functools.cache` on methods can lead to memory leaks" + .to_string() + } + + fn placeholder() -> Self { + CachedInstanceMethod + } +} + +define_violation!( + pub struct LoopVariableOverridesIterator(pub String); +); +impl Violation for LoopVariableOverridesIterator { + fn message(&self) -> String { + let LoopVariableOverridesIterator(name) = self; + format!("Loop control variable `{name}` overrides iterable it iterates") + } + + fn placeholder() -> Self { + LoopVariableOverridesIterator("...".to_string()) + } +} + +define_violation!( + pub struct FStringDocstring; +); +impl Violation for FStringDocstring { + fn message(&self) -> String { + "f-string used as docstring. This will be interpreted by python as a joined string rather \ + than a docstring." + .to_string() + } + + fn placeholder() -> Self { + FStringDocstring + } +} + +define_violation!( + pub struct UselessContextlibSuppress; +); +impl Violation for UselessContextlibSuppress { + fn message(&self) -> String { + "No arguments passed to `contextlib.suppress`. No exceptions will be suppressed and \ + therefore this context manager is redundant" + .to_string() + } + + fn placeholder() -> Self { + UselessContextlibSuppress + } +} + +define_violation!( + pub struct FunctionUsesLoopVariable(pub String); +); +impl Violation for FunctionUsesLoopVariable { + fn message(&self) -> String { + let FunctionUsesLoopVariable(name) = self; + format!("Function definition does not bind loop variable `{name}`") + } + + fn placeholder() -> Self { + FunctionUsesLoopVariable("...".to_string()) + } +} + +define_violation!( + pub struct AbstractBaseClassWithoutAbstractMethod(pub String); +); +impl Violation for AbstractBaseClassWithoutAbstractMethod { + fn message(&self) -> String { + let AbstractBaseClassWithoutAbstractMethod(name) = self; + format!("`{name}` is an abstract base class, but it has no abstract methods") + } + + fn placeholder() -> Self { + AbstractBaseClassWithoutAbstractMethod("...".to_string()) + } +} + +define_violation!( + pub struct DuplicateTryBlockException(pub String); +); +impl Violation for DuplicateTryBlockException { + fn message(&self) -> String { + let DuplicateTryBlockException(name) = self; + format!("try-except block with duplicate exception `{name}`") + } + + fn placeholder() -> Self { + DuplicateTryBlockException("Exception".to_string()) + } +} + +define_violation!( + pub struct StarArgUnpackingAfterKeywordArg; +); +impl Violation for StarArgUnpackingAfterKeywordArg { + fn message(&self) -> String { + "Star-arg unpacking after a keyword argument is strongly discouraged. It only works when \ + the keyword parameter is declared after all parameters supplied by the unpacked sequence, \ + and this change of ordering can surprise and mislead readers." + .to_string() + } + + fn placeholder() -> Self { + StarArgUnpackingAfterKeywordArg + } +} + +define_violation!( + pub struct EmptyMethodWithoutAbstractDecorator(pub String); +); +impl Violation for EmptyMethodWithoutAbstractDecorator { + fn message(&self) -> String { + let EmptyMethodWithoutAbstractDecorator(name) = self; + format!( + "`{name}` is an empty method in an abstract base class, but has no abstract decorator" + ) + } + + fn placeholder() -> Self { + EmptyMethodWithoutAbstractDecorator("...".to_string()) + } +} + +define_violation!( + pub struct RaiseWithoutFromInsideExcept; +); +impl Violation for RaiseWithoutFromInsideExcept { + fn message(&self) -> String { + "Within an except clause, raise exceptions with raise ... from err or raise ... from None \ + to distinguish them from errors in exception handling" + .to_string() + } + + fn placeholder() -> Self { + RaiseWithoutFromInsideExcept + } +} + +define_violation!( + pub struct ZipWithoutExplicitStrict; +); +impl Violation for ZipWithoutExplicitStrict { + fn message(&self) -> String { + "`zip()` without an explicit `strict=` parameter".to_string() + } + + fn placeholder() -> Self { + ZipWithoutExplicitStrict + } +} + +// flake8-blind-except + +define_violation!( + pub struct BlindExcept(pub String); +); +impl Violation for BlindExcept { + fn message(&self) -> String { + let BlindExcept(name) = self; + format!("Do not catch blind exception: `{name}`") + } + + fn placeholder() -> Self { + BlindExcept("Exception".to_string()) + } +} + +// flake8-comprehensions + +define_violation!( + pub struct UnnecessaryGeneratorList; +); +impl AlwaysAutofixableViolation for UnnecessaryGeneratorList { + fn message(&self) -> String { + "Unnecessary generator (rewrite as a `list` comprehension)".to_string() + } + + fn autofix_title(&self) -> String { + "Rewrite as a `list` comprehension".to_string() + } + + fn placeholder() -> Self { + UnnecessaryGeneratorList + } +} + +define_violation!( + pub struct UnnecessaryGeneratorSet; +); +impl AlwaysAutofixableViolation for UnnecessaryGeneratorSet { + fn message(&self) -> String { + "Unnecessary generator (rewrite as a `set` comprehension)".to_string() + } + + fn autofix_title(&self) -> String { + "Rewrite as a `set` comprehension".to_string() + } + + fn placeholder() -> Self { + UnnecessaryGeneratorSet + } +} + +define_violation!( + pub struct UnnecessaryGeneratorDict; +); +impl AlwaysAutofixableViolation for UnnecessaryGeneratorDict { + fn message(&self) -> String { + "Unnecessary generator (rewrite as a `dict` comprehension)".to_string() + } + + fn autofix_title(&self) -> String { + "Rewrite as a `dict` comprehension".to_string() + } + + fn placeholder() -> Self { + UnnecessaryGeneratorDict + } +} + +define_violation!( + pub struct UnnecessaryListComprehensionSet; +); +impl AlwaysAutofixableViolation for UnnecessaryListComprehensionSet { + fn message(&self) -> String { + "Unnecessary `list` comprehension (rewrite as a `set` comprehension)".to_string() + } + + fn autofix_title(&self) -> String { + "Rewrite as a `set` comprehension".to_string() + } + + fn placeholder() -> Self { + UnnecessaryListComprehensionSet + } +} + +define_violation!( + pub struct UnnecessaryListComprehensionDict; +); +impl AlwaysAutofixableViolation for UnnecessaryListComprehensionDict { + fn message(&self) -> String { + "Unnecessary `list` comprehension (rewrite as a `dict` comprehension)".to_string() + } + + fn autofix_title(&self) -> String { + "Rewrite as a `dict` comprehension".to_string() + } + + fn placeholder() -> Self { + UnnecessaryListComprehensionDict + } +} + +define_violation!( + pub struct UnnecessaryLiteralSet(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryLiteralSet { + fn message(&self) -> String { + let UnnecessaryLiteralSet(obj_type) = self; + format!("Unnecessary `{obj_type}` literal (rewrite as a `set` literal)") + } + + fn autofix_title(&self) -> String { + "Rewrite as a `set` literal".to_string() + } + + fn placeholder() -> Self { + UnnecessaryLiteralSet("(list|tuple)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryLiteralDict(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryLiteralDict { + fn message(&self) -> String { + let UnnecessaryLiteralDict(obj_type) = self; + format!("Unnecessary `{obj_type}` literal (rewrite as a `dict` literal)") + } + + fn autofix_title(&self) -> String { + "Rewrite as a `dict` literal".to_string() + } + + fn placeholder() -> Self { + UnnecessaryLiteralDict("(list|tuple)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryCollectionCall(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryCollectionCall { + fn message(&self) -> String { + let UnnecessaryCollectionCall(obj_type) = self; + format!("Unnecessary `{obj_type}` call (rewrite as a literal)") + } + + fn autofix_title(&self) -> String { + "Rewrite as a literal".to_string() + } + + fn placeholder() -> Self { + UnnecessaryCollectionCall("(dict|list|tuple)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryLiteralWithinTupleCall(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall { + fn message(&self) -> String { + let UnnecessaryLiteralWithinTupleCall(literal) = self; + if literal == "list" { + format!( + "Unnecessary `{literal}` literal passed to `tuple()` (rewrite as a `tuple` \ + literal)" + ) + } else { + format!( + "Unnecessary `{literal}` literal passed to `tuple()` (remove the outer call to \ + `tuple()`)" + ) + } + } + + fn autofix_title(&self) -> String { + let UnnecessaryLiteralWithinTupleCall(literal) = self; + { + if literal == "list" { + "Rewrite as a `tuple` literal".to_string() + } else { + "Remove outer `tuple` call".to_string() + } + } + } + + fn placeholder() -> Self { + UnnecessaryLiteralWithinTupleCall("(list|tuple)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryLiteralWithinListCall(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall { + fn message(&self) -> String { + let UnnecessaryLiteralWithinListCall(literal) = self; + if literal == "list" { + format!( + "Unnecessary `{literal}` literal passed to `list()` (remove the outer call to \ + `list()`)" + ) + } else { + format!( + "Unnecessary `{literal}` literal passed to `list()` (rewrite as a `list` literal)" + ) + } + } + + fn autofix_title(&self) -> String { + let UnnecessaryLiteralWithinListCall(literal) = self; + { + if literal == "list" { + "Remove outer `list` call".to_string() + } else { + "Rewrite as a `list` literal".to_string() + } + } + } + + fn placeholder() -> Self { + UnnecessaryLiteralWithinListCall("(list|tuple)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryListCall; +); +impl AlwaysAutofixableViolation for UnnecessaryListCall { + fn message(&self) -> String { + "Unnecessary `list` call (remove the outer call to `list()`)".to_string() + } + + fn autofix_title(&self) -> String { + "Remove outer `list` call".to_string() + } + + fn placeholder() -> Self { + UnnecessaryListCall + } +} + +define_violation!( + pub struct UnnecessaryCallAroundSorted(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryCallAroundSorted { + fn message(&self) -> String { + let UnnecessaryCallAroundSorted(func) = self; + format!("Unnecessary `{func}` call around `sorted()`") + } + + fn autofix_title(&self) -> String { + let UnnecessaryCallAroundSorted(func) = self; + format!("Remove unnecessary `{func}` call") + } + + fn placeholder() -> Self { + UnnecessaryCallAroundSorted("(list|reversed)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryDoubleCastOrProcess(pub String, pub String); +); +impl Violation for UnnecessaryDoubleCastOrProcess { + fn message(&self) -> String { + let UnnecessaryDoubleCastOrProcess(inner, outer) = self; + format!("Unnecessary `{inner}` call within `{outer}()`") + } + + fn placeholder() -> Self { + UnnecessaryDoubleCastOrProcess( + "(list|reversed|set|sorted|tuple)".to_string(), + "(list|set|sorted|tuple)".to_string(), + ) + } +} + +define_violation!( + pub struct UnnecessarySubscriptReversal(pub String); +); +impl Violation for UnnecessarySubscriptReversal { + fn message(&self) -> String { + let UnnecessarySubscriptReversal(func) = self; + format!("Unnecessary subscript reversal of iterable within `{func}()`") + } + + fn placeholder() -> Self { + UnnecessarySubscriptReversal("(reversed|set|sorted)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryComprehension(pub String); +); +impl AlwaysAutofixableViolation for UnnecessaryComprehension { + fn message(&self) -> String { + let UnnecessaryComprehension(obj_type) = self; + format!("Unnecessary `{obj_type}` comprehension (rewrite using `{obj_type}()`)") + } + + fn autofix_title(&self) -> String { + let UnnecessaryComprehension(obj_type) = self; + format!("Rewrite using `{obj_type}()`") + } + + fn placeholder() -> Self { + UnnecessaryComprehension("(list|set)".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryMap(pub String); +); +impl Violation for UnnecessaryMap { + fn message(&self) -> String { + let UnnecessaryMap(obj_type) = self; + if obj_type == "generator" { + "Unnecessary `map` usage (rewrite using a generator expression)".to_string() + } else { + format!("Unnecessary `map` usage (rewrite using a `{obj_type}` comprehension)") + } + } + + fn placeholder() -> Self { + UnnecessaryMap("(list|set|dict)".to_string()) + } +} + +// flake8-debugger + +define_violation!( + pub struct Debugger(pub DebuggerUsingType); +); +impl Violation for Debugger { + fn message(&self) -> String { + let Debugger(using_type) = self; + match using_type { + DebuggerUsingType::Call(name) => format!("Trace found: `{name}` used"), + DebuggerUsingType::Import(name) => format!("Import for `{name}` found"), + } + } + + fn placeholder() -> Self { + Debugger(DebuggerUsingType::Import("...".to_string())) + } +} + +// mccabe + +define_violation!( + pub struct FunctionIsTooComplex(pub String, pub usize); +); +impl Violation for FunctionIsTooComplex { + fn message(&self) -> String { + let FunctionIsTooComplex(name, complexity) = self; + format!("`{name}` is too complex ({complexity})") + } + + fn placeholder() -> Self { + FunctionIsTooComplex("...".to_string(), 10) + } +} + +// flake8-tidy-imports + +define_violation!( + pub struct BannedApi { + pub name: String, + pub message: String, + } +); +impl Violation for BannedApi { + fn message(&self) -> String { + let BannedApi { name, message } = self; + format!("`{name}` is banned: {message}") + } + + fn placeholder() -> Self { + BannedApi { + name: "...".to_string(), + message: "...".to_string(), + } + } +} + +define_violation!( + pub struct BannedRelativeImport(pub Strictness); +); +impl Violation for BannedRelativeImport { + fn message(&self) -> String { + let BannedRelativeImport(strictness) = self; + match strictness { + Strictness::Parents => "Relative imports from parent modules are banned".to_string(), + Strictness::All => "Relative imports are banned".to_string(), + } + } + + fn placeholder() -> Self { + BannedRelativeImport(Strictness::All) + } +} + +// flake8-return + +define_violation!( + pub struct UnnecessaryReturnNone; +); +impl AlwaysAutofixableViolation for UnnecessaryReturnNone { + fn message(&self) -> String { + "Do not explicitly `return None` in function if it is the only possible return value" + .to_string() + } + + fn autofix_title(&self) -> String { + "Remove explicit `return None`".to_string() + } + + fn placeholder() -> Self { + UnnecessaryReturnNone + } +} + +define_violation!( + pub struct ImplicitReturnValue; +); +impl AlwaysAutofixableViolation for ImplicitReturnValue { + fn message(&self) -> String { + "Do not implicitly `return None` in function able to return non-`None` value".to_string() + } + + fn autofix_title(&self) -> String { + "Add explicit `None` return value".to_string() + } + + fn placeholder() -> Self { + ImplicitReturnValue + } +} + +define_violation!( + pub struct ImplicitReturn; +); +impl AlwaysAutofixableViolation for ImplicitReturn { + fn message(&self) -> String { + "Missing explicit `return` at the end of function able to return non-`None` value" + .to_string() + } + + fn autofix_title(&self) -> String { + "Add explicit `return` statement".to_string() + } + + fn placeholder() -> Self { + ImplicitReturn + } +} + +define_violation!( + pub struct UnnecessaryAssign; +); +impl Violation for UnnecessaryAssign { + fn message(&self) -> String { + "Unnecessary variable assignment before `return` statement".to_string() + } + + fn placeholder() -> Self { + UnnecessaryAssign + } +} + +define_violation!( + pub struct SuperfluousElseReturn(pub Branch); +); +impl Violation for SuperfluousElseReturn { + fn message(&self) -> String { + let SuperfluousElseReturn(branch) = self; + format!("Unnecessary `{branch}` after `return` statement") + } + + fn placeholder() -> Self { + SuperfluousElseReturn(Branch::Else) + } +} + +define_violation!( + pub struct SuperfluousElseRaise(pub Branch); +); +impl Violation for SuperfluousElseRaise { + fn message(&self) -> String { + let SuperfluousElseRaise(branch) = self; + format!("Unnecessary `{branch}` after `raise` statement") + } + + fn placeholder() -> Self { + SuperfluousElseRaise(Branch::Else) + } +} + +define_violation!( + pub struct SuperfluousElseContinue(pub Branch); +); +impl Violation for SuperfluousElseContinue { + fn message(&self) -> String { + let SuperfluousElseContinue(branch) = self; + format!("Unnecessary `{branch}` after `continue` statement") + } + + fn placeholder() -> Self { + SuperfluousElseContinue(Branch::Else) + } +} + +define_violation!( + pub struct SuperfluousElseBreak(pub Branch); +); +impl Violation for SuperfluousElseBreak { + fn message(&self) -> String { + let SuperfluousElseBreak(branch) = self; + format!("Unnecessary `{branch}` after `break` statement") + } + + fn placeholder() -> Self { + SuperfluousElseBreak(Branch::Else) + } +} + +// flake8-implicit-str-concat + +define_violation!( + pub struct SingleLineImplicitStringConcatenation; +); +impl Violation for SingleLineImplicitStringConcatenation { + fn message(&self) -> String { + "Implicitly concatenated string literals on one line".to_string() + } + + fn placeholder() -> Self { + SingleLineImplicitStringConcatenation + } +} + +define_violation!( + pub struct MultiLineImplicitStringConcatenation; +); +impl Violation for MultiLineImplicitStringConcatenation { + fn message(&self) -> String { + "Implicitly concatenated string literals over continuation line".to_string() + } + + fn placeholder() -> Self { + MultiLineImplicitStringConcatenation + } +} + +define_violation!( + pub struct ExplicitStringConcatenation; +); +impl Violation for ExplicitStringConcatenation { + fn message(&self) -> String { + "Explicitly concatenated string should be implicitly concatenated".to_string() + } + + fn placeholder() -> Self { + ExplicitStringConcatenation + } +} + +// flake8-print + +define_violation!( + pub struct PrintFound; +); +impl AlwaysAutofixableViolation for PrintFound { + fn message(&self) -> String { + "`print` found".to_string() + } + + fn autofix_title(&self) -> String { + "Remove `print`".to_string() + } + + fn placeholder() -> Self { + PrintFound + } +} + +define_violation!( + pub struct PPrintFound; +); +impl AlwaysAutofixableViolation for PPrintFound { + fn message(&self) -> String { + "`pprint` found".to_string() + } + + fn autofix_title(&self) -> String { + "Remove `pprint`".to_string() + } + + fn placeholder() -> Self { + PPrintFound + } +} + +// flake8-quotes + +define_violation!( + pub struct BadQuotesInlineString(pub Quote); +); +impl Violation for BadQuotesInlineString { + fn message(&self) -> String { + let BadQuotesInlineString(quote) = self; + match quote { + Quote::Single => "Double quotes found but single quotes preferred".to_string(), + Quote::Double => "Single quotes found but double quotes preferred".to_string(), + } + } + + fn placeholder() -> Self { + BadQuotesInlineString(Quote::Double) + } +} + +define_violation!( + pub struct BadQuotesMultilineString(pub Quote); +); +impl Violation for BadQuotesMultilineString { + fn message(&self) -> String { + let BadQuotesMultilineString(quote) = self; + match quote { + Quote::Single => "Double quote multiline found but single quotes preferred".to_string(), + Quote::Double => "Single quote multiline found but double quotes preferred".to_string(), + } + } + + fn placeholder() -> Self { + BadQuotesMultilineString(Quote::Double) + } +} + +define_violation!( + pub struct BadQuotesDocstring(pub Quote); +); +impl Violation for BadQuotesDocstring { + fn message(&self) -> String { + let BadQuotesDocstring(quote) = self; + match quote { + Quote::Single => "Double quote docstring found but single quotes preferred".to_string(), + Quote::Double => "Single quote docstring found but double quotes preferred".to_string(), + } + } + + fn placeholder() -> Self { + BadQuotesDocstring(Quote::Double) + } +} + +define_violation!( + pub struct AvoidQuoteEscape; +); +impl Violation for AvoidQuoteEscape { + fn message(&self) -> String { + "Change outer quotes to avoid escaping inner quotes".to_string() + } + + fn placeholder() -> Self { + AvoidQuoteEscape + } +} + +// flake8-annotations + +define_violation!( + pub struct MissingTypeFunctionArgument(pub String); +); +impl Violation for MissingTypeFunctionArgument { + fn message(&self) -> String { + let MissingTypeFunctionArgument(name) = self; + format!("Missing type annotation for function argument `{name}`") + } + + fn placeholder() -> Self { + MissingTypeFunctionArgument("...".to_string()) + } +} + +define_violation!( + pub struct MissingTypeArgs(pub String); +); +impl Violation for MissingTypeArgs { + fn message(&self) -> String { + let MissingTypeArgs(name) = self; + format!("Missing type annotation for `*{name}`") + } + + fn placeholder() -> Self { + MissingTypeArgs("...".to_string()) + } +} + +define_violation!( + pub struct MissingTypeKwargs(pub String); +); +impl Violation for MissingTypeKwargs { + fn message(&self) -> String { + let MissingTypeKwargs(name) = self; + format!("Missing type annotation for `**{name}`") + } + + fn placeholder() -> Self { + MissingTypeKwargs("...".to_string()) + } +} + +define_violation!( + pub struct MissingTypeSelf(pub String); +); +impl Violation for MissingTypeSelf { + fn message(&self) -> String { + let MissingTypeSelf(name) = self; + format!("Missing type annotation for `{name}` in method") + } + + fn placeholder() -> Self { + MissingTypeSelf("...".to_string()) + } +} + +define_violation!( + pub struct MissingTypeCls(pub String); +); +impl Violation for MissingTypeCls { + fn message(&self) -> String { + let MissingTypeCls(name) = self; + format!("Missing type annotation for `{name}` in classmethod") + } + + fn placeholder() -> Self { + MissingTypeCls("...".to_string()) + } +} + +define_violation!( + pub struct MissingReturnTypePublicFunction(pub String); +); +impl Violation for MissingReturnTypePublicFunction { + fn message(&self) -> String { + let MissingReturnTypePublicFunction(name) = self; + format!("Missing return type annotation for public function `{name}`") + } + + fn placeholder() -> Self { + MissingReturnTypePublicFunction("...".to_string()) + } +} + +define_violation!( + pub struct MissingReturnTypePrivateFunction(pub String); +); +impl Violation for MissingReturnTypePrivateFunction { + fn message(&self) -> String { + let MissingReturnTypePrivateFunction(name) = self; + format!("Missing return type annotation for private function `{name}`") + } + + fn placeholder() -> Self { + MissingReturnTypePrivateFunction("...".to_string()) + } +} + +define_violation!( + pub struct MissingReturnTypeSpecialMethod(pub String); +); +impl AlwaysAutofixableViolation for MissingReturnTypeSpecialMethod { + fn message(&self) -> String { + let MissingReturnTypeSpecialMethod(name) = self; + format!("Missing return type annotation for special method `{name}`") + } + + fn autofix_title(&self) -> String { + "Add `None` return type".to_string() + } + + fn placeholder() -> Self { + MissingReturnTypeSpecialMethod("...".to_string()) + } +} + +define_violation!( + pub struct MissingReturnTypeStaticMethod(pub String); +); +impl Violation for MissingReturnTypeStaticMethod { + fn message(&self) -> String { + let MissingReturnTypeStaticMethod(name) = self; + format!("Missing return type annotation for staticmethod `{name}`") + } + + fn placeholder() -> Self { + MissingReturnTypeStaticMethod("...".to_string()) + } +} + +define_violation!( + pub struct MissingReturnTypeClassMethod(pub String); +); +impl Violation for MissingReturnTypeClassMethod { + fn message(&self) -> String { + let MissingReturnTypeClassMethod(name) = self; + format!("Missing return type annotation for classmethod `{name}`") + } + + fn placeholder() -> Self { + MissingReturnTypeClassMethod("...".to_string()) + } +} + +define_violation!( + pub struct DynamicallyTypedExpression(pub String); +); +impl Violation for DynamicallyTypedExpression { + fn message(&self) -> String { + let DynamicallyTypedExpression(name) = self; + format!("Dynamically typed expressions (typing.Any) are disallowed in `{name}`") + } + + fn placeholder() -> Self { + DynamicallyTypedExpression("...".to_string()) + } +} + +// flake8-2020 + +define_violation!( + pub struct SysVersionSlice3Referenced; +); +impl Violation for SysVersionSlice3Referenced { + fn message(&self) -> String { + "`sys.version[:3]` referenced (python3.10), use `sys.version_info`".to_string() + } + + fn placeholder() -> Self { + SysVersionSlice3Referenced + } +} + +define_violation!( + pub struct SysVersion2Referenced; +); +impl Violation for SysVersion2Referenced { + fn message(&self) -> String { + "`sys.version[2]` referenced (python3.10), use `sys.version_info`".to_string() + } + + fn placeholder() -> Self { + SysVersion2Referenced + } +} + +define_violation!( + pub struct SysVersionCmpStr3; +); +impl Violation for SysVersionCmpStr3 { + fn message(&self) -> String { + "`sys.version` compared to string (python3.10), use `sys.version_info`".to_string() + } + + fn placeholder() -> Self { + SysVersionCmpStr3 + } +} + +define_violation!( + pub struct SysVersionInfo0Eq3Referenced; +); +impl Violation for SysVersionInfo0Eq3Referenced { + fn message(&self) -> String { + "`sys.version_info[0] == 3` referenced (python4), use `>=`".to_string() + } + + fn placeholder() -> Self { + SysVersionInfo0Eq3Referenced + } +} + +define_violation!( + pub struct SixPY3Referenced; +); +impl Violation for SixPY3Referenced { + fn message(&self) -> String { + "`six.PY3` referenced (python4), use `not six.PY2`".to_string() + } + + fn placeholder() -> Self { + SixPY3Referenced + } +} + +define_violation!( + pub struct SysVersionInfo1CmpInt; +); +impl Violation for SysVersionInfo1CmpInt { + fn message(&self) -> String { + "`sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to tuple" + .to_string() + } + + fn placeholder() -> Self { + SysVersionInfo1CmpInt + } +} + +define_violation!( + pub struct SysVersionInfoMinorCmpInt; +); +impl Violation for SysVersionInfoMinorCmpInt { + fn message(&self) -> String { + "`sys.version_info.minor` compared to integer (python4), compare `sys.version_info` to \ + tuple" + .to_string() + } + + fn placeholder() -> Self { + SysVersionInfoMinorCmpInt + } +} + +define_violation!( + pub struct SysVersion0Referenced; +); +impl Violation for SysVersion0Referenced { + fn message(&self) -> String { + "`sys.version[0]` referenced (python10), use `sys.version_info`".to_string() + } + + fn placeholder() -> Self { + SysVersion0Referenced + } +} + +define_violation!( + pub struct SysVersionCmpStr10; +); +impl Violation for SysVersionCmpStr10 { + fn message(&self) -> String { + "`sys.version` compared to string (python10), use `sys.version_info`".to_string() + } + + fn placeholder() -> Self { + SysVersionCmpStr10 + } +} + +define_violation!( + pub struct SysVersionSlice1Referenced; +); +impl Violation for SysVersionSlice1Referenced { + fn message(&self) -> String { + "`sys.version[:1]` referenced (python10), use `sys.version_info`".to_string() + } + + fn placeholder() -> Self { + SysVersionSlice1Referenced + } +} + +// flake8-simplify + +define_violation!( + pub struct DuplicateIsinstanceCall(pub String); +); +impl AlwaysAutofixableViolation for DuplicateIsinstanceCall { + fn message(&self) -> String { + let DuplicateIsinstanceCall(name) = self; + format!("Multiple `isinstance` calls for `{name}`, merge into a single call") + } + + fn autofix_title(&self) -> String { + let DuplicateIsinstanceCall(name) = self; + format!("Merge `isinstance` calls for `{name}`") + } + + fn placeholder() -> Self { + DuplicateIsinstanceCall("...".to_string()) + } +} + +define_violation!( + pub struct NestedIfStatements; +); +impl Violation for NestedIfStatements { + fn message(&self) -> String { + "Use a single `if` statement instead of nested `if` statements".to_string() + } + + fn placeholder() -> Self { + NestedIfStatements + } +} + +define_violation!( + pub struct ReturnBoolConditionDirectly(pub String); +); +impl AlwaysAutofixableViolation for ReturnBoolConditionDirectly { + fn message(&self) -> String { + let ReturnBoolConditionDirectly(cond) = self; + format!("Return the condition `{cond}` directly") + } + + fn autofix_title(&self) -> String { + let ReturnBoolConditionDirectly(cond) = self; + format!("Replace with `return {cond}`") + } + + fn placeholder() -> Self { + ReturnBoolConditionDirectly("...".to_string()) + } +} + +define_violation!( + pub struct UseContextlibSuppress(pub String); +); +impl Violation for UseContextlibSuppress { + fn message(&self) -> String { + let UseContextlibSuppress(exception) = self; + format!("Use `contextlib.suppress({exception})` instead of try-except-pass") + } + + fn placeholder() -> Self { + UseContextlibSuppress("...".to_string()) + } +} + +define_violation!( + pub struct ReturnInTryExceptFinally; +); +impl Violation for ReturnInTryExceptFinally { + fn message(&self) -> String { + "Don't use `return` in `try`/`except` and `finally`".to_string() + } + + fn placeholder() -> Self { + ReturnInTryExceptFinally + } +} + +define_violation!( + pub struct UseTernaryOperator(pub String); +); +impl AlwaysAutofixableViolation for UseTernaryOperator { + fn message(&self) -> String { + let UseTernaryOperator(new_code) = self; + format!("Use ternary operator `{new_code}` instead of if-else-block") + } + + fn autofix_title(&self) -> String { + let UseTernaryOperator(new_code) = self; + format!("Replace if-else-block with `{new_code}`") + } + + fn placeholder() -> Self { + UseTernaryOperator("...".to_string()) + } +} + +define_violation!( + pub struct CompareWithTuple(pub String, pub Vec, pub String); +); +impl AlwaysAutofixableViolation for CompareWithTuple { + fn message(&self) -> String { + let CompareWithTuple(value, values, or_op) = self; + let values = values.join(", "); + format!("Use `{value} in ({values})` instead of `{or_op}`") + } + + fn autofix_title(&self) -> String { + let CompareWithTuple(value, values, or_op) = self; + let values = values.join(", "); + format!("Replace `{or_op}` with `{value} in {values}`") + } + + fn placeholder() -> Self { + CompareWithTuple( + "value".to_string(), + vec!["...".to_string(), "...".to_string()], + "value == ... or value == ...".to_string(), + ) + } +} + +define_violation!( + pub struct ConvertLoopToAny(pub String); +); +impl AlwaysAutofixableViolation for ConvertLoopToAny { + fn message(&self) -> String { + let ConvertLoopToAny(any) = self; + format!("Use `{any}` instead of `for` loop") + } + + fn autofix_title(&self) -> String { + let ConvertLoopToAny(any) = self; + format!("Replace with `{any}`") + } + + fn placeholder() -> Self { + ConvertLoopToAny("return any(x for x in y)".to_string()) + } +} + +define_violation!( + pub struct ConvertLoopToAll(pub String); +); +impl AlwaysAutofixableViolation for ConvertLoopToAll { + fn message(&self) -> String { + let ConvertLoopToAll(all) = self; + format!("Use `{all}` instead of `for` loop") + } + + fn autofix_title(&self) -> String { + let ConvertLoopToAll(all) = self; + format!("Replace with `{all}`") + } + + fn placeholder() -> Self { + ConvertLoopToAll("return all(x for x in y)".to_string()) + } +} + +define_violation!( + pub struct MultipleWithStatements; +); +impl Violation for MultipleWithStatements { + fn message(&self) -> String { + "Use a single `with` statement with multiple contexts instead of nested `with` statements" + .to_string() + } + + fn placeholder() -> Self { + MultipleWithStatements + } +} + +define_violation!( + pub struct KeyInDict(pub String, pub String); +); +impl AlwaysAutofixableViolation for KeyInDict { + fn message(&self) -> String { + let KeyInDict(key, dict) = self; + format!("Use `{key} in {dict}` instead of `{key} in {dict}.keys()`") + } + + fn autofix_title(&self) -> String { + let KeyInDict(key, dict) = self; + format!("Convert to `{key} in {dict}`") + } + + fn placeholder() -> Self { + KeyInDict("key".to_string(), "dict".to_string()) + } +} + +define_violation!( + pub struct NegateEqualOp(pub String, pub String); +); +impl AlwaysAutofixableViolation for NegateEqualOp { + fn message(&self) -> String { + let NegateEqualOp(left, right) = self; + format!("Use `{left} != {right}` instead of `not {left} == {right}`") + } + + fn autofix_title(&self) -> String { + "Replace with `!=` operator".to_string() + } + + fn placeholder() -> Self { + NegateEqualOp("left".to_string(), "right".to_string()) + } +} + +define_violation!( + pub struct NegateNotEqualOp(pub String, pub String); +); +impl AlwaysAutofixableViolation for NegateNotEqualOp { + fn message(&self) -> String { + let NegateNotEqualOp(left, right) = self; + format!("Use `{left} == {right}` instead of `not {left} != {right}`") + } + + fn autofix_title(&self) -> String { + "Replace with `==` operator".to_string() + } + + fn placeholder() -> Self { + NegateNotEqualOp("left".to_string(), "right".to_string()) + } +} + +define_violation!( + pub struct DoubleNegation(pub String); +); +impl AlwaysAutofixableViolation for DoubleNegation { + fn message(&self) -> String { + let DoubleNegation(expr) = self; + format!("Use `{expr}` instead of `not (not {expr})`") + } + + fn autofix_title(&self) -> String { + let DoubleNegation(expr) = self; + format!("Replace with `{expr}`") + } + + fn placeholder() -> Self { + DoubleNegation("expr".to_string()) + } +} + +define_violation!( + pub struct AAndNotA(pub String); +); +impl AlwaysAutofixableViolation for AAndNotA { + fn message(&self) -> String { + let AAndNotA(name) = self; + format!("Use `False` instead of `{name} and not {name}`") + } + + fn autofix_title(&self) -> String { + "Replace with `False`".to_string() + } + + fn placeholder() -> Self { + AAndNotA("...".to_string()) + } +} + +define_violation!( + pub struct AOrNotA(pub String); +); +impl AlwaysAutofixableViolation for AOrNotA { + fn message(&self) -> String { + let AOrNotA(name) = self; + format!("Use `True` instead of `{name} or not {name}`") + } + + fn autofix_title(&self) -> String { + "Replace with `True`".to_string() + } + + fn placeholder() -> Self { + AOrNotA("...".to_string()) + } +} + +define_violation!( + pub struct OrTrue; +); +impl AlwaysAutofixableViolation for OrTrue { + fn message(&self) -> String { + "Use `True` instead of `... or True`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `True`".to_string() + } + + fn placeholder() -> Self { + OrTrue + } +} + +define_violation!( + pub struct AndFalse; +); +impl AlwaysAutofixableViolation for AndFalse { + fn message(&self) -> String { + "Use `False` instead of `... and False`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `False`".to_string() + } + + fn placeholder() -> Self { + AndFalse + } +} + +define_violation!( + pub struct YodaConditions(pub String, pub String); +); +impl AlwaysAutofixableViolation for YodaConditions { + fn message(&self) -> String { + let YodaConditions(left, right) = self; + format!("Yoda conditions are discouraged, use `{left} == {right}` instead") + } + + fn autofix_title(&self) -> String { + let YodaConditions(left, right) = self; + format!("Replace Yoda condition with `{left} == {right}`") + } + + fn placeholder() -> Self { + YodaConditions("left".to_string(), "right".to_string()) + } +} + +define_violation!( + pub struct IfExprWithTrueFalse(pub String); +); +impl AlwaysAutofixableViolation for IfExprWithTrueFalse { + fn message(&self) -> String { + let IfExprWithTrueFalse(expr) = self; + format!("Use `bool({expr})` instead of `True if {expr} else False`") + } + + fn autofix_title(&self) -> String { + let IfExprWithTrueFalse(expr) = self; + format!("Replace with `not {expr}") + } + + fn placeholder() -> Self { + IfExprWithTrueFalse("expr".to_string()) + } +} + +define_violation!( + pub struct IfExprWithFalseTrue(pub String); +); +impl AlwaysAutofixableViolation for IfExprWithFalseTrue { + fn message(&self) -> String { + let IfExprWithFalseTrue(expr) = self; + format!("Use `not {expr}` instead of `False if {expr} else True`") + } + + fn autofix_title(&self) -> String { + let IfExprWithFalseTrue(expr) = self; + format!("Replace with `bool({expr})") + } + + fn placeholder() -> Self { + IfExprWithFalseTrue("expr".to_string()) + } +} + +define_violation!( + pub struct IfExprWithTwistedArms(pub String, pub String); +); +impl AlwaysAutofixableViolation for IfExprWithTwistedArms { + fn message(&self) -> String { + let IfExprWithTwistedArms(expr_body, expr_else) = self; + format!( + "Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not \ + {expr_else} else {expr_else}`" + ) + } + + fn autofix_title(&self) -> String { + let IfExprWithTwistedArms(expr_body, expr_else) = self; + format!("Replace with `{expr_else} if {expr_else} else {expr_body}`") + } + + fn placeholder() -> Self { + IfExprWithTwistedArms("else".to_string(), "body".to_string()) + } +} + +// pyupgrade + +define_violation!( + pub struct UselessMetaclassType; +); +impl AlwaysAutofixableViolation for UselessMetaclassType { + fn message(&self) -> String { + "`__metaclass__ = type` is implied".to_string() + } + + fn autofix_title(&self) -> String { + "Remove `__metaclass__ = type`".to_string() + } + + fn placeholder() -> Self { + UselessMetaclassType + } +} + +define_violation!( + pub struct TypeOfPrimitive(pub Primitive); +); +impl AlwaysAutofixableViolation for TypeOfPrimitive { + fn message(&self) -> String { + let TypeOfPrimitive(primitive) = self; + format!("Use `{}` instead of `type(...)`", primitive.builtin()) + } + + fn autofix_title(&self) -> String { + let TypeOfPrimitive(primitive) = self; + format!("Replace `type(...)` with `{}`", primitive.builtin()) + } + + fn placeholder() -> Self { + TypeOfPrimitive(Primitive::Str) + } +} + +define_violation!( + pub struct UselessObjectInheritance(pub String); +); +impl AlwaysAutofixableViolation for UselessObjectInheritance { + fn message(&self) -> String { + let UselessObjectInheritance(name) = self; + format!("Class `{name}` inherits from `object`") + } + + fn autofix_title(&self) -> String { + "Remove `object` inheritance".to_string() + } + + fn placeholder() -> Self { + UselessObjectInheritance("...".to_string()) + } +} + +define_violation!( + pub struct DeprecatedUnittestAlias(pub String, pub String); +); +impl AlwaysAutofixableViolation for DeprecatedUnittestAlias { + fn message(&self) -> String { + let DeprecatedUnittestAlias(alias, target) = self; + format!("`{alias}` is deprecated, use `{target}`") + } + + fn autofix_title(&self) -> String { + let DeprecatedUnittestAlias(alias, target) = self; + format!("Replace `{target}` with `{alias}`") + } + + fn placeholder() -> Self { + DeprecatedUnittestAlias("assertEquals".to_string(), "assertEqual".to_string()) + } +} + +define_violation!( + pub struct UsePEP585Annotation(pub String); +); +impl AlwaysAutofixableViolation for UsePEP585Annotation { + fn message(&self) -> String { + let UsePEP585Annotation(name) = self; + format!( + "Use `{}` instead of `{}` for type annotations", + name.to_lowercase(), + name, + ) + } + + fn autofix_title(&self) -> String { + let UsePEP585Annotation(name) = self; + format!("Replace `{name}` with `{}`", name.to_lowercase(),) + } + + fn placeholder() -> Self { + UsePEP585Annotation("List".to_string()) + } +} + +define_violation!( + pub struct UsePEP604Annotation; +); +impl AlwaysAutofixableViolation for UsePEP604Annotation { + fn message(&self) -> String { + "Use `X | Y` for type annotations".to_string() + } + + fn autofix_title(&self) -> String { + "Convert to `X | Y`".to_string() + } + + fn placeholder() -> Self { + UsePEP604Annotation + } +} + +define_violation!( + pub struct SuperCallWithParameters; +); +impl AlwaysAutofixableViolation for SuperCallWithParameters { + fn message(&self) -> String { + "Use `super()` instead of `super(__class__, self)`".to_string() + } + + fn autofix_title(&self) -> String { + "Remove `__super__` parameters".to_string() + } + + fn placeholder() -> Self { + SuperCallWithParameters + } +} + +define_violation!( + pub struct PEP3120UnnecessaryCodingComment; +); +impl AlwaysAutofixableViolation for PEP3120UnnecessaryCodingComment { + fn message(&self) -> String { + "UTF-8 encoding declaration is unnecessary".to_string() + } + + fn autofix_title(&self) -> String { + "Remove unnecessary coding comment".to_string() + } + + fn placeholder() -> Self { + PEP3120UnnecessaryCodingComment + } +} + +define_violation!( + pub struct UnnecessaryFutureImport(pub Vec); +); +impl AlwaysAutofixableViolation for UnnecessaryFutureImport { + fn message(&self) -> String { + let UnnecessaryFutureImport(names) = self; + if names.len() == 1 { + let import = &names[0]; + format!("Unnecessary `__future__` import `{import}` for target Python version") + } else { + let imports = names.iter().map(|name| format!("`{name}`")).join(", "); + format!("Unnecessary `__future__` imports {imports} for target Python version") + } + } + + fn autofix_title(&self) -> String { + "Remove unnecessary `__future__` import".to_string() + } + + fn placeholder() -> Self { + UnnecessaryFutureImport(vec!["...".to_string()]) + } +} + +define_violation!( + pub struct UnnecessaryLRUCacheParams; +); +impl AlwaysAutofixableViolation for UnnecessaryLRUCacheParams { + fn message(&self) -> String { + "Unnecessary parameters to `functools.lru_cache`".to_string() + } + + fn autofix_title(&self) -> String { + "Remove unnecessary parameters".to_string() + } + + fn placeholder() -> Self { + UnnecessaryLRUCacheParams + } +} + +define_violation!( + pub struct UnnecessaryEncodeUTF8; +); +impl AlwaysAutofixableViolation for UnnecessaryEncodeUTF8 { + fn message(&self) -> String { + "Unnecessary call to `encode` as UTF-8".to_string() + } + + fn autofix_title(&self) -> String { + "Remove unnecessary `encode`".to_string() + } + + fn placeholder() -> Self { + UnnecessaryEncodeUTF8 + } +} + +define_violation!( + pub struct ConvertTypedDictFunctionalToClass(pub String); +); +impl AlwaysAutofixableViolation for ConvertTypedDictFunctionalToClass { + fn message(&self) -> String { + let ConvertTypedDictFunctionalToClass(name) = self; + format!("Convert `{name}` from `TypedDict` functional to class syntax") + } + + fn autofix_title(&self) -> String { + let ConvertTypedDictFunctionalToClass(name) = self; + format!("Convert `{name}` to class syntax") + } + + fn placeholder() -> Self { + ConvertTypedDictFunctionalToClass("...".to_string()) + } +} + +define_violation!( + pub struct ConvertNamedTupleFunctionalToClass(pub String); +); +impl AlwaysAutofixableViolation for ConvertNamedTupleFunctionalToClass { + fn message(&self) -> String { + let ConvertNamedTupleFunctionalToClass(name) = self; + format!("Convert `{name}` from `NamedTuple` functional to class syntax") + } + + fn autofix_title(&self) -> String { + let ConvertNamedTupleFunctionalToClass(name) = self; + format!("Convert `{name}` to class syntax") + } + + fn placeholder() -> Self { + ConvertNamedTupleFunctionalToClass("...".to_string()) + } +} + +define_violation!( + pub struct RedundantOpenModes(pub Option); +); +impl AlwaysAutofixableViolation for RedundantOpenModes { + fn message(&self) -> String { + let RedundantOpenModes(replacement) = self; + match replacement { + None => "Unnecessary open mode parameters".to_string(), + Some(replacement) => { + format!("Unnecessary open mode parameters, use \"{replacement}\"") + } + } + } + + fn autofix_title(&self) -> String { + let RedundantOpenModes(replacement) = self; + match replacement { + None => "Remove open mode parameters".to_string(), + Some(replacement) => { + format!("Replace with \"{replacement}\"") + } + } + } + + fn placeholder() -> Self { + RedundantOpenModes(None) + } +} + +define_violation!( + pub struct RemoveSixCompat; +); +impl AlwaysAutofixableViolation for RemoveSixCompat { + fn message(&self) -> String { + "Unnecessary `six` compatibility usage".to_string() + } + + fn autofix_title(&self) -> String { + "Remove `six` usage".to_string() + } + + fn placeholder() -> Self { + RemoveSixCompat + } +} + +define_violation!( + pub struct DatetimeTimezoneUTC; +); +impl AlwaysAutofixableViolation for DatetimeTimezoneUTC { + fn message(&self) -> String { + "Use `datetime.UTC` alias".to_string() + } + + fn autofix_title(&self) -> String { + "Convert to `datetime.UTC` alias".to_string() + } + + fn placeholder() -> Self { + DatetimeTimezoneUTC + } +} + +define_violation!( + pub struct NativeLiterals(pub LiteralType); +); +impl AlwaysAutofixableViolation for NativeLiterals { + fn message(&self) -> String { + let NativeLiterals(literal_type) = self; + format!("Unnecessary call to `{literal_type}`") + } + + fn autofix_title(&self) -> String { + let NativeLiterals(literal_type) = self; + format!("Replace with `{literal_type}`") + } + + fn placeholder() -> Self { + NativeLiterals(LiteralType::Str) + } +} + +define_violation!( + pub struct TypingTextStrAlias; +); +impl AlwaysAutofixableViolation for TypingTextStrAlias { + fn message(&self) -> String { + "`typing.Text` is deprecated, use `str`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `str`".to_string() + } + + fn placeholder() -> Self { + TypingTextStrAlias + } +} + +define_violation!( + pub struct OpenAlias; +); +impl AlwaysAutofixableViolation for OpenAlias { + fn message(&self) -> String { + "Use builtin `open`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with builtin `open`".to_string() + } + + fn placeholder() -> Self { + OpenAlias + } +} + +define_violation!( + pub struct ReplaceUniversalNewlines; +); +impl AlwaysAutofixableViolation for ReplaceUniversalNewlines { + fn message(&self) -> String { + "`universal_newlines` is deprecated, use `text`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `text` keyword argument".to_string() + } + + fn placeholder() -> Self { + ReplaceUniversalNewlines + } +} + +define_violation!( + pub struct ReplaceStdoutStderr; +); +impl AlwaysAutofixableViolation for ReplaceStdoutStderr { + fn message(&self) -> String { + "Sending stdout and stderr to pipe is deprecated, use `capture_output`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `capture_output` keyword argument".to_string() + } + + fn placeholder() -> Self { + ReplaceStdoutStderr + } +} + +define_violation!( + pub struct RewriteCElementTree; +); +impl AlwaysAutofixableViolation for RewriteCElementTree { + fn message(&self) -> String { + "`cElementTree` is deprecated, use `ElementTree`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `ElementTree`".to_string() + } + + fn placeholder() -> Self { + RewriteCElementTree + } +} + +define_violation!( + pub struct OSErrorAlias(pub Option); +); +impl AlwaysAutofixableViolation for OSErrorAlias { + fn message(&self) -> String { + "Replace aliased errors with `OSError`".to_string() + } + + fn autofix_title(&self) -> String { + let OSErrorAlias(name) = self; + match name { + None => "Replace with builtin `OSError`".to_string(), + Some(name) => format!("Replace `{name}` with builtin `OSError`"), + } + } + + fn placeholder() -> Self { + OSErrorAlias(None) + } +} + +define_violation!( + pub struct RewriteUnicodeLiteral; +); +impl AlwaysAutofixableViolation for RewriteUnicodeLiteral { + fn message(&self) -> String { + "Remove unicode literals from strings".to_string() + } + + fn autofix_title(&self) -> String { + "Remove unicode prefix".to_string() + } + + fn placeholder() -> Self { + RewriteUnicodeLiteral + } +} + +define_violation!( + pub struct RewriteMockImport(pub MockReference); +); +impl AlwaysAutofixableViolation for RewriteMockImport { + fn message(&self) -> String { + "`mock` is deprecated, use `unittest.mock`".to_string() + } + + fn autofix_title(&self) -> String { + let RewriteMockImport(reference_type) = self; + match reference_type { + MockReference::Import => "Import from `unittest.mock` instead".to_string(), + MockReference::Attribute => "Replace `mock.mock` with `mock`".to_string(), + } + } + + fn placeholder() -> Self { + RewriteMockImport(MockReference::Import) + } +} + +define_violation!( + pub struct RewriteListComprehension; +); +impl AlwaysAutofixableViolation for RewriteListComprehension { + fn message(&self) -> String { + "Replace unpacked list comprehension with a generator expression".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with generator expression".to_string() + } + + fn placeholder() -> Self { + RewriteListComprehension + } +} + +define_violation!( + pub struct RewriteYieldFrom; +); +impl AlwaysAutofixableViolation for RewriteYieldFrom { + fn message(&self) -> String { + "Replace `yield` over `for` loop with `yield from`".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `yield from`".to_string() + } + + fn placeholder() -> Self { + RewriteYieldFrom + } +} + +define_violation!( + pub struct UnnecessaryBuiltinImport(pub Vec); +); +impl AlwaysAutofixableViolation for UnnecessaryBuiltinImport { + fn message(&self) -> String { + let UnnecessaryBuiltinImport(names) = self; + if names.len() == 1 { + let import = &names[0]; + format!("Unnecessary builtin import: `{import}`") + } else { + let imports = names.iter().map(|name| format!("`{name}`")).join(", "); + format!("Unnecessary builtin imports: {imports}") + } + } + + fn autofix_title(&self) -> String { + "Remove unnecessary builtin import".to_string() + } + + fn placeholder() -> Self { + UnnecessaryBuiltinImport(vec!["...".to_string()]) + } +} + +// pydocstyle + +define_violation!( + pub struct PublicModule; +); +impl Violation for PublicModule { + fn message(&self) -> String { + "Missing docstring in public module".to_string() + } + + fn placeholder() -> Self { + PublicModule + } +} + +define_violation!( + pub struct PublicClass; +); +impl Violation for PublicClass { + fn message(&self) -> String { + "Missing docstring in public class".to_string() + } + + fn placeholder() -> Self { + PublicClass + } +} + +define_violation!( + pub struct PublicMethod; +); +impl Violation for PublicMethod { + fn message(&self) -> String { + "Missing docstring in public method".to_string() + } + + fn placeholder() -> Self { + PublicMethod + } +} + +define_violation!( + pub struct PublicFunction; +); +impl Violation for PublicFunction { + fn message(&self) -> String { + "Missing docstring in public function".to_string() + } + + fn placeholder() -> Self { + PublicFunction + } +} + +define_violation!( + pub struct PublicPackage; +); +impl Violation for PublicPackage { + fn message(&self) -> String { + "Missing docstring in public package".to_string() + } + + fn placeholder() -> Self { + PublicPackage + } +} + +define_violation!( + pub struct MagicMethod; +); +impl Violation for MagicMethod { + fn message(&self) -> String { + "Missing docstring in magic method".to_string() + } + + fn placeholder() -> Self { + MagicMethod + } +} + +define_violation!( + pub struct PublicNestedClass; +); +impl Violation for PublicNestedClass { + fn message(&self) -> String { + "Missing docstring in public nested class".to_string() + } + + fn placeholder() -> Self { + PublicNestedClass + } +} + +define_violation!( + pub struct PublicInit; +); +impl Violation for PublicInit { + fn message(&self) -> String { + "Missing docstring in `__init__`".to_string() + } + + fn placeholder() -> Self { + PublicInit + } +} + +define_violation!( + pub struct FitsOnOneLine; +); +impl Violation for FitsOnOneLine { + fn message(&self) -> String { + "One-line docstring should fit on one line".to_string() + } + + fn placeholder() -> Self { + FitsOnOneLine + } +} + +define_violation!( + pub struct NoBlankLineBeforeFunction(pub usize); +); +impl AlwaysAutofixableViolation for NoBlankLineBeforeFunction { + fn message(&self) -> String { + let NoBlankLineBeforeFunction(num_lines) = self; + format!("No blank lines allowed before function docstring (found {num_lines})") + } + + fn autofix_title(&self) -> String { + "Remove blank line(s) before function docstring".to_string() + } + + fn placeholder() -> Self { + NoBlankLineBeforeFunction(1) + } +} + +define_violation!( + pub struct NoBlankLineAfterFunction(pub usize); +); +impl AlwaysAutofixableViolation for NoBlankLineAfterFunction { + fn message(&self) -> String { + let NoBlankLineAfterFunction(num_lines) = self; + format!("No blank lines allowed after function docstring (found {num_lines})") + } + + fn autofix_title(&self) -> String { + "Remove blank line(s) after function docstring".to_string() + } + + fn placeholder() -> Self { + NoBlankLineAfterFunction(1) + } +} + +define_violation!( + pub struct OneBlankLineBeforeClass(pub usize); +); +impl AlwaysAutofixableViolation for OneBlankLineBeforeClass { + fn message(&self) -> String { + "1 blank line required before class docstring".to_string() + } + + fn autofix_title(&self) -> String { + "Insert 1 blank line before class docstring".to_string() + } + + fn placeholder() -> Self { + OneBlankLineBeforeClass(0) + } +} + +define_violation!( + pub struct OneBlankLineAfterClass(pub usize); +); +impl AlwaysAutofixableViolation for OneBlankLineAfterClass { + fn message(&self) -> String { + "1 blank line required after class docstring".to_string() + } + + fn autofix_title(&self) -> String { + "Insert 1 blank line after class docstring".to_string() + } + + fn placeholder() -> Self { + OneBlankLineAfterClass(0) + } +} + +define_violation!( + pub struct BlankLineAfterSummary(pub usize); +); +fn fmt_blank_line_after_summary_autofix_msg(_: &BlankLineAfterSummary) -> String { + "Insert single blank line".to_string() +} +impl Violation for BlankLineAfterSummary { + fn message(&self) -> String { + let BlankLineAfterSummary(num_lines) = self; + if *num_lines == 0 { + "1 blank line required between summary line and description".to_string() + } else { + format!( + "1 blank line required between summary line and description (found {num_lines})" + ) + } + } + + fn autofix_title_formatter(&self) -> Option String> { + let num_lines = self.0; + if num_lines > 0 { + return Some(fmt_blank_line_after_summary_autofix_msg); + } + None + } + + fn placeholder() -> Self { + BlankLineAfterSummary(2) + } +} + +define_violation!( + pub struct IndentWithSpaces; +); +impl Violation for IndentWithSpaces { + fn message(&self) -> String { + "Docstring should be indented with spaces, not tabs".to_string() + } + + fn placeholder() -> Self { + IndentWithSpaces + } +} + +define_violation!( + pub struct NoUnderIndentation; +); +impl AlwaysAutofixableViolation for NoUnderIndentation { + fn message(&self) -> String { + "Docstring is under-indented".to_string() + } + + fn autofix_title(&self) -> String { + "Increase indentation".to_string() + } + + fn placeholder() -> Self { + NoUnderIndentation + } +} + +define_violation!( + pub struct NoOverIndentation; +); +impl AlwaysAutofixableViolation for NoOverIndentation { + fn message(&self) -> String { + "Docstring is over-indented".to_string() + } + + fn autofix_title(&self) -> String { + "Remove over-indentation".to_string() + } + + fn placeholder() -> Self { + NoOverIndentation + } +} + +define_violation!( + pub struct NewLineAfterLastParagraph; +); +impl AlwaysAutofixableViolation for NewLineAfterLastParagraph { + fn message(&self) -> String { + "Multi-line docstring closing quotes should be on a separate line".to_string() + } + + fn autofix_title(&self) -> String { + "Move closing quotes to new line".to_string() + } + + fn placeholder() -> Self { + NewLineAfterLastParagraph + } +} + +define_violation!( + pub struct NoSurroundingWhitespace; +); +impl AlwaysAutofixableViolation for NoSurroundingWhitespace { + fn message(&self) -> String { + "No whitespaces allowed surrounding docstring text".to_string() + } + + fn autofix_title(&self) -> String { + "Trim surrounding whitespace".to_string() + } + + fn placeholder() -> Self { + NoSurroundingWhitespace + } +} + +define_violation!( + pub struct NoBlankLineBeforeClass(pub usize); +); +impl AlwaysAutofixableViolation for NoBlankLineBeforeClass { + fn message(&self) -> String { + "No blank lines allowed before class docstring".to_string() + } + + fn autofix_title(&self) -> String { + "Remove blank line(s) before class docstring".to_string() + } + + fn placeholder() -> Self { + NoBlankLineBeforeClass(1) + } +} + +define_violation!( + pub struct MultiLineSummaryFirstLine; +); +impl Violation for MultiLineSummaryFirstLine { + fn message(&self) -> String { + "Multi-line docstring summary should start at the first line".to_string() + } + + fn placeholder() -> Self { + MultiLineSummaryFirstLine + } +} + +define_violation!( + pub struct MultiLineSummarySecondLine; +); +impl Violation for MultiLineSummarySecondLine { + fn message(&self) -> String { + "Multi-line docstring summary should start at the second line".to_string() + } + + fn placeholder() -> Self { + MultiLineSummarySecondLine + } +} + +define_violation!( + pub struct SectionNotOverIndented(pub String); +); +impl AlwaysAutofixableViolation for SectionNotOverIndented { + fn message(&self) -> String { + let SectionNotOverIndented(name) = self; + format!("Section is over-indented (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let SectionNotOverIndented(name) = self; + format!("Remove over-indentation from \"{name}\"") + } + + fn placeholder() -> Self { + SectionNotOverIndented("Returns".to_string()) + } +} + +define_violation!( + pub struct SectionUnderlineNotOverIndented(pub String); +); +impl AlwaysAutofixableViolation for SectionUnderlineNotOverIndented { + fn message(&self) -> String { + let SectionUnderlineNotOverIndented(name) = self; + format!("Section underline is over-indented (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let SectionUnderlineNotOverIndented(name) = self; + format!("Remove over-indentation from \"{name}\" underline") + } + + fn placeholder() -> Self { + SectionUnderlineNotOverIndented("Returns".to_string()) + } +} + +define_violation!( + pub struct UsesTripleQuotes; +); +impl Violation for UsesTripleQuotes { + fn message(&self) -> String { + r#"Use """triple double quotes""""#.to_string() + } + + fn placeholder() -> Self { + UsesTripleQuotes + } +} + +define_violation!( + pub struct UsesRPrefixForBackslashedContent; +); +impl Violation for UsesRPrefixForBackslashedContent { + fn message(&self) -> String { + r#"Use r""" if any backslashes in a docstring"#.to_string() + } + + fn placeholder() -> Self { + UsesRPrefixForBackslashedContent + } +} + +define_violation!( + pub struct EndsInPeriod; +); +impl AlwaysAutofixableViolation for EndsInPeriod { + fn message(&self) -> String { + "First line should end with a period".to_string() + } + + fn autofix_title(&self) -> String { + "Add period".to_string() + } + + fn placeholder() -> Self { + EndsInPeriod + } +} + +define_violation!( + pub struct NoSignature; +); +impl Violation for NoSignature { + fn message(&self) -> String { + "First line should not be the function's signature".to_string() + } + + fn placeholder() -> Self { + NoSignature + } +} + +define_violation!( + pub struct FirstLineCapitalized; +); +impl Violation for FirstLineCapitalized { + fn message(&self) -> String { + "First word of the first line should be properly capitalized".to_string() + } + + fn placeholder() -> Self { + FirstLineCapitalized + } +} + +define_violation!( + pub struct NoThisPrefix; +); +impl Violation for NoThisPrefix { + fn message(&self) -> String { + "First word of the docstring should not be \"This\"".to_string() + } + + fn placeholder() -> Self { + NoThisPrefix + } +} + +define_violation!( + pub struct CapitalizeSectionName(pub String); +); +impl AlwaysAutofixableViolation for CapitalizeSectionName { + fn message(&self) -> String { + let CapitalizeSectionName(name) = self; + format!("Section name should be properly capitalized (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let CapitalizeSectionName(name) = self; + format!("Capitalize \"{name}\"") + } + + fn placeholder() -> Self { + CapitalizeSectionName("returns".to_string()) + } +} + +define_violation!( + pub struct NewLineAfterSectionName(pub String); +); +impl AlwaysAutofixableViolation for NewLineAfterSectionName { + fn message(&self) -> String { + let NewLineAfterSectionName(name) = self; + format!("Section name should end with a newline (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let NewLineAfterSectionName(name) = self; + format!("Add newline after \"{name}\"") + } + + fn placeholder() -> Self { + NewLineAfterSectionName("Returns".to_string()) + } +} + +define_violation!( + pub struct DashedUnderlineAfterSection(pub String); +); +impl AlwaysAutofixableViolation for DashedUnderlineAfterSection { + fn message(&self) -> String { + let DashedUnderlineAfterSection(name) = self; + format!("Missing dashed underline after section (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let DashedUnderlineAfterSection(name) = self; + format!("Add dashed line under \"{name}\"") + } + + fn placeholder() -> Self { + DashedUnderlineAfterSection("Returns".to_string()) + } +} + +define_violation!( + pub struct SectionUnderlineAfterName(pub String); +); +impl AlwaysAutofixableViolation for SectionUnderlineAfterName { + fn message(&self) -> String { + let SectionUnderlineAfterName(name) = self; + format!("Section underline should be in the line following the section's name (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let SectionUnderlineAfterName(name) = self; + format!("Add underline to \"{name}\"") + } + + fn placeholder() -> Self { + SectionUnderlineAfterName("Returns".to_string()) + } +} + +define_violation!( + pub struct SectionUnderlineMatchesSectionLength(pub String); +); +impl AlwaysAutofixableViolation for SectionUnderlineMatchesSectionLength { + fn message(&self) -> String { + let SectionUnderlineMatchesSectionLength(name) = self; + format!("Section underline should match the length of its name (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let SectionUnderlineMatchesSectionLength(name) = self; + format!("Adjust underline length to match \"{name}\"") + } + + fn placeholder() -> Self { + SectionUnderlineMatchesSectionLength("Returns".to_string()) + } +} + +define_violation!( + pub struct BlankLineAfterSection(pub String); +); +impl AlwaysAutofixableViolation for BlankLineAfterSection { + fn message(&self) -> String { + let BlankLineAfterSection(name) = self; + format!("Missing blank line after section (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let BlankLineAfterSection(name) = self; + format!("Add blank line after \"{name}\"") + } + + fn placeholder() -> Self { + BlankLineAfterSection("Returns".to_string()) + } +} + +define_violation!( + pub struct BlankLineBeforeSection(pub String); +); +impl AlwaysAutofixableViolation for BlankLineBeforeSection { + fn message(&self) -> String { + let BlankLineBeforeSection(name) = self; + format!("Missing blank line before section (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let BlankLineBeforeSection(name) = self; + format!("Add blank line before \"{name}\"") + } + + fn placeholder() -> Self { + BlankLineBeforeSection("Returns".to_string()) + } +} + +define_violation!( + pub struct NoBlankLinesBetweenHeaderAndContent(pub String); +); +impl AlwaysAutofixableViolation for NoBlankLinesBetweenHeaderAndContent { + fn message(&self) -> String { + let NoBlankLinesBetweenHeaderAndContent(name) = self; + format!("No blank lines allowed between a section header and its content (\"{name}\")") + } + + fn autofix_title(&self) -> String { + "Remove blank line(s)".to_string() + } + + fn placeholder() -> Self { + NoBlankLinesBetweenHeaderAndContent("Returns".to_string()) + } +} + +define_violation!( + pub struct BlankLineAfterLastSection(pub String); +); +impl AlwaysAutofixableViolation for BlankLineAfterLastSection { + fn message(&self) -> String { + let BlankLineAfterLastSection(name) = self; + format!("Missing blank line after last section (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let BlankLineAfterLastSection(name) = self; + format!("Add blank line after \"{name}\"") + } + + fn placeholder() -> Self { + BlankLineAfterLastSection("Returns".to_string()) + } +} + +define_violation!( + pub struct NonEmptySection(pub String); +); +impl Violation for NonEmptySection { + fn message(&self) -> String { + let NonEmptySection(name) = self; + format!("Section has no content (\"{name}\")") + } + + fn placeholder() -> Self { + NonEmptySection("Returns".to_string()) + } +} + +define_violation!( + pub struct EndsInPunctuation; +); +impl AlwaysAutofixableViolation for EndsInPunctuation { + fn message(&self) -> String { + "First line should end with a period, question mark, or exclamation point".to_string() + } + + fn autofix_title(&self) -> String { + "Add closing punctuation".to_string() + } + + fn placeholder() -> Self { + EndsInPunctuation + } +} + +define_violation!( + pub struct SectionNameEndsInColon(pub String); +); +impl AlwaysAutofixableViolation for SectionNameEndsInColon { + fn message(&self) -> String { + let SectionNameEndsInColon(name) = self; + format!("Section name should end with a colon (\"{name}\")") + } + + fn autofix_title(&self) -> String { + let SectionNameEndsInColon(name) = self; + format!("Add colon to \"{name}\"") + } + + fn placeholder() -> Self { + SectionNameEndsInColon("Returns".to_string()) + } +} + +define_violation!( + pub struct DocumentAllArguments(pub Vec); +); +impl Violation for DocumentAllArguments { + fn message(&self) -> String { + let DocumentAllArguments(names) = self; + if names.len() == 1 { + let name = &names[0]; + format!("Missing argument description in the docstring: `{name}`") + } else { + let names = names.iter().map(|name| format!("`{name}`")).join(", "); + format!("Missing argument descriptions in the docstring: {names}") + } + } + + fn placeholder() -> Self { + DocumentAllArguments(vec!["x".to_string(), "y".to_string()]) + } +} + +define_violation!( + pub struct SkipDocstring; +); +impl Violation for SkipDocstring { + fn message(&self) -> String { + "Function decorated with `@overload` shouldn't contain a docstring".to_string() + } + + fn placeholder() -> Self { + SkipDocstring + } +} + +define_violation!( + pub struct NonEmpty; +); +impl Violation for NonEmpty { + fn message(&self) -> String { + "Docstring is empty".to_string() + } + + fn placeholder() -> Self { + NonEmpty + } +} + +// pep8-naming + +define_violation!( + pub struct InvalidClassName(pub String); +); +impl Violation for InvalidClassName { + fn message(&self) -> String { + let InvalidClassName(name) = self; + format!("Class name `{name}` should use CapWords convention ") + } + + fn placeholder() -> Self { + InvalidClassName("...".to_string()) + } +} + +define_violation!( + pub struct InvalidFunctionName(pub String); +); +impl Violation for InvalidFunctionName { + fn message(&self) -> String { + let InvalidFunctionName(name) = self; + format!("Function name `{name}` should be lowercase") + } + + fn placeholder() -> Self { + InvalidFunctionName("...".to_string()) + } +} + +define_violation!( + pub struct InvalidArgumentName(pub String); +); +impl Violation for InvalidArgumentName { + fn message(&self) -> String { + let InvalidArgumentName(name) = self; + format!("Argument name `{name}` should be lowercase") + } + + fn placeholder() -> Self { + InvalidArgumentName("...".to_string()) + } +} + +define_violation!( + pub struct InvalidFirstArgumentNameForClassMethod; +); +impl Violation for InvalidFirstArgumentNameForClassMethod { + fn message(&self) -> String { + "First argument of a class method should be named `cls`".to_string() + } + + fn placeholder() -> Self { + InvalidFirstArgumentNameForClassMethod + } +} + +define_violation!( + pub struct InvalidFirstArgumentNameForMethod; +); +impl Violation for InvalidFirstArgumentNameForMethod { + fn message(&self) -> String { + "First argument of a method should be named `self`".to_string() + } + + fn placeholder() -> Self { + InvalidFirstArgumentNameForMethod + } +} + +define_violation!( + pub struct NonLowercaseVariableInFunction(pub String); +); +impl Violation for NonLowercaseVariableInFunction { + fn message(&self) -> String { + let NonLowercaseVariableInFunction(name) = self; + format!("Variable `{name}` in function should be lowercase") + } + + fn placeholder() -> Self { + NonLowercaseVariableInFunction("...".to_string()) + } +} + +define_violation!( + pub struct DunderFunctionName; +); +impl Violation for DunderFunctionName { + fn message(&self) -> String { + "Function name should not start and end with `__`".to_string() + } + + fn placeholder() -> Self { + DunderFunctionName + } +} + +define_violation!( + pub struct ConstantImportedAsNonConstant(pub String, pub String); +); +impl Violation for ConstantImportedAsNonConstant { + fn message(&self) -> String { + let ConstantImportedAsNonConstant(name, asname) = self; + format!("Constant `{name}` imported as non-constant `{asname}`") + } + + fn placeholder() -> Self { + ConstantImportedAsNonConstant("...".to_string(), "...".to_string()) + } +} + +define_violation!( + pub struct LowercaseImportedAsNonLowercase(pub String, pub String); +); +impl Violation for LowercaseImportedAsNonLowercase { + fn message(&self) -> String { + let LowercaseImportedAsNonLowercase(name, asname) = self; + format!("Lowercase `{name}` imported as non-lowercase `{asname}`") + } + + fn placeholder() -> Self { + LowercaseImportedAsNonLowercase("...".to_string(), "...".to_string()) + } +} + +define_violation!( + pub struct CamelcaseImportedAsLowercase(pub String, pub String); +); +impl Violation for CamelcaseImportedAsLowercase { + fn message(&self) -> String { + let CamelcaseImportedAsLowercase(name, asname) = self; + format!("Camelcase `{name}` imported as lowercase `{asname}`") + } + + fn placeholder() -> Self { + CamelcaseImportedAsLowercase("...".to_string(), "...".to_string()) + } +} + +define_violation!( + pub struct CamelcaseImportedAsConstant(pub String, pub String); +); +impl Violation for CamelcaseImportedAsConstant { + fn message(&self) -> String { + let CamelcaseImportedAsConstant(name, asname) = self; + format!("Camelcase `{name}` imported as constant `{asname}`") + } + + fn placeholder() -> Self { + CamelcaseImportedAsConstant("...".to_string(), "...".to_string()) + } +} + +define_violation!( + pub struct MixedCaseVariableInClassScope(pub String); +); +impl Violation for MixedCaseVariableInClassScope { + fn message(&self) -> String { + let MixedCaseVariableInClassScope(name) = self; + format!("Variable `{name}` in class scope should not be mixedCase") + } + + fn placeholder() -> Self { + MixedCaseVariableInClassScope("mixedCase".to_string()) + } +} + +define_violation!( + pub struct MixedCaseVariableInGlobalScope(pub String); +); +impl Violation for MixedCaseVariableInGlobalScope { + fn message(&self) -> String { + let MixedCaseVariableInGlobalScope(name) = self; + format!("Variable `{name}` in global scope should not be mixedCase") + } + + fn placeholder() -> Self { + MixedCaseVariableInGlobalScope("mixedCase".to_string()) + } +} + +define_violation!( + pub struct CamelcaseImportedAsAcronym(pub String, pub String); +); +impl Violation for CamelcaseImportedAsAcronym { + fn message(&self) -> String { + let CamelcaseImportedAsAcronym(name, asname) = self; + format!("Camelcase `{name}` imported as acronym `{asname}`") + } + + fn placeholder() -> Self { + CamelcaseImportedAsAcronym("...".to_string(), "...".to_string()) + } +} + +define_violation!( + pub struct ErrorSuffixOnExceptionName(pub String); +); +impl Violation for ErrorSuffixOnExceptionName { + fn message(&self) -> String { + let ErrorSuffixOnExceptionName(name) = self; + format!("Exception name `{name}` should be named with an Error suffix") + } + + fn placeholder() -> Self { + ErrorSuffixOnExceptionName("...".to_string()) + } +} + +// isort + +define_violation!( + pub struct UnsortedImports; +); +impl AlwaysAutofixableViolation for UnsortedImports { + fn message(&self) -> String { + "Import block is un-sorted or un-formatted".to_string() + } + + fn autofix_title(&self) -> String { + "Organize imports".to_string() + } + + fn placeholder() -> Self { + UnsortedImports + } +} + +// eradicate + +define_violation!( + pub struct CommentedOutCode; +); +impl AlwaysAutofixableViolation for CommentedOutCode { + fn message(&self) -> String { + "Found commented-out code".to_string() + } + + fn autofix_title(&self) -> String { + "Remove commented-out code".to_string() + } + + fn placeholder() -> Self { + CommentedOutCode + } +} + +// flake8-bandit + +define_violation!( + pub struct AssertUsed; +); +impl Violation for AssertUsed { + fn message(&self) -> String { + "Use of `assert` detected".to_string() + } + + fn placeholder() -> Self { + AssertUsed + } +} + +define_violation!( + pub struct ExecUsed; +); +impl Violation for ExecUsed { + fn message(&self) -> String { + "Use of `exec` detected".to_string() + } + + fn placeholder() -> Self { + ExecUsed + } +} + +define_violation!( + pub struct BadFilePermissions(pub u16); +); +impl Violation for BadFilePermissions { + fn message(&self) -> String { + let BadFilePermissions(mask) = self; + format!("`os.chmod` setting a permissive mask `{mask:#o}` on file or directory",) + } + + fn placeholder() -> Self { + BadFilePermissions(0o777) + } +} + +define_violation!( + pub struct HardcodedBindAllInterfaces; +); +impl Violation for HardcodedBindAllInterfaces { + fn message(&self) -> String { + "Possible binding to all interfaces".to_string() + } + + fn placeholder() -> Self { + HardcodedBindAllInterfaces + } +} + +define_violation!( + pub struct HardcodedPasswordString(pub String); +); +impl Violation for HardcodedPasswordString { + fn message(&self) -> String { + let HardcodedPasswordString(string) = self; + format!("Possible hardcoded password: \"{}\"", string.escape_debug()) + } + + fn placeholder() -> Self { + HardcodedPasswordString("...".to_string()) + } +} + +define_violation!( + pub struct HardcodedPasswordFuncArg(pub String); +); +impl Violation for HardcodedPasswordFuncArg { + fn message(&self) -> String { + let HardcodedPasswordFuncArg(string) = self; + format!("Possible hardcoded password: \"{}\"", string.escape_debug()) + } + + fn placeholder() -> Self { + HardcodedPasswordFuncArg("...".to_string()) + } +} + +define_violation!( + pub struct HardcodedPasswordDefault(pub String); +); +impl Violation for HardcodedPasswordDefault { + fn message(&self) -> String { + let HardcodedPasswordDefault(string) = self; + format!("Possible hardcoded password: \"{}\"", string.escape_debug()) + } + + fn placeholder() -> Self { + HardcodedPasswordDefault("...".to_string()) + } +} + +define_violation!( + pub struct HardcodedTempFile(pub String); +); +impl Violation for HardcodedTempFile { + fn message(&self) -> String { + let HardcodedTempFile(string) = self; + format!( + "Probable insecure usage of temporary file or directory: \"{}\"", + string.escape_debug() + ) + } + + fn placeholder() -> Self { + HardcodedTempFile("...".to_string()) + } +} + +define_violation!( + pub struct RequestWithoutTimeout(pub Option); +); +impl Violation for RequestWithoutTimeout { + fn message(&self) -> String { + let RequestWithoutTimeout(timeout) = self; + match timeout { + Some(value) => { + format!("Probable use of requests call with timeout set to `{value}`") + } + None => "Probable use of requests call without timeout".to_string(), + } + } + + fn placeholder() -> Self { + RequestWithoutTimeout(None) + } +} + +define_violation!( + pub struct HashlibInsecureHashFunction(pub String); +); +impl Violation for HashlibInsecureHashFunction { + fn message(&self) -> String { + let HashlibInsecureHashFunction(string) = self; + format!( + "Probable use of insecure hash functions in `hashlib`: \"{}\"", + string.escape_debug() + ) + } + + fn placeholder() -> Self { + HashlibInsecureHashFunction("...".to_string()) + } +} + +define_violation!( + pub struct RequestWithNoCertValidation(pub String); +); +impl Violation for RequestWithNoCertValidation { + fn message(&self) -> String { + let RequestWithNoCertValidation(string) = self; + format!( + "Probable use of `{string}` call with `verify=False` disabling SSL certificate checks" + ) + } + + fn placeholder() -> Self { + RequestWithNoCertValidation("...".to_string()) + } +} + +define_violation!( + pub struct UnsafeYAMLLoad(pub Option); +); +impl Violation for UnsafeYAMLLoad { + fn message(&self) -> String { + let UnsafeYAMLLoad(loader) = self; + match loader { + Some(name) => { + format!( + "Probable use of unsafe loader `{name}` with `yaml.load`. Allows \ + instantiation of arbitrary objects. Consider `yaml.safe_load`." + ) + } + None => "Probable use of unsafe `yaml.load`. Allows instantiation of arbitrary \ + objects. Consider `yaml.safe_load`." + .to_string(), + } + } + + fn placeholder() -> Self { + UnsafeYAMLLoad(None) + } +} + +// flake8-boolean-trap + +define_violation!( + pub struct BooleanPositionalArgInFunctionDefinition; +); +impl Violation for BooleanPositionalArgInFunctionDefinition { + fn message(&self) -> String { + "Boolean positional arg in function definition".to_string() + } + + fn placeholder() -> Self { + BooleanPositionalArgInFunctionDefinition + } +} + +define_violation!( + pub struct BooleanDefaultValueInFunctionDefinition; +); +impl Violation for BooleanDefaultValueInFunctionDefinition { + fn message(&self) -> String { + "Boolean default value in function definition".to_string() + } + + fn placeholder() -> Self { + BooleanDefaultValueInFunctionDefinition + } +} + +define_violation!( + pub struct BooleanPositionalValueInFunctionCall; +); +impl Violation for BooleanPositionalValueInFunctionCall { + fn message(&self) -> String { + "Boolean positional value in function call".to_string() + } + + fn placeholder() -> Self { + BooleanPositionalValueInFunctionCall + } +} + +// flake8-unused-arguments + +define_violation!( + pub struct UnusedFunctionArgument(pub String); +); +impl Violation for UnusedFunctionArgument { + fn message(&self) -> String { + let UnusedFunctionArgument(name) = self; + format!("Unused function argument: `{name}`") + } + + fn placeholder() -> Self { + UnusedFunctionArgument("...".to_string()) + } +} + +define_violation!( + pub struct UnusedMethodArgument(pub String); +); +impl Violation for UnusedMethodArgument { + fn message(&self) -> String { + let UnusedMethodArgument(name) = self; + format!("Unused method argument: `{name}`") + } + + fn placeholder() -> Self { + UnusedMethodArgument("...".to_string()) + } +} + +define_violation!( + pub struct UnusedClassMethodArgument(pub String); +); +impl Violation for UnusedClassMethodArgument { + fn message(&self) -> String { + let UnusedClassMethodArgument(name) = self; + format!("Unused class method argument: `{name}`") + } + + fn placeholder() -> Self { + UnusedClassMethodArgument("...".to_string()) + } +} + +define_violation!( + pub struct UnusedStaticMethodArgument(pub String); +); +impl Violation for UnusedStaticMethodArgument { + fn message(&self) -> String { + let UnusedStaticMethodArgument(name) = self; + format!("Unused static method argument: `{name}`") + } + + fn placeholder() -> Self { + UnusedStaticMethodArgument("...".to_string()) + } +} + +define_violation!( + pub struct UnusedLambdaArgument(pub String); +); +impl Violation for UnusedLambdaArgument { + fn message(&self) -> String { + let UnusedLambdaArgument(name) = self; + format!("Unused lambda argument: `{name}`") + } + + fn placeholder() -> Self { + UnusedLambdaArgument("...".to_string()) + } +} + +// flake8-import-conventions + +define_violation!( + pub struct ImportAliasIsNotConventional(pub String, pub String); +); +impl Violation for ImportAliasIsNotConventional { + fn message(&self) -> String { + let ImportAliasIsNotConventional(name, asname) = self; + format!("`{name}` should be imported as `{asname}`") + } + + fn placeholder() -> Self { + ImportAliasIsNotConventional("...".to_string(), "...".to_string()) + } +} + +// flake8-datetimez + +define_violation!( + pub struct CallDatetimeWithoutTzinfo; +); +impl Violation for CallDatetimeWithoutTzinfo { + fn message(&self) -> String { + "The use of `datetime.datetime()` without `tzinfo` argument is not allowed".to_string() + } + + fn placeholder() -> Self { + CallDatetimeWithoutTzinfo + } +} + +define_violation!( + pub struct CallDatetimeToday; +); +impl Violation for CallDatetimeToday { + fn message(&self) -> String { + "The use of `datetime.datetime.today()` is not allowed. Use `datetime.datetime.now(tz=)` \ + instead." + .to_string() + } + + fn placeholder() -> Self { + CallDatetimeToday + } +} + +define_violation!( + pub struct CallDatetimeUtcnow; +); +impl Violation for CallDatetimeUtcnow { + fn message(&self) -> String { + "The use of `datetime.datetime.utcnow()` is not allowed. Use `datetime.datetime.now(tz=)` \ + instead." + .to_string() + } + + fn placeholder() -> Self { + CallDatetimeUtcnow + } +} + +define_violation!( + pub struct CallDatetimeUtcfromtimestamp; +); +impl Violation for CallDatetimeUtcfromtimestamp { + fn message(&self) -> String { + "The use of `datetime.datetime.utcfromtimestamp()` is not allowed. Use \ + `datetime.datetime.fromtimestamp(, tz=)` instead." + .to_string() + } + + fn placeholder() -> Self { + CallDatetimeUtcfromtimestamp + } +} + +define_violation!( + pub struct CallDatetimeNowWithoutTzinfo; +); +impl Violation for CallDatetimeNowWithoutTzinfo { + fn message(&self) -> String { + "The use of `datetime.datetime.now()` without `tz` argument is not allowed".to_string() + } + + fn placeholder() -> Self { + CallDatetimeNowWithoutTzinfo + } +} + +define_violation!( + pub struct CallDatetimeFromtimestamp; +); +impl Violation for CallDatetimeFromtimestamp { + fn message(&self) -> String { + "The use of `datetime.datetime.fromtimestamp()` without `tz` argument is not allowed" + .to_string() + } + + fn placeholder() -> Self { + CallDatetimeFromtimestamp + } +} + +define_violation!( + pub struct CallDatetimeStrptimeWithoutZone; +); +impl Violation for CallDatetimeStrptimeWithoutZone { + fn message(&self) -> String { + "The use of `datetime.datetime.strptime()` without %z must be followed by \ + `.replace(tzinfo=)`" + .to_string() + } + + fn placeholder() -> Self { + CallDatetimeStrptimeWithoutZone + } +} + +define_violation!( + pub struct CallDateToday; +); +impl Violation for CallDateToday { + fn message(&self) -> String { + "The use of `datetime.date.today()` is not allowed. Use \ + `datetime.datetime.now(tz=).date()` instead." + .to_string() + } + + fn placeholder() -> Self { + CallDateToday + } +} + +define_violation!( + pub struct CallDateFromtimestamp; +); +impl Violation for CallDateFromtimestamp { + fn message(&self) -> String { + "The use of `datetime.date.fromtimestamp()` is not allowed. Use \ + `datetime.datetime.fromtimestamp(, tz=).date()` instead." + .to_string() + } + + fn placeholder() -> Self { + CallDateFromtimestamp + } +} + +// pygrep-hooks + +define_violation!( + pub struct NoEval; +); +impl Violation for NoEval { + fn message(&self) -> String { + "No builtin `eval()` allowed".to_string() + } + + fn placeholder() -> Self { + NoEval + } +} + +define_violation!( + pub struct DeprecatedLogWarn; +); +impl Violation for DeprecatedLogWarn { + fn message(&self) -> String { + "`warn` is deprecated in favor of `warning`".to_string() + } + + fn placeholder() -> Self { + DeprecatedLogWarn + } +} + +define_violation!( + pub struct BlanketTypeIgnore; +); +impl Violation for BlanketTypeIgnore { + fn message(&self) -> String { + "Use specific error codes when ignoring type issues".to_string() + } + + fn placeholder() -> Self { + BlanketTypeIgnore + } +} + +define_violation!( + pub struct BlanketNOQA; +); +impl Violation for BlanketNOQA { + fn message(&self) -> String { + "Use specific error codes when using `noqa`".to_string() + } + + fn placeholder() -> Self { + BlanketNOQA + } +} + +// pandas-vet + +define_violation!( + pub struct UseOfInplaceArgument; +); +impl Violation for UseOfInplaceArgument { + fn message(&self) -> String { + "`inplace=True` should be avoided; it has inconsistent behavior".to_string() + } + + fn placeholder() -> Self { + UseOfInplaceArgument + } +} + +define_violation!( + pub struct UseOfDotIsNull; +); +impl Violation for UseOfDotIsNull { + fn message(&self) -> String { + "`.isna` is preferred to `.isnull`; functionality is equivalent".to_string() + } + + fn placeholder() -> Self { + UseOfDotIsNull + } +} + +define_violation!( + pub struct UseOfDotNotNull; +); +impl Violation for UseOfDotNotNull { + fn message(&self) -> String { + "`.notna` is preferred to `.notnull`; functionality is equivalent".to_string() + } + + fn placeholder() -> Self { + UseOfDotNotNull + } +} + +define_violation!( + pub struct UseOfDotIx; +); +impl Violation for UseOfDotIx { + fn message(&self) -> String { + "`.ix` is deprecated; use more explicit `.loc` or `.iloc`".to_string() + } + + fn placeholder() -> Self { + UseOfDotIx + } +} + +define_violation!( + pub struct UseOfDotAt; +); +impl Violation for UseOfDotAt { + fn message(&self) -> String { + "Use `.loc` instead of `.at`. If speed is important, use numpy.".to_string() + } + + fn placeholder() -> Self { + UseOfDotAt + } +} + +define_violation!( + pub struct UseOfDotIat; +); +impl Violation for UseOfDotIat { + fn message(&self) -> String { + "Use `.iloc` instead of `.iat`. If speed is important, use numpy.".to_string() + } + + fn placeholder() -> Self { + UseOfDotIat + } +} + +define_violation!( + pub struct UseOfDotPivotOrUnstack; +); +impl Violation for UseOfDotPivotOrUnstack { + fn message(&self) -> String { + "`.pivot_table` is preferred to `.pivot` or `.unstack`; provides same functionality" + .to_string() + } + + fn placeholder() -> Self { + UseOfDotPivotOrUnstack + } +} + +define_violation!( + pub struct UseOfDotValues; +); +impl Violation for UseOfDotValues { + fn message(&self) -> String { + "Use `.to_numpy()` instead of `.values`".to_string() + } + + fn placeholder() -> Self { + UseOfDotValues + } +} + +define_violation!( + pub struct UseOfDotReadTable; +); +impl Violation for UseOfDotReadTable { + fn message(&self) -> String { + "`.read_csv` is preferred to `.read_table`; provides same functionality".to_string() + } + + fn placeholder() -> Self { + UseOfDotReadTable + } +} + +define_violation!( + pub struct UseOfDotStack; +); +impl Violation for UseOfDotStack { + fn message(&self) -> String { + "`.melt` is preferred to `.stack`; provides same functionality".to_string() + } + + fn placeholder() -> Self { + UseOfDotStack + } +} + +define_violation!( + pub struct UseOfPdMerge; +); +impl Violation for UseOfPdMerge { + fn message(&self) -> String { + "Use `.merge` method instead of `pd.merge` function. They have equivalent functionality." + .to_string() + } + + fn placeholder() -> Self { + UseOfPdMerge + } +} + +define_violation!( + pub struct DfIsABadVariableName; +); +impl Violation for DfIsABadVariableName { + fn message(&self) -> String { + "`df` is a bad variable name. Be kinder to your future self.".to_string() + } + + fn placeholder() -> Self { + DfIsABadVariableName + } +} + +// flake8-errmsg + +define_violation!( + pub struct RawStringInException; +); +impl Violation for RawStringInException { + fn message(&self) -> String { + "Exception must not use a string literal, assign to variable first".to_string() + } + + fn placeholder() -> Self { + RawStringInException + } +} + +define_violation!( + pub struct FStringInException; +); +impl Violation for FStringInException { + fn message(&self) -> String { + "Exception must not use an f-string literal, assign to variable first".to_string() + } + + fn placeholder() -> Self { + FStringInException + } +} + +define_violation!( + pub struct DotFormatInException; +); +impl Violation for DotFormatInException { + fn message(&self) -> String { + "Exception must not use a `.format()` string directly, assign to variable first".to_string() + } + + fn placeholder() -> Self { + DotFormatInException + } +} + +// flake8-pytest-style + +define_violation!( + pub struct IncorrectFixtureParenthesesStyle(pub String, pub String); +); +impl AlwaysAutofixableViolation for IncorrectFixtureParenthesesStyle { + fn message(&self) -> String { + let IncorrectFixtureParenthesesStyle(expected_parens, actual_parens) = self; + format!("Use `@pytest.fixture{expected_parens}` over `@pytest.fixture{actual_parens}`") + } + + fn autofix_title(&self) -> String { + "Add/remove parentheses".to_string() + } + + fn placeholder() -> Self { + IncorrectFixtureParenthesesStyle("()".to_string(), String::new()) + } +} + +define_violation!( + pub struct FixturePositionalArgs(pub String); +); +impl Violation for FixturePositionalArgs { + fn message(&self) -> String { + let FixturePositionalArgs(function) = self; + format!("Configuration for fixture `{function}` specified via positional args, use kwargs") + } + + fn placeholder() -> Self { + FixturePositionalArgs("...".to_string()) + } +} + +define_violation!( + pub struct ExtraneousScopeFunction; +); +impl Violation for ExtraneousScopeFunction { + fn message(&self) -> String { + "`scope='function'` is implied in `@pytest.fixture()`".to_string() + } + + fn placeholder() -> Self { + ExtraneousScopeFunction + } +} + +define_violation!( + pub struct MissingFixtureNameUnderscore(pub String); +); +impl Violation for MissingFixtureNameUnderscore { + fn message(&self) -> String { + let MissingFixtureNameUnderscore(function) = self; + format!("Fixture `{function}` does not return anything, add leading underscore") + } + + fn placeholder() -> Self { + MissingFixtureNameUnderscore("...".to_string()) + } +} + +define_violation!( + pub struct IncorrectFixtureNameUnderscore(pub String); +); +impl Violation for IncorrectFixtureNameUnderscore { + fn message(&self) -> String { + let IncorrectFixtureNameUnderscore(function) = self; + format!("Fixture `{function}` returns a value, remove leading underscore") + } + + fn placeholder() -> Self { + IncorrectFixtureNameUnderscore("...".to_string()) + } +} + +define_violation!( + pub struct ParametrizeNamesWrongType(pub ParametrizeNameType); +); +impl AlwaysAutofixableViolation for ParametrizeNamesWrongType { + fn message(&self) -> String { + let ParametrizeNamesWrongType(expected) = self; + format!("Wrong name(s) type in `@pytest.mark.parametrize`, expected `{expected}`") + } + + fn autofix_title(&self) -> String { + let ParametrizeNamesWrongType(expected) = self; + format!("Use a `{expected}` for parameter names") + } + + fn placeholder() -> Self { + ParametrizeNamesWrongType(ParametrizeNameType::Tuple) + } +} + +define_violation!( + pub struct ParametrizeValuesWrongType(pub ParametrizeValuesType, pub ParametrizeValuesRowType); +); +impl Violation for ParametrizeValuesWrongType { + fn message(&self) -> String { + let ParametrizeValuesWrongType(values, row) = self; + format!("Wrong values type in `@pytest.mark.parametrize` expected `{values}` of `{row}`") + } + + fn placeholder() -> Self { + ParametrizeValuesWrongType(ParametrizeValuesType::List, ParametrizeValuesRowType::Tuple) + } +} + +define_violation!( + pub struct PatchWithLambda; +); +impl Violation for PatchWithLambda { + fn message(&self) -> String { + "Use `return_value=` instead of patching with `lambda`".to_string() + } + + fn placeholder() -> Self { + PatchWithLambda + } +} + +define_violation!( + pub struct UnittestAssertion(pub String); +); +impl AlwaysAutofixableViolation for UnittestAssertion { + fn message(&self) -> String { + let UnittestAssertion(assertion) = self; + format!("Use a regular `assert` instead of unittest-style `{assertion}`") + } + + fn autofix_title(&self) -> String { + let UnittestAssertion(assertion) = self; + format!("Replace `{assertion}(...)` with `assert ...`") + } + + fn placeholder() -> Self { + UnittestAssertion("...".to_string()) + } +} + +define_violation!( + pub struct RaisesWithoutException; +); +impl Violation for RaisesWithoutException { + fn message(&self) -> String { + "set the expected exception in `pytest.raises()`".to_string() + } + + fn placeholder() -> Self { + RaisesWithoutException + } +} + +define_violation!( + pub struct RaisesTooBroad(pub String); +); +impl Violation for RaisesTooBroad { + fn message(&self) -> String { + let RaisesTooBroad(exception) = self; + format!( + "`pytest.raises({exception})` is too broad, set the `match` parameter or use a more \ + specific exception" + ) + } + + fn placeholder() -> Self { + RaisesTooBroad("...".to_string()) + } +} + +define_violation!( + pub struct RaisesWithMultipleStatements; +); +impl Violation for RaisesWithMultipleStatements { + fn message(&self) -> String { + "`pytest.raises()` block should contain a single simple statement".to_string() + } + + fn placeholder() -> Self { + RaisesWithMultipleStatements + } +} + +define_violation!( + pub struct IncorrectPytestImport; +); +impl Violation for IncorrectPytestImport { + fn message(&self) -> String { + "Found incorrect import of pytest, use simple `import pytest` instead".to_string() + } + + fn placeholder() -> Self { + IncorrectPytestImport + } +} + +define_violation!( + pub struct AssertAlwaysFalse; +); +impl Violation for AssertAlwaysFalse { + fn message(&self) -> String { + "Assertion always fails, replace with `pytest.fail()`".to_string() + } + + fn placeholder() -> Self { + AssertAlwaysFalse + } +} + +define_violation!( + pub struct FailWithoutMessage; +); +impl Violation for FailWithoutMessage { + fn message(&self) -> String { + "No message passed to `pytest.fail()`".to_string() + } + + fn placeholder() -> Self { + FailWithoutMessage + } +} + +define_violation!( + pub struct AssertInExcept(pub String); +); +impl Violation for AssertInExcept { + fn message(&self) -> String { + let AssertInExcept(name) = self; + format!( + "Found assertion on exception `{name}` in except block, use `pytest.raises()` instead" + ) + } + + fn placeholder() -> Self { + AssertInExcept("...".to_string()) + } +} + +define_violation!( + pub struct CompositeAssertion; +); +impl Violation for CompositeAssertion { + fn message(&self) -> String { + "Assertion should be broken down into multiple parts".to_string() + } + + fn placeholder() -> Self { + CompositeAssertion + } +} + +define_violation!( + pub struct FixtureParamWithoutValue(pub String); +); +impl Violation for FixtureParamWithoutValue { + fn message(&self) -> String { + let FixtureParamWithoutValue(name) = self; + format!( + "Fixture `{name}` without value is injected as parameter, use \ + `@pytest.mark.usefixtures` instead" + ) + } + + fn placeholder() -> Self { + FixtureParamWithoutValue("...".to_string()) + } +} + +define_violation!( + pub struct DeprecatedYieldFixture; +); +impl Violation for DeprecatedYieldFixture { + fn message(&self) -> String { + "`@pytest.yield_fixture` is deprecated, use `@pytest.fixture`".to_string() + } + + fn placeholder() -> Self { + DeprecatedYieldFixture + } +} + +define_violation!( + pub struct FixtureFinalizerCallback; +); +impl Violation for FixtureFinalizerCallback { + fn message(&self) -> String { + "Use `yield` instead of `request.addfinalizer`".to_string() + } + + fn placeholder() -> Self { + FixtureFinalizerCallback + } +} + +define_violation!( + pub struct UselessYieldFixture(pub String); +); +impl AlwaysAutofixableViolation for UselessYieldFixture { + fn message(&self) -> String { + let UselessYieldFixture(name) = self; + format!("No teardown in fixture `{name}`, use `return` instead of `yield`") + } + + fn autofix_title(&self) -> String { + "Replace `yield` with `return`".to_string() + } + + fn placeholder() -> Self { + UselessYieldFixture("...".to_string()) + } +} + +define_violation!( + pub struct IncorrectMarkParenthesesStyle(pub String, pub String, pub String); +); +impl AlwaysAutofixableViolation for IncorrectMarkParenthesesStyle { + fn message(&self) -> String { + let IncorrectMarkParenthesesStyle(mark_name, expected_parens, actual_parens) = self; + format!( + "Use `@pytest.mark.{mark_name}{expected_parens}` over \ + `@pytest.mark.{mark_name}{actual_parens}`" + ) + } + + fn autofix_title(&self) -> String { + "Add/remove parentheses".to_string() + } + + fn placeholder() -> Self { + IncorrectMarkParenthesesStyle("...".to_string(), String::new(), "()".to_string()) + } +} + +define_violation!( + pub struct UnnecessaryAsyncioMarkOnFixture; +); +impl Violation for UnnecessaryAsyncioMarkOnFixture { + fn message(&self) -> String { + "`pytest.mark.asyncio` is unnecessary for fixtures".to_string() + } + + fn placeholder() -> Self { + UnnecessaryAsyncioMarkOnFixture + } +} + +define_violation!( + pub struct ErroneousUseFixturesOnFixture; +); +impl Violation for ErroneousUseFixturesOnFixture { + fn message(&self) -> String { + "`pytest.mark.usefixtures` has no effect on fixtures".to_string() + } + + fn placeholder() -> Self { + ErroneousUseFixturesOnFixture + } +} + +define_violation!( + pub struct UseFixturesWithoutParameters; +); +impl AlwaysAutofixableViolation for UseFixturesWithoutParameters { + fn message(&self) -> String { + "Useless `pytest.mark.usefixtures` without parameters".to_string() + } + + fn autofix_title(&self) -> String { + "Remove `usefixtures` decorator or pass parameters".to_string() + } + + fn placeholder() -> Self { + UseFixturesWithoutParameters + } +} + +// flake8-pie + +define_violation!( + pub struct NoUnnecessaryPass; +); +impl AlwaysAutofixableViolation for NoUnnecessaryPass { + fn message(&self) -> String { + "Unnecessary `pass` statement".to_string() + } + + fn autofix_title(&self) -> String { + "Remove unnecessary `pass`".to_string() + } + + fn placeholder() -> Self { + NoUnnecessaryPass + } +} + +define_violation!( + pub struct DupeClassFieldDefinitions(pub String); +); +impl AlwaysAutofixableViolation for DupeClassFieldDefinitions { + fn message(&self) -> String { + let DupeClassFieldDefinitions(name) = self; + format!("Class field `{name}` is defined multiple times") + } + + fn autofix_title(&self) -> String { + let DupeClassFieldDefinitions(name) = self; + format!("Remove duplicate field definition for `{name}`") + } + + fn placeholder() -> Self { + DupeClassFieldDefinitions("...".to_string()) + } +} + +define_violation!( + pub struct PreferListBuiltin; +); +impl AlwaysAutofixableViolation for PreferListBuiltin { + fn message(&self) -> String { + "Prefer `list()` over useless lambda".to_string() + } + + fn autofix_title(&self) -> String { + "Replace with `list`".to_string() + } + + fn placeholder() -> Self { + PreferListBuiltin + } +} + +// Ruff + +define_violation!( + pub struct AmbiguousUnicodeCharacterString(pub char, pub char); +); +impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterString { + fn message(&self) -> String { + let AmbiguousUnicodeCharacterString(confusable, representant) = self; + format!( + "String contains ambiguous unicode character '{confusable}' (did you mean \ + '{representant}'?)" + ) + } + + fn autofix_title(&self) -> String { + let AmbiguousUnicodeCharacterString(confusable, representant) = self; + format!("Replace '{confusable}' with '{representant}'") + } + + fn placeholder() -> Self { + AmbiguousUnicodeCharacterString('𝐁', 'B') + } +} + +define_violation!( + pub struct AmbiguousUnicodeCharacterDocstring(pub char, pub char); +); +impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterDocstring { + fn message(&self) -> String { + let AmbiguousUnicodeCharacterDocstring(confusable, representant) = self; + format!( + "Docstring contains ambiguous unicode character '{confusable}' (did you mean \ + '{representant}'?)" + ) + } + + fn autofix_title(&self) -> String { + let AmbiguousUnicodeCharacterDocstring(confusable, representant) = self; + format!("Replace '{confusable}' with '{representant}'") + } + + fn placeholder() -> Self { + AmbiguousUnicodeCharacterDocstring('𝐁', 'B') + } +} + +define_violation!( + pub struct AmbiguousUnicodeCharacterComment(pub char, pub char); +); +impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterComment { + fn message(&self) -> String { + let AmbiguousUnicodeCharacterComment(confusable, representant) = self; + format!( + "Comment contains ambiguous unicode character '{confusable}' (did you mean \ + '{representant}'?)" + ) + } + + fn autofix_title(&self) -> String { + let AmbiguousUnicodeCharacterComment(confusable, representant) = self; + format!("Replace '{confusable}' with '{representant}'") + } + + fn placeholder() -> Self { + AmbiguousUnicodeCharacterComment('𝐁', 'B') + } +} + +define_violation!( + pub struct KeywordArgumentBeforeStarArgument(pub String); +); +impl Violation for KeywordArgumentBeforeStarArgument { + fn message(&self) -> String { + let KeywordArgumentBeforeStarArgument(name) = self; + format!("Keyword argument `{name}` must come after starred arguments") + } + + fn placeholder() -> Self { + KeywordArgumentBeforeStarArgument("...".to_string()) + } +} + +define_violation!( + pub struct UnusedNOQA(pub Option); +); +impl AlwaysAutofixableViolation for UnusedNOQA { + fn message(&self) -> String { + let UnusedNOQA(codes) = self; + match codes { + None => "Unused blanket `noqa` directive".to_string(), + Some(codes) => { + let mut codes_by_reason = vec![]; + if !codes.unmatched.is_empty() { + codes_by_reason.push(format!( + "unused: {}", + codes + .unmatched + .iter() + .map(|code| format!("`{code}`")) + .join(", ") + )); + } + if !codes.disabled.is_empty() { + codes_by_reason.push(format!( + "non-enabled: {}", + codes + .disabled + .iter() + .map(|code| format!("`{code}`")) + .join(", ") + )); + } + if !codes.unknown.is_empty() { + codes_by_reason.push(format!( + "unknown: {}", + codes + .unknown + .iter() + .map(|code| format!("`{code}`")) + .join(", ") + )); + } + if codes_by_reason.is_empty() { + "Unused `noqa` directive".to_string() + } else { + format!("Unused `noqa` directive ({})", codes_by_reason.join("; ")) + } + } + } + } + + fn autofix_title(&self) -> String { + "Remove unused `noqa` directive".to_string() + } + + fn placeholder() -> Self { + UnusedNOQA(None) + } +}