Compare commits

...

8 Commits

Author SHA1 Message Date
Charlie Marsh
1e19142d0e Bump version to 0.0.184 2022-12-16 14:36:25 -05:00
Charlie Marsh
6a95dade6d Actually check-in snapshots for #1265 2022-12-16 14:36:00 -05:00
Charlie Marsh
d6e765877e Enable autofix for __init__ method with missing None-return (#1265) 2022-12-16 14:28:56 -05:00
Charlie Marsh
e4d36bae57 Replace ignore_noqa and autofix booleans with enums (#1264) 2022-12-16 14:01:25 -05:00
Harutaka Kawamura
e3531276a7 Fix F501 (line-too-long) start location (#1262) 2022-12-16 11:29:47 -05:00
Charlie Marsh
634553f188 Add ignore-variadic-names options to flake8-unused-arguments (#1261) 2022-12-16 00:22:38 -05:00
Edgar R. M
4ff0b75045 test: Fix flake8-errmsg snapshots (#1260) 2022-12-15 23:53:15 -05:00
Charlie Marsh
481d668511 Add flake8-errmsg to README 2022-12-15 23:16:38 -05:00
66 changed files with 638 additions and 178 deletions

View File

@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.183
rev: v0.0.184
hooks:
- id: ruff

8
Cargo.lock generated
View File

@@ -724,7 +724,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flake8-to-ruff"
version = "0.0.183-dev.0"
version = "0.0.184-dev.0"
dependencies = [
"anyhow",
"clap 4.0.29",
@@ -1845,7 +1845,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.183"
version = "0.0.184"
dependencies = [
"annotate-snippets 0.9.1",
"anyhow",
@@ -1901,7 +1901,7 @@ dependencies = [
[[package]]
name = "ruff_dev"
version = "0.0.183"
version = "0.0.184"
dependencies = [
"anyhow",
"clap 4.0.29",
@@ -1919,7 +1919,7 @@ dependencies = [
[[package]]
name = "ruff_macros"
version = "0.0.183"
version = "0.0.184"
dependencies = [
"proc-macro2",
"quote",

View File

@@ -6,7 +6,7 @@ members = [
[package]
name = "ruff"
version = "0.0.183"
version = "0.0.184"
edition = "2021"
rust-version = "1.65.0"
@@ -43,7 +43,7 @@ quick-junit = { version = "0.3.2" }
rayon = { version = "1.5.3" }
regex = { version = "1.6.0" }
ropey = { version = "1.5.0", features = ["cr_lines", "simd"], default-features = false }
ruff_macros = { version = "0.0.183", path = "ruff_macros" }
ruff_macros = { version = "0.0.184", path = "ruff_macros" }
rustc-hash = { version = "1.1.0" }
rustpython-ast = { features = ["unparse"], git = "https://github.com/RustPython/RustPython.git", rev = "8d879a53197f9c73062f6160410bdba796a71cbf" }
rustpython-common = { git = "https://github.com/RustPython/RustPython.git", rev = "8d879a53197f9c73062f6160410bdba796a71cbf" }

View File

@@ -157,7 +157,7 @@ Ruff also works with [pre-commit](https://pre-commit.com):
```yaml
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.183
rev: v0.0.184
hooks:
- id: ruff
```
@@ -673,7 +673,7 @@ For more, see [flake8-annotations](https://pypi.org/project/flake8-annotations/2
| ANN102 | MissingTypeCls | Missing type annotation for `...` in classmethod | |
| ANN201 | MissingReturnTypePublicFunction | Missing return type annotation for public function `...` | |
| ANN202 | MissingReturnTypePrivateFunction | Missing return type annotation for private function `...` | |
| ANN204 | MissingReturnTypeMagicMethod | Missing return type annotation for magic method `...` | |
| ANN204 | MissingReturnTypeSpecialMethod | Missing return type annotation for special method `...` | 🛠 |
| ANN205 | MissingReturnTypeStaticMethod | Missing return type annotation for staticmethod `...` | |
| ANN206 | MissingReturnTypeClassMethod | Missing return type annotation for classmethod `...` | |
| ANN401 | DynamicallyTypedExpression | Dynamically typed expressions (typing.Any) are disallowed in `...` | |
@@ -1100,6 +1100,7 @@ natively, including:
- [`flake8-debugger`](https://pypi.org/project/flake8-debugger/)
- [`flake8-docstrings`](https://pypi.org/project/flake8-docstrings/)
- [`flake8-eradicate`](https://pypi.org/project/flake8-eradicate/)
- [`flake8-errmsg`](https://pypi.org/project/flake8-errmsg/)
- [`flake8-import-conventions`](https://github.com/joaopalmeiro/flake8-import-conventions)
- [`flake8-print`](https://pypi.org/project/flake8-print/)
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
@@ -1153,6 +1154,7 @@ Today, Ruff can be used to replace Flake8 when used with any of the following pl
- [`flake8-debugger`](https://pypi.org/project/flake8-debugger/)
- [`flake8-docstrings`](https://pypi.org/project/flake8-docstrings/)
- [`flake8-eradicate`](https://pypi.org/project/flake8-eradicate/)
- [`flake8-errmsg`](https://pypi.org/project/flake8-errmsg/)
- [`flake8-import-conventions`](https://github.com/joaopalmeiro/flake8-import-conventions)
- [`flake8-print`](https://pypi.org/project/flake8-print/)
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
@@ -2142,6 +2144,25 @@ ban-relative-imports = "all"
---
### `flake8-unused-arguments`
#### [`ignore-variadic-names`](#ignore-variadic-names)
Whether to allow unused variadic arguments, like `*args` and `**kwargs`.
**Default value**: `false`
**Type**: `bool`
**Example usage**:
```toml
[tool.ruff.flake8-unused-arguments]
ignore-variadic-names = true
```
---
### `isort`
#### [`combine-as-imports`](#combine-as-imports)

View File

@@ -771,7 +771,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flake8_to_ruff"
version = "0.0.183"
version = "0.0.184"
dependencies = [
"anyhow",
"clap",
@@ -1975,7 +1975,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.183"
version = "0.0.184"
dependencies = [
"anyhow",
"bincode",

View File

@@ -1,6 +1,6 @@
[package]
name = "flake8-to-ruff"
version = "0.0.183-dev.0"
version = "0.0.184-dev.0"
edition = "2021"
[lib]

View File

@@ -288,6 +288,7 @@ mod tests {
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -336,6 +337,7 @@ mod tests {
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -384,6 +386,7 @@ mod tests {
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -432,6 +435,7 @@ mod tests {
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -485,6 +489,7 @@ mod tests {
}),
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -572,6 +577,7 @@ mod tests {
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -626,6 +632,7 @@ mod tests {
}),
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,

View File

@@ -5,6 +5,10 @@ def f_a():
raise RuntimeError("This is an example exception")
def f_a_short():
raise RuntimeError("Error")
def f_b():
example = "example"
raise RuntimeError(f"This is an {example} exception")

View File

@@ -27,7 +27,7 @@ def f(cls, x):
lambda x: print("Hello, world!")
class X:
class C:
###
# Unused arguments.
###

View File

@@ -0,0 +1,14 @@
def f(a, b):
print("Hello, world!")
def f(a, b, *args, **kwargs):
print("Hello, world!")
class C:
def f(self, a, b):
print("Hello, world!")
def f(self, a, b, *args, **kwargs):
print("Hello, world!")

View File

@@ -1,6 +1,6 @@
[package]
name = "ruff_dev"
version = "0.0.183"
version = "0.0.184"
edition = "2021"
[dependencies]

View File

@@ -1,6 +1,6 @@
[package]
name = "ruff_macros"
version = "0.0.183"
version = "0.0.184"
edition = "2021"
[lib]

View File

@@ -27,15 +27,6 @@ impl From<bool> for Mode {
}
}
impl From<&Mode> for bool {
fn from(value: &Mode) -> Self {
match value {
Mode::Generate | Mode::Apply => true,
Mode::None => false,
}
}
}
/// Auto-fix errors in a file, and write the fixed source code to disk.
pub fn fix_file<'a>(
checks: &'a [Check],

View File

@@ -31,7 +31,7 @@ use crate::python::future::ALL_FEATURE_NAMES;
use crate::python::typing;
use crate::python::typing::SubscriptKind;
use crate::settings::types::PythonVersion;
use crate::settings::Settings;
use crate::settings::{flags, Settings};
use crate::source_code_locator::SourceCodeLocator;
use crate::vendored::cformat::{CFormatError, CFormatErrorType};
use crate::visibility::{module_visibility, transition_scope, Modifier, Visibility, VisibleScope};
@@ -51,8 +51,8 @@ type DeferralContext<'a> = (Vec<usize>, Vec<RefEquality<'a, Stmt>>);
pub struct Checker<'a> {
// Input data.
path: &'a Path,
autofix: bool,
ignore_noqa: bool,
autofix: flags::Autofix,
noqa: flags::Noqa,
pub(crate) settings: &'a Settings,
pub(crate) noqa_line_for: &'a IntMap<usize, usize>,
pub(crate) locator: &'a SourceCodeLocator<'a>,
@@ -102,8 +102,8 @@ impl<'a> Checker<'a> {
pub fn new(
settings: &'a Settings,
noqa_line_for: &'a IntMap<usize, usize>,
autofix: bool,
ignore_noqa: bool,
autofix: flags::Autofix,
noqa: flags::Noqa,
path: &'a Path,
locator: &'a SourceCodeLocator,
) -> Checker<'a> {
@@ -111,7 +111,7 @@ impl<'a> Checker<'a> {
settings,
noqa_line_for,
autofix,
ignore_noqa,
noqa,
path,
locator,
checks: vec![],
@@ -182,7 +182,9 @@ impl<'a> Checker<'a> {
pub fn patch(&self, code: &CheckCode) -> bool {
// TODO(charlie): We can't fix errors in f-strings until RustPython adds
// location data.
self.autofix && self.in_f_string.is_none() && self.settings.fixable.contains(code)
matches!(self.autofix, flags::Autofix::Enabled)
&& self.in_f_string.is_none()
&& self.settings.fixable.contains(code)
}
/// Return `true` if the `Expr` is a reference to `typing.${target}`.
@@ -216,7 +218,7 @@ impl<'a> Checker<'a> {
// members from the fix that will eventually be excluded by a `noqa`.
// Unfortunately, we _do_ want to register a `Check` for each eventually-ignored
// import, so that our `noqa` counts are accurate.
if self.ignore_noqa {
if matches!(self.noqa, flags::Noqa::Disabled) {
return false;
}
let noqa_lineno = self.noqa_line_for.get(&lineno).unwrap_or(&lineno);
@@ -3758,11 +3760,11 @@ pub fn check_ast(
locator: &SourceCodeLocator,
noqa_line_for: &IntMap<usize, usize>,
settings: &Settings,
autofix: bool,
ignore_noqa: bool,
autofix: flags::Autofix,
noqa: flags::Noqa,
path: &Path,
) -> Vec<Check> {
let mut checker = Checker::new(settings, noqa_line_for, autofix, ignore_noqa, path, locator);
let mut checker = Checker::new(settings, noqa_line_for, autofix, noqa, path, locator);
checker.push_scope(Scope::new(ScopeKind::Module));
checker.bind_builtins();

View File

@@ -9,14 +9,14 @@ use crate::checks::Check;
use crate::directives::IsortDirectives;
use crate::isort;
use crate::isort::track::ImportTracker;
use crate::settings::Settings;
use crate::settings::{flags, Settings};
use crate::source_code_locator::SourceCodeLocator;
fn check_import_blocks(
tracker: ImportTracker,
locator: &SourceCodeLocator,
settings: &Settings,
autofix: bool,
autofix: flags::Autofix,
) -> Vec<Check> {
let mut checks = vec![];
for block in tracker.into_iter() {
@@ -34,7 +34,7 @@ pub fn check_imports(
locator: &SourceCodeLocator,
directives: &IsortDirectives,
settings: &Settings,
autofix: bool,
autofix: flags::Autofix,
path: &Path,
) -> Vec<Check> {
let mut tracker = ImportTracker::new(locator, directives, path);

View File

@@ -10,7 +10,7 @@ use crate::autofix::Fix;
use crate::checks::{Check, CheckCode, CheckKind, CODE_REDIRECTS};
use crate::noqa;
use crate::noqa::{is_file_exempt, Directive};
use crate::settings::Settings;
use crate::settings::{flags, Settings};
// Regex from PEP263.
static CODING_COMMENT_REGEX: Lazy<Regex> =
@@ -39,8 +39,8 @@ pub fn check_lines(
contents: &str,
noqa_line_for: &IntMap<usize, usize>,
settings: &Settings,
autofix: bool,
ignore_noqa: bool,
autofix: flags::Autofix,
noqa: flags::Noqa,
) {
let enforce_unnecessary_coding_comment = settings.enabled.contains(&CheckCode::UP009);
let enforce_line_too_long = settings.enabled.contains(&CheckCode::E501);
@@ -64,14 +64,14 @@ pub fn check_lines(
{
(Directive::All(..), matches) => {
matches.push($check.kind.code().as_ref());
if ignore_noqa {
if matches!(noqa, flags::Noqa::Disabled) {
line_checks.push($check);
}
}
(Directive::Codes(.., codes), matches) => {
if noqa::includes($check.kind.code(), codes) {
matches.push($check.kind.code().as_ref());
if ignore_noqa {
if matches!(noqa, flags::Noqa::Disabled) {
line_checks.push($check);
}
} else {
@@ -108,7 +108,9 @@ pub fn check_lines(
end_location: Location::new(lineno + 2, 0),
},
);
if autofix && settings.fixable.contains(check.kind.code()) {
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code())
{
check.amend(Fix::deletion(
Location::new(lineno + 1, 0),
Location::new(lineno + 2, 0),
@@ -155,7 +157,7 @@ pub fn check_lines(
let check = Check::new(
CheckKind::LineTooLong(line_length, settings.line_length),
Range {
location: Location::new(lineno + 1, 0),
location: Location::new(lineno + 1, settings.line_length),
end_location: Location::new(lineno + 1, line_length),
},
);
@@ -196,7 +198,9 @@ pub fn check_lines(
end_location: Location::new(row + 1, end),
},
);
if autofix && settings.fixable.contains(check.kind.code()) {
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code())
{
check.amend(Fix::deletion(
Location::new(row + 1, start - spaces),
Location::new(row + 1, lines[row].chars().count()),
@@ -225,7 +229,9 @@ pub fn check_lines(
end_location: Location::new(row + 1, end),
},
);
if autofix && settings.fixable.contains(check.kind.code()) {
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code())
{
if valid_codes.is_empty() {
check.amend(Fix::deletion(
Location::new(row + 1, start - spaces),
@@ -247,7 +253,7 @@ pub fn check_lines(
}
}
if !ignore_noqa {
if matches!(noqa, flags::Noqa::Enabled) {
ignored.sort_unstable();
for index in ignored.iter().rev() {
checks.swap_remove(*index);
@@ -262,7 +268,7 @@ mod tests {
use super::check_lines;
use crate::checks::{Check, CheckCode};
use crate::settings::Settings;
use crate::settings::{flags, Settings};
#[test]
fn e501_non_ascii_char() {
@@ -277,8 +283,8 @@ mod tests {
line_length,
..Settings::for_rule(CheckCode::E501)
},
true,
false,
flags::Autofix::Enabled,
flags::Noqa::Enabled,
);
checks
};

View File

@@ -5,6 +5,7 @@ use rustpython_parser::lexer::{LexResult, Tok};
use crate::checks::{Check, CheckCode};
use crate::lex::docstring_detection::StateMachine;
use crate::ruff::checks::Context;
use crate::settings::flags;
use crate::source_code_locator::SourceCodeLocator;
use crate::{eradicate, flake8_quotes, pycodestyle, ruff, Settings};
@@ -12,7 +13,7 @@ pub fn check_tokens(
locator: &SourceCodeLocator,
tokens: &[LexResult],
settings: &Settings,
autofix: bool,
autofix: flags::Autofix,
) -> Vec<Check> {
let mut checks: Vec<Check> = vec![];

View File

@@ -772,7 +772,7 @@ pub enum CheckKind {
MissingTypeCls(String),
MissingReturnTypePublicFunction(String),
MissingReturnTypePrivateFunction(String),
MissingReturnTypeMagicMethod(String),
MissingReturnTypeSpecialMethod(String),
MissingReturnTypeStaticMethod(String),
MissingReturnTypeClassMethod(String),
DynamicallyTypedExpression(String),
@@ -1126,7 +1126,7 @@ impl CheckCode {
CheckCode::ANN102 => CheckKind::MissingTypeCls("...".to_string()),
CheckCode::ANN201 => CheckKind::MissingReturnTypePublicFunction("...".to_string()),
CheckCode::ANN202 => CheckKind::MissingReturnTypePrivateFunction("...".to_string()),
CheckCode::ANN204 => CheckKind::MissingReturnTypeMagicMethod("...".to_string()),
CheckCode::ANN204 => CheckKind::MissingReturnTypeSpecialMethod("...".to_string()),
CheckCode::ANN205 => CheckKind::MissingReturnTypeStaticMethod("...".to_string()),
CheckCode::ANN206 => CheckKind::MissingReturnTypeClassMethod("...".to_string()),
CheckCode::ANN401 => CheckKind::DynamicallyTypedExpression("...".to_string()),
@@ -1733,7 +1733,7 @@ impl CheckKind {
CheckKind::MissingTypeCls(_) => &CheckCode::ANN102,
CheckKind::MissingReturnTypePublicFunction(_) => &CheckCode::ANN201,
CheckKind::MissingReturnTypePrivateFunction(_) => &CheckCode::ANN202,
CheckKind::MissingReturnTypeMagicMethod(_) => &CheckCode::ANN204,
CheckKind::MissingReturnTypeSpecialMethod(_) => &CheckCode::ANN204,
CheckKind::MissingReturnTypeStaticMethod(_) => &CheckCode::ANN205,
CheckKind::MissingReturnTypeClassMethod(_) => &CheckCode::ANN206,
CheckKind::DynamicallyTypedExpression(_) => &CheckCode::ANN401,
@@ -2390,8 +2390,8 @@ impl CheckKind {
CheckKind::MissingReturnTypePrivateFunction(name) => {
format!("Missing return type annotation for private function `{name}`")
}
CheckKind::MissingReturnTypeMagicMethod(name) => {
format!("Missing return type annotation for magic method `{name}`")
CheckKind::MissingReturnTypeSpecialMethod(name) => {
format!("Missing return type annotation for special method `{name}`")
}
CheckKind::MissingReturnTypeStaticMethod(name) => {
format!("Missing return type annotation for staticmethod `{name}`")
@@ -2817,7 +2817,6 @@ impl CheckKind {
| CheckKind::CommentedOutCode
| CheckKind::ConvertNamedTupleFunctionalToClass(..)
| CheckKind::ConvertTypedDictFunctionalToClass(..)
| CheckKind::RemoveSixCompat
| CheckKind::DashedUnderlineAfterSection(..)
| CheckKind::DeprecatedUnittestAlias(..)
| CheckKind::DoNotAssertFalse
@@ -2831,6 +2830,7 @@ impl CheckKind {
| CheckKind::IsLiteral
| CheckKind::KeyInDict(..)
| CheckKind::MisplacedComparisonConstant(..)
| CheckKind::MissingReturnTypeSpecialMethod(..)
| CheckKind::NewLineAfterLastParagraph
| CheckKind::NewLineAfterSectionName(..)
| CheckKind::NoBlankLineAfterFunction(..)
@@ -2845,13 +2845,14 @@ impl CheckKind {
| CheckKind::NotIsTest
| CheckKind::OneBlankLineAfterClass(..)
| CheckKind::OneBlankLineBeforeClass(..)
| CheckKind::PercentFormatExtraNamedArguments(..)
| CheckKind::PEP3120UnnecessaryCodingComment
| CheckKind::PPrintFound
| CheckKind::PercentFormatExtraNamedArguments(..)
| CheckKind::PrintFound
| CheckKind::RaiseNotImplemented
| CheckKind::RedundantOpenModes
| CheckKind::RedundantTupleInExceptionHandler(..)
| CheckKind::RemoveSixCompat
| CheckKind::SectionNameEndsInColon(..)
| CheckKind::SectionNotOverIndented(..)
| CheckKind::SectionUnderlineAfterName(..)

View File

@@ -4,6 +4,7 @@ use crate::ast::types::Range;
use crate::autofix::Fix;
use crate::checks::{CheckCode, CheckKind};
use crate::eradicate::detection::comment_contains_code;
use crate::settings::flags;
use crate::{Check, Settings, SourceCodeLocator};
fn is_standalone_comment(line: &str) -> bool {
@@ -23,7 +24,7 @@ pub fn commented_out_code(
start: Location,
end: Location,
settings: &Settings,
autofix: bool,
autofix: flags::Autofix,
) -> Option<Check> {
let location = Location::new(start.row(), 0);
let end_location = Location::new(end.row() + 1, 0);
@@ -41,7 +42,9 @@ pub fn commented_out_code(
end_location: end,
},
);
if autofix && settings.fixable.contains(&CheckCode::ERA001) {
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&CheckCode::ERA001)
{
check.amend(Fix::deletion(location, end_location));
}
Some(check)

View File

@@ -21,7 +21,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -29,7 +29,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -0,0 +1,45 @@
use anyhow::{bail, Result};
use rustpython_ast::Stmt;
use rustpython_parser::lexer;
use rustpython_parser::lexer::Tok;
use crate::ast::helpers;
use crate::ast::types::Range;
use crate::autofix::Fix;
use crate::source_code_locator::SourceCodeLocator;
/// ANN204
pub fn add_return_none_annotation(locator: &SourceCodeLocator, stmt: &Stmt) -> Result<Fix> {
let range = Range::from_located(stmt);
let contents = locator.slice_source_code_range(&range);
// Find the colon (following the `def` keyword).
let mut seen_lpar = false;
let mut seen_rpar = false;
let mut count: usize = 0;
for (start, tok, ..) in lexer::make_tokenizer(&contents).flatten() {
if seen_lpar && seen_rpar {
if matches!(tok, Tok::Colon) {
return Ok(Fix::insertion(
" -> None".to_string(),
helpers::to_absolute(start, range.location),
));
}
}
if matches!(tok, Tok::Lpar) {
if count == 0 {
seen_lpar = true;
}
count += 1;
}
if matches!(tok, Tok::Rpar) {
count -= 1;
if count == 0 {
seen_rpar = true;
}
}
}
bail!("Unable to locate colon in function definition");
}

View File

@@ -1,3 +1,4 @@
mod fixes;
pub mod helpers;
pub mod plugins;
pub mod settings;
@@ -31,7 +32,6 @@ mod tests {
CheckCode::ANN401,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -57,7 +57,6 @@ mod tests {
CheckCode::ANN102,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -83,7 +82,6 @@ mod tests {
CheckCode::ANN206,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -109,7 +107,6 @@ mod tests {
CheckCode::ANN206,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -129,7 +126,6 @@ mod tests {
},
..Settings::for_rules(vec![CheckCode::ANN401])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -149,7 +145,6 @@ mod tests {
CheckCode::ANN206,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);

View File

@@ -1,3 +1,4 @@
use log::error;
use rustpython_ast::{Constant, Expr, ExprKind, Stmt, StmtKind};
use crate::ast::types::Range;
@@ -6,6 +7,7 @@ use crate::ast::{cast, visitor};
use crate::check_ast::Checker;
use crate::checks::{CheckCode, CheckKind};
use crate::docstrings::definition::{Definition, DefinitionKind};
use crate::flake8_annotations::fixes;
use crate::flake8_annotations::helpers::match_function_def;
use crate::visibility::Visibility;
use crate::{visibility, Check};
@@ -295,8 +297,8 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
check_dynamically_typed(checker, expr, || name.to_string());
}
} else {
// Allow omission of return annotation in `__init__` functions, if the function
// only returns `None` (explicitly or implicitly).
// Allow omission of return annotation if the function only returns `None`
// (explicitly or implicitly).
if checker.settings.flake8_annotations.suppress_none_returning
&& is_none_returning(body)
{
@@ -317,13 +319,6 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
Range::from_located(stmt),
));
}
} else if visibility::is_magic(stmt) {
if checker.settings.enabled.contains(&CheckCode::ANN204) {
checker.add_check(Check::new(
CheckKind::MissingReturnTypeMagicMethod(name.to_string()),
Range::from_located(stmt),
));
}
} else if visibility::is_init(stmt) {
// Allow omission of return annotation in `__init__` functions, as long as at
// least one argument is typed.
@@ -331,12 +326,26 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if !(checker.settings.flake8_annotations.mypy_init_return
&& has_any_typed_arg)
{
checker.add_check(Check::new(
CheckKind::MissingReturnTypeMagicMethod(name.to_string()),
let mut check = Check::new(
CheckKind::MissingReturnTypeSpecialMethod(name.to_string()),
Range::from_located(stmt),
));
);
if checker.patch(check.kind.code()) {
match fixes::add_return_none_annotation(checker.locator, stmt) {
Ok(fix) => check.amend(fix),
Err(e) => error!("Failed to generate fix: {e}"),
}
}
checker.add_check(check);
}
}
} else if visibility::is_magic(stmt) {
if checker.settings.enabled.contains(&CheckCode::ANN204) {
checker.add_check(Check::new(
CheckKind::MissingReturnTypeSpecialMethod(name.to_string()),
Range::from_located(stmt),
));
}
} else {
match visibility {
Visibility::Public => {

View File

@@ -3,23 +3,37 @@ source: src/flake8_annotations/mod.rs
expression: checks
---
- kind:
MissingReturnTypeMagicMethod: __init__
MissingReturnTypeSpecialMethod: __init__
location:
row: 5
column: 4
end_location:
row: 6
column: 11
fix: ~
fix:
content: " -> None"
location:
row: 5
column: 22
end_location:
row: 5
column: 22
- kind:
MissingReturnTypeMagicMethod: __init__
MissingReturnTypeSpecialMethod: __init__
location:
row: 11
column: 4
end_location:
row: 12
column: 11
fix: ~
fix:
content: " -> None"
location:
row: 11
column: 27
end_location:
row: 11
column: 27
- kind:
MissingReturnTypePrivateFunction: __init__
location:

View File

@@ -26,7 +26,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -20,7 +20,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -22,7 +22,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -47,7 +47,6 @@ mod tests {
.join(path)
.as_path(),
&Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -68,7 +67,6 @@ mod tests {
},
..Settings::for_rules(vec![CheckCode::B008])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -23,7 +23,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -37,7 +37,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -20,7 +20,6 @@ mod tests {
CheckCode::EM102,
CheckCode::EM103,
]),
false,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!("defaults", checks);
@@ -41,7 +40,6 @@ mod tests {
CheckCode::EM103,
])
},
false,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!("custom", checks);

View File

@@ -12,18 +12,18 @@ expression: checks
fix: ~
- kind: FStringInException
location:
row: 10
row: 14
column: 23
end_location:
row: 10
row: 14
column: 56
fix: ~
- kind: DotFormatInException
location:
row: 14
row: 18
column: 23
end_location:
row: 14
row: 18
column: 81
fix: ~

View File

@@ -10,20 +10,28 @@ expression: checks
row: 5
column: 53
fix: ~
- kind: FStringInException
- kind: RawStringInException
location:
row: 10
row: 9
column: 23
end_location:
row: 10
row: 9
column: 30
fix: ~
- kind: FStringInException
location:
row: 14
column: 23
end_location:
row: 14
column: 56
fix: ~
- kind: DotFormatInException
location:
row: 14
row: 18
column: 23
end_location:
row: 14
row: 18
column: 81
fix: ~

View File

@@ -18,7 +18,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/flake8_import_conventions/defaults.py"),
&Settings::for_rule(CheckCode::ICN001),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!("defaults", checks);
@@ -42,7 +41,6 @@ mod tests {
),
..Settings::for_rule(CheckCode::ICN001)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!("custom", checks);
@@ -68,7 +66,6 @@ mod tests {
),
..Settings::for_rule(CheckCode::ICN001)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!("remove_default", checks);
@@ -92,7 +89,6 @@ mod tests {
),
..Settings::for_rule(CheckCode::ICN001)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!("override_default", checks);

View File

@@ -23,7 +23,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -38,7 +38,6 @@ mod tests {
CheckCode::Q003,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -70,7 +69,6 @@ mod tests {
CheckCode::Q003,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -107,7 +105,6 @@ mod tests {
CheckCode::Q003,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -144,7 +141,6 @@ mod tests {
CheckCode::Q003,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -28,7 +28,6 @@ mod tests {
.join(path)
.as_path(),
&Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -20,7 +20,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -22,7 +22,6 @@ mod tests {
},
..Settings::for_rules(vec![CheckCode::TID252])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -39,7 +38,6 @@ mod tests {
},
..Settings::for_rules(vec![CheckCode::TID252])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);

View File

@@ -1,5 +1,6 @@
mod helpers;
pub mod plugins;
pub mod settings;
mod types;
#[cfg(test)]
@@ -12,7 +13,7 @@ mod tests {
use crate::checks::CheckCode;
use crate::linter::test_path;
use crate::settings;
use crate::{flake8_unused_arguments, settings};
#[test_case(CheckCode::ARG001, Path::new("ARG.py"); "ARG001")]
#[test_case(CheckCode::ARG002, Path::new("ARG.py"); "ARG002")]
@@ -26,10 +27,53 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
Ok(())
}
#[test]
fn ignore_variadic_names() -> Result<()> {
let mut checks = test_path(
Path::new("./resources/test/fixtures/flake8_unused_arguments/ignore_variadic_names.py"),
&settings::Settings {
flake8_unused_arguments: flake8_unused_arguments::settings::Settings {
ignore_variadic_names: true,
},
..settings::Settings::for_rules(vec![
CheckCode::ARG001,
CheckCode::ARG002,
CheckCode::ARG003,
CheckCode::ARG004,
CheckCode::ARG005,
])
},
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
Ok(())
}
#[test]
fn enforce_variadic_names() -> Result<()> {
let mut checks = test_path(
Path::new("./resources/test/fixtures/flake8_unused_arguments/ignore_variadic_names.py"),
&settings::Settings {
flake8_unused_arguments: flake8_unused_arguments::settings::Settings {
ignore_variadic_names: false,
},
..settings::Settings::for_rules(vec![
CheckCode::ARG001,
CheckCode::ARG002,
CheckCode::ARG003,
CheckCode::ARG004,
CheckCode::ARG005,
])
},
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
Ok(())
}
}

View File

@@ -6,7 +6,6 @@ use rustpython_ast::{Arg, Arguments};
use crate::ast::function_type;
use crate::ast::function_type::FunctionType;
use crate::ast::helpers::collect_arg_names;
use crate::ast::types::{Binding, BindingKind, FunctionDef, Lambda, Scope, ScopeKind};
use crate::check_ast::Checker;
use crate::flake8_unused_arguments::helpers;
@@ -20,16 +19,35 @@ fn function(
values: &FxHashMap<&str, usize>,
bindings: &[Binding],
dummy_variable_rgx: &Regex,
ignore_variadic_names: bool,
) -> Vec<Check> {
let mut checks: Vec<Check> = vec![];
for arg_name in collect_arg_names(args) {
if let Some(binding) = values.get(arg_name).map(|index| &bindings[*index]) {
for arg in args
.posonlyargs
.iter()
.chain(args.args.iter())
.chain(args.kwonlyargs.iter())
.chain(
iter::once::<Option<&Arg>>(args.vararg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
)
.chain(
iter::once::<Option<&Arg>>(args.kwarg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
)
{
if let Some(binding) = values
.get(&arg.node.arg.as_str())
.map(|index| &bindings[*index])
{
if binding.used.is_none()
&& matches!(binding.kind, BindingKind::Argument)
&& !dummy_variable_rgx.is_match(arg_name)
&& !dummy_variable_rgx.is_match(arg.node.arg.as_str())
{
checks.push(Check::new(
argumentable.check_for(arg_name.to_string()),
argumentable.check_for(arg.node.arg.to_string()),
binding.range,
));
}
@@ -45,6 +63,7 @@ fn method(
values: &FxHashMap<&str, usize>,
bindings: &[Binding],
dummy_variable_rgx: &Regex,
ignore_variadic_names: bool,
) -> Vec<Check> {
let mut checks: Vec<Check> = vec![];
for arg in args
@@ -53,8 +72,16 @@ fn method(
.chain(args.args.iter())
.skip(1)
.chain(args.kwonlyargs.iter())
.chain(iter::once::<Option<&Arg>>(args.vararg.as_deref()).flatten())
.chain(iter::once::<Option<&Arg>>(args.kwarg.as_deref()).flatten())
.chain(
iter::once::<Option<&Arg>>(args.vararg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
)
.chain(
iter::once::<Option<&Arg>>(args.kwarg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
)
{
if let Some(binding) = values
.get(&arg.node.arg.as_str())
@@ -110,6 +137,10 @@ pub fn unused_arguments(
&scope.values,
bindings,
&checker.settings.dummy_variable_rgx,
checker
.settings
.flake8_unused_arguments
.ignore_variadic_names,
)
} else {
vec![]
@@ -130,6 +161,10 @@ pub fn unused_arguments(
&scope.values,
bindings,
&checker.settings.dummy_variable_rgx,
checker
.settings
.flake8_unused_arguments
.ignore_variadic_names,
)
} else {
vec![]
@@ -150,6 +185,10 @@ pub fn unused_arguments(
&scope.values,
bindings,
&checker.settings.dummy_variable_rgx,
checker
.settings
.flake8_unused_arguments
.ignore_variadic_names,
)
} else {
vec![]
@@ -170,6 +209,10 @@ pub fn unused_arguments(
&scope.values,
bindings,
&checker.settings.dummy_variable_rgx,
checker
.settings
.flake8_unused_arguments
.ignore_variadic_names,
)
} else {
vec![]
@@ -189,6 +232,10 @@ pub fn unused_arguments(
&scope.values,
bindings,
&checker.settings.dummy_variable_rgx,
checker
.settings
.flake8_unused_arguments
.ignore_variadic_names,
)
} else {
vec![]

View File

@@ -0,0 +1,32 @@
//! Settings for the `flake8-unused-arguments` plugin.
use ruff_macros::ConfigurationOptions;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default, ConfigurationOptions)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Options {
#[option(
doc = r#"
Whether to allow unused variadic arguments, like `*args` and `**kwargs`.
"#,
default = "false",
value_type = "bool",
example = "ignore-variadic-names = true"
)]
pub ignore_variadic_names: Option<bool>,
}
#[derive(Debug, Hash, Default)]
pub struct Settings {
pub ignore_variadic_names: bool,
}
impl Settings {
#[allow(clippy::needless_pass_by_value)]
pub fn from_options(options: Options) -> Self {
Self {
ignore_variadic_names: options.ignore_variadic_names.unwrap_or_default(),
}
}
}

View File

@@ -0,0 +1,113 @@
---
source: src/flake8_unused_arguments/mod.rs
expression: checks
---
- kind:
UnusedFunctionArgument: a
location:
row: 1
column: 6
end_location:
row: 1
column: 7
fix: ~
- kind:
UnusedFunctionArgument: b
location:
row: 1
column: 9
end_location:
row: 1
column: 10
fix: ~
- kind:
UnusedFunctionArgument: a
location:
row: 5
column: 6
end_location:
row: 5
column: 7
fix: ~
- kind:
UnusedFunctionArgument: b
location:
row: 5
column: 9
end_location:
row: 5
column: 10
fix: ~
- kind:
UnusedFunctionArgument: args
location:
row: 5
column: 13
end_location:
row: 5
column: 17
fix: ~
- kind:
UnusedFunctionArgument: kwargs
location:
row: 5
column: 21
end_location:
row: 5
column: 27
fix: ~
- kind:
UnusedMethodArgument: a
location:
row: 10
column: 16
end_location:
row: 10
column: 17
fix: ~
- kind:
UnusedMethodArgument: b
location:
row: 10
column: 19
end_location:
row: 10
column: 20
fix: ~
- kind:
UnusedMethodArgument: a
location:
row: 13
column: 16
end_location:
row: 13
column: 17
fix: ~
- kind:
UnusedMethodArgument: b
location:
row: 13
column: 19
end_location:
row: 13
column: 20
fix: ~
- kind:
UnusedMethodArgument: args
location:
row: 13
column: 23
end_location:
row: 13
column: 27
fix: ~
- kind:
UnusedMethodArgument: kwargs
location:
row: 13
column: 31
end_location:
row: 13
column: 37
fix: ~

View File

@@ -0,0 +1,77 @@
---
source: src/flake8_unused_arguments/mod.rs
expression: checks
---
- kind:
UnusedFunctionArgument: a
location:
row: 1
column: 6
end_location:
row: 1
column: 7
fix: ~
- kind:
UnusedFunctionArgument: b
location:
row: 1
column: 9
end_location:
row: 1
column: 10
fix: ~
- kind:
UnusedFunctionArgument: a
location:
row: 5
column: 6
end_location:
row: 5
column: 7
fix: ~
- kind:
UnusedFunctionArgument: b
location:
row: 5
column: 9
end_location:
row: 5
column: 10
fix: ~
- kind:
UnusedMethodArgument: a
location:
row: 10
column: 16
end_location:
row: 10
column: 17
fix: ~
- kind:
UnusedMethodArgument: b
location:
row: 10
column: 19
end_location:
row: 10
column: 20
fix: ~
- kind:
UnusedMethodArgument: a
location:
row: 13
column: 16
end_location:
row: 13
column: 17
fix: ~
- kind:
UnusedMethodArgument: b
location:
row: 13
column: 19
end_location:
row: 13
column: 20
fix: ~

View File

@@ -590,7 +590,6 @@ mod tests {
src: vec![Path::new("resources/test/fixtures/isort").to_path_buf()],
..Settings::for_rule(CheckCode::I001)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -612,7 +611,6 @@ mod tests {
src: vec![Path::new("resources/test/fixtures/isort").to_path_buf()],
..Settings::for_rule(CheckCode::I001)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -635,7 +633,6 @@ mod tests {
src: vec![Path::new("resources/test/fixtures/isort").to_path_buf()],
..Settings::for_rule(CheckCode::I001)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -10,6 +10,7 @@ use crate::autofix::Fix;
use crate::checks::CheckKind;
use crate::isort::track::Block;
use crate::isort::{comments, format_imports};
use crate::settings::flags;
use crate::{Check, Settings, SourceCodeLocator};
fn extract_range(body: &[&Stmt]) -> Range {
@@ -34,7 +35,7 @@ pub fn check_imports(
block: &Block,
locator: &SourceCodeLocator,
settings: &Settings,
autofix: bool,
autofix: flags::Autofix,
) -> Option<Check> {
let indentation = locator.slice_source_code_range(&extract_indentation_range(&block.imports));
let indentation = leading_space(&indentation);
@@ -87,7 +88,9 @@ pub fn check_imports(
None
} else {
let mut check = Check::new(CheckKind::UnsortedImports, range);
if autofix && settings.fixable.contains(check.kind.code()) {
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code())
{
check.amend(Fix::replacement(
indent(&expected, indentation),
range.location,

View File

@@ -23,6 +23,7 @@ use crate::checks::Check;
use crate::linter::check_path;
use crate::resolver::Relativity;
use crate::settings::configuration::Configuration;
use crate::settings::flags;
use crate::source_code_locator::SourceCodeLocator;
mod ast;
@@ -127,8 +128,8 @@ pub fn check(path: &Path, contents: &str, autofix: bool) -> Result<Vec<Check>> {
&locator,
&directives,
&settings,
autofix,
false,
autofix.into(),
flags::Noqa::Enabled,
)?;
Ok(checks)

View File

@@ -22,7 +22,7 @@ use crate::code_gen::SourceGenerator;
use crate::directives::Directives;
use crate::message::{Message, Source};
use crate::noqa::add_noqa;
use crate::settings::Settings;
use crate::settings::{flags, Settings};
use crate::source_code_locator::SourceCodeLocator;
use crate::{cache, directives, fs, rustpython_helpers};
@@ -55,8 +55,8 @@ pub(crate) fn check_path(
locator: &SourceCodeLocator,
directives: &Directives,
settings: &Settings,
autofix: bool,
ignore_noqa: bool,
autofix: flags::Autofix,
noqa: flags::Noqa,
) -> Result<Vec<Check>> {
// Aggregate all checks.
let mut checks: Vec<Check> = vec![];
@@ -89,7 +89,7 @@ pub(crate) fn check_path(
&directives.noqa_line_for,
settings,
autofix,
ignore_noqa,
noqa,
path,
));
}
@@ -125,7 +125,7 @@ pub(crate) fn check_path(
&directives.noqa_line_for,
settings,
autofix,
ignore_noqa,
noqa,
);
// Create path ignores.
@@ -205,8 +205,8 @@ pub fn add_noqa_to_path(path: &Path, settings: &Settings) -> Result<usize> {
isort: directives.isort,
},
settings,
false,
true,
flags::Autofix::Disabled,
flags::Noqa::Disabled,
)?;
add_noqa(
@@ -293,7 +293,7 @@ fn lint(
&directives,
settings,
autofix.into(),
false,
flags::Noqa::Enabled,
)?;
// Apply autofix.
@@ -332,7 +332,7 @@ fn lint(
}
#[cfg(test)]
pub fn test_path(path: &Path, settings: &Settings, autofix: bool) -> Result<Vec<Check>> {
pub fn test_path(path: &Path, settings: &Settings) -> Result<Vec<Check>> {
let contents = fs::read_file(path)?;
let tokens: Vec<LexResult> = rustpython_helpers::tokenize(&contents);
let locator = SourceCodeLocator::new(&contents);
@@ -348,7 +348,7 @@ pub fn test_path(path: &Path, settings: &Settings, autofix: bool) -> Result<Vec<
&locator,
&directives,
settings,
autofix,
false,
flags::Autofix::Enabled,
flags::Noqa::Enabled,
)
}

View File

@@ -23,7 +23,6 @@ mod tests {
mccabe: mccabe::settings::Settings { max_complexity },
..Settings::for_rules(vec![CheckCode::C901])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -12,6 +12,7 @@ mod tests {
use crate::checks::CheckCode;
use crate::checks_gen::CheckCodePrefix;
use crate::linter::check_path;
use crate::settings::flags;
use crate::source_code_locator::SourceCodeLocator;
use crate::{directives, rustpython_helpers, settings};
@@ -32,8 +33,8 @@ mod tests {
&locator,
&directives,
&settings,
true,
false,
flags::Autofix::Enabled,
flags::Noqa::Enabled,
)?;
checks.sort_by_key(|check| check.location);
let actual = checks

View File

@@ -37,7 +37,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -38,7 +38,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -50,7 +49,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/pycodestyle/constant_literals.py"),
&settings::Settings::for_rules(vec![CheckCode::E711, CheckCode::E712, CheckCode::F632]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);

View File

@@ -8,7 +8,7 @@ expression: checks
- 88
location:
row: 5
column: 0
column: 88
end_location:
row: 5
column: 123
@@ -19,7 +19,7 @@ expression: checks
- 88
location:
row: 25
column: 0
column: 88
end_location:
row: 25
column: 127
@@ -30,7 +30,7 @@ expression: checks
- 88
location:
row: 40
column: 0
column: 88
end_location:
row: 40
column: 132
@@ -41,7 +41,7 @@ expression: checks
- 88
location:
row: 43
column: 0
column: 88
end_location:
row: 43
column: 105

View File

@@ -67,7 +67,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -18,6 +18,7 @@ mod tests {
use crate::checks::CheckCode;
use crate::checks_gen::CheckCodePrefix;
use crate::linter::{check_path, test_path};
use crate::settings::flags;
use crate::source_code_locator::SourceCodeLocator;
use crate::{directives, rustpython_helpers, settings};
@@ -109,7 +110,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -124,7 +124,6 @@ mod tests {
dummy_variable_rgx: Regex::new(r"^z$").unwrap(),
..settings::Settings::for_rule(CheckCode::F841)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -136,7 +135,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/pyflakes/__init__.py"),
&settings::Settings::for_rules(vec![CheckCode::F821, CheckCode::F822]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -148,7 +146,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/pyflakes/future_annotations.py"),
&settings::Settings::for_rules(vec![CheckCode::F401, CheckCode::F821]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -160,7 +157,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/pyflakes/multi_statement_lines.py"),
&settings::Settings::for_rule(CheckCode::F401),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -186,8 +182,8 @@ mod tests {
&locator,
&directives,
&settings,
true,
false,
flags::Autofix::Enabled,
flags::Noqa::Enabled,
)?;
checks.sort_by_key(|check| check.location);
let actual = checks

View File

@@ -21,7 +21,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -36,7 +36,6 @@ mod tests {
.join(path)
.as_path(),
&Settings::for_rules(vec![check_code]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);

View File

@@ -44,7 +44,6 @@ mod tests {
.join(path)
.as_path(),
&settings::Settings::for_rule(check_code),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
@@ -59,7 +58,6 @@ mod tests {
target_version: PythonVersion::Py37,
..settings::Settings::for_rule(CheckCode::UP006)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -74,7 +72,6 @@ mod tests {
target_version: PythonVersion::Py310,
..settings::Settings::for_rule(CheckCode::UP006)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -89,7 +86,6 @@ mod tests {
target_version: PythonVersion::Py37,
..settings::Settings::for_rule(CheckCode::UP007)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -104,7 +100,6 @@ mod tests {
target_version: PythonVersion::Py310,
..settings::Settings::for_rule(CheckCode::UP007)
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);

View File

@@ -5,6 +5,7 @@ use rustpython_ast::Location;
use crate::ast::types::Range;
use crate::autofix::Fix;
use crate::checks::CheckKind;
use crate::settings::flags;
use crate::source_code_locator::SourceCodeLocator;
use crate::{Check, Settings};
@@ -1609,7 +1610,7 @@ pub fn ambiguous_unicode_character(
end: Location,
context: Context,
settings: &Settings,
autofix: bool,
autofix: flags::Autofix,
) -> Vec<Check> {
let mut checks = vec![];
@@ -1653,7 +1654,9 @@ pub fn ambiguous_unicode_character(
},
);
if settings.enabled.contains(check.kind.code()) {
if autofix && settings.fixable.contains(check.kind.code()) {
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code())
{
check.amend(Fix::replacement(
representant.to_string(),
location,

View File

@@ -25,7 +25,6 @@ mod tests {
CheckCode::RUF003,
])
},
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -41,7 +40,6 @@ mod tests {
CheckCode::E501,
CheckCode::F841,
]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -53,7 +51,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/ruff/flake8_noqa.py"),
&settings::Settings::for_rules(vec![CheckCode::F401, CheckCode::F841]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -65,7 +62,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/ruff/ruff_noqa.py"),
&settings::Settings::for_rules(vec![CheckCode::F401, CheckCode::F841]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
@@ -77,7 +73,6 @@ mod tests {
let mut checks = test_path(
Path::new("./resources/test/fixtures/ruff/redirects.py"),
&settings::Settings::for_rules(vec![CheckCode::UP007]),
true,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);

View File

@@ -15,7 +15,7 @@ use crate::settings::pyproject::load_options;
use crate::settings::types::{FilePattern, PerFileIgnore, PythonVersion, SerializationFormat};
use crate::{
flake8_annotations, flake8_bugbear, flake8_errmsg, flake8_import_conventions, flake8_quotes,
flake8_tidy_imports, fs, isort, mccabe, pep8_naming, pyupgrade,
flake8_tidy_imports, flake8_unused_arguments, fs, isort, mccabe, pep8_naming, pyupgrade,
};
#[derive(Debug, Default)]
@@ -48,6 +48,7 @@ pub struct Configuration {
pub flake8_import_conventions: Option<flake8_import_conventions::settings::Options>,
pub flake8_quotes: Option<flake8_quotes::settings::Options>,
pub flake8_tidy_imports: Option<flake8_tidy_imports::settings::Options>,
pub flake8_unused_arguments: Option<flake8_unused_arguments::settings::Options>,
pub isort: Option<isort::settings::Options>,
pub mccabe: Option<mccabe::settings::Options>,
pub pep8_naming: Option<pep8_naming::settings::Options>,
@@ -123,6 +124,7 @@ impl Configuration {
flake8_import_conventions: options.flake8_import_conventions,
flake8_quotes: options.flake8_quotes,
flake8_tidy_imports: options.flake8_tidy_imports,
flake8_unused_arguments: options.flake8_unused_arguments,
isort: options.isort,
mccabe: options.mccabe,
pep8_naming: options.pep8_naming,
@@ -177,6 +179,9 @@ impl Configuration {
.or(config.flake8_import_conventions),
flake8_quotes: self.flake8_quotes.or(config.flake8_quotes),
flake8_tidy_imports: self.flake8_tidy_imports.or(config.flake8_tidy_imports),
flake8_unused_arguments: self
.flake8_unused_arguments
.or(config.flake8_unused_arguments),
isort: self.isort.or(config.isort),
mccabe: self.mccabe.or(config.mccabe),
pep8_naming: self.pep8_naming.or(config.pep8_naming),

43
src/settings/flags.rs Normal file
View File

@@ -0,0 +1,43 @@
/// Simple flags used to drive program behavior.
use crate::autofix::fixer;
#[derive(Debug, Copy, Clone)]
pub enum Autofix {
Enabled,
Disabled,
}
impl From<bool> for Autofix {
fn from(value: bool) -> Self {
if value {
Autofix::Enabled
} else {
Autofix::Disabled
}
}
}
impl From<&fixer::Mode> for Autofix {
fn from(value: &fixer::Mode) -> Self {
match value {
fixer::Mode::Generate | fixer::Mode::Apply => Autofix::Enabled,
fixer::Mode::None => Autofix::Disabled,
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum Noqa {
Enabled,
Disabled,
}
impl From<bool> for Noqa {
fn from(value: bool) -> Self {
if value {
Noqa::Enabled
} else {
Noqa::Disabled
}
}
}

View File

@@ -19,10 +19,11 @@ use crate::settings::configuration::Configuration;
use crate::settings::types::{FilePattern, PerFileIgnore, PythonVersion, SerializationFormat};
use crate::{
flake8_annotations, flake8_bugbear, flake8_errmsg, flake8_import_conventions, flake8_quotes,
flake8_tidy_imports, isort, mccabe, pep8_naming, pyupgrade,
flake8_tidy_imports, flake8_unused_arguments, isort, mccabe, pep8_naming, pyupgrade,
};
pub mod configuration;
pub mod flags;
pub mod options;
pub mod options_base;
pub mod pyproject;
@@ -54,6 +55,7 @@ pub struct Settings {
pub flake8_import_conventions: flake8_import_conventions::settings::Settings,
pub flake8_quotes: flake8_quotes::settings::Settings,
pub flake8_tidy_imports: flake8_tidy_imports::settings::Settings,
pub flake8_unused_arguments: flake8_unused_arguments::settings::Settings,
pub isort: isort::settings::Settings,
pub mccabe: mccabe::settings::Settings,
pub pep8_naming: pep8_naming::settings::Settings,
@@ -161,6 +163,10 @@ impl Settings {
.flake8_tidy_imports
.map(flake8_tidy_imports::settings::Settings::from_options)
.unwrap_or_default(),
flake8_unused_arguments: config
.flake8_unused_arguments
.map(flake8_unused_arguments::settings::Settings::from_options)
.unwrap_or_default(),
isort: config
.isort
.map(isort::settings::Settings::from_options)
@@ -206,6 +212,7 @@ impl Settings {
flake8_import_conventions: flake8_import_conventions::settings::Settings::default(),
flake8_quotes: flake8_quotes::settings::Settings::default(),
flake8_tidy_imports: flake8_tidy_imports::settings::Settings::default(),
flake8_unused_arguments: flake8_unused_arguments::settings::Settings::default(),
isort: isort::settings::Settings::default(),
mccabe: mccabe::settings::Settings::default(),
pep8_naming: pep8_naming::settings::Settings::default(),
@@ -237,6 +244,7 @@ impl Settings {
flake8_import_conventions: flake8_import_conventions::settings::Settings::default(),
flake8_quotes: flake8_quotes::settings::Settings::default(),
flake8_tidy_imports: flake8_tidy_imports::settings::Settings::default(),
flake8_unused_arguments: flake8_unused_arguments::settings::Settings::default(),
isort: isort::settings::Settings::default(),
mccabe: mccabe::settings::Settings::default(),
pep8_naming: pep8_naming::settings::Settings::default(),
@@ -275,9 +283,11 @@ impl Hash for Settings {
// Add plugin properties in alphabetical order.
self.flake8_annotations.hash(state);
self.flake8_bugbear.hash(state);
self.flake8_errmsg.hash(state);
self.flake8_import_conventions.hash(state);
self.flake8_quotes.hash(state);
self.flake8_tidy_imports.hash(state);
self.flake8_unused_arguments.hash(state);
self.isort.hash(state);
self.mccabe.hash(state);
self.pep8_naming.hash(state);

View File

@@ -8,7 +8,7 @@ use crate::checks_gen::CheckCodePrefix;
use crate::settings::types::{PythonVersion, SerializationFormat};
use crate::{
flake8_annotations, flake8_bugbear, flake8_errmsg, flake8_import_conventions, flake8_quotes,
flake8_tidy_imports, isort, mccabe, pep8_naming, pyupgrade,
flake8_tidy_imports, flake8_unused_arguments, isort, mccabe, pep8_naming, pyupgrade,
};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default, ConfigurationOptions)]
@@ -315,6 +315,8 @@ pub struct Options {
#[option_group]
pub flake8_import_conventions: Option<flake8_import_conventions::settings::Options>,
#[option_group]
pub flake8_unused_arguments: Option<flake8_unused_arguments::settings::Options>,
#[option_group]
pub isort: Option<isort::settings::Options>,
#[option_group]
pub mccabe: Option<mccabe::settings::Options>,

View File

@@ -140,6 +140,7 @@ mod tests {
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -186,6 +187,7 @@ line-length = 79
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -232,6 +234,7 @@ exclude = ["foo.py"]
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -278,6 +281,7 @@ select = ["E501"]
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -325,6 +329,7 @@ ignore = ["E501"]
flake8_quotes: None,
flake8_tidy_imports: None,
flake8_import_conventions: None,
flake8_unused_arguments: None,
isort: None,
mccabe: None,
pep8_naming: None,
@@ -436,6 +441,7 @@ other-attribute = 1
"dd".to_string(),
)])),
}),
flake8_unused_arguments: None,
isort: None,
mccabe: Some(mccabe::settings::Options {
max_complexity: Some(10),