Rename `Check` to `Diagnostic` (#1725)

Along with:

- `CheckKind` -> `DiagnosticKind`
- `CheckCode` -> `RuleCode`
- `CheckCodePrefix` -> `RuleCodePrefix`
This commit is contained in:
Charlie Marsh 2023-01-08 17:46:20 -05:00 committed by GitHub
parent 498134b7ee
commit 09dc3c7225
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
204 changed files with 4222 additions and 4145 deletions

View File

@ -344,7 +344,7 @@ Options:
--isolated --isolated
Ignore all configuration files Ignore all configuration files
--select <SELECT> --select <SELECT>
Comma-separated list of error codes to enable (or ALL, to enable all checks) Comma-separated list of rule codes to enable (or ALL, to enable all rules)
--extend-select <EXTEND_SELECT> --extend-select <EXTEND_SELECT>
Like --select, but adds additional error codes on top of the selected ones Like --select, but adds additional error codes on top of the selected ones
--ignore <IGNORE> --ignore <IGNORE>
@ -1867,7 +1867,7 @@ by `ignore`.
**Default value**: `[]` **Default value**: `[]`
**Type**: `Vec<CheckCodePrefix>` **Type**: `Vec<RuleCodePrefix>`
**Example usage**: **Example usage**:
@ -1886,7 +1886,7 @@ by `select`.
**Default value**: `[]` **Default value**: `[]`
**Type**: `Vec<CheckCodePrefix>` **Type**: `Vec<RuleCodePrefix>`
**Example usage**: **Example usage**:
@ -1961,7 +1961,7 @@ A list of check code prefixes to consider autofix-able.
**Default value**: `["A", "ANN", "ARG", "B", "BLE", "C", "D", "E", "ERA", "F", "FBT", "I", "ICN", "N", "PGH", "PLC", "PLE", "PLR", "PLW", "Q", "RET", "RUF", "S", "T", "TID", "UP", "W", "YTT"]` **Default value**: `["A", "ANN", "ARG", "B", "BLE", "C", "D", "E", "ERA", "F", "FBT", "I", "ICN", "N", "PGH", "PLC", "PLE", "PLR", "PLW", "Q", "RET", "RUF", "S", "T", "TID", "UP", "W", "YTT"]`
**Type**: `Vec<CheckCodePrefix>` **Type**: `Vec<RuleCodePrefix>`
**Example usage**: **Example usage**:
@ -2033,7 +2033,7 @@ specific prefixes.
**Default value**: `[]` **Default value**: `[]`
**Type**: `Vec<CheckCodePrefix>` **Type**: `Vec<RuleCodePrefix>`
**Example usage**: **Example usage**:
@ -2092,7 +2092,7 @@ when considering any matching files.
**Default value**: `{}` **Default value**: `{}`
**Type**: `HashMap<String, Vec<CheckCodePrefix>>` **Type**: `HashMap<String, Vec<RuleCodePrefix>>`
**Example usage**: **Example usage**:
@ -2156,7 +2156,7 @@ specific prefixes.
**Default value**: `["E", "F"]` **Default value**: `["E", "F"]`
**Type**: `Vec<CheckCodePrefix>` **Type**: `Vec<RuleCodePrefix>`
**Example usage**: **Example usage**:
@ -2276,7 +2276,7 @@ A list of check code prefixes to consider un-autofix-able.
**Default value**: `[]` **Default value**: `[]`
**Type**: `Vec<CheckCodePrefix>` **Type**: `Vec<RuleCodePrefix>`
**Example usage**: **Example usage**:

View File

@ -7,7 +7,7 @@ use ruff::flake8_pytest_style::types::{
use ruff::flake8_quotes::settings::Quote; use ruff::flake8_quotes::settings::Quote;
use ruff::flake8_tidy_imports::settings::Strictness; use ruff::flake8_tidy_imports::settings::Strictness;
use ruff::pydocstyle::settings::Convention; use ruff::pydocstyle::settings::Convention;
use ruff::registry::CheckCodePrefix; use ruff::registry::RuleCodePrefix;
use ruff::settings::options::Options; use ruff::settings::options::Options;
use ruff::settings::pyproject::Pyproject; use ruff::settings::pyproject::Pyproject;
use ruff::{ use ruff::{
@ -30,7 +30,7 @@ pub fn convert(
.expect("Unable to find flake8 section in INI file"); .expect("Unable to find flake8 section in INI file");
// Extract all referenced check code prefixes, to power plugin inference. // Extract all referenced check code prefixes, to power plugin inference.
let mut referenced_codes: BTreeSet<CheckCodePrefix> = BTreeSet::default(); let mut referenced_codes: BTreeSet<RuleCodePrefix> = BTreeSet::default();
for (key, value) in flake8 { for (key, value) in flake8 {
if let Some(value) = value { if let Some(value) = value {
match key.as_str() { match key.as_str() {
@ -60,7 +60,7 @@ pub fn convert(
} }
let from_codes = plugin::infer_plugins_from_codes(&referenced_codes); let from_codes = plugin::infer_plugins_from_codes(&referenced_codes);
if !from_codes.is_empty() { if !from_codes.is_empty() {
eprintln!("Inferred plugins from referenced check codes: {from_codes:#?}"); eprintln!("Inferred plugins from referenced codes: {from_codes:#?}");
} }
from_options.into_iter().chain(from_codes).collect() from_options.into_iter().chain(from_codes).collect()
}); });
@ -345,7 +345,7 @@ mod tests {
use anyhow::Result; use anyhow::Result;
use ruff::pydocstyle::settings::Convention; use ruff::pydocstyle::settings::Convention;
use ruff::registry::CheckCodePrefix; use ruff::registry::RuleCodePrefix;
use ruff::settings::options::Options; use ruff::settings::options::Options;
use ruff::settings::pyproject::Pyproject; use ruff::settings::pyproject::Pyproject;
use ruff::{flake8_quotes, pydocstyle}; use ruff::{flake8_quotes, pydocstyle};
@ -382,9 +382,9 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,
@ -445,9 +445,9 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,
@ -508,9 +508,9 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,
@ -571,9 +571,9 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,
@ -634,9 +634,9 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,
@ -705,10 +705,10 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::D, RuleCodePrefix::D,
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,
@ -771,10 +771,10 @@ mod tests {
required_version: None, required_version: None,
respect_gitignore: None, respect_gitignore: None,
select: Some(vec![ select: Some(vec![
CheckCodePrefix::E, RuleCodePrefix::E,
CheckCodePrefix::F, RuleCodePrefix::F,
CheckCodePrefix::Q, RuleCodePrefix::Q,
CheckCodePrefix::W, RuleCodePrefix::W,
]), ]),
show_source: None, show_source: None,
src: None, src: None,

View File

@ -3,16 +3,16 @@ use std::str::FromStr;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use ruff::registry::{CheckCodePrefix, PREFIX_REDIRECTS}; use ruff::registry::{RuleCodePrefix, PREFIX_REDIRECTS};
use ruff::settings::types::PatternPrefixPair; use ruff::settings::types::PatternPrefixPair;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
static COMMA_SEPARATED_LIST_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[,\s]").unwrap()); static COMMA_SEPARATED_LIST_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[,\s]").unwrap());
/// Parse a comma-separated list of `CheckCodePrefix` values (e.g., /// Parse a comma-separated list of `RuleCodePrefix` values (e.g.,
/// "F401,E501"). /// "F401,E501").
pub fn parse_prefix_codes(value: &str) -> Vec<CheckCodePrefix> { pub fn parse_prefix_codes(value: &str) -> Vec<RuleCodePrefix> {
let mut codes: Vec<CheckCodePrefix> = vec![]; let mut codes: Vec<RuleCodePrefix> = vec![];
for code in COMMA_SEPARATED_LIST_RE.split(value) { for code in COMMA_SEPARATED_LIST_RE.split(value) {
let code = code.trim(); let code = code.trim();
if code.is_empty() { if code.is_empty() {
@ -20,7 +20,7 @@ pub fn parse_prefix_codes(value: &str) -> Vec<CheckCodePrefix> {
} }
if let Some(code) = PREFIX_REDIRECTS.get(code) { if let Some(code) = PREFIX_REDIRECTS.get(code) {
codes.push(code.clone()); codes.push(code.clone());
} else if let Ok(code) = CheckCodePrefix::from_str(code) { } else if let Ok(code) = RuleCodePrefix::from_str(code) {
codes.push(code); codes.push(code);
} else { } else {
eprintln!("Unsupported prefix code: {code}"); eprintln!("Unsupported prefix code: {code}");
@ -81,7 +81,8 @@ impl State {
} }
} }
/// Generate the list of `StrCheckCodePair` pairs for the current state. /// Generate the list of `StrRuleCodePair` pairs for the current
/// state.
fn parse(&self) -> Vec<PatternPrefixPair> { fn parse(&self) -> Vec<PatternPrefixPair> {
let mut codes: Vec<PatternPrefixPair> = vec![]; let mut codes: Vec<PatternPrefixPair> = vec![];
for code in &self.codes { for code in &self.codes {
@ -92,7 +93,7 @@ impl State {
prefix: code.clone(), prefix: code.clone(),
}); });
} }
} else if let Ok(code) = CheckCodePrefix::from_str(code) { } else if let Ok(code) = RuleCodePrefix::from_str(code) {
for filename in &self.filenames { for filename in &self.filenames {
codes.push(PatternPrefixPair { codes.push(PatternPrefixPair {
pattern: filename.clone(), pattern: filename.clone(),
@ -186,8 +187,8 @@ pub fn parse_files_to_codes_mapping(value: &str) -> Result<Vec<PatternPrefixPair
/// Collect a list of `PatternPrefixPair` structs as a `BTreeMap`. /// Collect a list of `PatternPrefixPair` structs as a `BTreeMap`.
pub fn collect_per_file_ignores( pub fn collect_per_file_ignores(
pairs: Vec<PatternPrefixPair>, pairs: Vec<PatternPrefixPair>,
) -> FxHashMap<String, Vec<CheckCodePrefix>> { ) -> FxHashMap<String, Vec<RuleCodePrefix>> {
let mut per_file_ignores: FxHashMap<String, Vec<CheckCodePrefix>> = FxHashMap::default(); let mut per_file_ignores: FxHashMap<String, Vec<RuleCodePrefix>> = FxHashMap::default();
for pair in pairs { for pair in pairs {
per_file_ignores per_file_ignores
.entry(pair.pattern) .entry(pair.pattern)
@ -200,7 +201,7 @@ pub fn collect_per_file_ignores(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use ruff::registry::CheckCodePrefix; use ruff::registry::RuleCodePrefix;
use ruff::settings::types::PatternPrefixPair; use ruff::settings::types::PatternPrefixPair;
use crate::parser::{parse_files_to_codes_mapping, parse_prefix_codes, parse_strings}; use crate::parser::{parse_files_to_codes_mapping, parse_prefix_codes, parse_strings};
@ -208,27 +209,27 @@ mod tests {
#[test] #[test]
fn it_parses_prefix_codes() { fn it_parses_prefix_codes() {
let actual = parse_prefix_codes(""); let actual = parse_prefix_codes("");
let expected: Vec<CheckCodePrefix> = vec![]; let expected: Vec<RuleCodePrefix> = vec![];
assert_eq!(actual, expected); assert_eq!(actual, expected);
let actual = parse_prefix_codes(" "); let actual = parse_prefix_codes(" ");
let expected: Vec<CheckCodePrefix> = vec![]; let expected: Vec<RuleCodePrefix> = vec![];
assert_eq!(actual, expected); assert_eq!(actual, expected);
let actual = parse_prefix_codes("F401"); let actual = parse_prefix_codes("F401");
let expected = vec![CheckCodePrefix::F401]; let expected = vec![RuleCodePrefix::F401];
assert_eq!(actual, expected); assert_eq!(actual, expected);
let actual = parse_prefix_codes("F401,"); let actual = parse_prefix_codes("F401,");
let expected = vec![CheckCodePrefix::F401]; let expected = vec![RuleCodePrefix::F401];
assert_eq!(actual, expected); assert_eq!(actual, expected);
let actual = parse_prefix_codes("F401,E501"); let actual = parse_prefix_codes("F401,E501");
let expected = vec![CheckCodePrefix::F401, CheckCodePrefix::E501]; let expected = vec![RuleCodePrefix::F401, RuleCodePrefix::E501];
assert_eq!(actual, expected); assert_eq!(actual, expected);
let actual = parse_prefix_codes("F401, E501"); let actual = parse_prefix_codes("F401, E501");
let expected = vec![CheckCodePrefix::F401, CheckCodePrefix::E501]; let expected = vec![RuleCodePrefix::F401, RuleCodePrefix::E501];
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -281,11 +282,11 @@ mod tests {
let expected: Vec<PatternPrefixPair> = vec![ let expected: Vec<PatternPrefixPair> = vec![
PatternPrefixPair { PatternPrefixPair {
pattern: "locust/test/*".to_string(), pattern: "locust/test/*".to_string(),
prefix: CheckCodePrefix::F841, prefix: RuleCodePrefix::F841,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "examples/*".to_string(), pattern: "examples/*".to_string(),
prefix: CheckCodePrefix::F841, prefix: RuleCodePrefix::F841,
}, },
]; ];
assert_eq!(actual, expected); assert_eq!(actual, expected);
@ -301,23 +302,23 @@ mod tests {
let expected: Vec<PatternPrefixPair> = vec![ let expected: Vec<PatternPrefixPair> = vec![
PatternPrefixPair { PatternPrefixPair {
pattern: "t/*".to_string(), pattern: "t/*".to_string(),
prefix: CheckCodePrefix::D, prefix: RuleCodePrefix::D,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "setup.py".to_string(), pattern: "setup.py".to_string(),
prefix: CheckCodePrefix::D, prefix: RuleCodePrefix::D,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "examples/*".to_string(), pattern: "examples/*".to_string(),
prefix: CheckCodePrefix::D, prefix: RuleCodePrefix::D,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "docs/*".to_string(), pattern: "docs/*".to_string(),
prefix: CheckCodePrefix::D, prefix: RuleCodePrefix::D,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "extra/*".to_string(), pattern: "extra/*".to_string(),
prefix: CheckCodePrefix::D, prefix: RuleCodePrefix::D,
}, },
]; ];
assert_eq!(actual, expected); assert_eq!(actual, expected);
@ -339,47 +340,47 @@ mod tests {
let expected: Vec<PatternPrefixPair> = vec![ let expected: Vec<PatternPrefixPair> = vec![
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/__init__.py".to_string(), pattern: "scrapy/__init__.py".to_string(),
prefix: CheckCodePrefix::E402, prefix: RuleCodePrefix::E402,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/core/downloader/handlers/http.py".to_string(), pattern: "scrapy/core/downloader/handlers/http.py".to_string(),
prefix: CheckCodePrefix::F401, prefix: RuleCodePrefix::F401,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/http/__init__.py".to_string(), pattern: "scrapy/http/__init__.py".to_string(),
prefix: CheckCodePrefix::F401, prefix: RuleCodePrefix::F401,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/linkextractors/__init__.py".to_string(), pattern: "scrapy/linkextractors/__init__.py".to_string(),
prefix: CheckCodePrefix::E402, prefix: RuleCodePrefix::E402,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/linkextractors/__init__.py".to_string(), pattern: "scrapy/linkextractors/__init__.py".to_string(),
prefix: CheckCodePrefix::F401, prefix: RuleCodePrefix::F401,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/selector/__init__.py".to_string(), pattern: "scrapy/selector/__init__.py".to_string(),
prefix: CheckCodePrefix::F401, prefix: RuleCodePrefix::F401,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/spiders/__init__.py".to_string(), pattern: "scrapy/spiders/__init__.py".to_string(),
prefix: CheckCodePrefix::E402, prefix: RuleCodePrefix::E402,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/spiders/__init__.py".to_string(), pattern: "scrapy/spiders/__init__.py".to_string(),
prefix: CheckCodePrefix::F401, prefix: RuleCodePrefix::F401,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/utils/url.py".to_string(), pattern: "scrapy/utils/url.py".to_string(),
prefix: CheckCodePrefix::F403, prefix: RuleCodePrefix::F403,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "scrapy/utils/url.py".to_string(), pattern: "scrapy/utils/url.py".to_string(),
prefix: CheckCodePrefix::F405, prefix: RuleCodePrefix::F405,
}, },
PatternPrefixPair { PatternPrefixPair {
pattern: "tests/test_loader.py".to_string(), pattern: "tests/test_loader.py".to_string(),
prefix: CheckCodePrefix::E741, prefix: RuleCodePrefix::E741,
}, },
]; ];
assert_eq!(actual, expected); assert_eq!(actual, expected);

View File

@ -3,7 +3,7 @@ use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use anyhow::anyhow; use anyhow::anyhow;
use ruff::registry::CheckCodePrefix; use ruff::registry::RuleCodePrefix;
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Plugin { pub enum Plugin {
@ -97,32 +97,32 @@ impl fmt::Debug for Plugin {
} }
impl Plugin { impl Plugin {
pub fn prefix(&self) -> CheckCodePrefix { pub fn prefix(&self) -> RuleCodePrefix {
match self { match self {
Plugin::Flake8Annotations => CheckCodePrefix::ANN, Plugin::Flake8Annotations => RuleCodePrefix::ANN,
Plugin::Flake8Bandit => CheckCodePrefix::S, Plugin::Flake8Bandit => RuleCodePrefix::S,
// TODO(charlie): Handle rename of `B` to `BLE`. // TODO(charlie): Handle rename of `B` to `BLE`.
Plugin::Flake8BlindExcept => CheckCodePrefix::BLE, Plugin::Flake8BlindExcept => RuleCodePrefix::BLE,
Plugin::Flake8Bugbear => CheckCodePrefix::B, Plugin::Flake8Bugbear => RuleCodePrefix::B,
Plugin::Flake8Builtins => CheckCodePrefix::A, Plugin::Flake8Builtins => RuleCodePrefix::A,
Plugin::Flake8Comprehensions => CheckCodePrefix::C4, Plugin::Flake8Comprehensions => RuleCodePrefix::C4,
Plugin::Flake8Datetimez => CheckCodePrefix::DTZ, Plugin::Flake8Datetimez => RuleCodePrefix::DTZ,
Plugin::Flake8Debugger => CheckCodePrefix::T1, Plugin::Flake8Debugger => RuleCodePrefix::T1,
Plugin::Flake8Docstrings => CheckCodePrefix::D, Plugin::Flake8Docstrings => RuleCodePrefix::D,
// TODO(charlie): Handle rename of `E` to `ERA`. // TODO(charlie): Handle rename of `E` to `ERA`.
Plugin::Flake8Eradicate => CheckCodePrefix::ERA, Plugin::Flake8Eradicate => RuleCodePrefix::ERA,
Plugin::Flake8ErrMsg => CheckCodePrefix::EM, Plugin::Flake8ErrMsg => RuleCodePrefix::EM,
Plugin::Flake8ImplicitStrConcat => CheckCodePrefix::ISC, Plugin::Flake8ImplicitStrConcat => RuleCodePrefix::ISC,
Plugin::Flake8Print => CheckCodePrefix::T2, Plugin::Flake8Print => RuleCodePrefix::T2,
Plugin::Flake8PytestStyle => CheckCodePrefix::PT, Plugin::Flake8PytestStyle => RuleCodePrefix::PT,
Plugin::Flake8Quotes => CheckCodePrefix::Q, Plugin::Flake8Quotes => RuleCodePrefix::Q,
Plugin::Flake8Return => CheckCodePrefix::RET, Plugin::Flake8Return => RuleCodePrefix::RET,
Plugin::Flake8Simplify => CheckCodePrefix::SIM, Plugin::Flake8Simplify => RuleCodePrefix::SIM,
Plugin::Flake8TidyImports => CheckCodePrefix::TID25, Plugin::Flake8TidyImports => RuleCodePrefix::TID25,
Plugin::McCabe => CheckCodePrefix::C9, Plugin::McCabe => RuleCodePrefix::C9,
Plugin::PandasVet => CheckCodePrefix::PD, Plugin::PandasVet => RuleCodePrefix::PD,
Plugin::PEP8Naming => CheckCodePrefix::N, Plugin::PEP8Naming => RuleCodePrefix::N,
Plugin::Pyupgrade => CheckCodePrefix::UP, Plugin::Pyupgrade => RuleCodePrefix::UP,
} }
} }
} }
@ -269,7 +269,7 @@ pub fn infer_plugins_from_options(flake8: &HashMap<String, Option<String>>) -> V
/// ///
/// For example, if the user ignores `ANN101`, we should infer that /// For example, if the user ignores `ANN101`, we should infer that
/// `flake8-annotations` is active. /// `flake8-annotations` is active.
pub fn infer_plugins_from_codes(codes: &BTreeSet<CheckCodePrefix>) -> Vec<Plugin> { pub fn infer_plugins_from_codes(codes: &BTreeSet<RuleCodePrefix>) -> Vec<Plugin> {
[ [
Plugin::Flake8Annotations, Plugin::Flake8Annotations,
Plugin::Flake8Bandit, Plugin::Flake8Bandit,
@ -307,9 +307,10 @@ pub fn infer_plugins_from_codes(codes: &BTreeSet<CheckCodePrefix>) -> Vec<Plugin
.collect() .collect()
} }
/// Resolve the set of enabled `CheckCodePrefix` values for the given plugins. /// Resolve the set of enabled `RuleCodePrefix` values for the given
pub fn resolve_select(plugins: &[Plugin]) -> BTreeSet<CheckCodePrefix> { /// plugins.
let mut select = BTreeSet::from([CheckCodePrefix::F, CheckCodePrefix::E, CheckCodePrefix::W]); pub fn resolve_select(plugins: &[Plugin]) -> BTreeSet<RuleCodePrefix> {
let mut select = BTreeSet::from([RuleCodePrefix::F, RuleCodePrefix::E, RuleCodePrefix::W]);
select.extend(plugins.iter().map(Plugin::prefix)); select.extend(plugins.iter().map(Plugin::prefix));
select select
} }

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
use anyhow::Result; use anyhow::Result;
use clap::Args; use clap::Args;
use itertools::Itertools; use itertools::Itertools;
use ruff::registry::{CheckCategory, CheckCode}; use ruff::registry::{CheckCategory, RuleCode};
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
use crate::utils::replace_readme_section; use crate::utils::replace_readme_section;
@ -55,15 +55,15 @@ pub fn main(cli: &Cli) -> Result<()> {
table_out.push_str("| ---- | ---- | ------- | --- |"); table_out.push_str("| ---- | ---- | ------- | --- |");
table_out.push('\n'); table_out.push('\n');
for check_code in CheckCode::iter() { for rule_code in RuleCode::iter() {
if check_code.category() == check_category { if rule_code.category() == check_category {
let check_kind = check_code.kind(); let kind = rule_code.kind();
let fix_token = if check_kind.fixable() { "🛠" } else { "" }; let fix_token = if kind.fixable() { "🛠" } else { "" };
table_out.push_str(&format!( table_out.push_str(&format!(
"| {} | {} | {} | {} |", "| {} | {} | {} | {} |",
check_kind.code().as_ref(), kind.code().as_ref(),
check_kind.as_ref(), kind.as_ref(),
check_kind.summary().replace('|', r"\|"), kind.summary().replace('|', r"\|"),
fix_token fix_token
)); ));
table_out.push('\n'); table_out.push('\n');

View File

@ -14,8 +14,8 @@
use syn::{parse_macro_input, DeriveInput}; use syn::{parse_macro_input, DeriveInput};
mod check_code_prefix;
mod config; mod config;
mod rule_code_prefix;
#[proc_macro_derive(ConfigurationOptions, attributes(option, doc, option_group))] #[proc_macro_derive(ConfigurationOptions, attributes(option, doc, option_group))]
pub fn derive_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn derive_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
@ -26,11 +26,11 @@ pub fn derive_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream
.into() .into()
} }
#[proc_macro_derive(CheckCodePrefix)] #[proc_macro_derive(RuleCodePrefix)]
pub fn derive_check_code_prefix(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn derive_rule_code_prefix(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput); let input = parse_macro_input!(input as DeriveInput);
check_code_prefix::derive_impl(input) rule_code_prefix::derive_impl(input)
.unwrap_or_else(syn::Error::into_compile_error) .unwrap_or_else(syn::Error::into_compile_error)
.into() .into()
} }

View File

@ -9,7 +9,8 @@ use syn::{DataEnum, DeriveInput, Ident, Variant};
const ALL: &str = "ALL"; const ALL: &str = "ALL";
/// A hash map from deprecated `CheckCodePrefix` to latest `CheckCodePrefix`. /// A hash map from deprecated `RuleCodePrefix` to latest
/// `RuleCodePrefix`.
pub static PREFIX_REDIRECTS: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| { pub static PREFIX_REDIRECTS: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
HashMap::from_iter([ HashMap::from_iter([
// TODO(charlie): Remove by 2023-01-01. // TODO(charlie): Remove by 2023-01-01.
@ -90,7 +91,7 @@ pub fn derive_impl(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream>
let syn::Data::Enum(DataEnum { variants, .. }) = data else { let syn::Data::Enum(DataEnum { variants, .. }) = data else {
return Err(syn::Error::new( return Err(syn::Error::new(
ident.span(), ident.span(),
"Can only derive `CheckCodePrefix` from enums.", "Can only derive `RuleCodePrefix` from enums.",
)); ));
}; };
@ -117,7 +118,7 @@ fn expand(
prefix_ident: &Ident, prefix_ident: &Ident,
variants: &Punctuated<Variant, Comma>, variants: &Punctuated<Variant, Comma>,
) -> proc_macro2::TokenStream { ) -> proc_macro2::TokenStream {
// Build up a map from prefix to matching CheckCodes. // Build up a map from prefix to matching RuleCodes.
let mut prefix_to_codes: BTreeMap<Ident, BTreeSet<String>> = BTreeMap::default(); let mut prefix_to_codes: BTreeMap<Ident, BTreeSet<String>> = BTreeMap::default();
for variant in variants { for variant in variants {
let span = variant.ident.span(); let span = variant.ident.span();
@ -141,12 +142,12 @@ fn expand(
} }
// Add any prefix aliases (e.g., "U" to "UP"). // Add any prefix aliases (e.g., "U" to "UP").
for (alias, check_code) in PREFIX_REDIRECTS.iter() { for (alias, rule_code) in PREFIX_REDIRECTS.iter() {
prefix_to_codes.insert( prefix_to_codes.insert(
Ident::new(alias, Span::call_site()), Ident::new(alias, Span::call_site()),
prefix_to_codes prefix_to_codes
.get(&Ident::new(check_code, Span::call_site())) .get(&Ident::new(rule_code, Span::call_site()))
.unwrap_or_else(|| panic!("Unknown CheckCode: {alias:?}")) .unwrap_or_else(|| panic!("Unknown RuleCode: {alias:?}"))
.clone(), .clone(),
); );
} }
@ -159,8 +160,8 @@ fn expand(
let prefix_impl = generate_impls(ident, prefix_ident, &prefix_to_codes); let prefix_impl = generate_impls(ident, prefix_ident, &prefix_to_codes);
let prefix_redirects = PREFIX_REDIRECTS.iter().map(|(alias, check_code)| { let prefix_redirects = PREFIX_REDIRECTS.iter().map(|(alias, rule_code)| {
let code = Ident::new(check_code, Span::call_site()); let code = Ident::new(rule_code, Span::call_site());
quote! { quote! {
(#alias, #prefix_ident::#code) (#alias, #prefix_ident::#code)
} }
@ -186,7 +187,7 @@ fn expand(
#prefix_impl #prefix_impl
/// A hash map from deprecated `CheckCodePrefix` to latest `CheckCodePrefix`. /// A hash map from deprecated `RuleCodePrefix` to latest `RuleCodePrefix`.
pub static PREFIX_REDIRECTS: ::once_cell::sync::Lazy<::rustc_hash::FxHashMap<&'static str, #prefix_ident>> = ::once_cell::sync::Lazy::new(|| { pub static PREFIX_REDIRECTS: ::once_cell::sync::Lazy<::rustc_hash::FxHashMap<&'static str, #prefix_ident>> = ::once_cell::sync::Lazy::new(|| {
::rustc_hash::FxHashMap::from_iter([ ::rustc_hash::FxHashMap::from_iter([
#(#prefix_redirects),* #(#prefix_redirects),*

View File

@ -43,9 +43,9 @@ def main(*, name: str, code: str, plugin: str) -> None:
with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/mod.rs"), "w") as fp: with open(os.path.join(ROOT_DIR, f"src/{dir_name(plugin)}/mod.rs"), "w") as fp:
for line in content.splitlines(): for line in content.splitlines():
if line.strip() == "fn checks(check_code: CheckCode, path: &Path) -> Result<()> {": if line.strip() == "fn diagnostics(check_code: RuleCode, path: &Path) -> Result<()> {":
indent = line.split("fn checks(check_code: CheckCode, path: &Path) -> Result<()> {")[0] indent = line.split("fn diagnostics(check_code: RuleCode, path: &Path) -> Result<()> {")[0]
fp.write(f'{indent}#[test_case(CheckCode::{code}, Path::new("{code}.py"); "{code}")]') fp.write(f'{indent}#[test_case(RuleCode::{code}, Path::new("{code}.py"); "{code}")]')
fp.write("\n") fp.write("\n")
fp.write(line) fp.write(line)
@ -73,39 +73,39 @@ pub fn {snake_case(name)}(checker: &mut Checker) {{}}
if line.strip() == f"// {plugin}": if line.strip() == f"// {plugin}":
if index == 0: if index == 0:
# `CheckCode` definition # `RuleCode` definition
indent = line.split(f"// {plugin}")[0] indent = line.split(f"// {plugin}")[0]
fp.write(f"{indent}{code},") fp.write(f"{indent}{code},")
fp.write("\n") fp.write("\n")
elif index == 1: elif index == 1:
# `CheckKind` definition # `DiagnosticKind` definition
indent = line.split(f"// {plugin}")[0] indent = line.split(f"// {plugin}")[0]
fp.write(f"{indent}{name},") fp.write(f"{indent}{name},")
fp.write("\n") fp.write("\n")
elif index == 2: elif index == 2:
# `CheckCode#kind()` # `RuleCode#kind()`
indent = line.split(f"// {plugin}")[0] indent = line.split(f"// {plugin}")[0]
fp.write(f"{indent}CheckCode::{code} => CheckKind::{name},") fp.write(f"{indent}RuleCode::{code} => DiagnosticKind::{name},")
fp.write("\n") fp.write("\n")
elif index == 3: elif index == 3:
# `CheckCode#category()` # `RuleCode#category()`
indent = line.split(f"// {plugin}")[0] indent = line.split(f"// {plugin}")[0]
fp.write(f"{indent}CheckCode::{code} => CheckCategory::{pascal_case(plugin)},") fp.write(f"{indent}RuleCode::{code} => CheckCategory::{pascal_case(plugin)},")
fp.write("\n") fp.write("\n")
elif index == 4: elif index == 4:
# `CheckKind#code()` # `DiagnosticKind#code()`
indent = line.split(f"// {plugin}")[0] indent = line.split(f"// {plugin}")[0]
fp.write(f"{indent}CheckKind::{name} => &CheckCode::{code},") fp.write(f"{indent}DiagnosticKind::{name} => &RuleCode::{code},")
fp.write("\n") fp.write("\n")
elif index == 5: elif index == 5:
# `CheckCode#body` # `RuleCode#body`
indent = line.split(f"// {plugin}")[0] indent = line.split(f"// {plugin}")[0]
fp.write(f'{indent}CheckKind::{name} => todo!("Write message body for {code}"),') fp.write(f'{indent}DiagnosticKind::{name} => todo!("Write message body for {code}"),')
fp.write("\n") fp.write("\n")
index += 1 index += 1

View File

@ -45,19 +45,19 @@ mod tests {
use anyhow::Result; use anyhow::Result;
use test_case::test_case; use test_case::test_case;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::linter::test_path; use crate::linter::test_path;
use crate::settings; use crate::settings;
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(check_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics =test_path(
Path::new("./resources/test/fixtures/%s") Path::new("./resources/test/fixtures/%s")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(check_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }
@ -90,8 +90,8 @@ mod tests {
fp.write(f'{indent}CheckCategory::{pascal_case(plugin)} => "{plugin}",') fp.write(f'{indent}CheckCategory::{pascal_case(plugin)} => "{plugin}",')
fp.write("\n") fp.write("\n")
elif line.strip() == "CheckCategory::Ruff => vec![CheckCodePrefix::RUF],": elif line.strip() == "CheckCategory::Ruff => vec![RuleCodePrefix::RUF],":
indent = line.split("CheckCategory::Ruff => vec![CheckCodePrefix::RUF],")[0] indent = line.split("CheckCategory::Ruff => vec![RuleCodePrefix::RUF],")[0]
fp.write( fp.write(
f"{indent}CheckCategory::{pascal_case(plugin)} => vec![\n" f"{indent}CheckCategory::{pascal_case(plugin)} => vec![\n"
f'{indent} todo!("Fill-in prefix after generating codes")\n' f'{indent} todo!("Fill-in prefix after generating codes")\n'

View File

@ -7,7 +7,7 @@ use rustpython_parser::ast::Location;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_locator::SourceCodeLocator; use crate::source_code_locator::SourceCodeLocator;
#[derive(Debug, Copy, Clone, Hash)] #[derive(Debug, Copy, Clone, Hash)]
@ -30,7 +30,7 @@ impl From<bool> for Mode {
/// Auto-fix errors in a file, and write the fixed source code to disk. /// Auto-fix errors in a file, and write the fixed source code to disk.
pub fn fix_file<'a>( pub fn fix_file<'a>(
checks: &'a [Check], checks: &'a [Diagnostic],
locator: &'a SourceCodeLocator<'a>, locator: &'a SourceCodeLocator<'a>,
) -> Option<(Cow<'a, str>, usize)> { ) -> Option<(Cow<'a, str>, usize)> {
if checks.iter().all(|check| check.fix.is_none()) { if checks.iter().all(|check| check.fix.is_none()) {

File diff suppressed because it is too large Load Diff

View File

@ -8,7 +8,7 @@ use crate::ast::visitor::Visitor;
use crate::directives::IsortDirectives; use crate::directives::IsortDirectives;
use crate::isort; use crate::isort;
use crate::isort::track::ImportTracker; use crate::isort::track::ImportTracker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::settings::{flags, Settings}; use crate::settings::{flags, Settings};
use crate::source_code_locator::SourceCodeLocator; use crate::source_code_locator::SourceCodeLocator;
use crate::source_code_style::SourceCodeStyleDetector; use crate::source_code_style::SourceCodeStyleDetector;
@ -20,18 +20,18 @@ fn check_import_blocks(
stylist: &SourceCodeStyleDetector, stylist: &SourceCodeStyleDetector,
autofix: flags::Autofix, autofix: flags::Autofix,
package: Option<&Path>, package: Option<&Path>,
) -> Vec<Check> { ) -> Vec<Diagnostic> {
let mut checks = vec![]; let mut diagnostics = vec![];
for block in tracker.into_iter() { for block in tracker.into_iter() {
if !block.imports.is_empty() { if !block.imports.is_empty() {
if let Some(check) = if let Some(diagnostic) =
isort::plugins::check_imports(&block, locator, settings, stylist, autofix, package) isort::plugins::check_imports(&block, locator, settings, stylist, autofix, package)
{ {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
checks diagnostics
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
@ -44,7 +44,7 @@ pub fn check_imports(
autofix: flags::Autofix, autofix: flags::Autofix,
path: &Path, path: &Path,
package: Option<&Path>, package: Option<&Path>,
) -> Vec<Check> { ) -> Vec<Diagnostic> {
let mut tracker = ImportTracker::new(locator, directives, path); let mut tracker = ImportTracker::new(locator, directives, path);
for stmt in python_ast { for stmt in python_ast {
tracker.visit_stmt(stmt); tracker.visit_stmt(stmt);

View File

@ -3,7 +3,7 @@
use crate::pycodestyle::checks::{line_too_long, no_newline_at_end_of_file}; use crate::pycodestyle::checks::{line_too_long, no_newline_at_end_of_file};
use crate::pygrep_hooks::plugins::{blanket_noqa, blanket_type_ignore}; use crate::pygrep_hooks::plugins::{blanket_noqa, blanket_type_ignore};
use crate::pyupgrade::checks::unnecessary_coding_comment; use crate::pyupgrade::checks::unnecessary_coding_comment;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::settings::{flags, Settings}; use crate::settings::{flags, Settings};
pub fn check_lines( pub fn check_lines(
@ -11,14 +11,14 @@ pub fn check_lines(
commented_lines: &[usize], commented_lines: &[usize],
settings: &Settings, settings: &Settings,
autofix: flags::Autofix, autofix: flags::Autofix,
) -> Vec<Check> { ) -> Vec<Diagnostic> {
let mut checks: Vec<Check> = vec![]; let mut checks: Vec<Diagnostic> = vec![];
let enforce_unnecessary_coding_comment = settings.enabled.contains(&CheckCode::UP009); let enforce_unnecessary_coding_comment = settings.enabled.contains(&RuleCode::UP009);
let enforce_line_too_long = settings.enabled.contains(&CheckCode::E501); let enforce_line_too_long = settings.enabled.contains(&RuleCode::E501);
let enforce_no_newline_at_end_of_file = settings.enabled.contains(&CheckCode::W292); let enforce_no_newline_at_end_of_file = settings.enabled.contains(&RuleCode::W292);
let enforce_blanket_type_ignore = settings.enabled.contains(&CheckCode::PGH003); let enforce_blanket_type_ignore = settings.enabled.contains(&RuleCode::PGH003);
let enforce_blanket_noqa = settings.enabled.contains(&CheckCode::PGH004); let enforce_blanket_noqa = settings.enabled.contains(&RuleCode::PGH004);
let mut commented_lines_iter = commented_lines.iter().peekable(); let mut commented_lines_iter = commented_lines.iter().peekable();
for (index, line) in contents.lines().enumerate() { for (index, line) in contents.lines().enumerate() {
@ -32,7 +32,7 @@ pub fn check_lines(
index, index,
line, line,
matches!(autofix, flags::Autofix::Enabled) matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&CheckCode::UP009), && settings.fixable.contains(&RuleCode::UP009),
) { ) {
checks.push(check); checks.push(check);
} }
@ -67,7 +67,7 @@ pub fn check_lines(
if let Some(check) = no_newline_at_end_of_file( if let Some(check) = no_newline_at_end_of_file(
contents, contents,
matches!(autofix, flags::Autofix::Enabled) matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&CheckCode::W292), && settings.fixable.contains(&RuleCode::W292),
) { ) {
checks.push(check); checks.push(check);
} }
@ -80,7 +80,7 @@ pub fn check_lines(
mod tests { mod tests {
use super::check_lines; use super::check_lines;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings::{flags, Settings}; use crate::settings::{flags, Settings};
#[test] #[test]
@ -92,7 +92,7 @@ mod tests {
&[], &[],
&Settings { &Settings {
line_length, line_length,
..Settings::for_rule(CheckCode::E501) ..Settings::for_rule(RuleCode::E501)
}, },
flags::Autofix::Enabled, flags::Autofix::Enabled,
) )

View File

@ -8,12 +8,12 @@ use rustpython_parser::ast::Location;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::noqa::{is_file_exempt, Directive}; use crate::noqa::{is_file_exempt, Directive};
use crate::registry::{Check, CheckCode, CheckKind, UnusedCodes, CODE_REDIRECTS}; use crate::registry::{Diagnostic, DiagnosticKind, RuleCode, UnusedCodes, CODE_REDIRECTS};
use crate::settings::{flags, Settings}; use crate::settings::{flags, Settings};
use crate::{noqa, violations}; use crate::{noqa, violations};
pub fn check_noqa( pub fn check_noqa(
checks: &mut Vec<Check>, checks: &mut Vec<Diagnostic>,
contents: &str, contents: &str,
commented_lines: &[usize], commented_lines: &[usize],
noqa_line_for: &IntMap<usize, usize>, noqa_line_for: &IntMap<usize, usize>,
@ -23,7 +23,7 @@ pub fn check_noqa(
let mut noqa_directives: IntMap<usize, (Directive, Vec<&str>)> = IntMap::default(); let mut noqa_directives: IntMap<usize, (Directive, Vec<&str>)> = IntMap::default();
let mut ignored = vec![]; let mut ignored = vec![];
let enforce_noqa = settings.enabled.contains(&CheckCode::RUF100); let enforce_noqa = settings.enabled.contains(&RuleCode::RUF100);
let lines: Vec<&str> = contents.lines().collect(); let lines: Vec<&str> = contents.lines().collect();
for lineno in commented_lines { for lineno in commented_lines {
@ -42,7 +42,7 @@ pub fn check_noqa(
// Remove any ignored checks. // Remove any ignored checks.
for (index, check) in checks.iter().enumerate() { for (index, check) in checks.iter().enumerate() {
if matches!(check.kind, CheckKind::BlanketNOQA(..)) { if matches!(check.kind, DiagnosticKind::BlanketNOQA(..)) {
continue; continue;
} }
@ -100,7 +100,7 @@ pub fn check_noqa(
match directive { match directive {
Directive::All(spaces, start, end) => { Directive::All(spaces, start, end) => {
if matches.is_empty() { if matches.is_empty() {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnusedNOQA(None), violations::UnusedNOQA(None),
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)), Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
); );
@ -123,7 +123,7 @@ pub fn check_noqa(
let mut self_ignore = false; let mut self_ignore = false;
for code in codes { for code in codes {
let code = CODE_REDIRECTS.get(code).map_or(code, AsRef::as_ref); let code = CODE_REDIRECTS.get(code).map_or(code, AsRef::as_ref);
if code == CheckCode::RUF100.as_ref() { if code == RuleCode::RUF100.as_ref() {
self_ignore = true; self_ignore = true;
break; break;
} }
@ -131,8 +131,8 @@ pub fn check_noqa(
if matches.contains(&code) || settings.external.contains(code) { if matches.contains(&code) || settings.external.contains(code) {
valid_codes.push(code); valid_codes.push(code);
} else { } else {
if let Ok(check_code) = CheckCode::from_str(code) { if let Ok(rule_code) = RuleCode::from_str(code) {
if settings.enabled.contains(&check_code) { if settings.enabled.contains(&rule_code) {
unmatched_codes.push(code); unmatched_codes.push(code);
} else { } else {
disabled_codes.push(code); disabled_codes.push(code);
@ -151,7 +151,7 @@ pub fn check_noqa(
&& unknown_codes.is_empty() && unknown_codes.is_empty()
&& unmatched_codes.is_empty()) && unmatched_codes.is_empty())
{ {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnusedNOQA(Some(UnusedCodes { violations::UnusedNOQA(Some(UnusedCodes {
disabled: disabled_codes disabled: disabled_codes
.iter() .iter()

View File

@ -3,7 +3,7 @@
use rustpython_parser::lexer::{LexResult, Tok}; use rustpython_parser::lexer::{LexResult, Tok};
use crate::lex::docstring_detection::StateMachine; use crate::lex::docstring_detection::StateMachine;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::ruff::checks::Context; use crate::ruff::checks::Context;
use crate::settings::flags; use crate::settings::flags;
use crate::source_code_locator::SourceCodeLocator; use crate::source_code_locator::SourceCodeLocator;
@ -14,20 +14,20 @@ pub fn check_tokens(
tokens: &[LexResult], tokens: &[LexResult],
settings: &Settings, settings: &Settings,
autofix: flags::Autofix, autofix: flags::Autofix,
) -> Vec<Check> { ) -> Vec<Diagnostic> {
let mut checks: Vec<Check> = vec![]; let mut checks: Vec<Diagnostic> = vec![];
let enforce_ambiguous_unicode_character = settings.enabled.contains(&CheckCode::RUF001) let enforce_ambiguous_unicode_character = settings.enabled.contains(&RuleCode::RUF001)
|| settings.enabled.contains(&CheckCode::RUF002) || settings.enabled.contains(&RuleCode::RUF002)
|| settings.enabled.contains(&CheckCode::RUF003); || settings.enabled.contains(&RuleCode::RUF003);
let enforce_quotes = settings.enabled.contains(&CheckCode::Q000) let enforce_quotes = settings.enabled.contains(&RuleCode::Q000)
|| settings.enabled.contains(&CheckCode::Q001) || settings.enabled.contains(&RuleCode::Q001)
|| settings.enabled.contains(&CheckCode::Q002) || settings.enabled.contains(&RuleCode::Q002)
|| settings.enabled.contains(&CheckCode::Q003); || settings.enabled.contains(&RuleCode::Q003);
let enforce_commented_out_code = settings.enabled.contains(&CheckCode::ERA001); let enforce_commented_out_code = settings.enabled.contains(&RuleCode::ERA001);
let enforce_invalid_escape_sequence = settings.enabled.contains(&CheckCode::W605); let enforce_invalid_escape_sequence = settings.enabled.contains(&RuleCode::W605);
let enforce_implicit_string_concatenation = settings.enabled.contains(&CheckCode::ISC001) let enforce_implicit_string_concatenation = settings.enabled.contains(&RuleCode::ISC001)
|| settings.enabled.contains(&CheckCode::ISC002); || settings.enabled.contains(&RuleCode::ISC002);
let mut state_machine = StateMachine::default(); let mut state_machine = StateMachine::default();
for &(start, ref tok, end) in tokens.iter().flatten() { for &(start, ref tok, end) in tokens.iter().flatten() {
@ -95,7 +95,7 @@ pub fn check_tokens(
start, start,
end, end,
matches!(autofix, flags::Autofix::Enabled) matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&CheckCode::W605), && settings.fixable.contains(&RuleCode::W605),
)); ));
} }
} }

View File

@ -6,7 +6,7 @@ use rustc_hash::FxHashMap;
use crate::fs; use crate::fs;
use crate::logging::LogLevel; use crate::logging::LogLevel;
use crate::registry::{CheckCode, CheckCodePrefix}; use crate::registry::{RuleCode, RuleCodePrefix};
use crate::settings::types::{ use crate::settings::types::{
FilePattern, PatternPrefixPair, PerFileIgnore, PythonVersion, SerializationFormat, FilePattern, PatternPrefixPair, PerFileIgnore, PythonVersion, SerializationFormat,
}; };
@ -59,21 +59,21 @@ pub struct Cli {
/// Ignore all configuration files. /// Ignore all configuration files.
#[arg(long, conflicts_with = "config")] #[arg(long, conflicts_with = "config")]
pub isolated: bool, pub isolated: bool,
/// Comma-separated list of error codes to enable (or ALL, to enable all /// Comma-separated list of rule codes to enable (or ALL, to enable all
/// checks). /// rules).
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub select: Option<Vec<CheckCodePrefix>>, pub select: Option<Vec<RuleCodePrefix>>,
/// Like --select, but adds additional error codes on top of the selected /// Like --select, but adds additional error codes on top of the selected
/// ones. /// ones.
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub extend_select: Option<Vec<CheckCodePrefix>>, pub extend_select: Option<Vec<RuleCodePrefix>>,
/// Comma-separated list of error codes to disable. /// Comma-separated list of error codes to disable.
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub ignore: Option<Vec<CheckCodePrefix>>, pub ignore: Option<Vec<RuleCodePrefix>>,
/// Like --ignore, but adds additional error codes on top of the ignored /// Like --ignore, but adds additional error codes on top of the ignored
/// ones. /// ones.
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub extend_ignore: Option<Vec<CheckCodePrefix>>, pub extend_ignore: Option<Vec<RuleCodePrefix>>,
/// List of paths, used to exclude files and/or directories from checks. /// List of paths, used to exclude files and/or directories from checks.
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub exclude: Option<Vec<FilePattern>>, pub exclude: Option<Vec<FilePattern>>,
@ -84,11 +84,11 @@ pub struct Cli {
/// List of error codes to treat as eligible for autofix. Only applicable /// List of error codes to treat as eligible for autofix. Only applicable
/// when autofix itself is enabled (e.g., via `--fix`). /// when autofix itself is enabled (e.g., via `--fix`).
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub fixable: Option<Vec<CheckCodePrefix>>, pub fixable: Option<Vec<RuleCodePrefix>>,
/// List of error codes to treat as ineligible for autofix. Only applicable /// List of error codes to treat as ineligible for autofix. Only applicable
/// when autofix itself is enabled (e.g., via `--fix`). /// when autofix itself is enabled (e.g., via `--fix`).
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub unfixable: Option<Vec<CheckCodePrefix>>, pub unfixable: Option<Vec<RuleCodePrefix>>,
/// List of mappings from file pattern to code to exclude /// List of mappings from file pattern to code to exclude
#[arg(long, value_delimiter = ',')] #[arg(long, value_delimiter = ',')]
pub per_file_ignores: Option<Vec<PatternPrefixPair>>, pub per_file_ignores: Option<Vec<PatternPrefixPair>>,
@ -179,7 +179,7 @@ pub struct Cli {
conflicts_with = "stdin_filename", conflicts_with = "stdin_filename",
conflicts_with = "watch", conflicts_with = "watch",
)] )]
pub explain: Option<CheckCode>, pub explain: Option<RuleCode>,
/// Generate shell completion /// Generate shell completion
#[arg( #[arg(
long, long,
@ -302,7 +302,7 @@ pub struct Arguments {
pub config: Option<PathBuf>, pub config: Option<PathBuf>,
pub diff: bool, pub diff: bool,
pub exit_zero: bool, pub exit_zero: bool,
pub explain: Option<CheckCode>, pub explain: Option<RuleCode>,
pub files: Vec<PathBuf>, pub files: Vec<PathBuf>,
pub generate_shell_completion: Option<clap_complete_command::Shell>, pub generate_shell_completion: Option<clap_complete_command::Shell>,
pub isolated: bool, pub isolated: bool,
@ -323,18 +323,18 @@ pub struct Overrides {
pub dummy_variable_rgx: Option<Regex>, pub dummy_variable_rgx: Option<Regex>,
pub exclude: Option<Vec<FilePattern>>, pub exclude: Option<Vec<FilePattern>>,
pub extend_exclude: Option<Vec<FilePattern>>, pub extend_exclude: Option<Vec<FilePattern>>,
pub extend_ignore: Option<Vec<CheckCodePrefix>>, pub extend_ignore: Option<Vec<RuleCodePrefix>>,
pub extend_select: Option<Vec<CheckCodePrefix>>, pub extend_select: Option<Vec<RuleCodePrefix>>,
pub fixable: Option<Vec<CheckCodePrefix>>, pub fixable: Option<Vec<RuleCodePrefix>>,
pub ignore: Option<Vec<CheckCodePrefix>>, pub ignore: Option<Vec<RuleCodePrefix>>,
pub line_length: Option<usize>, pub line_length: Option<usize>,
pub max_complexity: Option<usize>, pub max_complexity: Option<usize>,
pub per_file_ignores: Option<Vec<PatternPrefixPair>>, pub per_file_ignores: Option<Vec<PatternPrefixPair>>,
pub respect_gitignore: Option<bool>, pub respect_gitignore: Option<bool>,
pub select: Option<Vec<CheckCodePrefix>>, pub select: Option<Vec<RuleCodePrefix>>,
pub show_source: Option<bool>, pub show_source: Option<bool>,
pub target_version: Option<PythonVersion>, pub target_version: Option<PythonVersion>,
pub unfixable: Option<Vec<CheckCodePrefix>>, pub unfixable: Option<Vec<RuleCodePrefix>>,
// TODO(charlie): Captured in pyproject.toml as a default, but not part of `Settings`. // TODO(charlie): Captured in pyproject.toml as a default, but not part of `Settings`.
pub cache_dir: Option<PathBuf>, pub cache_dir: Option<PathBuf>,
pub fix: Option<bool>, pub fix: Option<bool>,
@ -359,7 +359,7 @@ pub fn extract_log_level(cli: &Arguments) -> LogLevel {
/// Convert a list of `PatternPrefixPair` structs to `PerFileIgnore`. /// Convert a list of `PatternPrefixPair` structs to `PerFileIgnore`.
pub fn collect_per_file_ignores(pairs: Vec<PatternPrefixPair>) -> Vec<PerFileIgnore> { pub fn collect_per_file_ignores(pairs: Vec<PatternPrefixPair>) -> Vec<PerFileIgnore> {
let mut per_file_ignores: FxHashMap<String, Vec<CheckCodePrefix>> = FxHashMap::default(); let mut per_file_ignores: FxHashMap<String, Vec<RuleCodePrefix>> = FxHashMap::default();
for pair in pairs { for pair in pairs {
per_file_ignores per_file_ignores
.entry(pair.pattern) .entry(pair.pattern)

View File

@ -22,7 +22,7 @@ use crate::iterators::par_iter;
use crate::linter::{add_noqa_to_path, lint_path, lint_stdin, Diagnostics}; use crate::linter::{add_noqa_to_path, lint_path, lint_stdin, Diagnostics};
use crate::logging::LogLevel; use crate::logging::LogLevel;
use crate::message::Message; use crate::message::Message;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::resolver::{FileDiscovery, PyprojectDiscovery}; use crate::resolver::{FileDiscovery, PyprojectDiscovery};
use crate::settings::flags; use crate::settings::flags;
use crate::settings::types::SerializationFormat; use crate::settings::types::SerializationFormat;
@ -117,7 +117,7 @@ pub fn run(
.unwrap_or_else(|(path, message)| { .unwrap_or_else(|(path, message)| {
if let Some(path) = &path { if let Some(path) = &path {
let settings = resolver.resolve(path, pyproject_strategy); let settings = resolver.resolve(path, pyproject_strategy);
if settings.enabled.contains(&CheckCode::E902) { if settings.enabled.contains(&RuleCode::E902) {
Diagnostics::new(vec![Message { Diagnostics::new(vec![Message {
kind: violations::IOError(message).into(), kind: violations::IOError(message).into(),
location: Location::default(), location: Location::default(),
@ -302,8 +302,8 @@ struct Explanation<'a> {
summary: &'a str, summary: &'a str,
} }
/// Explain a `CheckCode` to the user. /// Explain a `RuleCode` to the user.
pub fn explain(code: &CheckCode, format: &SerializationFormat) -> Result<()> { pub fn explain(code: &RuleCode, format: &SerializationFormat) -> Result<()> {
match format { match format {
SerializationFormat::Text | SerializationFormat::Grouped => { SerializationFormat::Text | SerializationFormat::Grouped => {
println!( println!(

View File

@ -20,7 +20,7 @@ impl Flags {
if settings if settings
.enabled .enabled
.iter() .iter()
.any(|check_code| matches!(check_code.lint_source(), LintSource::Imports)) .any(|rule_code| matches!(rule_code.lint_source(), LintSource::Imports))
{ {
Flags::NOQA | Flags::ISORT Flags::NOQA | Flags::ISORT
} else { } else {

View File

@ -3,9 +3,9 @@ use rustpython_ast::Location;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::eradicate::detection::comment_contains_code; use crate::eradicate::detection::comment_contains_code;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings::flags; use crate::settings::flags;
use crate::{violations, Check, Settings, SourceCodeLocator}; use crate::{violations, Diagnostic, Settings, SourceCodeLocator};
fn is_standalone_comment(line: &str) -> bool { fn is_standalone_comment(line: &str) -> bool {
for char in line.chars() { for char in line.chars() {
@ -25,16 +25,16 @@ pub fn commented_out_code(
end: Location, end: Location,
settings: &Settings, settings: &Settings,
autofix: flags::Autofix, autofix: flags::Autofix,
) -> Option<Check> { ) -> Option<Diagnostic> {
let location = Location::new(start.row(), 0); let location = Location::new(start.row(), 0);
let end_location = Location::new(end.row() + 1, 0); let end_location = Location::new(end.row() + 1, 0);
let line = locator.slice_source_code_range(&Range::new(location, end_location)); let line = locator.slice_source_code_range(&Range::new(location, end_location));
// Verify that the comment is on its own line, and that it contains 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[..]) { if is_standalone_comment(&line) && comment_contains_code(&line, &settings.task_tags[..]) {
let mut check = Check::new(violations::CommentedOutCode, Range::new(start, end)); let mut check = Diagnostic::new(violations::CommentedOutCode, Range::new(start, end));
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&CheckCode::ERA001) && settings.fixable.contains(&RuleCode::ERA001)
{ {
check.amend(Fix::deletion(location, end_location)); check.amend(Fix::deletion(location, end_location));
} }

View File

@ -10,19 +10,19 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::ERA001, Path::new("ERA001.py"); "ERA001")] #[test_case(RuleCode::ERA001, Path::new("ERA001.py"); "ERA001")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/eradicate") Path::new("./resources/test/fixtures/eradicate")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -9,28 +9,28 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::YTT101, Path::new("YTT101.py"); "YTT101")] #[test_case(RuleCode::YTT101, Path::new("YTT101.py"); "YTT101")]
#[test_case(CheckCode::YTT102, Path::new("YTT102.py"); "YTT102")] #[test_case(RuleCode::YTT102, Path::new("YTT102.py"); "YTT102")]
#[test_case(CheckCode::YTT103, Path::new("YTT103.py"); "YTT103")] #[test_case(RuleCode::YTT103, Path::new("YTT103.py"); "YTT103")]
#[test_case(CheckCode::YTT201, Path::new("YTT201.py"); "YTT201")] #[test_case(RuleCode::YTT201, Path::new("YTT201.py"); "YTT201")]
#[test_case(CheckCode::YTT202, Path::new("YTT202.py"); "YTT202")] #[test_case(RuleCode::YTT202, Path::new("YTT202.py"); "YTT202")]
#[test_case(CheckCode::YTT203, Path::new("YTT203.py"); "YTT203")] #[test_case(RuleCode::YTT203, Path::new("YTT203.py"); "YTT203")]
#[test_case(CheckCode::YTT204, Path::new("YTT204.py"); "YTT204")] #[test_case(RuleCode::YTT204, Path::new("YTT204.py"); "YTT204")]
#[test_case(CheckCode::YTT301, Path::new("YTT301.py"); "YTT301")] #[test_case(RuleCode::YTT301, Path::new("YTT301.py"); "YTT301")]
#[test_case(CheckCode::YTT302, Path::new("YTT302.py"); "YTT302")] #[test_case(RuleCode::YTT302, Path::new("YTT302.py"); "YTT302")]
#[test_case(CheckCode::YTT303, Path::new("YTT303.py"); "YTT303")] #[test_case(RuleCode::YTT303, Path::new("YTT303.py"); "YTT303")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_2020") Path::new("./resources/test/fixtures/flake8_2020")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -4,7 +4,7 @@ use rustpython_ast::{Cmpop, Constant, Expr, ExprKind, Located};
use crate::ast::helpers::match_module_member; use crate::ast::helpers::match_module_member;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
fn is_sys(checker: &Checker, expr: &Expr, target: &str) -> bool { fn is_sys(checker: &Checker, expr: &Expr, target: &str) -> bool {
@ -32,17 +32,16 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
.. ..
} = &upper.node } = &upper.node
{ {
if *i == BigInt::from(1) if *i == BigInt::from(1) && checker.settings.enabled.contains(&RuleCode::YTT303)
&& checker.settings.enabled.contains(&CheckCode::YTT303)
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionSlice1Referenced, violations::SysVersionSlice1Referenced,
Range::from_located(value), Range::from_located(value),
)); ));
} else if *i == BigInt::from(3) } else if *i == BigInt::from(3)
&& checker.settings.enabled.contains(&CheckCode::YTT101) && checker.settings.enabled.contains(&RuleCode::YTT101)
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionSlice3Referenced, violations::SysVersionSlice3Referenced,
Range::from_located(value), Range::from_located(value),
)); ));
@ -54,15 +53,15 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
value: Constant::Int(i), value: Constant::Int(i),
.. ..
} => { } => {
if *i == BigInt::from(2) && checker.settings.enabled.contains(&CheckCode::YTT102) { if *i == BigInt::from(2) && checker.settings.enabled.contains(&RuleCode::YTT102) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersion2Referenced, violations::SysVersion2Referenced,
Range::from_located(value), Range::from_located(value),
)); ));
} else if *i == BigInt::from(0) } else if *i == BigInt::from(0)
&& checker.settings.enabled.contains(&CheckCode::YTT301) && checker.settings.enabled.contains(&RuleCode::YTT301)
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersion0Referenced, violations::SysVersion0Referenced,
Range::from_located(value), Range::from_located(value),
)); ));
@ -97,9 +96,9 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
) = (ops, comparators) ) = (ops, comparators)
{ {
if *n == BigInt::from(3) if *n == BigInt::from(3)
&& checker.settings.enabled.contains(&CheckCode::YTT201) && checker.settings.enabled.contains(&RuleCode::YTT201)
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionInfo0Eq3Referenced, violations::SysVersionInfo0Eq3Referenced,
Range::from_located(left), Range::from_located(left),
)); ));
@ -118,8 +117,8 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
}], }],
) = (ops, comparators) ) = (ops, comparators)
{ {
if checker.settings.enabled.contains(&CheckCode::YTT203) { if checker.settings.enabled.contains(&RuleCode::YTT203) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionInfo1CmpInt, violations::SysVersionInfo1CmpInt,
Range::from_located(left), Range::from_located(left),
)); ));
@ -144,8 +143,8 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
}], }],
) = (ops, comparators) ) = (ops, comparators)
{ {
if checker.settings.enabled.contains(&CheckCode::YTT204) { if checker.settings.enabled.contains(&RuleCode::YTT204) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionInfoMinorCmpInt, violations::SysVersionInfoMinorCmpInt,
Range::from_located(left), Range::from_located(left),
)); ));
@ -170,14 +169,14 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
) = (ops, comparators) ) = (ops, comparators)
{ {
if s.len() == 1 { if s.len() == 1 {
if checker.settings.enabled.contains(&CheckCode::YTT302) { if checker.settings.enabled.contains(&RuleCode::YTT302) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionCmpStr10, violations::SysVersionCmpStr10,
Range::from_located(left), Range::from_located(left),
)); ));
} }
} else if checker.settings.enabled.contains(&CheckCode::YTT103) { } else if checker.settings.enabled.contains(&RuleCode::YTT103) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SysVersionCmpStr3, violations::SysVersionCmpStr3,
Range::from_located(left), Range::from_located(left),
)); ));
@ -195,7 +194,7 @@ pub fn name_or_attribute(checker: &mut Checker, expr: &Expr) {
&checker.from_imports, &checker.from_imports,
&checker.import_aliases, &checker.import_aliases,
) { ) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SixPY3Referenced, violations::SixPY3Referenced,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -10,36 +10,36 @@ mod tests {
use anyhow::Result; use anyhow::Result;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::{flake8_annotations, Settings}; use crate::{flake8_annotations, Settings};
#[test] #[test]
fn defaults() -> Result<()> { fn defaults() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_annotations/annotation_presence.py"), Path::new("./resources/test/fixtures/flake8_annotations/annotation_presence.py"),
&Settings { &Settings {
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::ANN001, RuleCode::ANN001,
CheckCode::ANN002, RuleCode::ANN002,
CheckCode::ANN003, RuleCode::ANN003,
CheckCode::ANN101, RuleCode::ANN101,
CheckCode::ANN102, RuleCode::ANN102,
CheckCode::ANN201, RuleCode::ANN201,
CheckCode::ANN202, RuleCode::ANN202,
CheckCode::ANN204, RuleCode::ANN204,
CheckCode::ANN205, RuleCode::ANN205,
CheckCode::ANN206, RuleCode::ANN206,
CheckCode::ANN401, RuleCode::ANN401,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(checks); insta::assert_yaml_snapshot!(diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn suppress_dummy_args() -> Result<()> { fn suppress_dummy_args() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_annotations/suppress_dummy_args.py"), Path::new("./resources/test/fixtures/flake8_annotations/suppress_dummy_args.py"),
&Settings { &Settings {
flake8_annotations: flake8_annotations::settings::Settings { flake8_annotations: flake8_annotations::settings::Settings {
@ -49,21 +49,21 @@ mod tests {
allow_star_arg_any: false, allow_star_arg_any: false,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::ANN001, RuleCode::ANN001,
CheckCode::ANN002, RuleCode::ANN002,
CheckCode::ANN003, RuleCode::ANN003,
CheckCode::ANN101, RuleCode::ANN101,
CheckCode::ANN102, RuleCode::ANN102,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(checks); insta::assert_yaml_snapshot!(diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn mypy_init_return() -> Result<()> { fn mypy_init_return() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_annotations/mypy_init_return.py"), Path::new("./resources/test/fixtures/flake8_annotations/mypy_init_return.py"),
&Settings { &Settings {
flake8_annotations: flake8_annotations::settings::Settings { flake8_annotations: flake8_annotations::settings::Settings {
@ -73,21 +73,21 @@ mod tests {
allow_star_arg_any: false, allow_star_arg_any: false,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::ANN201, RuleCode::ANN201,
CheckCode::ANN202, RuleCode::ANN202,
CheckCode::ANN204, RuleCode::ANN204,
CheckCode::ANN205, RuleCode::ANN205,
CheckCode::ANN206, RuleCode::ANN206,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(checks); insta::assert_yaml_snapshot!(diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn suppress_none_returning() -> Result<()> { fn suppress_none_returning() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_annotations/suppress_none_returning.py"), Path::new("./resources/test/fixtures/flake8_annotations/suppress_none_returning.py"),
&Settings { &Settings {
flake8_annotations: flake8_annotations::settings::Settings { flake8_annotations: flake8_annotations::settings::Settings {
@ -97,21 +97,21 @@ mod tests {
allow_star_arg_any: false, allow_star_arg_any: false,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::ANN201, RuleCode::ANN201,
CheckCode::ANN202, RuleCode::ANN202,
CheckCode::ANN204, RuleCode::ANN204,
CheckCode::ANN205, RuleCode::ANN205,
CheckCode::ANN206, RuleCode::ANN206,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(checks); insta::assert_yaml_snapshot!(diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn allow_star_arg_any() -> Result<()> { fn allow_star_arg_any() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_annotations/allow_star_arg_any.py"), Path::new("./resources/test/fixtures/flake8_annotations/allow_star_arg_any.py"),
&Settings { &Settings {
flake8_annotations: flake8_annotations::settings::Settings { flake8_annotations: flake8_annotations::settings::Settings {
@ -120,28 +120,28 @@ mod tests {
suppress_none_returning: false, suppress_none_returning: false,
allow_star_arg_any: true, allow_star_arg_any: true,
}, },
..Settings::for_rules(vec![CheckCode::ANN401]) ..Settings::for_rules(vec![RuleCode::ANN401])
}, },
)?; )?;
insta::assert_yaml_snapshot!(checks); insta::assert_yaml_snapshot!(diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn allow_overload() -> Result<()> { fn allow_overload() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_annotations/allow_overload.py"), Path::new("./resources/test/fixtures/flake8_annotations/allow_overload.py"),
&Settings { &Settings {
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::ANN201, RuleCode::ANN201,
CheckCode::ANN202, RuleCode::ANN202,
CheckCode::ANN204, RuleCode::ANN204,
CheckCode::ANN205, RuleCode::ANN205,
CheckCode::ANN206, RuleCode::ANN206,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(checks); insta::assert_yaml_snapshot!(diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -8,9 +8,9 @@ use crate::checkers::ast::Checker;
use crate::docstrings::definition::{Definition, DefinitionKind}; use crate::docstrings::definition::{Definition, DefinitionKind};
use crate::flake8_annotations::fixes; use crate::flake8_annotations::fixes;
use crate::flake8_annotations::helpers::match_function_def; use crate::flake8_annotations::helpers::match_function_def;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::visibility::Visibility; use crate::visibility::Visibility;
use crate::{violations, visibility, Check}; use crate::{violations, visibility, Diagnostic};
#[derive(Default)] #[derive(Default)]
struct ReturnStatementVisitor<'a> { struct ReturnStatementVisitor<'a> {
@ -57,7 +57,7 @@ where
F: FnOnce() -> String, F: FnOnce() -> String,
{ {
if checker.match_typing_expr(annotation, "Any") { if checker.match_typing_expr(annotation, "Any") {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::DynamicallyTypedExpression(func()), violations::DynamicallyTypedExpression(func()),
Range::from_located(annotation), Range::from_located(annotation),
)); ));
@ -85,15 +85,15 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
.chain(args.kwonlyargs.iter()) .chain(args.kwonlyargs.iter())
{ {
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
check_dynamically_typed(checker, expr, || arg.node.arg.to_string()); check_dynamically_typed(checker, expr, || arg.node.arg.to_string());
}; };
} else { } else {
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.enabled.contains(&CheckCode::ANN001) { if checker.settings.enabled.contains(&RuleCode::ANN001) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeFunctionArgument(arg.node.arg.to_string()), violations::MissingTypeFunctionArgument(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -106,7 +106,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if let Some(arg) = &args.vararg { if let Some(arg) = &args.vararg {
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
if !checker.settings.flake8_annotations.allow_star_arg_any { if !checker.settings.flake8_annotations.allow_star_arg_any {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
let name = arg.node.arg.to_string(); let name = arg.node.arg.to_string();
check_dynamically_typed(checker, expr, || format!("*{name}")); check_dynamically_typed(checker, expr, || format!("*{name}"));
} }
@ -115,8 +115,8 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.enabled.contains(&CheckCode::ANN002) { if checker.settings.enabled.contains(&RuleCode::ANN002) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeArgs(arg.node.arg.to_string()), violations::MissingTypeArgs(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -129,7 +129,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if let Some(arg) = &args.kwarg { if let Some(arg) = &args.kwarg {
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
if !checker.settings.flake8_annotations.allow_star_arg_any { if !checker.settings.flake8_annotations.allow_star_arg_any {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
let name = arg.node.arg.to_string(); let name = arg.node.arg.to_string();
check_dynamically_typed(checker, expr, || format!("**{name}")); check_dynamically_typed(checker, expr, || format!("**{name}"));
} }
@ -138,8 +138,8 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.enabled.contains(&CheckCode::ANN003) { if checker.settings.enabled.contains(&RuleCode::ANN003) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeKwargs(arg.node.arg.to_string()), violations::MissingTypeKwargs(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -150,7 +150,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
// ANN201, ANN202, ANN401 // ANN201, ANN202, ANN401
if let Some(expr) = &returns { if let Some(expr) = &returns {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
check_dynamically_typed(checker, expr, || name.to_string()); check_dynamically_typed(checker, expr, || name.to_string());
}; };
} else { } else {
@ -164,16 +164,16 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
match visibility { match visibility {
Visibility::Public => { Visibility::Public => {
if checker.settings.enabled.contains(&CheckCode::ANN201) { if checker.settings.enabled.contains(&RuleCode::ANN201) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypePublicFunction(name.to_string()), violations::MissingReturnTypePublicFunction(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));
} }
} }
Visibility::Private => { Visibility::Private => {
if checker.settings.enabled.contains(&CheckCode::ANN202) { if checker.settings.enabled.contains(&RuleCode::ANN202) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypePrivateFunction(name.to_string()), violations::MissingReturnTypePrivateFunction(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));
@ -203,15 +203,15 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
// ANN401 for dynamically typed arguments // ANN401 for dynamically typed arguments
if let Some(annotation) = &arg.node.annotation { if let Some(annotation) = &arg.node.annotation {
has_any_typed_arg = true; has_any_typed_arg = true;
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
check_dynamically_typed(checker, annotation, || arg.node.arg.to_string()); check_dynamically_typed(checker, annotation, || arg.node.arg.to_string());
} }
} else { } else {
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.enabled.contains(&CheckCode::ANN001) { if checker.settings.enabled.contains(&RuleCode::ANN001) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeFunctionArgument(arg.node.arg.to_string()), violations::MissingTypeFunctionArgument(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -225,7 +225,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
has_any_typed_arg = true; has_any_typed_arg = true;
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
if !checker.settings.flake8_annotations.allow_star_arg_any { if !checker.settings.flake8_annotations.allow_star_arg_any {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
let name = arg.node.arg.to_string(); let name = arg.node.arg.to_string();
check_dynamically_typed(checker, expr, || format!("*{name}")); check_dynamically_typed(checker, expr, || format!("*{name}"));
} }
@ -234,8 +234,8 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.enabled.contains(&CheckCode::ANN002) { if checker.settings.enabled.contains(&RuleCode::ANN002) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeArgs(arg.node.arg.to_string()), violations::MissingTypeArgs(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -249,7 +249,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
has_any_typed_arg = true; has_any_typed_arg = true;
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
if !checker.settings.flake8_annotations.allow_star_arg_any { if !checker.settings.flake8_annotations.allow_star_arg_any {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
let name = arg.node.arg.to_string(); let name = arg.node.arg.to_string();
check_dynamically_typed(checker, expr, || format!("**{name}")); check_dynamically_typed(checker, expr, || format!("**{name}"));
} }
@ -258,8 +258,8 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.enabled.contains(&CheckCode::ANN003) { if checker.settings.enabled.contains(&RuleCode::ANN003) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeKwargs(arg.node.arg.to_string()), violations::MissingTypeKwargs(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -273,15 +273,15 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if let Some(arg) = args.args.first() { if let Some(arg) = args.args.first() {
if arg.node.annotation.is_none() { if arg.node.annotation.is_none() {
if visibility::is_classmethod(checker, cast::decorator_list(stmt)) { if visibility::is_classmethod(checker, cast::decorator_list(stmt)) {
if checker.settings.enabled.contains(&CheckCode::ANN102) { if checker.settings.enabled.contains(&RuleCode::ANN102) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeCls(arg.node.arg.to_string()), violations::MissingTypeCls(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
} }
} else { } else {
if checker.settings.enabled.contains(&CheckCode::ANN101) { if checker.settings.enabled.contains(&RuleCode::ANN101) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingTypeSelf(arg.node.arg.to_string()), violations::MissingTypeSelf(arg.node.arg.to_string()),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -293,7 +293,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
// ANN201, ANN202 // ANN201, ANN202
if let Some(expr) = &returns { if let Some(expr) = &returns {
if checker.settings.enabled.contains(&CheckCode::ANN401) { if checker.settings.enabled.contains(&RuleCode::ANN401) {
check_dynamically_typed(checker, expr, || name.to_string()); check_dynamically_typed(checker, expr, || name.to_string());
} }
} else { } else {
@ -306,15 +306,15 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
} }
if visibility::is_classmethod(checker, cast::decorator_list(stmt)) { if visibility::is_classmethod(checker, cast::decorator_list(stmt)) {
if checker.settings.enabled.contains(&CheckCode::ANN206) { if checker.settings.enabled.contains(&RuleCode::ANN206) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypeClassMethod(name.to_string()), violations::MissingReturnTypeClassMethod(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));
} }
} else if visibility::is_staticmethod(checker, cast::decorator_list(stmt)) { } else if visibility::is_staticmethod(checker, cast::decorator_list(stmt)) {
if checker.settings.enabled.contains(&CheckCode::ANN205) { if checker.settings.enabled.contains(&RuleCode::ANN205) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypeStaticMethod(name.to_string()), violations::MissingReturnTypeStaticMethod(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));
@ -322,11 +322,11 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
} else if visibility::is_init(stmt) { } else if visibility::is_init(stmt) {
// Allow omission of return annotation in `__init__` functions, as long as at // Allow omission of return annotation in `__init__` functions, as long as at
// least one argument is typed. // least one argument is typed.
if checker.settings.enabled.contains(&CheckCode::ANN204) { if checker.settings.enabled.contains(&RuleCode::ANN204) {
if !(checker.settings.flake8_annotations.mypy_init_return if !(checker.settings.flake8_annotations.mypy_init_return
&& has_any_typed_arg) && has_any_typed_arg)
{ {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::MissingReturnTypeSpecialMethod(name.to_string()), violations::MissingReturnTypeSpecialMethod(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
); );
@ -338,12 +338,12 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
} else if visibility::is_magic(stmt) { } else if visibility::is_magic(stmt) {
if checker.settings.enabled.contains(&CheckCode::ANN204) { if checker.settings.enabled.contains(&RuleCode::ANN204) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypeSpecialMethod(name.to_string()), violations::MissingReturnTypeSpecialMethod(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));
@ -351,16 +351,16 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
} else { } else {
match visibility { match visibility {
Visibility::Public => { Visibility::Public => {
if checker.settings.enabled.contains(&CheckCode::ANN201) { if checker.settings.enabled.contains(&RuleCode::ANN201) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypePublicFunction(name.to_string()), violations::MissingReturnTypePublicFunction(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));
} }
} }
Visibility::Private => { Visibility::Private => {
if checker.settings.enabled.contains(&CheckCode::ANN202) { if checker.settings.enabled.contains(&RuleCode::ANN202) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingReturnTypePrivateFunction(name.to_string()), violations::MissingReturnTypePrivateFunction(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));

View File

@ -1,10 +1,10 @@
use rustpython_ast::{Located, StmtKind}; use rustpython_ast::{Located, StmtKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// S101 /// S101
pub fn assert_used(stmt: &Located<StmtKind>) -> Check { pub fn assert_used(stmt: &Located<StmtKind>) -> Diagnostic {
Check::new(violations::AssertUsed, Range::from_located(stmt)) Diagnostic::new(violations::AssertUsed, Range::from_located(stmt))
} }

View File

@ -5,7 +5,7 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword, Operator};
use crate::ast::helpers::{compose_call_path, match_module_member, SimpleCallArgs}; use crate::ast::helpers::{compose_call_path, match_module_member, SimpleCallArgs};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const WRITE_WORLD: u16 = 0o2; const WRITE_WORLD: u16 = 0o2;
@ -91,13 +91,13 @@ pub fn bad_file_permissions(
keywords: &[Keyword], keywords: &[Keyword],
from_imports: &FxHashMap<&str, FxHashSet<&str>>, from_imports: &FxHashMap<&str, FxHashSet<&str>>,
import_aliases: &FxHashMap<&str, &str>, import_aliases: &FxHashMap<&str, &str>,
) -> Option<Check> { ) -> Option<Diagnostic> {
if match_module_member(func, "os", "chmod", from_imports, import_aliases) { if match_module_member(func, "os", "chmod", from_imports, import_aliases) {
let call_args = SimpleCallArgs::new(args, keywords); let call_args = SimpleCallArgs::new(args, keywords);
if let Some(mode_arg) = call_args.get_argument("mode", Some(1)) { if let Some(mode_arg) = call_args.get_argument("mode", Some(1)) {
if let Some(int_value) = get_int_value(mode_arg) { if let Some(int_value) = get_int_value(mode_arg) {
if (int_value & WRITE_WORLD > 0) || (int_value & EXECUTE_GROUP > 0) { if (int_value & WRITE_WORLD > 0) || (int_value & EXECUTE_GROUP > 0) {
return Some(Check::new( return Some(Diagnostic::new(
violations::BadFilePermissions(int_value), violations::BadFilePermissions(int_value),
Range::from_located(mode_arg), Range::from_located(mode_arg),
)); ));

View File

@ -1,16 +1,19 @@
use rustpython_ast::{Expr, ExprKind}; use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// S102 /// S102
pub fn exec_used(expr: &Expr, func: &Expr) -> Option<Check> { pub fn exec_used(expr: &Expr, func: &Expr) -> Option<Diagnostic> {
let ExprKind::Name { id, .. } = &func.node else { let ExprKind::Name { id, .. } = &func.node else {
return None; return None;
}; };
if id != "exec" { if id != "exec" {
return None; return None;
} }
Some(Check::new(violations::ExecUsed, Range::from_located(expr))) Some(Diagnostic::new(
violations::ExecUsed,
Range::from_located(expr),
))
} }

View File

@ -1,11 +1,14 @@
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// S104 /// S104
pub fn hardcoded_bind_all_interfaces(value: &str, range: &Range) -> Option<Check> { pub fn hardcoded_bind_all_interfaces(value: &str, range: &Range) -> Option<Diagnostic> {
if value == "0.0.0.0" { if value == "0.0.0.0" {
Some(Check::new(violations::HardcodedBindAllInterfaces, *range)) Some(Diagnostic::new(
violations::HardcodedBindAllInterfaces,
*range,
))
} else { } else {
None None
} }

View File

@ -2,24 +2,24 @@ use rustpython_ast::{ArgData, Arguments, Expr, Located};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_bandit::helpers::{matches_password_name, string_literal}; use crate::flake8_bandit::helpers::{matches_password_name, string_literal};
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
fn check_password_kwarg(arg: &Located<ArgData>, default: &Expr) -> Option<Check> { fn check_password_kwarg(arg: &Located<ArgData>, default: &Expr) -> Option<Diagnostic> {
let string = string_literal(default)?; let string = string_literal(default)?;
let kwarg_name = &arg.node.arg; let kwarg_name = &arg.node.arg;
if !matches_password_name(kwarg_name) { if !matches_password_name(kwarg_name) {
return None; return None;
} }
Some(Check::new( Some(Diagnostic::new(
violations::HardcodedPasswordDefault(string.to_string()), violations::HardcodedPasswordDefault(string.to_string()),
Range::from_located(default), Range::from_located(default),
)) ))
} }
/// S107 /// S107
pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Check> { pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Diagnostic> {
let mut checks: Vec<Check> = Vec::new(); let mut checks: Vec<Diagnostic> = Vec::new();
let defaults_start = let defaults_start =
arguments.posonlyargs.len() + arguments.args.len() - arguments.defaults.len(); arguments.posonlyargs.len() + arguments.args.len() - arguments.defaults.len();

View File

@ -2,11 +2,11 @@ use rustpython_ast::Keyword;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_bandit::helpers::{matches_password_name, string_literal}; use crate::flake8_bandit::helpers::{matches_password_name, string_literal};
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// S106 /// S106
pub fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec<Check> { pub fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec<Diagnostic> {
keywords keywords
.iter() .iter()
.filter_map(|keyword| { .filter_map(|keyword| {
@ -15,7 +15,7 @@ pub fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec<Check> {
if !matches_password_name(arg) { if !matches_password_name(arg) {
return None; return None;
} }
Some(Check::new( Some(Diagnostic::new(
violations::HardcodedPasswordFuncArg(string.to_string()), violations::HardcodedPasswordFuncArg(string.to_string()),
Range::from_located(keyword), Range::from_located(keyword),
)) ))

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Constant, Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_bandit::helpers::{matches_password_name, string_literal}; use crate::flake8_bandit::helpers::{matches_password_name, string_literal};
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
fn is_password_target(target: &Expr) -> bool { fn is_password_target(target: &Expr) -> bool {
@ -26,7 +26,7 @@ fn is_password_target(target: &Expr) -> bool {
} }
/// S105 /// S105
pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) -> Vec<Check> { pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) -> Vec<Diagnostic> {
comparators comparators
.iter() .iter()
.filter_map(|comp| { .filter_map(|comp| {
@ -34,7 +34,7 @@ pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) -
if !is_password_target(left) { if !is_password_target(left) {
return None; return None;
} }
Some(Check::new( Some(Diagnostic::new(
violations::HardcodedPasswordString(string.to_string()), violations::HardcodedPasswordString(string.to_string()),
Range::from_located(comp), Range::from_located(comp),
)) ))
@ -43,11 +43,11 @@ pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) -
} }
/// S105 /// S105
pub fn assign_hardcoded_password_string(value: &Expr, targets: &[Expr]) -> Option<Check> { pub fn assign_hardcoded_password_string(value: &Expr, targets: &[Expr]) -> Option<Diagnostic> {
if let Some(string) = string_literal(value) { if let Some(string) = string_literal(value) {
for target in targets { for target in targets {
if is_password_target(target) { if is_password_target(target) {
return Some(Check::new( return Some(Diagnostic::new(
violations::HardcodedPasswordString(string.to_string()), violations::HardcodedPasswordString(string.to_string()),
Range::from_located(value), Range::from_located(value),
)); ));

View File

@ -1,13 +1,17 @@
use rustpython_ast::Expr; use rustpython_ast::Expr;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// S108 /// S108
pub fn hardcoded_tmp_directory(expr: &Expr, value: &str, prefixes: &[String]) -> Option<Check> { pub fn hardcoded_tmp_directory(
expr: &Expr,
value: &str,
prefixes: &[String],
) -> Option<Diagnostic> {
if prefixes.iter().any(|prefix| value.starts_with(prefix)) { if prefixes.iter().any(|prefix| value.starts_with(prefix)) {
Some(Check::new( Some(Diagnostic::new(
violations::HardcodedTempFile(value.to_string()), violations::HardcodedTempFile(value.to_string()),
Range::from_located(expr), Range::from_located(expr),
)) ))

View File

@ -4,7 +4,7 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword};
use crate::ast::helpers::{match_module_member, SimpleCallArgs}; use crate::ast::helpers::{match_module_member, SimpleCallArgs};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_bandit::helpers::string_literal; use crate::flake8_bandit::helpers::string_literal;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const WEAK_HASHES: [&str; 4] = ["md4", "md5", "sha", "sha1"]; const WEAK_HASHES: [&str; 4] = ["md4", "md5", "sha", "sha1"];
@ -29,7 +29,7 @@ pub fn hashlib_insecure_hash_functions(
keywords: &[Keyword], keywords: &[Keyword],
from_imports: &FxHashMap<&str, FxHashSet<&str>>, from_imports: &FxHashMap<&str, FxHashSet<&str>>,
import_aliases: &FxHashMap<&str, &str>, import_aliases: &FxHashMap<&str, &str>,
) -> Option<Check> { ) -> Option<Diagnostic> {
if match_module_member(func, "hashlib", "new", from_imports, import_aliases) { if match_module_member(func, "hashlib", "new", from_imports, import_aliases) {
let call_args = SimpleCallArgs::new(args, keywords); let call_args = SimpleCallArgs::new(args, keywords);
@ -41,7 +41,7 @@ pub fn hashlib_insecure_hash_functions(
let hash_func_name = string_literal(name_arg)?; let hash_func_name = string_literal(name_arg)?;
if WEAK_HASHES.contains(&hash_func_name.to_lowercase().as_str()) { if WEAK_HASHES.contains(&hash_func_name.to_lowercase().as_str()) {
return Some(Check::new( return Some(Diagnostic::new(
violations::HashlibInsecureHashFunction(hash_func_name.to_string()), violations::HashlibInsecureHashFunction(hash_func_name.to_string()),
Range::from_located(name_arg), Range::from_located(name_arg),
)); ));
@ -56,7 +56,7 @@ pub fn hashlib_insecure_hash_functions(
return None; return None;
} }
return Some(Check::new( return Some(Diagnostic::new(
violations::HashlibInsecureHashFunction((*func_name).to_string()), violations::HashlibInsecureHashFunction((*func_name).to_string()),
Range::from_located(func), Range::from_located(func),
)); ));

View File

@ -4,7 +4,7 @@ use rustpython_parser::ast::Constant;
use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path, SimpleCallArgs}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path, SimpleCallArgs};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const REQUESTS_HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"]; const REQUESTS_HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"];
@ -29,7 +29,7 @@ pub fn request_with_no_cert_validation(
keywords: &[Keyword], keywords: &[Keyword],
from_imports: &FxHashMap<&str, FxHashSet<&str>>, from_imports: &FxHashMap<&str, FxHashSet<&str>>,
import_aliases: &FxHashMap<&str, &str>, import_aliases: &FxHashMap<&str, &str>,
) -> Option<Check> { ) -> Option<Diagnostic> {
let call_path = dealias_call_path(collect_call_paths(func), import_aliases); let call_path = dealias_call_path(collect_call_paths(func), import_aliases);
let call_args = SimpleCallArgs::new(args, keywords); let call_args = SimpleCallArgs::new(args, keywords);
@ -41,7 +41,7 @@ pub fn request_with_no_cert_validation(
.. ..
} = &verify_arg.node } = &verify_arg.node
{ {
return Some(Check::new( return Some(Diagnostic::new(
violations::RequestWithNoCertValidation("requests".to_string()), violations::RequestWithNoCertValidation("requests".to_string()),
Range::from_located(verify_arg), Range::from_located(verify_arg),
)); ));
@ -58,7 +58,7 @@ pub fn request_with_no_cert_validation(
.. ..
} = &verify_arg.node } = &verify_arg.node
{ {
return Some(Check::new( return Some(Diagnostic::new(
violations::RequestWithNoCertValidation("httpx".to_string()), violations::RequestWithNoCertValidation("httpx".to_string()),
Range::from_located(verify_arg), Range::from_located(verify_arg),
)); ));

View File

@ -4,7 +4,7 @@ use rustpython_parser::ast::Constant;
use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path, SimpleCallArgs}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path, SimpleCallArgs};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"]; const HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"];
@ -16,7 +16,7 @@ pub fn request_without_timeout(
keywords: &[Keyword], keywords: &[Keyword],
from_imports: &FxHashMap<&str, FxHashSet<&str>>, from_imports: &FxHashMap<&str, FxHashSet<&str>>,
import_aliases: &FxHashMap<&str, &str>, import_aliases: &FxHashMap<&str, &str>,
) -> Option<Check> { ) -> Option<Diagnostic> {
let call_path = dealias_call_path(collect_call_paths(func), import_aliases); let call_path = dealias_call_path(collect_call_paths(func), import_aliases);
for func_name in &HTTP_VERBS { for func_name in &HTTP_VERBS {
if match_call_path(&call_path, "requests", func_name, from_imports) { if match_call_path(&call_path, "requests", func_name, from_imports) {
@ -29,13 +29,13 @@ pub fn request_without_timeout(
} => Some(value.to_string()), } => Some(value.to_string()),
_ => None, _ => None,
} { } {
return Some(Check::new( return Some(Diagnostic::new(
violations::RequestWithoutTimeout(Some(timeout)), violations::RequestWithoutTimeout(Some(timeout)),
Range::from_located(timeout_arg), Range::from_located(timeout_arg),
)); ));
} }
} else { } else {
return Some(Check::new( return Some(Diagnostic::new(
violations::RequestWithoutTimeout(None), violations::RequestWithoutTimeout(None),
Range::from_located(func), Range::from_located(func),
)); ));

View File

@ -3,7 +3,7 @@ use rustpython_ast::{Expr, ExprKind, Keyword};
use crate::ast::helpers::{match_module_member, SimpleCallArgs}; use crate::ast::helpers::{match_module_member, SimpleCallArgs};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// S506 /// S506
@ -13,7 +13,7 @@ pub fn unsafe_yaml_load(
keywords: &[Keyword], keywords: &[Keyword],
from_imports: &FxHashMap<&str, FxHashSet<&str>>, from_imports: &FxHashMap<&str, FxHashSet<&str>>,
import_aliases: &FxHashMap<&str, &str>, import_aliases: &FxHashMap<&str, &str>,
) -> Option<Check> { ) -> Option<Diagnostic> {
if match_module_member(func, "yaml", "load", from_imports, import_aliases) { if match_module_member(func, "yaml", "load", from_imports, import_aliases) {
let call_args = SimpleCallArgs::new(args, keywords); let call_args = SimpleCallArgs::new(args, keywords);
if let Some(loader_arg) = call_args.get_argument("Loader", Some(1)) { if let Some(loader_arg) = call_args.get_argument("Loader", Some(1)) {
@ -35,13 +35,13 @@ pub fn unsafe_yaml_load(
ExprKind::Name { id, .. } => Some(id.to_string()), ExprKind::Name { id, .. } => Some(id.to_string()),
_ => None, _ => None,
}; };
return Some(Check::new( return Some(Diagnostic::new(
violations::UnsafeYAMLLoad(loader), violations::UnsafeYAMLLoad(loader),
Range::from_located(loader_arg), Range::from_located(loader_arg),
)); ));
} }
} else { } else {
return Some(Check::new( return Some(Diagnostic::new(
violations::UnsafeYAMLLoad(None), violations::UnsafeYAMLLoad(None),
Range::from_located(func), Range::from_located(func),
)); ));

View File

@ -10,36 +10,36 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::{flake8_bandit, Settings}; use crate::{flake8_bandit, Settings};
#[test_case(CheckCode::S101, Path::new("S101.py"); "S101")] #[test_case(RuleCode::S101, Path::new("S101.py"); "S101")]
#[test_case(CheckCode::S102, Path::new("S102.py"); "S102")] #[test_case(RuleCode::S102, Path::new("S102.py"); "S102")]
#[test_case(CheckCode::S103, Path::new("S103.py"); "S103")] #[test_case(RuleCode::S103, Path::new("S103.py"); "S103")]
#[test_case(CheckCode::S104, Path::new("S104.py"); "S104")] #[test_case(RuleCode::S104, Path::new("S104.py"); "S104")]
#[test_case(CheckCode::S105, Path::new("S105.py"); "S105")] #[test_case(RuleCode::S105, Path::new("S105.py"); "S105")]
#[test_case(CheckCode::S106, Path::new("S106.py"); "S106")] #[test_case(RuleCode::S106, Path::new("S106.py"); "S106")]
#[test_case(CheckCode::S107, Path::new("S107.py"); "S107")] #[test_case(RuleCode::S107, Path::new("S107.py"); "S107")]
#[test_case(CheckCode::S108, Path::new("S108.py"); "S108")] #[test_case(RuleCode::S108, Path::new("S108.py"); "S108")]
#[test_case(CheckCode::S113, Path::new("S113.py"); "S113")] #[test_case(RuleCode::S113, Path::new("S113.py"); "S113")]
#[test_case(CheckCode::S324, Path::new("S324.py"); "S324")] #[test_case(RuleCode::S324, Path::new("S324.py"); "S324")]
#[test_case(CheckCode::S501, Path::new("S501.py"); "S501")] #[test_case(RuleCode::S501, Path::new("S501.py"); "S501")]
#[test_case(CheckCode::S506, Path::new("S506.py"); "S506")] #[test_case(RuleCode::S506, Path::new("S506.py"); "S506")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_bandit") Path::new("./resources/test/fixtures/flake8_bandit")
.join(path) .join(path)
.as_path(), .as_path(),
&Settings::for_rule(check_code), &Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn check_hardcoded_tmp_additional_dirs() -> Result<()> { fn check_hardcoded_tmp_additional_dirs() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_bandit/S108.py"), Path::new("./resources/test/fixtures/flake8_bandit/S108.py"),
&Settings { &Settings {
flake8_bandit: flake8_bandit::settings::Settings { flake8_bandit: flake8_bandit::settings::Settings {
@ -50,10 +50,10 @@ mod tests {
"/foo".to_string(), "/foo".to_string(),
], ],
}, },
..Settings::for_rule(CheckCode::S108) ..Settings::for_rule(RuleCode::S108)
}, },
)?; )?;
insta::assert_yaml_snapshot!("S108_extend", checks); insta::assert_yaml_snapshot!("S108_extend", diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -9,19 +9,19 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::BLE001, Path::new("BLE.py"); "BLE001")] #[test_case(RuleCode::BLE001, Path::new("BLE.py"); "BLE001")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_blind_except") Path::new("./resources/test/fixtures/flake8_blind_except")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind, Stmt, StmtKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// BLE001 /// BLE001
@ -36,7 +36,7 @@ pub fn blind_except(
false false
} }
}) { }) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::BlindExcept(id.to_string()), violations::BlindExcept(id.to_string()),
Range::from_located(type_), Range::from_located(type_),
)); ));

View File

@ -9,21 +9,21 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::FBT001, Path::new("FBT.py"); "FBT001")] #[test_case(RuleCode::FBT001, Path::new("FBT.py"); "FBT001")]
#[test_case(CheckCode::FBT002, Path::new("FBT.py"); "FBT002")] #[test_case(RuleCode::FBT002, Path::new("FBT.py"); "FBT002")]
#[test_case(CheckCode::FBT003, Path::new("FBT.py"); "FBT003")] #[test_case(RuleCode::FBT003, Path::new("FBT.py"); "FBT003")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_boolean_trap") Path::new("./resources/test/fixtures/flake8_boolean_trap")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -3,7 +3,7 @@ use rustpython_parser::ast::{Constant, Expr};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckKind}; use crate::registry::{Diagnostic, DiagnosticKind};
use crate::violations; use crate::violations;
const FUNC_NAME_ALLOWLIST: &[&str] = &[ const FUNC_NAME_ALLOWLIST: &[&str] = &[
@ -47,11 +47,11 @@ fn is_boolean_arg(arg: &Expr) -> bool {
) )
} }
fn add_if_boolean(checker: &mut Checker, arg: &Expr, kind: CheckKind) { fn add_if_boolean(checker: &mut Checker, arg: &Expr, kind: DiagnosticKind) {
if is_boolean_arg(arg) { if is_boolean_arg(arg) {
checker checker
.checks .diagnostics
.push(Check::new(kind, Range::from_located(arg))); .push(Diagnostic::new(kind, Range::from_located(arg)));
} }
} }
@ -76,7 +76,7 @@ pub fn check_positional_boolean_in_def(checker: &mut Checker, arguments: &Argume
if !hint { if !hint {
continue; continue;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::BooleanPositionalArgInFunctionDefinition, violations::BooleanPositionalArgInFunctionDefinition,
Range::from_located(arg), Range::from_located(arg),
)); ));

View File

@ -9,53 +9,53 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::{flake8_bugbear, Settings}; use crate::{flake8_bugbear, Settings};
#[test_case(CheckCode::B002, Path::new("B002.py"); "B002")] #[test_case(RuleCode::B002, Path::new("B002.py"); "B002")]
#[test_case(CheckCode::B003, Path::new("B003.py"); "B003")] #[test_case(RuleCode::B003, Path::new("B003.py"); "B003")]
#[test_case(CheckCode::B004, Path::new("B004.py"); "B004")] #[test_case(RuleCode::B004, Path::new("B004.py"); "B004")]
#[test_case(CheckCode::B005, Path::new("B005.py"); "B005")] #[test_case(RuleCode::B005, Path::new("B005.py"); "B005")]
#[test_case(CheckCode::B006, Path::new("B006_B008.py"); "B006")] #[test_case(RuleCode::B006, Path::new("B006_B008.py"); "B006")]
#[test_case(CheckCode::B007, Path::new("B007.py"); "B007")] #[test_case(RuleCode::B007, Path::new("B007.py"); "B007")]
#[test_case(CheckCode::B008, Path::new("B006_B008.py"); "B008")] #[test_case(RuleCode::B008, Path::new("B006_B008.py"); "B008")]
#[test_case(CheckCode::B009, Path::new("B009_B010.py"); "B009")] #[test_case(RuleCode::B009, Path::new("B009_B010.py"); "B009")]
#[test_case(CheckCode::B010, Path::new("B009_B010.py"); "B010")] #[test_case(RuleCode::B010, Path::new("B009_B010.py"); "B010")]
#[test_case(CheckCode::B011, Path::new("B011.py"); "B011")] #[test_case(RuleCode::B011, Path::new("B011.py"); "B011")]
#[test_case(CheckCode::B012, Path::new("B012.py"); "B012")] #[test_case(RuleCode::B012, Path::new("B012.py"); "B012")]
#[test_case(CheckCode::B013, Path::new("B013.py"); "B013")] #[test_case(RuleCode::B013, Path::new("B013.py"); "B013")]
#[test_case(CheckCode::B014, Path::new("B014.py"); "B014")] #[test_case(RuleCode::B014, Path::new("B014.py"); "B014")]
#[test_case(CheckCode::B015, Path::new("B015.py"); "B015")] #[test_case(RuleCode::B015, Path::new("B015.py"); "B015")]
#[test_case(CheckCode::B016, Path::new("B016.py"); "B016")] #[test_case(RuleCode::B016, Path::new("B016.py"); "B016")]
#[test_case(CheckCode::B017, Path::new("B017.py"); "B017")] #[test_case(RuleCode::B017, Path::new("B017.py"); "B017")]
#[test_case(CheckCode::B018, Path::new("B018.py"); "B018")] #[test_case(RuleCode::B018, Path::new("B018.py"); "B018")]
#[test_case(CheckCode::B019, Path::new("B019.py"); "B019")] #[test_case(RuleCode::B019, Path::new("B019.py"); "B019")]
#[test_case(CheckCode::B020, Path::new("B020.py"); "B020")] #[test_case(RuleCode::B020, Path::new("B020.py"); "B020")]
#[test_case(CheckCode::B021, Path::new("B021.py"); "B021")] #[test_case(RuleCode::B021, Path::new("B021.py"); "B021")]
#[test_case(CheckCode::B022, Path::new("B022.py"); "B022")] #[test_case(RuleCode::B022, Path::new("B022.py"); "B022")]
#[test_case(CheckCode::B023, Path::new("B023.py"); "B023")] #[test_case(RuleCode::B023, Path::new("B023.py"); "B023")]
#[test_case(CheckCode::B024, Path::new("B024.py"); "B024")] #[test_case(RuleCode::B024, Path::new("B024.py"); "B024")]
#[test_case(CheckCode::B025, Path::new("B025.py"); "B025")] #[test_case(RuleCode::B025, Path::new("B025.py"); "B025")]
#[test_case(CheckCode::B026, Path::new("B026.py"); "B026")] #[test_case(RuleCode::B026, Path::new("B026.py"); "B026")]
#[test_case(CheckCode::B027, Path::new("B027.py"); "B027")] #[test_case(RuleCode::B027, Path::new("B027.py"); "B027")]
#[test_case(CheckCode::B904, Path::new("B904.py"); "B904")] #[test_case(RuleCode::B904, Path::new("B904.py"); "B904")]
#[test_case(CheckCode::B905, Path::new("B905.py"); "B905")] #[test_case(RuleCode::B905, Path::new("B905.py"); "B905")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_bugbear") Path::new("./resources/test/fixtures/flake8_bugbear")
.join(path) .join(path)
.as_path(), .as_path(),
&Settings::for_rule(check_code), &Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn extend_immutable_calls() -> Result<()> { fn extend_immutable_calls() -> Result<()> {
let snapshot = "extend_immutable_calls".to_string(); let snapshot = "extend_immutable_calls".to_string();
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_bugbear/B008_extended.py"), Path::new("./resources/test/fixtures/flake8_bugbear/B008_extended.py"),
&Settings { &Settings {
flake8_bugbear: flake8_bugbear::settings::Settings { flake8_bugbear: flake8_bugbear::settings::Settings {
@ -64,10 +64,10 @@ mod tests {
"fastapi.Query".to_string(), "fastapi.Query".to_string(),
], ],
}, },
..Settings::for_rules(vec![CheckCode::B008]) ..Settings::for_rules(vec![RuleCode::B008])
}, },
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -4,7 +4,7 @@ use rustpython_ast::{Constant, Expr, ExprKind, Keyword, Stmt, StmtKind};
use crate::ast::helpers::match_module_member; use crate::ast::helpers::match_module_member;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
fn is_abc_class( fn is_abc_class(
@ -108,7 +108,7 @@ pub fn abstract_base_class(
has_abstract_method |= has_abstract_decorator; has_abstract_method |= has_abstract_decorator;
if !checker.settings.enabled.contains(&CheckCode::B027) { if !checker.settings.enabled.contains(&RuleCode::B027) {
continue; continue;
} }
@ -118,15 +118,15 @@ pub fn abstract_base_class(
.iter() .iter()
.any(|d| is_overload(d, &checker.from_imports, &checker.import_aliases)) .any(|d| is_overload(d, &checker.from_imports, &checker.import_aliases))
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::EmptyMethodWithoutAbstractDecorator(name.to_string()), violations::EmptyMethodWithoutAbstractDecorator(name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
)); ));
} }
} }
if checker.settings.enabled.contains(&CheckCode::B024) { if checker.settings.enabled.contains(&RuleCode::B024) {
if !has_abstract_method { if !has_abstract_method {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::AbstractBaseClassWithoutAbstractMethod(name.to_string()), violations::AbstractBaseClassWithoutAbstractMethod(name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
)); ));

View File

@ -3,7 +3,7 @@ use rustpython_ast::{Constant, Expr, ExprContext, ExprKind, Location, Stmt, Stmt
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_generator::SourceCodeGenerator;
use crate::violations; use crate::violations;
@ -46,7 +46,7 @@ pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option
return; return;
}; };
let mut check = Check::new(violations::DoNotAssertFalse, Range::from_located(test)); let mut check = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test));
if checker.patch(check.kind.code()) { if checker.patch(check.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_stmt(&assertion_error(msg)); generator.unparse_stmt(&assertion_error(msg));
@ -56,5 +56,5 @@ pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }

View File

@ -3,7 +3,7 @@ use rustpython_ast::{ExprKind, Stmt, Withitem};
use crate::ast::helpers::match_module_member; use crate::ast::helpers::match_module_member;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B017 /// B017
@ -34,7 +34,7 @@ pub fn assert_raises_exception(checker: &mut Checker, stmt: &Stmt, items: &[With
return; return;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::NoAssertRaisesException, violations::NoAssertRaisesException,
Range::from_located(stmt), Range::from_located(stmt),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B003 /// B003
@ -23,7 +23,7 @@ pub fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) {
if id != "os" { if id != "os" {
return; return;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::AssignmentToOsEnviron, violations::AssignmentToOsEnviron,
Range::from_located(target), Range::from_located(target),
)); ));

View File

@ -3,7 +3,7 @@ use rustpython_ast::{Expr, ExprKind};
use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path};
use crate::ast::types::{Range, ScopeKind}; use crate::ast::types::{Range, ScopeKind};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
fn is_cache_func(checker: &Checker, expr: &Expr) -> bool { fn is_cache_func(checker: &Checker, expr: &Expr) -> bool {
@ -34,7 +34,7 @@ pub fn cached_instance_method(checker: &mut Checker, decorator_list: &[Expr]) {
_ => decorator, _ => decorator,
}, },
) { ) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CachedInstanceMethod, violations::CachedInstanceMethod,
Range::from_located(decorator), Range::from_located(decorator),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B016 /// B016
@ -10,7 +10,7 @@ pub fn cannot_raise_literal(checker: &mut Checker, expr: &Expr) {
let ExprKind::Constant { .. } = &expr.node else { let ExprKind::Constant { .. } = &expr.node else {
return; return;
}; };
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CannotRaiseLiteral, violations::CannotRaiseLiteral,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -6,7 +6,7 @@ use crate::ast::helpers;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_generator::SourceCodeGenerator;
use crate::violations; use crate::violations;
@ -41,10 +41,10 @@ fn duplicate_handler_exceptions<'a>(
} }
} }
if checker.settings.enabled.contains(&CheckCode::B014) { if checker.settings.enabled.contains(&RuleCode::B014) {
// TODO(charlie): Handle "BaseException" and redundant exception aliases. // TODO(charlie): Handle "BaseException" and redundant exception aliases.
if !duplicates.is_empty() { if !duplicates.is_empty() {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::DuplicateHandlerException( violations::DuplicateHandlerException(
duplicates duplicates
.into_iter() .into_iter()
@ -67,7 +67,7 @@ fn duplicate_handler_exceptions<'a>(
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
@ -105,10 +105,10 @@ pub fn duplicate_exceptions(checker: &mut Checker, handlers: &[Excepthandler]) {
} }
} }
if checker.settings.enabled.contains(&CheckCode::B025) { if checker.settings.enabled.contains(&RuleCode::B025) {
for (name, exprs) in duplicates { for (name, exprs) in duplicates {
for expr in exprs { for expr in exprs {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::DuplicateTryBlockException(name.join(".")), violations::DuplicateTryBlockException(name.join(".")),
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{ExprKind, Stmt, StmtKind};
use crate::ast::helpers; use crate::ast::helpers;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B021 /// B021
@ -16,7 +16,7 @@ pub fn f_string_docstring(checker: &mut Checker, body: &[Stmt]) {
let ExprKind::JoinedStr { .. } = value.node else { let ExprKind::JoinedStr { .. } = value.node else {
return; return;
}; };
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FStringDocstring, violations::FStringDocstring,
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
)); ));

View File

@ -9,7 +9,7 @@ use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::flake8_bugbear::plugins::mutable_argument_default::is_mutable_func; use crate::flake8_bugbear::plugins::mutable_argument_default::is_mutable_func;
use crate::registry::{Check, CheckKind}; use crate::registry::{Diagnostic, DiagnosticKind};
use crate::violations; use crate::violations;
const IMMUTABLE_FUNCS: [(&str, &str); 7] = [ const IMMUTABLE_FUNCS: [(&str, &str); 7] = [
@ -36,7 +36,7 @@ fn is_immutable_func(
} }
struct ArgumentDefaultVisitor<'a> { struct ArgumentDefaultVisitor<'a> {
checks: Vec<(CheckKind, Range)>, checks: Vec<(DiagnosticKind, Range)>,
extend_immutable_calls: &'a [(&'a str, &'a str)], extend_immutable_calls: &'a [(&'a str, &'a str)],
from_imports: &'a FxHashMap<&'a str, FxHashSet<&'a str>>, from_imports: &'a FxHashMap<&'a str, FxHashSet<&'a str>>,
import_aliases: &'a FxHashMap<&'a str, &'a str>, import_aliases: &'a FxHashMap<&'a str, &'a str>,
@ -118,6 +118,6 @@ pub fn function_call_argument_default(checker: &mut Checker, arguments: &Argumen
visitor.visit_expr(expr); visitor.visit_expr(expr);
} }
for (check, range) in visitor.checks { for (check, range) in visitor.checks {
checker.checks.push(Check::new(check, range)); checker.diagnostics.push(Diagnostic::new(check, range));
} }
} }

View File

@ -6,7 +6,7 @@ use crate::ast::types::{Node, Range};
use crate::ast::visitor; use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
#[derive(Default)] #[derive(Default)]
@ -212,7 +212,7 @@ where
if reassigned_in_loop.contains(name) { if reassigned_in_loop.contains(name) {
if !checker.flake8_bugbear_seen.contains(&expr) { if !checker.flake8_bugbear_seen.contains(&expr) {
checker.flake8_bugbear_seen.push(expr); checker.flake8_bugbear_seen.push(expr);
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FunctionUsesLoopVariable(name.to_string()), violations::FunctionUsesLoopVariable(name.to_string()),
range, range,
)); ));

View File

@ -5,7 +5,7 @@ use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::python::identifiers::IDENTIFIER_REGEX; use crate::python::identifiers::IDENTIFIER_REGEX;
use crate::python::keyword::KWLIST; use crate::python::keyword::KWLIST;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_generator::SourceCodeGenerator;
use crate::violations; use crate::violations;
@ -45,7 +45,7 @@ pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
return; return;
} }
let mut check = Check::new(violations::GetAttrWithConstant, Range::from_located(expr)); let mut check = Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) { if checker.patch(check.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&attribute(obj, value), 0); generator.unparse_expr(&attribute(obj, value), 0);
@ -55,5 +55,5 @@ pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }

View File

@ -2,13 +2,13 @@ use rustpython_ast::{Stmt, StmtKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
fn walk_stmt(checker: &mut Checker, body: &[Stmt], f: fn(&Stmt) -> bool) { fn walk_stmt(checker: &mut Checker, body: &[Stmt], f: fn(&Stmt) -> bool) {
for stmt in body { for stmt in body {
if f(stmt) { if f(stmt) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::JumpStatementInFinally(match &stmt.node { violations::JumpStatementInFinally(match &stmt.node {
StmtKind::Break { .. } => "break".to_string(), StmtKind::Break { .. } => "break".to_string(),
StmtKind::Continue { .. } => "continue".to_string(), StmtKind::Continue { .. } => "continue".to_string(),

View File

@ -5,7 +5,7 @@ use crate::ast::types::Range;
use crate::ast::visitor; use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
#[derive(Default)] #[derive(Default)]
@ -56,7 +56,7 @@ pub fn loop_variable_overrides_iterator(checker: &mut Checker, target: &Expr, it
for (name, expr) in target_names { for (name, expr) in target_names {
if iter_names.contains_key(name) { if iter_names.contains_key(name) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::LoopVariableOverridesIterator(name.to_string()), violations::LoopVariableOverridesIterator(name.to_string()),
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -4,7 +4,7 @@ use rustpython_ast::{Arguments, Constant, Expr, ExprKind, Operator};
use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const MUTABLE_FUNCS: &[(&str, &str)] = &[ const MUTABLE_FUNCS: &[(&str, &str)] = &[
@ -165,7 +165,7 @@ pub fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) {
!is_immutable_annotation(expr, &checker.from_imports, &checker.import_aliases) !is_immutable_annotation(expr, &checker.from_imports, &checker.import_aliases)
}) })
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MutableArgumentDefault, violations::MutableArgumentDefault,
Range::from_located(default), Range::from_located(default),
)); ));

View File

@ -4,11 +4,11 @@ use crate::ast::types::Range;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::python::string::is_lower; use crate::python::string::is_lower;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
struct RaiseVisitor { struct RaiseVisitor {
checks: Vec<Check>, checks: Vec<Diagnostic>,
} }
impl<'a> Visitor<'a> for RaiseVisitor { impl<'a> Visitor<'a> for RaiseVisitor {
@ -20,7 +20,7 @@ impl<'a> Visitor<'a> for RaiseVisitor {
} => match &exc.node { } => match &exc.node {
ExprKind::Name { id, .. } if is_lower(id) => {} ExprKind::Name { id, .. } if is_lower(id) => {}
_ => { _ => {
self.checks.push(Check::new( self.checks.push(Diagnostic::new(
violations::RaiseWithoutFromInsideExcept, violations::RaiseWithoutFromInsideExcept,
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -50,5 +50,5 @@ pub fn raise_without_from_inside_except(checker: &mut Checker, body: &[Stmt]) {
for stmt in body { for stmt in body {
visitor.visit_stmt(stmt); visitor.visit_stmt(stmt);
} }
checker.checks.extend(visitor.checks); checker.diagnostics.extend(visitor.checks);
} }

View File

@ -3,7 +3,7 @@ use rustpython_ast::{Excepthandler, ExcepthandlerKind, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_generator::SourceCodeGenerator;
use crate::violations; use crate::violations;
@ -19,7 +19,7 @@ pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[E
let [elt] = &elts[..] else { let [elt] = &elts[..] else {
continue; continue;
}; };
let mut check = Check::new( let mut check = Diagnostic::new(
violations::RedundantTupleInExceptionHandler(elt.to_string()), violations::RedundantTupleInExceptionHandler(elt.to_string()),
Range::from_located(type_), Range::from_located(type_),
); );
@ -32,6 +32,6 @@ pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[E
type_.end_location.unwrap(), type_.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }

View File

@ -5,7 +5,7 @@ use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::python::identifiers::IDENTIFIER_REGEX; use crate::python::identifiers::IDENTIFIER_REGEX;
use crate::python::keyword::KWLIST; use crate::python::keyword::KWLIST;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_generator::SourceCodeGenerator;
use crate::source_code_style::SourceCodeStyleDetector; use crate::source_code_style::SourceCodeStyleDetector;
use crate::violations; use crate::violations;
@ -61,7 +61,8 @@ pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
// (i.e., it's directly within an `StmtKind::Expr`). // (i.e., it's directly within an `StmtKind::Expr`).
if let StmtKind::Expr { value: child } = &checker.current_stmt().node { if let StmtKind::Expr { value: child } = &checker.current_stmt().node {
if expr == child.as_ref() { if expr == child.as_ref() {
let mut check = Check::new(violations::SetAttrWithConstant, Range::from_located(expr)); let mut check =
Diagnostic::new(violations::SetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) { if checker.patch(check.kind.code()) {
check.amend(Fix::replacement( check.amend(Fix::replacement(
assignment(obj, name, value, checker.style), assignment(obj, name, value, checker.style),
@ -69,7 +70,7 @@ pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
} }

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind, Keyword};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B026 /// B026
@ -21,7 +21,7 @@ pub fn star_arg_unpacking_after_keyword_arg(
if arg.location <= keyword.location { if arg.location <= keyword.location {
continue; continue;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::StarArgUnpackingAfterKeywordArg, violations::StarArgUnpackingAfterKeywordArg,
Range::from_located(arg), Range::from_located(arg),
)); ));

View File

@ -3,7 +3,7 @@ use rustpython_ast::{Constant, Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B005 /// B005
@ -26,7 +26,7 @@ pub fn strip_with_multi_characters(checker: &mut Checker, expr: &Expr, func: &Ex
}; };
if value.len() > 1 && value.chars().unique().count() != value.len() { if value.len() > 1 && value.chars().unique().count() != value.len() {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::StripWithMultiCharacters, violations::StripWithMultiCharacters,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind, Unaryop};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B002 /// B002
@ -16,7 +16,7 @@ pub fn unary_prefix_increment(checker: &mut Checker, expr: &Expr, op: &Unaryop,
if !matches!(op, Unaryop::UAdd) { if !matches!(op, Unaryop::UAdd) {
return; return;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UnaryPrefixIncrement, violations::UnaryPrefixIncrement,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Constant, Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B004 /// B004
@ -26,7 +26,7 @@ pub fn unreliable_callable_check(checker: &mut Checker, expr: &Expr, func: &Expr
if s != "__call__" { if s != "__call__" {
return; return;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UnreliableCallableCheck, violations::UnreliableCallableCheck,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -6,7 +6,7 @@ use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// Identify all `ExprKind::Name` nodes in an AST. /// Identify all `ExprKind::Name` nodes in an AST.
@ -62,7 +62,7 @@ pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body:
continue; continue;
} }
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnusedLoopControlVariable(name.to_string()), violations::UnusedLoopControlVariable(name.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
@ -74,6 +74,6 @@ pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body:
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }

View File

@ -2,12 +2,12 @@ use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
pub fn useless_comparison(checker: &mut Checker, expr: &Expr) { pub fn useless_comparison(checker: &mut Checker, expr: &Expr) {
if matches!(expr.node, ExprKind::Compare { .. }) { if matches!(expr.node, ExprKind::Compare { .. }) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UselessComparison, violations::UselessComparison,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -3,7 +3,7 @@ use rustpython_ast::Expr;
use crate::ast::helpers::{collect_call_paths, match_call_path}; use crate::ast::helpers::{collect_call_paths, match_call_path};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B005 /// B005
@ -15,7 +15,7 @@ pub fn useless_contextlib_suppress(checker: &mut Checker, expr: &Expr, args: &[E
&checker.from_imports, &checker.from_imports,
) && args.is_empty() ) && args.is_empty()
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UselessContextlibSuppress, violations::UselessContextlibSuppress,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Constant, ExprKind, Stmt, StmtKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
// B018 // B018
@ -11,7 +11,7 @@ pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) {
if let StmtKind::Expr { value } = &stmt.node { if let StmtKind::Expr { value } = &stmt.node {
match &value.node { match &value.node {
ExprKind::List { .. } | ExprKind::Dict { .. } | ExprKind::Set { .. } => { ExprKind::List { .. } | ExprKind::Dict { .. } | ExprKind::Set { .. } => {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UselessExpression, violations::UselessExpression,
Range::from_located(value), Range::from_located(value),
)); ));
@ -19,7 +19,7 @@ pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) {
ExprKind::Constant { value: val, .. } => match &val { ExprKind::Constant { value: val, .. } => match &val {
Constant::Str { .. } | Constant::Ellipsis => {} Constant::Str { .. } | Constant::Ellipsis => {}
_ => { _ => {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UselessExpression, violations::UselessExpression,
Range::from_located(value), Range::from_located(value),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind, Keyword};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// B905 /// B905
@ -23,7 +23,7 @@ pub fn zip_without_explicit_strict(
.map_or(false, |name| name == "strict") .map_or(false, |name| name == "strict")
}) })
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ZipWithoutExplicitStrict, violations::ZipWithoutExplicitStrict,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -3,7 +3,7 @@ use rustpython_ast::Located;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_builtins::types::ShadowingType; use crate::flake8_builtins::types::ShadowingType;
use crate::python::builtins::BUILTINS; use crate::python::builtins::BUILTINS;
use crate::registry::{Check, CheckKind}; use crate::registry::{Diagnostic, DiagnosticKind};
use crate::violations; use crate::violations;
/// Check builtin name shadowing. /// Check builtin name shadowing.
@ -11,9 +11,9 @@ pub fn builtin_shadowing<T>(
name: &str, name: &str,
located: &Located<T>, located: &Located<T>,
node_type: ShadowingType, node_type: ShadowingType,
) -> Option<Check> { ) -> Option<Diagnostic> {
if BUILTINS.contains(&name) { if BUILTINS.contains(&name) {
Some(Check::new::<CheckKind>( Some(Diagnostic::new::<DiagnosticKind>(
match node_type { match node_type {
ShadowingType::Variable => { ShadowingType::Variable => {
violations::BuiltinVariableShadowing(name.to_string()).into() violations::BuiltinVariableShadowing(name.to_string()).into()

View File

@ -10,21 +10,21 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::A001, Path::new("A001.py"); "A001")] #[test_case(RuleCode::A001, Path::new("A001.py"); "A001")]
#[test_case(CheckCode::A002, Path::new("A002.py"); "A002")] #[test_case(RuleCode::A002, Path::new("A002.py"); "A002")]
#[test_case(CheckCode::A003, Path::new("A003.py"); "A003")] #[test_case(RuleCode::A003, Path::new("A003.py"); "A003")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_builtins") Path::new("./resources/test/fixtures/flake8_builtins")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -6,7 +6,7 @@ use rustpython_ast::{
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_comprehensions::fixes; use crate::flake8_comprehensions::fixes;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_locator::SourceCodeLocator; use crate::source_code_locator::SourceCodeLocator;
use crate::violations; use crate::violations;
@ -56,10 +56,10 @@ pub fn unnecessary_generator_list(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?;
if let ExprKind::GeneratorExp { .. } = argument { if let ExprKind::GeneratorExp { .. } = argument {
let mut check = Check::new(violations::UnnecessaryGeneratorList, location); let mut check = Diagnostic::new(violations::UnnecessaryGeneratorList, location);
if fix { if fix {
match fixes::fix_unnecessary_generator_list(locator, expr) { match fixes::fix_unnecessary_generator_list(locator, expr) {
Ok(fix) => { Ok(fix) => {
@ -82,10 +82,10 @@ pub fn unnecessary_generator_set(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
if let ExprKind::GeneratorExp { .. } = argument { if let ExprKind::GeneratorExp { .. } = argument {
let mut check = Check::new(violations::UnnecessaryGeneratorSet, location); let mut check = Diagnostic::new(violations::UnnecessaryGeneratorSet, location);
if fix { if fix {
match fixes::fix_unnecessary_generator_set(locator, expr) { match fixes::fix_unnecessary_generator_set(locator, expr) {
Ok(fix) => { Ok(fix) => {
@ -108,12 +108,12 @@ pub fn unnecessary_generator_dict(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?;
if let ExprKind::GeneratorExp { elt, .. } = argument { if let ExprKind::GeneratorExp { elt, .. } = argument {
match &elt.node { match &elt.node {
ExprKind::Tuple { elts, .. } if elts.len() == 2 => { ExprKind::Tuple { elts, .. } if elts.len() == 2 => {
let mut check = Check::new(violations::UnnecessaryGeneratorDict, location); let mut check = Diagnostic::new(violations::UnnecessaryGeneratorDict, location);
if fix { if fix {
match fixes::fix_unnecessary_generator_dict(locator, expr) { match fixes::fix_unnecessary_generator_dict(locator, expr) {
Ok(fix) => { Ok(fix) => {
@ -139,10 +139,10 @@ pub fn unnecessary_list_comprehension_set(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
if let ExprKind::ListComp { .. } = &argument { if let ExprKind::ListComp { .. } = &argument {
let mut check = Check::new(violations::UnnecessaryListComprehensionSet, location); let mut check = Diagnostic::new(violations::UnnecessaryListComprehensionSet, location);
if fix { if fix {
match fixes::fix_unnecessary_list_comprehension_set(locator, expr) { match fixes::fix_unnecessary_list_comprehension_set(locator, expr) {
Ok(fix) => { Ok(fix) => {
@ -165,7 +165,7 @@ pub fn unnecessary_list_comprehension_dict(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?;
let ExprKind::ListComp { elt, .. } = &argument else { let ExprKind::ListComp { elt, .. } = &argument else {
return None; return None;
@ -176,7 +176,7 @@ pub fn unnecessary_list_comprehension_dict(
if elts.len() != 2 { if elts.len() != 2 {
return None; return None;
} }
let mut check = Check::new(violations::UnnecessaryListComprehensionDict, location); let mut check = Diagnostic::new(violations::UnnecessaryListComprehensionDict, location);
if fix { if fix {
match fixes::fix_unnecessary_list_comprehension_dict(locator, expr) { match fixes::fix_unnecessary_list_comprehension_dict(locator, expr) {
Ok(fix) => { Ok(fix) => {
@ -197,14 +197,14 @@ pub fn unnecessary_literal_set(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
let kind = match argument { let kind = match argument {
ExprKind::List { .. } => "list", ExprKind::List { .. } => "list",
ExprKind::Tuple { .. } => "tuple", ExprKind::Tuple { .. } => "tuple",
_ => return None, _ => return None,
}; };
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryLiteralSet(kind.to_string()), violations::UnnecessaryLiteralSet(kind.to_string()),
location, location,
); );
@ -228,7 +228,7 @@ pub fn unnecessary_literal_dict(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("dict", func, args, keywords)?;
let (kind, elts) = match argument { let (kind, elts) = match argument {
ExprKind::Tuple { elts, .. } => ("tuple", elts), ExprKind::Tuple { elts, .. } => ("tuple", elts),
@ -242,7 +242,7 @@ pub fn unnecessary_literal_dict(
{ {
return None; return None;
} }
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryLiteralDict(kind.to_string()), violations::UnnecessaryLiteralDict(kind.to_string()),
location, location,
); );
@ -266,7 +266,7 @@ pub fn unnecessary_collection_call(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
if !args.is_empty() { if !args.is_empty() {
return None; return None;
} }
@ -280,7 +280,7 @@ pub fn unnecessary_collection_call(
} }
_ => return None, _ => return None,
}; };
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryCollectionCall(id.to_string()), violations::UnnecessaryCollectionCall(id.to_string()),
location, location,
); );
@ -303,14 +303,14 @@ pub fn unnecessary_literal_within_tuple_call(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = first_argument_with_matching_function("tuple", func, args)?; let argument = first_argument_with_matching_function("tuple", func, args)?;
let argument_kind = match argument { let argument_kind = match argument {
ExprKind::Tuple { .. } => "tuple", ExprKind::Tuple { .. } => "tuple",
ExprKind::List { .. } => "list", ExprKind::List { .. } => "list",
_ => return None, _ => return None,
}; };
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()), violations::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()),
location, location,
); );
@ -333,14 +333,14 @@ pub fn unnecessary_literal_within_list_call(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = first_argument_with_matching_function("list", func, args)?; let argument = first_argument_with_matching_function("list", func, args)?;
let argument_kind = match argument { let argument_kind = match argument {
ExprKind::Tuple { .. } => "tuple", ExprKind::Tuple { .. } => "tuple",
ExprKind::List { .. } => "list", ExprKind::List { .. } => "list",
_ => return None, _ => return None,
}; };
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryLiteralWithinListCall(argument_kind.to_string()), violations::UnnecessaryLiteralWithinListCall(argument_kind.to_string()),
location, location,
); );
@ -363,12 +363,12 @@ pub fn unnecessary_list_call(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let argument = first_argument_with_matching_function("list", func, args)?; let argument = first_argument_with_matching_function("list", func, args)?;
if !matches!(argument, ExprKind::ListComp { .. }) { if !matches!(argument, ExprKind::ListComp { .. }) {
return None; return None;
} }
let mut check = Check::new(violations::UnnecessaryListCall, location); let mut check = Diagnostic::new(violations::UnnecessaryListCall, location);
if fix { if fix {
match fixes::fix_unnecessary_list_call(locator, expr) { match fixes::fix_unnecessary_list_call(locator, expr) {
Ok(fix) => { Ok(fix) => {
@ -388,7 +388,7 @@ pub fn unnecessary_call_around_sorted(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let outer = function_name(func)?; let outer = function_name(func)?;
if !(outer == "list" || outer == "reversed") { if !(outer == "list" || outer == "reversed") {
return None; return None;
@ -400,7 +400,7 @@ pub fn unnecessary_call_around_sorted(
return None; return None;
} }
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryCallAroundSorted(outer.to_string()), violations::UnnecessaryCallAroundSorted(outer.to_string()),
location, location,
); );
@ -420,9 +420,9 @@ pub fn unnecessary_double_cast_or_process(
func: &Expr, func: &Expr,
args: &[Expr], args: &[Expr],
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
fn new_check(inner: &str, outer: &str, location: Range) -> Check { fn new_check(inner: &str, outer: &str, location: Range) -> Diagnostic {
Check::new( Diagnostic::new(
violations::UnnecessaryDoubleCastOrProcess(inner.to_string(), outer.to_string()), violations::UnnecessaryDoubleCastOrProcess(inner.to_string(), outer.to_string()),
location, location,
) )
@ -463,7 +463,7 @@ pub fn unnecessary_subscript_reversal(
func: &Expr, func: &Expr,
args: &[Expr], args: &[Expr],
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
let first_arg = args.first()?; let first_arg = args.first()?;
let id = function_name(func)?; let id = function_name(func)?;
if !["set", "sorted", "reversed"].contains(&id) { if !["set", "sorted", "reversed"].contains(&id) {
@ -493,7 +493,7 @@ pub fn unnecessary_subscript_reversal(
if *val != BigInt::from(1) { if *val != BigInt::from(1) {
return None; return None;
}; };
Some(Check::new( Some(Diagnostic::new(
violations::UnnecessarySubscriptReversal(id.to_string()), violations::UnnecessarySubscriptReversal(id.to_string()),
location, location,
)) ))
@ -507,7 +507,7 @@ pub fn unnecessary_comprehension(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
fix: bool, fix: bool,
location: Range, location: Range,
) -> Option<Check> { ) -> Option<Diagnostic> {
if generators.len() != 1 { if generators.len() != 1 {
return None; return None;
} }
@ -525,7 +525,7 @@ pub fn unnecessary_comprehension(
ExprKind::SetComp { .. } => "set", ExprKind::SetComp { .. } => "set",
_ => return None, _ => return None,
}; };
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnnecessaryComprehension(expr_kind.to_string()), violations::UnnecessaryComprehension(expr_kind.to_string()),
location, location,
); );
@ -541,9 +541,9 @@ pub fn unnecessary_comprehension(
} }
/// C417 /// C417
pub fn unnecessary_map(func: &Expr, args: &[Expr], location: Range) -> Option<Check> { pub fn unnecessary_map(func: &Expr, args: &[Expr], location: Range) -> Option<Diagnostic> {
fn new_check(kind: &str, location: Range) -> Check { fn new_check(kind: &str, location: Range) -> Diagnostic {
Check::new(violations::UnnecessaryMap(kind.to_string()), location) Diagnostic::new(violations::UnnecessaryMap(kind.to_string()), location)
} }
let id = function_name(func)?; let id = function_name(func)?;
match id { match id {

View File

@ -10,35 +10,35 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::C400, Path::new("C400.py"); "C400")] #[test_case(RuleCode::C400, Path::new("C400.py"); "C400")]
#[test_case(CheckCode::C401, Path::new("C401.py"); "C401")] #[test_case(RuleCode::C401, Path::new("C401.py"); "C401")]
#[test_case(CheckCode::C402, Path::new("C402.py"); "C402")] #[test_case(RuleCode::C402, Path::new("C402.py"); "C402")]
#[test_case(CheckCode::C403, Path::new("C403.py"); "C403")] #[test_case(RuleCode::C403, Path::new("C403.py"); "C403")]
#[test_case(CheckCode::C404, Path::new("C404.py"); "C404")] #[test_case(RuleCode::C404, Path::new("C404.py"); "C404")]
#[test_case(CheckCode::C405, Path::new("C405.py"); "C405")] #[test_case(RuleCode::C405, Path::new("C405.py"); "C405")]
#[test_case(CheckCode::C406, Path::new("C406.py"); "C406")] #[test_case(RuleCode::C406, Path::new("C406.py"); "C406")]
#[test_case(CheckCode::C408, Path::new("C408.py"); "C408")] #[test_case(RuleCode::C408, Path::new("C408.py"); "C408")]
#[test_case(CheckCode::C409, Path::new("C409.py"); "C409")] #[test_case(RuleCode::C409, Path::new("C409.py"); "C409")]
#[test_case(CheckCode::C410, Path::new("C410.py"); "C410")] #[test_case(RuleCode::C410, Path::new("C410.py"); "C410")]
#[test_case(CheckCode::C411, Path::new("C411.py"); "C411")] #[test_case(RuleCode::C411, Path::new("C411.py"); "C411")]
#[test_case(CheckCode::C413, Path::new("C413.py"); "C413")] #[test_case(RuleCode::C413, Path::new("C413.py"); "C413")]
#[test_case(CheckCode::C414, Path::new("C414.py"); "C414")] #[test_case(RuleCode::C414, Path::new("C414.py"); "C414")]
#[test_case(CheckCode::C415, Path::new("C415.py"); "C415")] #[test_case(RuleCode::C415, Path::new("C415.py"); "C415")]
#[test_case(CheckCode::C416, Path::new("C416.py"); "C416")] #[test_case(RuleCode::C416, Path::new("C416.py"); "C416")]
#[test_case(CheckCode::C417, Path::new("C417.py"); "C417")] #[test_case(RuleCode::C417, Path::new("C417.py"); "C417")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_comprehensions") Path::new("./resources/test/fixtures/flake8_comprehensions")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -9,27 +9,27 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::DTZ001, Path::new("DTZ001.py"); "DTZ001")] #[test_case(RuleCode::DTZ001, Path::new("DTZ001.py"); "DTZ001")]
#[test_case(CheckCode::DTZ002, Path::new("DTZ002.py"); "DTZ002")] #[test_case(RuleCode::DTZ002, Path::new("DTZ002.py"); "DTZ002")]
#[test_case(CheckCode::DTZ003, Path::new("DTZ003.py"); "DTZ003")] #[test_case(RuleCode::DTZ003, Path::new("DTZ003.py"); "DTZ003")]
#[test_case(CheckCode::DTZ004, Path::new("DTZ004.py"); "DTZ004")] #[test_case(RuleCode::DTZ004, Path::new("DTZ004.py"); "DTZ004")]
#[test_case(CheckCode::DTZ005, Path::new("DTZ005.py"); "DTZ005")] #[test_case(RuleCode::DTZ005, Path::new("DTZ005.py"); "DTZ005")]
#[test_case(CheckCode::DTZ006, Path::new("DTZ006.py"); "DTZ006")] #[test_case(RuleCode::DTZ006, Path::new("DTZ006.py"); "DTZ006")]
#[test_case(CheckCode::DTZ007, Path::new("DTZ007.py"); "DTZ007")] #[test_case(RuleCode::DTZ007, Path::new("DTZ007.py"); "DTZ007")]
#[test_case(CheckCode::DTZ011, Path::new("DTZ011.py"); "DTZ011")] #[test_case(RuleCode::DTZ011, Path::new("DTZ011.py"); "DTZ011")]
#[test_case(CheckCode::DTZ012, Path::new("DTZ012.py"); "DTZ012")] #[test_case(RuleCode::DTZ012, Path::new("DTZ012.py"); "DTZ012")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_datetimez") Path::new("./resources/test/fixtures/flake8_datetimez")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -5,7 +5,7 @@ use crate::ast::helpers::{
}; };
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
pub fn call_datetime_without_tzinfo( pub fn call_datetime_without_tzinfo(
@ -22,17 +22,19 @@ pub fn call_datetime_without_tzinfo(
// No positional arg: keyword is missing or constant None. // No positional arg: keyword is missing or constant None.
if args.len() < 8 && !has_non_none_keyword(keywords, "tzinfo") { if args.len() < 8 && !has_non_none_keyword(keywords, "tzinfo") {
checker checker.diagnostics.push(Diagnostic::new(
.checks violations::CallDatetimeWithoutTzinfo,
.push(Check::new(violations::CallDatetimeWithoutTzinfo, location)); location,
));
return; return;
} }
// Positional arg: is constant None. // Positional arg: is constant None.
if args.len() >= 8 && is_const_none(&args[7]) { if args.len() >= 8 && is_const_none(&args[7]) {
checker checker.diagnostics.push(Diagnostic::new(
.checks violations::CallDatetimeWithoutTzinfo,
.push(Check::new(violations::CallDatetimeWithoutTzinfo, location)); location,
));
} }
} }
@ -46,8 +48,8 @@ pub fn call_datetime_today(checker: &mut Checker, func: &Expr, location: Range)
&checker.from_imports, &checker.from_imports,
) { ) {
checker checker
.checks .diagnostics
.push(Check::new(violations::CallDatetimeToday, location)); .push(Diagnostic::new(violations::CallDatetimeToday, location));
} }
} }
@ -61,8 +63,8 @@ pub fn call_datetime_utcnow(checker: &mut Checker, func: &Expr, location: Range)
&checker.from_imports, &checker.from_imports,
) { ) {
checker checker
.checks .diagnostics
.push(Check::new(violations::CallDatetimeUtcnow, location)); .push(Diagnostic::new(violations::CallDatetimeUtcnow, location));
} }
} }
@ -75,7 +77,7 @@ pub fn call_datetime_utcfromtimestamp(checker: &mut Checker, func: &Expr, locati
"utcfromtimestamp", "utcfromtimestamp",
&checker.from_imports, &checker.from_imports,
) { ) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CallDatetimeUtcfromtimestamp, violations::CallDatetimeUtcfromtimestamp,
location, location,
)); ));
@ -102,7 +104,7 @@ pub fn call_datetime_now_without_tzinfo(
// no args / no args unqualified // no args / no args unqualified
if args.is_empty() && keywords.is_empty() { if args.is_empty() && keywords.is_empty() {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CallDatetimeNowWithoutTzinfo, violations::CallDatetimeNowWithoutTzinfo,
location, location,
)); ));
@ -111,7 +113,7 @@ pub fn call_datetime_now_without_tzinfo(
// none args // none args
if !args.is_empty() && is_const_none(&args[0]) { if !args.is_empty() && is_const_none(&args[0]) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CallDatetimeNowWithoutTzinfo, violations::CallDatetimeNowWithoutTzinfo,
location, location,
)); ));
@ -120,7 +122,7 @@ pub fn call_datetime_now_without_tzinfo(
// wrong keywords / none keyword // wrong keywords / none keyword
if !keywords.is_empty() && !has_non_none_keyword(keywords, "tz") { if !keywords.is_empty() && !has_non_none_keyword(keywords, "tz") {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CallDatetimeNowWithoutTzinfo, violations::CallDatetimeNowWithoutTzinfo,
location, location,
)); ));
@ -147,25 +149,28 @@ pub fn call_datetime_fromtimestamp(
// no args / no args unqualified // no args / no args unqualified
if args.len() < 2 && keywords.is_empty() { if args.len() < 2 && keywords.is_empty() {
checker checker.diagnostics.push(Diagnostic::new(
.checks violations::CallDatetimeFromtimestamp,
.push(Check::new(violations::CallDatetimeFromtimestamp, location)); location,
));
return; return;
} }
// none args // none args
if args.len() > 1 && is_const_none(&args[1]) { if args.len() > 1 && is_const_none(&args[1]) {
checker checker.diagnostics.push(Diagnostic::new(
.checks violations::CallDatetimeFromtimestamp,
.push(Check::new(violations::CallDatetimeFromtimestamp, location)); location,
));
return; return;
} }
// wrong keywords / none keyword // wrong keywords / none keyword
if !keywords.is_empty() && !has_non_none_keyword(keywords, "tz") { if !keywords.is_empty() && !has_non_none_keyword(keywords, "tz") {
checker checker.diagnostics.push(Diagnostic::new(
.checks violations::CallDatetimeFromtimestamp,
.push(Check::new(violations::CallDatetimeFromtimestamp, location)); location,
));
} }
} }
@ -198,7 +203,7 @@ pub fn call_datetime_strptime_without_zone(
}; };
let (Some(grandparent), Some(parent)) = (checker.current_expr_grandparent(), checker.current_expr_parent()) else { let (Some(grandparent), Some(parent)) = (checker.current_expr_grandparent(), checker.current_expr_parent()) else {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CallDatetimeStrptimeWithoutZone, violations::CallDatetimeStrptimeWithoutZone,
location, location,
)); ));
@ -221,7 +226,7 @@ pub fn call_datetime_strptime_without_zone(
} }
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::CallDatetimeStrptimeWithoutZone, violations::CallDatetimeStrptimeWithoutZone,
location, location,
)); ));
@ -232,8 +237,8 @@ pub fn call_date_today(checker: &mut Checker, func: &Expr, location: Range) {
let call_path = dealias_call_path(collect_call_paths(func), &checker.import_aliases); let call_path = dealias_call_path(collect_call_paths(func), &checker.import_aliases);
if match_call_path(&call_path, "datetime.date", "today", &checker.from_imports) { if match_call_path(&call_path, "datetime.date", "today", &checker.from_imports) {
checker checker
.checks .diagnostics
.push(Check::new(violations::CallDateToday, location)); .push(Diagnostic::new(violations::CallDateToday, location));
} }
} }
@ -247,7 +252,7 @@ pub fn call_date_fromtimestamp(checker: &mut Checker, func: &Expr, location: Ran
&checker.from_imports, &checker.from_imports,
) { ) {
checker checker
.checks .diagnostics
.push(Check::new(violations::CallDateFromtimestamp, location)); .push(Diagnostic::new(violations::CallDateFromtimestamp, location));
} }
} }

View File

@ -4,7 +4,7 @@ use rustpython_ast::{Expr, Stmt};
use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path}; use crate::ast::helpers::{collect_call_paths, dealias_call_path, match_call_path};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_debugger::types::DebuggerUsingType; use crate::flake8_debugger::types::DebuggerUsingType;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const DEBUGGERS: &[(&str, &str)] = &[ const DEBUGGERS: &[(&str, &str)] = &[
@ -25,13 +25,13 @@ pub fn debugger_call(
func: &Expr, func: &Expr,
from_imports: &FxHashMap<&str, FxHashSet<&str>>, from_imports: &FxHashMap<&str, FxHashSet<&str>>,
import_aliases: &FxHashMap<&str, &str>, import_aliases: &FxHashMap<&str, &str>,
) -> Option<Check> { ) -> Option<Diagnostic> {
let call_path = dealias_call_path(collect_call_paths(func), import_aliases); let call_path = dealias_call_path(collect_call_paths(func), import_aliases);
if DEBUGGERS if DEBUGGERS
.iter() .iter()
.any(|(module, member)| match_call_path(&call_path, module, member, from_imports)) .any(|(module, member)| match_call_path(&call_path, module, member, from_imports))
{ {
Some(Check::new( Some(Diagnostic::new(
violations::Debugger(DebuggerUsingType::Call(call_path.join("."))), violations::Debugger(DebuggerUsingType::Call(call_path.join("."))),
Range::from_located(expr), Range::from_located(expr),
)) ))
@ -41,7 +41,7 @@ pub fn debugger_call(
} }
/// Checks for the presence of a debugger import. /// Checks for the presence of a debugger import.
pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option<Check> { pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option<Diagnostic> {
// Special-case: allow `import builtins`, which is far more general than (e.g.) // Special-case: allow `import builtins`, which is far more general than (e.g.)
// `import celery.contrib.rdb`). // `import celery.contrib.rdb`).
if module.is_none() && name == "builtins" { if module.is_none() && name == "builtins" {
@ -53,7 +53,7 @@ pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option<
.iter() .iter()
.find(|(module_name, member)| module_name == &module && member == &name) .find(|(module_name, member)| module_name == &module && member == &name)
{ {
return Some(Check::new( return Some(Diagnostic::new(
violations::Debugger(DebuggerUsingType::Import(format!("{module_name}.{member}"))), violations::Debugger(DebuggerUsingType::Import(format!("{module_name}.{member}"))),
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -62,7 +62,7 @@ pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option<
.iter() .iter()
.any(|(module_name, ..)| module_name == &name) .any(|(module_name, ..)| module_name == &name)
{ {
return Some(Check::new( return Some(Diagnostic::new(
violations::Debugger(DebuggerUsingType::Import(name.to_string())), violations::Debugger(DebuggerUsingType::Import(name.to_string())),
Range::from_located(stmt), Range::from_located(stmt),
)); ));

View File

@ -10,19 +10,19 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::T100, Path::new("T100.py"); "T100")] #[test_case(RuleCode::T100, Path::new("T100.py"); "T100")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_debugger") Path::new("./resources/test/fixtures/flake8_debugger")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -8,39 +8,35 @@ mod tests {
use anyhow::Result; use anyhow::Result;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::{flake8_errmsg, settings}; use crate::{flake8_errmsg, settings};
#[test] #[test]
fn defaults() -> Result<()> { fn defaults() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_errmsg/EM.py"), Path::new("./resources/test/fixtures/flake8_errmsg/EM.py"),
&settings::Settings::for_rules(vec![ &settings::Settings::for_rules(vec![RuleCode::EM101, RuleCode::EM102, RuleCode::EM103]),
CheckCode::EM101,
CheckCode::EM102,
CheckCode::EM103,
]),
)?; )?;
insta::assert_yaml_snapshot!("defaults", checks); insta::assert_yaml_snapshot!("defaults", diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn custom() -> Result<()> { fn custom() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_errmsg/EM.py"), Path::new("./resources/test/fixtures/flake8_errmsg/EM.py"),
&settings::Settings { &settings::Settings {
flake8_errmsg: flake8_errmsg::settings::Settings { flake8_errmsg: flake8_errmsg::settings::Settings {
max_string_length: 20, max_string_length: 20,
}, },
..settings::Settings::for_rules(vec![ ..settings::Settings::for_rules(vec![
CheckCode::EM101, RuleCode::EM101,
CheckCode::EM102, RuleCode::EM102,
CheckCode::EM103, RuleCode::EM103,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!("custom", checks); insta::assert_yaml_snapshot!("custom", diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -2,7 +2,7 @@ use rustpython_ast::{Constant, Expr, ExprKind};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
/// EM101, EM102, EM103 /// EM101, EM102, EM103
@ -15,9 +15,9 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) {
value: Constant::Str(string), value: Constant::Str(string),
.. ..
} => { } => {
if checker.settings.enabled.contains(&CheckCode::EM101) { if checker.settings.enabled.contains(&RuleCode::EM101) {
if string.len() > checker.settings.flake8_errmsg.max_string_length { if string.len() > checker.settings.flake8_errmsg.max_string_length {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::RawStringInException, violations::RawStringInException,
Range::from_located(first), Range::from_located(first),
)); ));
@ -26,8 +26,8 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) {
} }
// Check for f-strings // Check for f-strings
ExprKind::JoinedStr { .. } => { ExprKind::JoinedStr { .. } => {
if checker.settings.enabled.contains(&CheckCode::EM102) { if checker.settings.enabled.contains(&RuleCode::EM102) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FStringInException, violations::FStringInException,
Range::from_located(first), Range::from_located(first),
)); ));
@ -35,10 +35,10 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) {
} }
// Check for .format() calls // Check for .format() calls
ExprKind::Call { func, .. } => { ExprKind::Call { func, .. } => {
if checker.settings.enabled.contains(&CheckCode::EM103) { if checker.settings.enabled.contains(&RuleCode::EM103) {
if let ExprKind::Attribute { value, attr, .. } = &func.node { if let ExprKind::Attribute { value, attr, .. } = &func.node {
if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) { if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::DotFormatInException, violations::DotFormatInException,
Range::from_located(first), Range::from_located(first),
)); ));

View File

@ -3,19 +3,19 @@ use rustpython_ast::{Constant, Expr, ExprKind, Location, Operator};
use rustpython_parser::lexer::{LexResult, Tok}; use rustpython_parser::lexer::{LexResult, Tok};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_locator::SourceCodeLocator; use crate::source_code_locator::SourceCodeLocator;
use crate::violations; use crate::violations;
/// ISC001, ISC002 /// ISC001, ISC002
pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec<Check> { pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec<Diagnostic> {
let mut checks = vec![]; let mut diagnostics = vec![];
for ((a_start, a_tok, a_end), (b_start, b_tok, b_end)) in for ((a_start, a_tok, a_end), (b_start, b_tok, b_end)) in
tokens.iter().flatten().tuple_windows() tokens.iter().flatten().tuple_windows()
{ {
if matches!(a_tok, Tok::String { .. }) && matches!(b_tok, Tok::String { .. }) { if matches!(a_tok, Tok::String { .. }) && matches!(b_tok, Tok::String { .. }) {
if a_end.row() == b_start.row() { if a_end.row() == b_start.row() {
checks.push(Check::new( diagnostics.push(Diagnostic::new(
violations::SingleLineImplicitStringConcatenation, violations::SingleLineImplicitStringConcatenation,
Range { Range {
location: *a_start, location: *a_start,
@ -30,7 +30,7 @@ pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec<Check>
end_location: Location::new(a_end.row() + 1, 0), end_location: Location::new(a_end.row() + 1, 0),
}); });
if contents.trim_end().ends_with('\\') { if contents.trim_end().ends_with('\\') {
checks.push(Check::new( diagnostics.push(Diagnostic::new(
violations::MultiLineImplicitStringConcatenation, violations::MultiLineImplicitStringConcatenation,
Range { Range {
location: *a_start, location: *a_start,
@ -41,11 +41,11 @@ pub fn implicit(tokens: &[LexResult], locator: &SourceCodeLocator) -> Vec<Check>
} }
} }
} }
checks diagnostics
} }
/// ISC003 /// ISC003
pub fn explicit(expr: &Expr) -> Option<Check> { pub fn explicit(expr: &Expr) -> Option<Diagnostic> {
if let ExprKind::BinOp { left, op, right } = &expr.node { if let ExprKind::BinOp { left, op, right } = &expr.node {
if matches!(op, Operator::Add) { if matches!(op, Operator::Add) {
if matches!( if matches!(
@ -63,7 +63,7 @@ pub fn explicit(expr: &Expr) -> Option<Check> {
.. ..
} }
) { ) {
return Some(Check::new( return Some(Diagnostic::new(
violations::ExplicitStringConcatenation, violations::ExplicitStringConcatenation,
Range::from_located(expr), Range::from_located(expr),
)); ));

View File

@ -9,21 +9,21 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::ISC001, Path::new("ISC.py"); "ISC001")] #[test_case(RuleCode::ISC001, Path::new("ISC.py"); "ISC001")]
#[test_case(CheckCode::ISC002, Path::new("ISC.py"); "ISC002")] #[test_case(RuleCode::ISC002, Path::new("ISC.py"); "ISC002")]
#[test_case(CheckCode::ISC003, Path::new("ISC.py"); "ISC003")] #[test_case(RuleCode::ISC003, Path::new("ISC.py"); "ISC003")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_implicit_str_concat") Path::new("./resources/test/fixtures/flake8_implicit_str_concat")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -2,7 +2,7 @@ use rustc_hash::FxHashMap;
use rustpython_ast::Stmt; use rustpython_ast::Stmt;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// ICN001 /// ICN001
@ -11,7 +11,7 @@ pub fn check_conventional_import(
name: &str, name: &str,
asname: Option<&str>, asname: Option<&str>,
conventions: &FxHashMap<String, String>, conventions: &FxHashMap<String, String>,
) -> Option<Check> { ) -> Option<Diagnostic> {
let mut is_valid_import = true; let mut is_valid_import = true;
if let Some(expected_alias) = conventions.get(name) { if let Some(expected_alias) = conventions.get(name) {
if !expected_alias.is_empty() { if !expected_alias.is_empty() {
@ -24,7 +24,7 @@ pub fn check_conventional_import(
} }
} }
if !is_valid_import { if !is_valid_import {
return Some(Check::new( return Some(Diagnostic::new(
violations::ImportAliasIsNotConventional( violations::ImportAliasIsNotConventional(
name.to_string(), name.to_string(),
expected_alias.to_string(), expected_alias.to_string(),

View File

@ -10,22 +10,22 @@ mod tests {
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::{flake8_import_conventions, Settings}; use crate::{flake8_import_conventions, Settings};
#[test] #[test]
fn defaults() -> Result<()> { fn defaults() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_import_conventions/defaults.py"), Path::new("./resources/test/fixtures/flake8_import_conventions/defaults.py"),
&Settings::for_rule(CheckCode::ICN001), &Settings::for_rule(RuleCode::ICN001),
)?; )?;
insta::assert_yaml_snapshot!("defaults", checks); insta::assert_yaml_snapshot!("defaults", diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn custom() -> Result<()> { fn custom() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_import_conventions/custom.py"), Path::new("./resources/test/fixtures/flake8_import_conventions/custom.py"),
&Settings { &Settings {
flake8_import_conventions: flake8_import_conventions::settings::Options { flake8_import_conventions: flake8_import_conventions::settings::Options {
@ -36,16 +36,16 @@ mod tests {
])), ])),
} }
.into(), .into(),
..Settings::for_rule(CheckCode::ICN001) ..Settings::for_rule(RuleCode::ICN001)
}, },
)?; )?;
insta::assert_yaml_snapshot!("custom", checks); insta::assert_yaml_snapshot!("custom", diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn remove_defaults() -> Result<()> { fn remove_defaults() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_import_conventions/remove_default.py"), Path::new("./resources/test/fixtures/flake8_import_conventions/remove_default.py"),
&Settings { &Settings {
flake8_import_conventions: flake8_import_conventions::settings::Options { flake8_import_conventions: flake8_import_conventions::settings::Options {
@ -58,16 +58,16 @@ mod tests {
extend_aliases: None, extend_aliases: None,
} }
.into(), .into(),
..Settings::for_rule(CheckCode::ICN001) ..Settings::for_rule(RuleCode::ICN001)
}, },
)?; )?;
insta::assert_yaml_snapshot!("remove_default", checks); insta::assert_yaml_snapshot!("remove_default", diagnostics);
Ok(()) Ok(())
} }
#[test] #[test]
fn override_defaults() -> Result<()> { fn override_defaults() -> Result<()> {
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_import_conventions/override_default.py"), Path::new("./resources/test/fixtures/flake8_import_conventions/override_default.py"),
&Settings { &Settings {
flake8_import_conventions: flake8_import_conventions::settings::Options { flake8_import_conventions: flake8_import_conventions::settings::Options {
@ -78,10 +78,10 @@ mod tests {
)])), )])),
} }
.into(), .into(),
..Settings::for_rule(CheckCode::ICN001) ..Settings::for_rule(RuleCode::ICN001)
}, },
)?; )?;
insta::assert_yaml_snapshot!("override_default", checks); insta::assert_yaml_snapshot!("override_default", diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -9,21 +9,21 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::PIE790, Path::new("PIE790.py"); "PIE790")] #[test_case(RuleCode::PIE790, Path::new("PIE790.py"); "PIE790")]
#[test_case(CheckCode::PIE794, Path::new("PIE794.py"); "PIE794")] #[test_case(RuleCode::PIE794, Path::new("PIE794.py"); "PIE794")]
#[test_case(CheckCode::PIE807, Path::new("PIE807.py"); "PIE807")] #[test_case(RuleCode::PIE807, Path::new("PIE807.py"); "PIE807")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_pie") Path::new("./resources/test/fixtures/flake8_pie")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -6,7 +6,7 @@ use crate::ast::types::Range;
use crate::autofix::helpers::delete_stmt; use crate::autofix::helpers::delete_stmt;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
/// PIE790 /// PIE790
@ -27,11 +27,11 @@ pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) {
} }
) { ) {
if matches!(pass_stmt.node, StmtKind::Pass) { if matches!(pass_stmt.node, StmtKind::Pass) {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::NoUnnecessaryPass, violations::NoUnnecessaryPass,
Range::from_located(pass_stmt), Range::from_located(pass_stmt),
); );
if checker.patch(&CheckCode::PIE790) { if checker.patch(&RuleCode::PIE790) {
match delete_stmt(pass_stmt, None, &[], checker.locator) { match delete_stmt(pass_stmt, None, &[], checker.locator) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); check.amend(fix);
@ -41,7 +41,7 @@ pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) {
} }
} }
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
} }
@ -78,14 +78,14 @@ pub fn dupe_class_field_definitions(checker: &mut Checker, bases: &[Expr], body:
}; };
if seen_targets.contains(target) { if seen_targets.contains(target) {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::DupeClassFieldDefinitions(target.to_string()), violations::DupeClassFieldDefinitions(target.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(&CheckCode::PIE794) { if checker.patch(&RuleCode::PIE794) {
check.amend(Fix::deletion(stmt.location, stmt.end_location.unwrap())); check.amend(Fix::deletion(stmt.location, stmt.end_location.unwrap()));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} else { } else {
seen_targets.insert(target); seen_targets.insert(target);
} }
@ -101,15 +101,15 @@ pub fn prefer_list_builtin(checker: &mut Checker, expr: &Expr) {
if let ExprKind::List { elts, .. } = &body.node { if let ExprKind::List { elts, .. } = &body.node {
if elts.is_empty() { if elts.is_empty() {
let mut check = let mut check =
Check::new(violations::PreferListBuiltin, Range::from_located(expr)); Diagnostic::new(violations::PreferListBuiltin, Range::from_located(expr));
if checker.patch(&CheckCode::PIE807) { if checker.patch(&RuleCode::PIE807) {
check.amend(Fix::replacement( check.amend(Fix::replacement(
"list".to_string(), "list".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
} }

View File

@ -9,20 +9,20 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::T201, Path::new("T201.py"); "T201")] #[test_case(RuleCode::T201, Path::new("T201.py"); "T201")]
#[test_case(CheckCode::T203, Path::new("T203.py"); "T203")] #[test_case(RuleCode::T203, Path::new("T203.py"); "T203")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_print") Path::new("./resources/test/fixtures/flake8_print")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings::for_rule(check_code), &settings::Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -5,7 +5,7 @@ use crate::ast::helpers::{collect_call_paths, dealias_call_path, is_const_none,
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::helpers; use crate::autofix::helpers;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// T201, T203 /// T201, T203
@ -28,9 +28,9 @@ pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) {
} }
} }
} }
Check::new(violations::PrintFound, Range::from_located(func)) Diagnostic::new(violations::PrintFound, Range::from_located(func))
} else if match_call_path(&call_path, "pprint", "pprint", &checker.from_imports) { } else if match_call_path(&call_path, "pprint", "pprint", &checker.from_imports) {
Check::new(violations::PPrintFound, Range::from_located(func)) Diagnostic::new(violations::PPrintFound, Range::from_located(func))
} else { } else {
return; return;
} }
@ -66,5 +66,5 @@ pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) {
} }
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }

View File

@ -12,12 +12,12 @@ mod tests {
use crate::flake8_pytest_style::settings::Settings; use crate::flake8_pytest_style::settings::Settings;
use crate::flake8_pytest_style::types; use crate::flake8_pytest_style::types;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::settings; use crate::settings;
#[test_case(CheckCode::PT001, Path::new("PT001.py"), Settings::default(), "PT001_default"; "PT001_0")] #[test_case(RuleCode::PT001, Path::new("PT001.py"), Settings::default(), "PT001_default"; "PT001_0")]
#[test_case( #[test_case(
CheckCode::PT001, RuleCode::PT001,
Path::new("PT001.py"), Path::new("PT001.py"),
Settings { Settings {
fixture_parentheses: false, fixture_parentheses: false,
@ -26,13 +26,13 @@ mod tests {
"PT001_no_parentheses"; "PT001_no_parentheses";
"PT001_1" "PT001_1"
)] )]
#[test_case(CheckCode::PT002, Path::new("PT002.py"), Settings::default(), "PT002"; "PT002")] #[test_case(RuleCode::PT002, Path::new("PT002.py"), Settings::default(), "PT002"; "PT002")]
#[test_case(CheckCode::PT003, Path::new("PT003.py"), Settings::default(), "PT003"; "PT003")] #[test_case(RuleCode::PT003, Path::new("PT003.py"), Settings::default(), "PT003"; "PT003")]
#[test_case(CheckCode::PT004, Path::new("PT004.py"), Settings::default(), "PT004"; "PT004")] #[test_case(RuleCode::PT004, Path::new("PT004.py"), Settings::default(), "PT004"; "PT004")]
#[test_case(CheckCode::PT005, Path::new("PT005.py"), Settings::default(), "PT005"; "PT005")] #[test_case(RuleCode::PT005, Path::new("PT005.py"), Settings::default(), "PT005"; "PT005")]
#[test_case(CheckCode::PT006, Path::new("PT006.py"), Settings::default(), "PT006_default"; "PT006_0")] #[test_case(RuleCode::PT006, Path::new("PT006.py"), Settings::default(), "PT006_default"; "PT006_0")]
#[test_case( #[test_case(
CheckCode::PT006, RuleCode::PT006,
Path::new("PT006.py"), Path::new("PT006.py"),
Settings { Settings {
parametrize_names_type: types::ParametrizeNameType::CSV, parametrize_names_type: types::ParametrizeNameType::CSV,
@ -42,7 +42,7 @@ mod tests {
"PT006_1" "PT006_1"
)] )]
#[test_case( #[test_case(
CheckCode::PT006, RuleCode::PT006,
Path::new("PT006.py"), Path::new("PT006.py"),
Settings { Settings {
parametrize_names_type: types::ParametrizeNameType::List, parametrize_names_type: types::ParametrizeNameType::List,
@ -52,14 +52,14 @@ mod tests {
"PT006_2" "PT006_2"
)] )]
#[test_case( #[test_case(
CheckCode::PT007, RuleCode::PT007,
Path::new("PT007.py"), Path::new("PT007.py"),
Settings::default(), Settings::default(),
"PT007_list_of_tuples"; "PT007_list_of_tuples";
"PT007_0" "PT007_0"
)] )]
#[test_case( #[test_case(
CheckCode::PT007, RuleCode::PT007,
Path::new("PT007.py"), Path::new("PT007.py"),
Settings { Settings {
parametrize_values_type: types::ParametrizeValuesType::Tuple, parametrize_values_type: types::ParametrizeValuesType::Tuple,
@ -69,7 +69,7 @@ mod tests {
"PT007_1" "PT007_1"
)] )]
#[test_case( #[test_case(
CheckCode::PT007, RuleCode::PT007,
Path::new("PT007.py"), Path::new("PT007.py"),
Settings { Settings {
parametrize_values_type: types::ParametrizeValuesType::Tuple, parametrize_values_type: types::ParametrizeValuesType::Tuple,
@ -80,7 +80,7 @@ mod tests {
"PT007_2" "PT007_2"
)] )]
#[test_case( #[test_case(
CheckCode::PT007, RuleCode::PT007,
Path::new("PT007.py"), Path::new("PT007.py"),
Settings { Settings {
parametrize_values_row_type: types::ParametrizeValuesRowType::List, parametrize_values_row_type: types::ParametrizeValuesRowType::List,
@ -90,29 +90,29 @@ mod tests {
"PT007_3" "PT007_3"
)] )]
#[test_case( #[test_case(
CheckCode::PT008, RuleCode::PT008,
Path::new("PT008.py"), Path::new("PT008.py"),
Settings::default(), Settings::default(),
"PT008"; "PT008";
"PT008" "PT008"
)] )]
#[test_case( #[test_case(
CheckCode::PT009, RuleCode::PT009,
Path::new("PT009.py"), Path::new("PT009.py"),
Settings::default(), Settings::default(),
"PT009"; "PT009";
"PT009" "PT009"
)] )]
#[test_case(CheckCode::PT010, Path::new("PT010.py"), Settings::default(), "PT010"; "PT0010")] #[test_case(RuleCode::PT010, Path::new("PT010.py"), Settings::default(), "PT010"; "PT0010")]
#[test_case( #[test_case(
CheckCode::PT011, RuleCode::PT011,
Path::new("PT011.py"), Path::new("PT011.py"),
Settings::default(), Settings::default(),
"PT011_default"; "PT011_default";
"PT011_0" "PT011_0"
)] )]
#[test_case( #[test_case(
CheckCode::PT011, RuleCode::PT011,
Path::new("PT011.py"), Path::new("PT011.py"),
Settings { Settings {
raises_extend_require_match_for: vec!["ZeroDivisionError".to_string()], raises_extend_require_match_for: vec!["ZeroDivisionError".to_string()],
@ -122,7 +122,7 @@ mod tests {
"PT011_1" "PT011_1"
)] )]
#[test_case( #[test_case(
CheckCode::PT011, RuleCode::PT011,
Path::new("PT011.py"), Path::new("PT011.py"),
Settings { Settings {
raises_require_match_for: vec!["ZeroDivisionError".to_string()], raises_require_match_for: vec!["ZeroDivisionError".to_string()],
@ -132,84 +132,84 @@ mod tests {
"PT011_2" "PT011_2"
)] )]
#[test_case( #[test_case(
CheckCode::PT012, RuleCode::PT012,
Path::new("PT012.py"), Path::new("PT012.py"),
Settings::default(), Settings::default(),
"PT012"; "PT012";
"PT012" "PT012"
)] )]
#[test_case( #[test_case(
CheckCode::PT013, RuleCode::PT013,
Path::new("PT013.py"), Path::new("PT013.py"),
Settings::default(), Settings::default(),
"PT013"; "PT013";
"PT013" "PT013"
)] )]
#[test_case( #[test_case(
CheckCode::PT015, RuleCode::PT015,
Path::new("PT015.py"), Path::new("PT015.py"),
Settings::default(), Settings::default(),
"PT015"; "PT015";
"PT015" "PT015"
)] )]
#[test_case( #[test_case(
CheckCode::PT016, RuleCode::PT016,
Path::new("PT016.py"), Path::new("PT016.py"),
Settings::default(), Settings::default(),
"PT016"; "PT016";
"PT016" "PT016"
)] )]
#[test_case( #[test_case(
CheckCode::PT017, RuleCode::PT017,
Path::new("PT017.py"), Path::new("PT017.py"),
Settings::default(), Settings::default(),
"PT017"; "PT017";
"PT017" "PT017"
)] )]
#[test_case( #[test_case(
CheckCode::PT018, RuleCode::PT018,
Path::new("PT018.py"), Path::new("PT018.py"),
Settings::default(), Settings::default(),
"PT018"; "PT018";
"PT018" "PT018"
)] )]
#[test_case( #[test_case(
CheckCode::PT019, RuleCode::PT019,
Path::new("PT019.py"), Path::new("PT019.py"),
Settings::default(), Settings::default(),
"PT019"; "PT019";
"PT019" "PT019"
)] )]
#[test_case( #[test_case(
CheckCode::PT020, RuleCode::PT020,
Path::new("PT020.py"), Path::new("PT020.py"),
Settings::default(), Settings::default(),
"PT020"; "PT020";
"PT020" "PT020"
)] )]
#[test_case( #[test_case(
CheckCode::PT021, RuleCode::PT021,
Path::new("PT021.py"), Path::new("PT021.py"),
Settings::default(), Settings::default(),
"PT021"; "PT021";
"PT021" "PT021"
)] )]
#[test_case( #[test_case(
CheckCode::PT022, RuleCode::PT022,
Path::new("PT022.py"), Path::new("PT022.py"),
Settings::default(), Settings::default(),
"PT022"; "PT022";
"PT022" "PT022"
)] )]
#[test_case( #[test_case(
CheckCode::PT023, RuleCode::PT023,
Path::new("PT023.py"), Path::new("PT023.py"),
Settings::default(), Settings::default(),
"PT023_default"; "PT023_default";
"PT023_0" "PT023_0"
)] )]
#[test_case( #[test_case(
CheckCode::PT023, RuleCode::PT023,
Path::new("PT023.py"), Path::new("PT023.py"),
Settings { Settings {
mark_parentheses: false, mark_parentheses: false,
@ -219,43 +219,43 @@ mod tests {
"PT023_1" "PT023_1"
)] )]
#[test_case( #[test_case(
CheckCode::PT024, RuleCode::PT024,
Path::new("PT024.py"), Path::new("PT024.py"),
Settings::default(), Settings::default(),
"PT024"; "PT024";
"PT024" "PT024"
)] )]
#[test_case( #[test_case(
CheckCode::PT025, RuleCode::PT025,
Path::new("PT025.py"), Path::new("PT025.py"),
Settings::default(), Settings::default(),
"PT025"; "PT025";
"PT025" "PT025"
)] )]
#[test_case( #[test_case(
CheckCode::PT026, RuleCode::PT026,
Path::new("PT026.py"), Path::new("PT026.py"),
Settings::default(), Settings::default(),
"PT026"; "PT026";
"PT026" "PT026"
)] )]
fn test_pytest_style( fn test_pytest_style(
check_code: CheckCode, rule_code: RuleCode,
path: &Path, path: &Path,
plugin_settings: Settings, plugin_settings: Settings,
name: &str, name: &str,
) -> Result<()> { ) -> Result<()> {
let mut checks = test_path( let mut diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_pytest_style") Path::new("./resources/test/fixtures/flake8_pytest_style")
.join(path) .join(path)
.as_path(), .as_path(),
&settings::Settings { &settings::Settings {
flake8_pytest_style: plugin_settings, flake8_pytest_style: plugin_settings,
..settings::Settings::for_rule(check_code) ..settings::Settings::for_rule(rule_code)
}, },
)?; )?;
checks.sort_by_key(|check| check.location); diagnostics.sort_by_key(|diagnostic| diagnostic.location);
insta::assert_yaml_snapshot!(name, checks); insta::assert_yaml_snapshot!(name, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -10,7 +10,7 @@ use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
/// Visitor that tracks assert statements and checks if they reference /// Visitor that tracks assert statements and checks if they reference
@ -18,7 +18,7 @@ use crate::violations;
struct ExceptionHandlerVisitor<'a> { struct ExceptionHandlerVisitor<'a> {
exception_name: &'a str, exception_name: &'a str,
current_assert: Option<&'a Stmt>, current_assert: Option<&'a Stmt>,
errors: Vec<Check>, errors: Vec<Diagnostic>,
} }
impl<'a> ExceptionHandlerVisitor<'a> { impl<'a> ExceptionHandlerVisitor<'a> {
@ -51,7 +51,7 @@ where
ExprKind::Name { id, .. } => { ExprKind::Name { id, .. } => {
if let Some(current_assert) = self.current_assert { if let Some(current_assert) = self.current_assert {
if id.as_str() == self.exception_name { if id.as_str() == self.exception_name {
self.errors.push(Check::new( self.errors.push(Diagnostic::new(
violations::AssertInExcept(id.to_string()), violations::AssertInExcept(id.to_string()),
Range::from_located(current_assert), Range::from_located(current_assert),
)); ));
@ -79,7 +79,7 @@ fn is_composite_condition(test: &Expr) -> bool {
} }
} }
fn check_assert_in_except(name: &str, body: &[Stmt]) -> Vec<Check> { fn check_assert_in_except(name: &str, body: &[Stmt]) -> Vec<Diagnostic> {
// Walk body to find assert statements that reference the exception name // Walk body to find assert statements that reference the exception name
let mut visitor = ExceptionHandlerVisitor::new(name); let mut visitor = ExceptionHandlerVisitor::new(name);
for stmt in body { for stmt in body {
@ -95,11 +95,11 @@ pub fn unittest_assertion(
func: &Expr, func: &Expr,
args: &[Expr], args: &[Expr],
keywords: &[Keyword], keywords: &[Keyword],
) -> Option<Check> { ) -> Option<Diagnostic> {
match &func.node { match &func.node {
ExprKind::Attribute { attr, .. } => { ExprKind::Attribute { attr, .. } => {
if let Ok(unittest_assert) = UnittestAssert::try_from(attr.as_str()) { if let Ok(unittest_assert) = UnittestAssert::try_from(attr.as_str()) {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UnittestAssertion(unittest_assert.to_string()), violations::UnittestAssertion(unittest_assert.to_string()),
Range::from_located(func), Range::from_located(func),
); );
@ -122,9 +122,9 @@ pub fn unittest_assertion(
} }
/// PT015 /// PT015
pub fn assert_falsy(assert_stmt: &Stmt, test_expr: &Expr) -> Option<Check> { pub fn assert_falsy(assert_stmt: &Stmt, test_expr: &Expr) -> Option<Diagnostic> {
if is_falsy_constant(test_expr) { if is_falsy_constant(test_expr) {
Some(Check::new( Some(Diagnostic::new(
violations::AssertAlwaysFalse, violations::AssertAlwaysFalse,
Range::from_located(assert_stmt), Range::from_located(assert_stmt),
)) ))
@ -134,7 +134,7 @@ pub fn assert_falsy(assert_stmt: &Stmt, test_expr: &Expr) -> Option<Check> {
} }
/// PT017 /// PT017
pub fn assert_in_exception_handler(handlers: &[Excepthandler]) -> Vec<Check> { pub fn assert_in_exception_handler(handlers: &[Excepthandler]) -> Vec<Diagnostic> {
handlers handlers
.iter() .iter()
.flat_map(|handler| match &handler.node { .flat_map(|handler| match &handler.node {
@ -150,9 +150,9 @@ pub fn assert_in_exception_handler(handlers: &[Excepthandler]) -> Vec<Check> {
} }
/// PT018 /// PT018
pub fn composite_condition(assert_stmt: &Stmt, test_expr: &Expr) -> Option<Check> { pub fn composite_condition(assert_stmt: &Stmt, test_expr: &Expr) -> Option<Diagnostic> {
if is_composite_condition(test_expr) { if is_composite_condition(test_expr) {
Some(Check::new( Some(Diagnostic::new(
violations::CompositeAssertion, violations::CompositeAssertion,
Range::from_located(assert_stmt), Range::from_located(assert_stmt),
)) ))

View File

@ -4,7 +4,7 @@ use super::helpers::{is_empty_or_null_string, is_pytest_fail};
use crate::ast::helpers::SimpleCallArgs; use crate::ast::helpers::SimpleCallArgs;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
pub fn fail_call(checker: &mut Checker, call: &Expr, args: &[Expr], keywords: &[Keyword]) { pub fn fail_call(checker: &mut Checker, call: &Expr, args: &[Expr], keywords: &[Keyword]) {
@ -14,13 +14,13 @@ pub fn fail_call(checker: &mut Checker, call: &Expr, args: &[Expr], keywords: &[
if let Some(msg) = msg { if let Some(msg) = msg {
if is_empty_or_null_string(msg) { if is_empty_or_null_string(msg) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FailWithoutMessage, violations::FailWithoutMessage,
Range::from_located(call), Range::from_located(call),
)); ));
} }
} else { } else {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FailWithoutMessage, violations::FailWithoutMessage,
Range::from_located(call), Range::from_located(call),
)); ));

View File

@ -10,7 +10,7 @@ use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
#[derive(Default)] #[derive(Default)]
@ -79,14 +79,14 @@ fn pytest_fixture_parentheses(
preferred: &str, preferred: &str,
actual: &str, actual: &str,
) { ) {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()), violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()),
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(check.kind.code()) { if checker.patch(check.kind.code()) {
check.amend(fix); check.amend(fix);
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
/// PT001, PT002, PT003 /// PT001, PT002, PT003
@ -98,7 +98,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
keywords, keywords,
.. ..
} => { } => {
if checker.settings.enabled.contains(&CheckCode::PT001) if checker.settings.enabled.contains(&RuleCode::PT001)
&& !checker.settings.flake8_pytest_style.fixture_parentheses && !checker.settings.flake8_pytest_style.fixture_parentheses
&& args.is_empty() && args.is_empty()
&& keywords.is_empty() && keywords.is_empty()
@ -111,21 +111,21 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
pytest_fixture_parentheses(checker, decorator, fix, "", "()"); pytest_fixture_parentheses(checker, decorator, fix, "", "()");
} }
if checker.settings.enabled.contains(&CheckCode::PT002) && !args.is_empty() { if checker.settings.enabled.contains(&RuleCode::PT002) && !args.is_empty() {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FixturePositionalArgs(func_name.to_string()), violations::FixturePositionalArgs(func_name.to_string()),
Range::from_located(decorator), Range::from_located(decorator),
)); ));
} }
if checker.settings.enabled.contains(&CheckCode::PT003) { if checker.settings.enabled.contains(&RuleCode::PT003) {
let scope_keyword = keywords let scope_keyword = keywords
.iter() .iter()
.find(|kw| kw.node.arg == Some("scope".to_string())); .find(|kw| kw.node.arg == Some("scope".to_string()));
if let Some(scope_keyword) = scope_keyword { if let Some(scope_keyword) = scope_keyword {
if keyword_is_literal(scope_keyword, "function") { if keyword_is_literal(scope_keyword, "function") {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ExtraneousScopeFunction, violations::ExtraneousScopeFunction,
Range::from_located(scope_keyword), Range::from_located(scope_keyword),
)); ));
@ -134,7 +134,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
} }
} }
_ => { _ => {
if checker.settings.enabled.contains(&CheckCode::PT001) if checker.settings.enabled.contains(&RuleCode::PT001)
&& checker.settings.flake8_pytest_style.fixture_parentheses && checker.settings.flake8_pytest_style.fixture_parentheses
{ {
let fix = Fix::insertion("()".to_string(), decorator.end_location.unwrap()); let fix = Fix::insertion("()".to_string(), decorator.end_location.unwrap());
@ -152,31 +152,31 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
visitor.visit_stmt(stmt); visitor.visit_stmt(stmt);
} }
if checker.settings.enabled.contains(&CheckCode::PT005) if checker.settings.enabled.contains(&RuleCode::PT005)
&& visitor.has_return_with_value && visitor.has_return_with_value
&& func_name.starts_with('_') && func_name.starts_with('_')
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::IncorrectFixtureNameUnderscore(func_name.to_string()), violations::IncorrectFixtureNameUnderscore(func_name.to_string()),
Range::from_located(func), Range::from_located(func),
)); ));
} else if checker.settings.enabled.contains(&CheckCode::PT004) } else if checker.settings.enabled.contains(&RuleCode::PT004)
&& !visitor.has_return_with_value && !visitor.has_return_with_value
&& !visitor.has_yield_from && !visitor.has_yield_from
&& !func_name.starts_with('_') && !func_name.starts_with('_')
{ {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::MissingFixtureNameUnderscore(func_name.to_string()), violations::MissingFixtureNameUnderscore(func_name.to_string()),
Range::from_located(func), Range::from_located(func),
)); ));
} }
if checker.settings.enabled.contains(&CheckCode::PT022) { if checker.settings.enabled.contains(&RuleCode::PT022) {
if let Some(stmt) = body.last() { if let Some(stmt) = body.last() {
if let StmtKind::Expr { value, .. } = &stmt.node { if let StmtKind::Expr { value, .. } = &stmt.node {
if let ExprKind::Yield { .. } = value.node { if let ExprKind::Yield { .. } = value.node {
if visitor.yield_statements.len() == 1 { if visitor.yield_statements.len() == 1 {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UselessYieldFixture(func_name.to_string()), violations::UselessYieldFixture(func_name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
@ -190,7 +190,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
), ),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
} }
@ -203,7 +203,7 @@ fn check_test_function_args(checker: &mut Checker, args: &Arguments) {
args.args.iter().chain(&args.kwonlyargs).for_each(|arg| { args.args.iter().chain(&args.kwonlyargs).for_each(|arg| {
let name = arg.node.arg.to_string(); let name = arg.node.arg.to_string();
if name.starts_with('_') { if name.starts_with('_') {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FixtureParamWithoutValue(name), violations::FixtureParamWithoutValue(name),
Range::from_located(arg), Range::from_located(arg),
)); ));
@ -214,7 +214,7 @@ fn check_test_function_args(checker: &mut Checker, args: &Arguments) {
/// PT020 /// PT020
fn check_fixture_decorator_name(checker: &mut Checker, decorator: &Expr) { fn check_fixture_decorator_name(checker: &mut Checker, decorator: &Expr) {
if is_pytest_yield_fixture(decorator, checker) { if is_pytest_yield_fixture(decorator, checker) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::DeprecatedYieldFixture, violations::DeprecatedYieldFixture,
Range::from_located(decorator), Range::from_located(decorator),
)); ));
@ -234,7 +234,7 @@ fn check_fixture_addfinalizer(checker: &mut Checker, args: &Arguments, body: &[S
} }
if let Some(addfinalizer) = visitor.addfinalizer_call { if let Some(addfinalizer) = visitor.addfinalizer_call {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::FixtureFinalizerCallback, violations::FixtureFinalizerCallback,
Range::from_located(addfinalizer), Range::from_located(addfinalizer),
)); ));
@ -246,18 +246,18 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) {
for mark in get_mark_decorators(decorators) { for mark in get_mark_decorators(decorators) {
let name = get_mark_name(mark); let name = get_mark_name(mark);
if checker.settings.enabled.contains(&CheckCode::PT024) { if checker.settings.enabled.contains(&RuleCode::PT024) {
if name == "asyncio" { if name == "asyncio" {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UnnecessaryAsyncioMarkOnFixture, violations::UnnecessaryAsyncioMarkOnFixture,
Range::from_located(mark), Range::from_located(mark),
)); ));
} }
} }
if checker.settings.enabled.contains(&CheckCode::PT025) { if checker.settings.enabled.contains(&RuleCode::PT025) {
if name == "usefixtures" { if name == "usefixtures" {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ErroneousUseFixturesOnFixture, violations::ErroneousUseFixturesOnFixture,
Range::from_located(mark), Range::from_located(mark),
)); ));
@ -276,39 +276,39 @@ pub fn fixture(
) { ) {
let decorator = get_fixture_decorator(checker, decorators); let decorator = get_fixture_decorator(checker, decorators);
if let Some(decorator) = decorator { if let Some(decorator) = decorator {
if checker.settings.enabled.contains(&CheckCode::PT001) if checker.settings.enabled.contains(&RuleCode::PT001)
|| checker.settings.enabled.contains(&CheckCode::PT002) || checker.settings.enabled.contains(&RuleCode::PT002)
|| checker.settings.enabled.contains(&CheckCode::PT003) || checker.settings.enabled.contains(&RuleCode::PT003)
{ {
check_fixture_decorator(checker, func_name, decorator); check_fixture_decorator(checker, func_name, decorator);
} }
if checker.settings.enabled.contains(&CheckCode::PT020) if checker.settings.enabled.contains(&RuleCode::PT020)
&& checker.settings.flake8_pytest_style.fixture_parentheses && checker.settings.flake8_pytest_style.fixture_parentheses
{ {
check_fixture_decorator_name(checker, decorator); check_fixture_decorator_name(checker, decorator);
} }
if (checker.settings.enabled.contains(&CheckCode::PT004) if (checker.settings.enabled.contains(&RuleCode::PT004)
|| checker.settings.enabled.contains(&CheckCode::PT005) || checker.settings.enabled.contains(&RuleCode::PT005)
|| checker.settings.enabled.contains(&CheckCode::PT022)) || checker.settings.enabled.contains(&RuleCode::PT022))
&& !has_abstractmethod_decorator(decorators, checker) && !has_abstractmethod_decorator(decorators, checker)
{ {
check_fixture_returns(checker, func, func_name, body); check_fixture_returns(checker, func, func_name, body);
} }
if checker.settings.enabled.contains(&CheckCode::PT021) { if checker.settings.enabled.contains(&RuleCode::PT021) {
check_fixture_addfinalizer(checker, args, body); check_fixture_addfinalizer(checker, args, body);
} }
if checker.settings.enabled.contains(&CheckCode::PT024) if checker.settings.enabled.contains(&RuleCode::PT024)
|| checker.settings.enabled.contains(&CheckCode::PT025) || checker.settings.enabled.contains(&RuleCode::PT025)
{ {
check_fixture_marks(checker, decorators); check_fixture_marks(checker, decorators);
} }
} }
if checker.settings.enabled.contains(&CheckCode::PT019) && func_name.starts_with("test_") { if checker.settings.enabled.contains(&RuleCode::PT019) && func_name.starts_with("test_") {
check_test_function_args(checker, args); check_test_function_args(checker, args);
} }
} }

View File

@ -1,7 +1,7 @@
use rustpython_ast::Stmt; use rustpython_ast::Stmt;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
fn is_pytest_or_subpackage(imported_name: &str) -> bool { fn is_pytest_or_subpackage(imported_name: &str) -> bool {
@ -9,11 +9,11 @@ fn is_pytest_or_subpackage(imported_name: &str) -> bool {
} }
/// PT013 /// PT013
pub fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option<Check> { pub fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option<Diagnostic> {
if is_pytest_or_subpackage(name) { if is_pytest_or_subpackage(name) {
if let Some(alias) = asname { if let Some(alias) = asname {
if alias != name { if alias != name {
return Some(Check::new( return Some(Diagnostic::new(
violations::IncorrectPytestImport, violations::IncorrectPytestImport,
Range::from_located(import_from), Range::from_located(import_from),
)); ));
@ -28,7 +28,7 @@ pub fn import_from(
import_from: &Stmt, import_from: &Stmt,
module: Option<&str>, module: Option<&str>,
level: Option<&usize>, level: Option<&usize>,
) -> Option<Check> { ) -> Option<Diagnostic> {
// If level is not zero or module is none, return // If level is not zero or module is none, return
if let Some(level) = level { if let Some(level) = level {
if *level != 0 { if *level != 0 {
@ -38,7 +38,7 @@ pub fn import_from(
if let Some(module) = module { if let Some(module) = module {
if is_pytest_or_subpackage(module) { if is_pytest_or_subpackage(module) {
return Some(Check::new( return Some(Diagnostic::new(
violations::IncorrectPytestImport, violations::IncorrectPytestImport,
Range::from_located(import_from), Range::from_located(import_from),
)); ));

View File

@ -4,7 +4,7 @@ use super::helpers::{get_mark_decorators, get_mark_name};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
fn pytest_mark_parentheses( fn pytest_mark_parentheses(
@ -14,7 +14,7 @@ fn pytest_mark_parentheses(
preferred: &str, preferred: &str,
actual: &str, actual: &str,
) { ) {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::IncorrectMarkParenthesesStyle( violations::IncorrectMarkParenthesesStyle(
get_mark_name(decorator).to_string(), get_mark_name(decorator).to_string(),
preferred.to_string(), preferred.to_string(),
@ -25,7 +25,7 @@ fn pytest_mark_parentheses(
if checker.patch(check.kind.code()) { if checker.patch(check.kind.code()) {
check.amend(fix); check.amend(fix);
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
fn check_mark_parentheses(checker: &mut Checker, decorator: &Expr) { fn check_mark_parentheses(checker: &mut Checker, decorator: &Expr) {
@ -71,7 +71,7 @@ fn check_useless_usefixtures(checker: &mut Checker, decorator: &Expr) {
} }
if !has_parameters { if !has_parameters {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::UseFixturesWithoutParameters, violations::UseFixturesWithoutParameters,
Range::from_located(decorator), Range::from_located(decorator),
); );
@ -79,13 +79,13 @@ fn check_useless_usefixtures(checker: &mut Checker, decorator: &Expr) {
let at_start = Location::new(decorator.location.row(), decorator.location.column() - 1); let at_start = Location::new(decorator.location.row(), decorator.location.column() - 1);
check.amend(Fix::deletion(at_start, decorator.end_location.unwrap())); check.amend(Fix::deletion(at_start, decorator.end_location.unwrap()));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
pub fn marks(checker: &mut Checker, decorators: &[Expr]) { pub fn marks(checker: &mut Checker, decorators: &[Expr]) {
let enforce_parentheses = checker.settings.enabled.contains(&CheckCode::PT023); let enforce_parentheses = checker.settings.enabled.contains(&RuleCode::PT023);
let enforce_useless_usefixtures = checker.settings.enabled.contains(&CheckCode::PT026); let enforce_useless_usefixtures = checker.settings.enabled.contains(&RuleCode::PT026);
for mark in get_mark_decorators(decorators) { for mark in get_mark_decorators(decorators) {
if enforce_parentheses { if enforce_parentheses {

View File

@ -6,7 +6,7 @@ use crate::ast::types::Range;
use crate::autofix::Fix; use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::flake8_pytest_style::types; use crate::flake8_pytest_style::types;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::source_code_generator::SourceCodeGenerator; use crate::source_code_generator::SourceCodeGenerator;
use crate::violations; use crate::violations;
@ -80,7 +80,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
if names.len() > 1 { if names.len() > 1 {
match names_type { match names_type {
types::ParametrizeNameType::Tuple => { types::ParametrizeNameType::Tuple => {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
@ -107,10 +107,10 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
types::ParametrizeNameType::List => { types::ParametrizeNameType::List => {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
@ -137,7 +137,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
types::ParametrizeNameType::CSV => {} types::ParametrizeNameType::CSV => {}
} }
@ -152,7 +152,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
match names_type { match names_type {
types::ParametrizeNameType::Tuple => {} types::ParametrizeNameType::Tuple => {}
types::ParametrizeNameType::List => { types::ParametrizeNameType::List => {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
@ -171,10 +171,10 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
types::ParametrizeNameType::CSV => { types::ParametrizeNameType::CSV => {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
@ -187,7 +187,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
)); ));
} }
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
}; };
@ -201,7 +201,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
match names_type { match names_type {
types::ParametrizeNameType::List => {} types::ParametrizeNameType::List => {}
types::ParametrizeNameType::Tuple => { types::ParametrizeNameType::Tuple => {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
@ -220,10 +220,10 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
types::ParametrizeNameType::CSV => { types::ParametrizeNameType::CSV => {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
@ -236,7 +236,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
)); ));
} }
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
}; };
@ -257,7 +257,7 @@ fn check_values(checker: &mut Checker, expr: &Expr) {
match &expr.node { match &expr.node {
ExprKind::List { elts, .. } => { ExprKind::List { elts, .. } => {
if values_type != types::ParametrizeValuesType::List { if values_type != types::ParametrizeValuesType::List {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ParametrizeValuesWrongType(values_type, values_row_type), violations::ParametrizeValuesWrongType(values_type, values_row_type),
Range::from_located(expr), Range::from_located(expr),
)); ));
@ -266,7 +266,7 @@ fn check_values(checker: &mut Checker, expr: &Expr) {
} }
ExprKind::Tuple { elts, .. } => { ExprKind::Tuple { elts, .. } => {
if values_type != types::ParametrizeValuesType::Tuple { if values_type != types::ParametrizeValuesType::Tuple {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ParametrizeValuesWrongType(values_type, values_row_type), violations::ParametrizeValuesWrongType(values_type, values_row_type),
Range::from_located(expr), Range::from_located(expr),
)); ));
@ -278,7 +278,7 @@ fn check_values(checker: &mut Checker, expr: &Expr) {
} }
fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) { fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
let mut check = Check::new( let mut check = Diagnostic::new(
violations::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV), violations::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV),
Range::from_located(expr), Range::from_located(expr),
); );
@ -292,7 +292,7 @@ fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
fn handle_value_rows( fn handle_value_rows(
@ -305,7 +305,7 @@ fn handle_value_rows(
match &elt.node { match &elt.node {
ExprKind::Tuple { .. } => { ExprKind::Tuple { .. } => {
if values_row_type != types::ParametrizeValuesRowType::Tuple { if values_row_type != types::ParametrizeValuesRowType::Tuple {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ParametrizeValuesWrongType(values_type, values_row_type), violations::ParametrizeValuesWrongType(values_type, values_row_type),
Range::from_located(elt), Range::from_located(elt),
)); ));
@ -313,7 +313,7 @@ fn handle_value_rows(
} }
ExprKind::List { .. } => { ExprKind::List { .. } => {
if values_row_type != types::ParametrizeValuesRowType::List { if values_row_type != types::ParametrizeValuesRowType::List {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ParametrizeValuesWrongType(values_type, values_row_type), violations::ParametrizeValuesWrongType(values_type, values_row_type),
Range::from_located(elt), Range::from_located(elt),
)); ));
@ -328,12 +328,12 @@ pub fn parametrize(checker: &mut Checker, decorators: &[Expr]) {
let decorator = get_parametrize_decorator(checker, decorators); let decorator = get_parametrize_decorator(checker, decorators);
if let Some(decorator) = decorator { if let Some(decorator) = decorator {
if let ExprKind::Call { args, .. } = &decorator.node { if let ExprKind::Call { args, .. } = &decorator.node {
if checker.settings.enabled.contains(&CheckCode::PT006) { if checker.settings.enabled.contains(&RuleCode::PT006) {
if let Some(arg) = args.get(0) { if let Some(arg) = args.get(0) {
check_names(checker, arg); check_names(checker, arg);
} }
} }
if checker.settings.enabled.contains(&CheckCode::PT007) { if checker.settings.enabled.contains(&RuleCode::PT007) {
if let Some(arg) = args.get(1) { if let Some(arg) = args.get(1) {
check_values(checker, arg); check_values(checker, arg);
} }

View File

@ -5,7 +5,7 @@ use crate::ast::helpers::{collect_arg_names, compose_call_path, SimpleCallArgs};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::ast::visitor; use crate::ast::visitor;
use crate::ast::visitor::Visitor; use crate::ast::visitor::Visitor;
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
const PATCH_NAMES: &[&str] = &[ const PATCH_NAMES: &[&str] = &[
@ -56,7 +56,7 @@ fn check_patch_call(
args: &[Expr], args: &[Expr],
keywords: &[Keyword], keywords: &[Keyword],
new_arg_number: usize, new_arg_number: usize,
) -> Option<Check> { ) -> Option<Diagnostic> {
let simple_args = SimpleCallArgs::new(args, keywords); let simple_args = SimpleCallArgs::new(args, keywords);
if simple_args.get_argument("return_value", None).is_some() { if simple_args.get_argument("return_value", None).is_some() {
return None; return None;
@ -72,7 +72,7 @@ fn check_patch_call(
visitor.visit_expr(body); visitor.visit_expr(body);
if !visitor.uses_args { if !visitor.uses_args {
return Some(Check::new( return Some(Diagnostic::new(
violations::PatchWithLambda, violations::PatchWithLambda,
Range::from_located(call), Range::from_located(call),
)); ));
@ -82,7 +82,7 @@ fn check_patch_call(
None None
} }
pub fn patch_with_lambda(call: &Expr, args: &[Expr], keywords: &[Keyword]) -> Option<Check> { pub fn patch_with_lambda(call: &Expr, args: &[Expr], keywords: &[Keyword]) -> Option<Diagnostic> {
if let Some(call_path) = compose_call_path(call) { if let Some(call_path) = compose_call_path(call) {
if PATCH_NAMES.contains(&call_path.as_str()) { if PATCH_NAMES.contains(&call_path.as_str()) {
check_patch_call(call, args, keywords, 1) check_patch_call(call, args, keywords, 1)

View File

@ -8,7 +8,7 @@ use crate::ast::helpers::{
}; };
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckCode}; use crate::registry::{Diagnostic, RuleCode};
use crate::violations; use crate::violations;
fn is_pytest_raises( fn is_pytest_raises(
@ -31,16 +31,16 @@ fn is_non_trivial_with_body(body: &[Stmt]) -> bool {
pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) {
if is_pytest_raises(func, &checker.from_imports, &checker.import_aliases) { if is_pytest_raises(func, &checker.from_imports, &checker.import_aliases) {
if checker.settings.enabled.contains(&CheckCode::PT010) { if checker.settings.enabled.contains(&RuleCode::PT010) {
if args.is_empty() && keywords.is_empty() { if args.is_empty() && keywords.is_empty() {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::RaisesWithoutException, violations::RaisesWithoutException,
Range::from_located(func), Range::from_located(func),
)); ));
} }
} }
if checker.settings.enabled.contains(&CheckCode::PT011) { if checker.settings.enabled.contains(&RuleCode::PT011) {
let match_keyword = keywords let match_keyword = keywords
.iter() .iter()
.find(|kw| kw.node.arg == Some("match".to_string())); .find(|kw| kw.node.arg == Some("match".to_string()));
@ -91,7 +91,7 @@ pub fn complex_raises(checker: &mut Checker, stmt: &Stmt, items: &[Withitem], bo
} }
if is_too_complex { if is_too_complex {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::RaisesWithMultipleStatements, violations::RaisesWithMultipleStatements,
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -118,7 +118,7 @@ fn exception_needs_match(checker: &mut Checker, exception: &Expr) {
.any(|(module, member)| match_call_path(&call_path, module, member, &checker.from_imports)); .any(|(module, member)| match_call_path(&call_path, module, member, &checker.from_imports));
if is_broad_exception { if is_broad_exception {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::RaisesTooBroad(call_path.join(".")), violations::RaisesTooBroad(call_path.join(".")),
Range::from_located(exception), Range::from_located(exception),
)); ));

View File

@ -2,7 +2,7 @@ use rustpython_ast::Location;
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::flake8_quotes::settings::{Quote, Settings}; use crate::flake8_quotes::settings::{Quote, Settings};
use crate::registry::Check; use crate::registry::Diagnostic;
use crate::source_code_locator::SourceCodeLocator; use crate::source_code_locator::SourceCodeLocator;
use crate::violations; use crate::violations;
@ -47,7 +47,7 @@ pub fn quotes(
end: Location, end: Location,
is_docstring: bool, is_docstring: bool,
settings: &Settings, settings: &Settings,
) -> Option<Check> { ) -> Option<Diagnostic> {
let text = locator.slice_source_code_range(&Range::new(start, end)); let text = locator.slice_source_code_range(&Range::new(start, end));
// Remove any prefixes (e.g., remove `u` from `u"foo"`). // Remove any prefixes (e.g., remove `u` from `u"foo"`).
@ -72,7 +72,7 @@ pub fn quotes(
return None; return None;
} }
Some(Check::new( Some(Diagnostic::new(
violations::BadQuotesDocstring(settings.docstring_quotes.clone()), violations::BadQuotesDocstring(settings.docstring_quotes.clone()),
Range::new(start, end), Range::new(start, end),
)) ))
@ -87,7 +87,7 @@ pub fn quotes(
return None; return None;
} }
Some(Check::new( Some(Diagnostic::new(
violations::BadQuotesMultilineString(settings.multiline_quotes.clone()), violations::BadQuotesMultilineString(settings.multiline_quotes.clone()),
Range::new(start, end), Range::new(start, end),
)) ))
@ -102,7 +102,7 @@ pub fn quotes(
if string_contents.contains(good_single(&settings.inline_quotes)) if string_contents.contains(good_single(&settings.inline_quotes))
&& !string_contents.contains(bad_single(&settings.inline_quotes)) && !string_contents.contains(bad_single(&settings.inline_quotes))
{ {
return Some(Check::new( return Some(Diagnostic::new(
violations::AvoidQuoteEscape, violations::AvoidQuoteEscape,
Range::new(start, end), Range::new(start, end),
)); ));
@ -112,7 +112,7 @@ pub fn quotes(
// If we're not using the preferred type, only allow use to avoid escapes. // If we're not using the preferred type, only allow use to avoid escapes.
if !string_contents.contains(good_single(&settings.inline_quotes)) { if !string_contents.contains(good_single(&settings.inline_quotes)) {
return Some(Check::new( return Some(Diagnostic::new(
violations::BadQuotesInlineString(settings.inline_quotes.clone()), violations::BadQuotesInlineString(settings.inline_quotes.clone()),
Range::new(start, end), Range::new(start, end),
)); ));

View File

@ -10,7 +10,7 @@ mod tests {
use crate::flake8_quotes::settings::Quote; use crate::flake8_quotes::settings::Quote;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::{flake8_quotes, Settings}; use crate::{flake8_quotes, Settings};
#[test_case(Path::new("doubles.py"))] #[test_case(Path::new("doubles.py"))]
@ -20,7 +20,7 @@ mod tests {
#[test_case(Path::new("doubles_wrapped.py"))] #[test_case(Path::new("doubles_wrapped.py"))]
fn doubles(path: &Path) -> Result<()> { fn doubles(path: &Path) -> Result<()> {
let snapshot = format!("doubles_{}", path.to_string_lossy()); let snapshot = format!("doubles_{}", path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_quotes") Path::new("./resources/test/fixtures/flake8_quotes")
.join(path) .join(path)
.as_path(), .as_path(),
@ -32,14 +32,14 @@ mod tests {
avoid_escape: true, avoid_escape: true,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::Q000, RuleCode::Q000,
CheckCode::Q001, RuleCode::Q001,
CheckCode::Q002, RuleCode::Q002,
CheckCode::Q003, RuleCode::Q003,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
@ -50,7 +50,7 @@ mod tests {
#[test_case(Path::new("singles_wrapped.py"))] #[test_case(Path::new("singles_wrapped.py"))]
fn singles(path: &Path) -> Result<()> { fn singles(path: &Path) -> Result<()> {
let snapshot = format!("singles_{}", path.to_string_lossy()); let snapshot = format!("singles_{}", path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_quotes") Path::new("./resources/test/fixtures/flake8_quotes")
.join(path) .join(path)
.as_path(), .as_path(),
@ -62,14 +62,14 @@ mod tests {
avoid_escape: true, avoid_escape: true,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::Q000, RuleCode::Q000,
CheckCode::Q001, RuleCode::Q001,
CheckCode::Q002, RuleCode::Q002,
CheckCode::Q003, RuleCode::Q003,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
@ -85,7 +85,7 @@ mod tests {
#[test_case(Path::new("docstring_singles_function.py"))] #[test_case(Path::new("docstring_singles_function.py"))]
fn double_docstring(path: &Path) -> Result<()> { fn double_docstring(path: &Path) -> Result<()> {
let snapshot = format!("double_docstring_{}", path.to_string_lossy()); let snapshot = format!("double_docstring_{}", path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_quotes") Path::new("./resources/test/fixtures/flake8_quotes")
.join(path) .join(path)
.as_path(), .as_path(),
@ -97,14 +97,14 @@ mod tests {
avoid_escape: true, avoid_escape: true,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::Q000, RuleCode::Q000,
CheckCode::Q001, RuleCode::Q001,
CheckCode::Q002, RuleCode::Q002,
CheckCode::Q003, RuleCode::Q003,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
@ -120,7 +120,7 @@ mod tests {
#[test_case(Path::new("docstring_singles_function.py"))] #[test_case(Path::new("docstring_singles_function.py"))]
fn single_docstring(path: &Path) -> Result<()> { fn single_docstring(path: &Path) -> Result<()> {
let snapshot = format!("single_docstring_{}", path.to_string_lossy()); let snapshot = format!("single_docstring_{}", path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_quotes") Path::new("./resources/test/fixtures/flake8_quotes")
.join(path) .join(path)
.as_path(), .as_path(),
@ -132,14 +132,14 @@ mod tests {
avoid_escape: true, avoid_escape: true,
}, },
..Settings::for_rules(vec![ ..Settings::for_rules(vec![
CheckCode::Q000, RuleCode::Q000,
CheckCode::Q001, RuleCode::Q001,
CheckCode::Q002, RuleCode::Q002,
CheckCode::Q003, RuleCode::Q003,
]) ])
}, },
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -10,26 +10,26 @@ mod tests {
use test_case::test_case; use test_case::test_case;
use crate::linter::test_path; use crate::linter::test_path;
use crate::registry::CheckCode; use crate::registry::RuleCode;
use crate::Settings; use crate::Settings;
#[test_case(CheckCode::RET501, Path::new("RET501.py"); "RET501")] #[test_case(RuleCode::RET501, Path::new("RET501.py"); "RET501")]
#[test_case(CheckCode::RET502, Path::new("RET502.py"); "RET502")] #[test_case(RuleCode::RET502, Path::new("RET502.py"); "RET502")]
#[test_case(CheckCode::RET503, Path::new("RET503.py"); "RET503")] #[test_case(RuleCode::RET503, Path::new("RET503.py"); "RET503")]
#[test_case(CheckCode::RET504, Path::new("RET504.py"); "RET504")] #[test_case(RuleCode::RET504, Path::new("RET504.py"); "RET504")]
#[test_case(CheckCode::RET505, Path::new("RET505.py"); "RET505")] #[test_case(RuleCode::RET505, Path::new("RET505.py"); "RET505")]
#[test_case(CheckCode::RET506, Path::new("RET506.py"); "RET506")] #[test_case(RuleCode::RET506, Path::new("RET506.py"); "RET506")]
#[test_case(CheckCode::RET507, Path::new("RET507.py"); "RET507")] #[test_case(RuleCode::RET507, Path::new("RET507.py"); "RET507")]
#[test_case(CheckCode::RET508, Path::new("RET508.py"); "RET508")] #[test_case(RuleCode::RET508, Path::new("RET508.py"); "RET508")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> { fn diagnostics(rule_code: RuleCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy()); let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let checks = test_path( let diagnostics = test_path(
Path::new("./resources/test/fixtures/flake8_return") Path::new("./resources/test/fixtures/flake8_return")
.join(path) .join(path)
.as_path(), .as_path(),
&Settings::for_rule(check_code), &Settings::for_rule(rule_code),
)?; )?;
insta::assert_yaml_snapshot!(snapshot, checks); insta::assert_yaml_snapshot!(snapshot, diagnostics);
Ok(()) Ok(())
} }
} }

View File

@ -8,8 +8,8 @@ use crate::autofix::Fix;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::flake8_return::helpers::result_exists; use crate::flake8_return::helpers::result_exists;
use crate::flake8_return::visitor::{ReturnVisitor, Stack}; use crate::flake8_return::visitor::{ReturnVisitor, Stack};
use crate::registry::{Branch, CheckCode}; use crate::registry::{Branch, RuleCode};
use crate::{violations, Check}; use crate::{violations, Diagnostic};
/// RET501 /// RET501
fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) { fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) {
@ -26,15 +26,16 @@ fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) {
) { ) {
continue; continue;
} }
let mut check = Check::new(violations::UnnecessaryReturnNone, Range::from_located(stmt)); let mut check =
if checker.patch(&CheckCode::RET501) { Diagnostic::new(violations::UnnecessaryReturnNone, Range::from_located(stmt));
if checker.patch(&RuleCode::RET501) {
check.amend(Fix::replacement( check.amend(Fix::replacement(
"return".to_string(), "return".to_string(),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
@ -44,15 +45,15 @@ fn implicit_return_value(checker: &mut Checker, stack: &Stack) {
if expr.is_some() { if expr.is_some() {
continue; continue;
} }
let mut check = Check::new(violations::ImplicitReturnValue, Range::from_located(stmt)); let mut check = Diagnostic::new(violations::ImplicitReturnValue, Range::from_located(stmt));
if checker.patch(&CheckCode::RET502) { if checker.patch(&RuleCode::RET502) {
check.amend(Fix::replacement( check.amend(Fix::replacement(
"return None".to_string(), "return None".to_string(),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
@ -61,7 +62,7 @@ fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) {
match &last_stmt.node { match &last_stmt.node {
StmtKind::If { body, orelse, .. } => { StmtKind::If { body, orelse, .. } => {
if body.is_empty() || orelse.is_empty() { if body.is_empty() || orelse.is_empty() {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::ImplicitReturn, violations::ImplicitReturn,
Range::from_located(last_stmt), Range::from_located(last_stmt),
)); ));
@ -100,8 +101,9 @@ fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) {
| StmtKind::Raise { .. } | StmtKind::Raise { .. }
| StmtKind::Try { .. } => {} | StmtKind::Try { .. } => {}
_ => { _ => {
let mut check = Check::new(violations::ImplicitReturn, Range::from_located(last_stmt)); let mut check =
if checker.patch(&CheckCode::RET503) { Diagnostic::new(violations::ImplicitReturn, Range::from_located(last_stmt));
if checker.patch(&RuleCode::RET503) {
let mut content = String::new(); let mut content = String::new();
content.push_str(&indentation(checker, last_stmt)); content.push_str(&indentation(checker, last_stmt));
content.push_str("return None"); content.push_str("return None");
@ -111,7 +113,7 @@ fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) {
Location::new(last_stmt.end_location.unwrap().row() + 1, 0), Location::new(last_stmt.end_location.unwrap().row() + 1, 0),
)); ));
} }
checker.checks.push(check); checker.diagnostics.push(check);
} }
} }
} }
@ -190,7 +192,7 @@ fn unnecessary_assign(checker: &mut Checker, stack: &Stack, expr: &Expr) {
} }
if !stack.refs.contains_key(id.as_str()) { if !stack.refs.contains_key(id.as_str()) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UnnecessaryAssign, violations::UnnecessaryAssign,
Range::from_located(expr), Range::from_located(expr),
)); ));
@ -207,7 +209,7 @@ fn unnecessary_assign(checker: &mut Checker, stack: &Stack, expr: &Expr) {
return; return;
} }
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::UnnecessaryAssign, violations::UnnecessaryAssign,
Range::from_located(expr), Range::from_located(expr),
)); ));
@ -221,8 +223,8 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) ->
}; };
for child in body { for child in body {
if matches!(child.node, StmtKind::Return { .. }) { if matches!(child.node, StmtKind::Return { .. }) {
if checker.settings.enabled.contains(&CheckCode::RET505) { if checker.settings.enabled.contains(&RuleCode::RET505) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SuperfluousElseReturn(branch), violations::SuperfluousElseReturn(branch),
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -230,8 +232,8 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) ->
return true; return true;
} }
if matches!(child.node, StmtKind::Break) { if matches!(child.node, StmtKind::Break) {
if checker.settings.enabled.contains(&CheckCode::RET508) { if checker.settings.enabled.contains(&RuleCode::RET508) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SuperfluousElseBreak(branch), violations::SuperfluousElseBreak(branch),
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -239,8 +241,8 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) ->
return true; return true;
} }
if matches!(child.node, StmtKind::Raise { .. }) { if matches!(child.node, StmtKind::Raise { .. }) {
if checker.settings.enabled.contains(&CheckCode::RET506) { if checker.settings.enabled.contains(&RuleCode::RET506) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SuperfluousElseRaise(branch), violations::SuperfluousElseRaise(branch),
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -248,8 +250,8 @@ fn superfluous_else_node(checker: &mut Checker, stmt: &Stmt, branch: Branch) ->
return true; return true;
} }
if matches!(child.node, StmtKind::Continue) { if matches!(child.node, StmtKind::Continue) {
if checker.settings.enabled.contains(&CheckCode::RET507) { if checker.settings.enabled.contains(&RuleCode::RET507) {
checker.checks.push(Check::new( checker.diagnostics.push(Diagnostic::new(
violations::SuperfluousElseContinue(branch), violations::SuperfluousElseContinue(branch),
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -310,10 +312,10 @@ pub fn function(checker: &mut Checker, body: &[Stmt]) {
visitor.stack visitor.stack
}; };
if checker.settings.enabled.contains(&CheckCode::RET505) if checker.settings.enabled.contains(&RuleCode::RET505)
|| checker.settings.enabled.contains(&CheckCode::RET506) || checker.settings.enabled.contains(&RuleCode::RET506)
|| checker.settings.enabled.contains(&CheckCode::RET507) || checker.settings.enabled.contains(&RuleCode::RET507)
|| checker.settings.enabled.contains(&CheckCode::RET508) || checker.settings.enabled.contains(&RuleCode::RET508)
{ {
if superfluous_elif(checker, &stack) { if superfluous_elif(checker, &stack) {
return; return;
@ -329,20 +331,20 @@ pub fn function(checker: &mut Checker, body: &[Stmt]) {
} }
if !result_exists(&stack.returns) { if !result_exists(&stack.returns) {
if checker.settings.enabled.contains(&CheckCode::RET501) { if checker.settings.enabled.contains(&RuleCode::RET501) {
unnecessary_return_none(checker, &stack); unnecessary_return_none(checker, &stack);
} }
return; return;
} }
if checker.settings.enabled.contains(&CheckCode::RET502) { if checker.settings.enabled.contains(&RuleCode::RET502) {
implicit_return_value(checker, &stack); implicit_return_value(checker, &stack);
} }
if checker.settings.enabled.contains(&CheckCode::RET503) { if checker.settings.enabled.contains(&RuleCode::RET503) {
implicit_return(checker, last_stmt); implicit_return(checker, last_stmt);
} }
if checker.settings.enabled.contains(&CheckCode::RET504) { if checker.settings.enabled.contains(&RuleCode::RET504) {
for (_, expr) in &stack.returns { for (_, expr) in &stack.returns {
if let Some(expr) = expr { if let Some(expr) = expr {
unnecessary_assign(checker, &stack, expr); unnecessary_assign(checker, &stack, expr);

Some files were not shown because too many files have changed in this diff Show More